diff --git a/inferredbugs-0045/instruction.md b/inferredbugs-0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71ebeb8cdda0226a22d7c6ffd24224387c63aa41 --- /dev/null +++ b/inferredbugs-0045/instruction.md @@ -0,0 +1,473 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ecommon +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Threading; +using System.Threading.Tasks; +using ECommon.Extensions; +using ECommon.Logging; +using ECommon.Utilities; + +namespace ECommon.IO +{ + /// An IO action helper class. + /// + public class IOHelper + { + private readonly ILogger _logger; + + public IOHelper(ILoggerFactory loggerFactory) + { + _logger = loggerFactory.Create(GetType().FullName); + } + + public void TryIOAction(string actionName, Func getContextInfo, Action action, int maxRetryTimes, bool continueRetryWhenRetryFailed = false, int retryInterval = 1000) + { + Ensure.NotNull(actionName, "actionName"); + Ensure.NotNull(getContextInfo, "getContextInfo"); + Ensure.NotNull(action, "action"); + TryIOActionRecursivelyInternal(actionName, getContextInfo, (x, y, z) => action(), 0, maxRetryTimes, continueRetryWhenRetryFailed, retryInterval); + } + public T TryIOFunc(string funcName, Func getContextInfo, Func func, int maxRetryTimes, bool continueRetryWhenRetryFailed = false, int retryInterval = 1000) + { + Ensure.NotNull(funcName, "funcName"); + Ensure.NotNull(getContextInfo, "getContextInfo"); + Ensure.NotNull(func, "func"); + return TryIOFuncRecursivelyInternal(funcName, getContextInfo, (x, y, z) => func(), 0, maxRetryTimes, continueRetryWhenRetryFailed, retryInterval); + } + + #region TryAsyncActionRecursively + + public void TryAsyncActionRecursively( + string asyncActionName, + Func> asyncAction, + Action mainAction, + Action successAction, + Func getContextInfoFunc, + Action failedAction, + int retryTimes, + bool retryWhenFailed = false, + int maxRetryTimes = 3, + int retryInterval = 1000) where TAsyncResult : AsyncTaskResult + { + try + { + asyncAction().ContinueWith(TaskContinueAction, new TaskExecutionContext + { + AsyncActionName = asyncActionName, + MainAction = mainAction, + SuccessAction = successAction, + GetContextInfoFunc = getContextInfoFunc, + FailedAction = failedAction, + RetryTimes = retryTimes, + RetryWhenFailed = retryWhenFailed, + MaxRetryTimes = maxRetryTimes, + RetryInterval = retryInterval + }); + } + catch (IOException ex) + { + _logger.Error(string.Format("IOException raised when executing async task '{0}', contextInfo:{1}, current retryTimes:{2}, try to execute the async task again.", asyncActionName, GetContextInfo(getContextInfoFunc), retryTimes), ex); + ExecuteRetryAction(asyncActionName, getContextInfoFunc, mainAction, retryTimes, maxRetryTimes, retryInterval); + } + catch (Exception ex) + { + _logger.Error(string.Format("Unknown exception raised when executing async task '{0}', contextInfo:{1}, current retryTimes:{2}", asyncActionName, GetContextInfo(getContextInfoFunc), retryTimes), ex); + if (retryWhenFailed) + { + ExecuteRetryAction(asyncActionName, getContextInfoFunc, mainAction, retryTimes, maxRetryTimes, retryInterval); + } + else + { + ExecuteFailedAction(asyncActionName, getContextInfoFunc, failedAction, ex.Message); + } + } + } + + private string GetContextInfo(Func func) + { + try + { + return func(); + } + catch (Exception ex) + { + _logger.Error("Failed to execute the getContextInfoFunc.", ex); + return null; + } + } + private void ExecuteFailedAction(string asyncActionName, Func getContextInfoFunc, Action failedAction, string errorMessage) + { + try + { + if (failedAction != null) + { + failedAction(errorMessage); + } + } + catch (Exception ex) + { + _logger.Error(string.Format("Failed to execute the failedAction of asyncAction:{0}, contextInfo:{1}", asyncActionName, GetContextInfo(getContextInfoFunc)), ex); + } + } + private void ExecuteRetryAction(string asyncActionName, Func getContextInfoFunc, Action mainAction, int currentRetryTimes, int maxRetryTimes, int retryInterval) + { + try + { + if (currentRetryTimes >= maxRetryTimes) + { + Task.Factory.StartDelayedTask(retryInterval, () => mainAction(currentRetryTimes + 1)); + } + else + { + mainAction(currentRetryTimes + 1); + } + } + catch (Exception ex) + { + _logger.Error(string.Format("Failed to execute the retryAction, asyncActionName:{0}, contextInfo:{1}", asyncActionName, GetContextInfo(getContextInfoFunc)), ex); + } + } + private void ProcessTaskException(string asyncActionName, Func getContextInfoFunc, Action mainAction, Action failedAction, Exception exception, int currentRetryTimes, int maxRetryTimes, int retryInterval, bool retryWhenFailed) + { + if (exception is IOException) + { + _logger.Error(string.Format("Async task '{0}' has io exception, contextInfo:{1}, current retryTimes:{2}, try to run the async task again.", asyncActionName, GetContextInfo(getContextInfoFunc), currentRetryTimes), exception); + ExecuteRetryAction(asyncActionName, getContextInfoFunc, mainAction, currentRetryTimes, maxRetryTimes, retryInterval); + } + else + { + _logger.Error(string.Format("Async task '{0}' has unknown exception, contextInfo:{1}, current retryTimes:{2}", asyncActionName, GetContextInfo(getContextInfoFunc), currentRetryTimes), exception); + if (retryWhenFailed) + { + ExecuteRetryAction(asyncActionName, getContextInfoFunc, mainAction, currentRetryTimes, maxRetryTimes, retryInterval); + } + else + { + ExecuteFailedAction(asyncActionName, getContextInfoFunc, failedAction, exception.Message); + } + } + } + private void TaskContinueAction(Task task, object obj) where TAsyncResult : AsyncTaskResult + { + var context = obj as TaskExecutionContext; + try + { + if (task.Exception != null) + { + ProcessTaskException( + context.AsyncActionName, + context.GetContextInfoFunc, + context.MainAction, + context.FailedAction, + task.Exception, + context.RetryTimes, + context.MaxRetryTimes, + context.RetryInterval, + context.RetryWhenFailed); + return; + } + if (task.IsCanceled) + { + _logger.ErrorFormat("Async task '{0}' was cancelled, contextInfo:{1}, current retryTimes:{2}.", + context.AsyncActionName, + GetContextInfo(context.GetContextInfoFunc), + context.RetryTimes); + ExecuteFailedAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.FailedAction, + string.Format("Async task '{0}' was cancelled.", context.AsyncActionName)); + return; + } + var result = task.Result; + if (result == null) + { + _logger.ErrorFormat("Async task '{0}' result is null, contextInfo:{1}, current retryTimes:{2}", + context.AsyncActionName, + GetContextInfo(context.GetContextInfoFunc), + context.RetryTimes); + if (context.RetryWhenFailed) + { + ExecuteRetryAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.MainAction, + context.RetryTimes, + context.MaxRetryTimes, + context.RetryInterval); + } + else + { + ExecuteFailedAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.FailedAction, + string.Format("Async task '{0}' result is null.", context.AsyncActionName)); + } + return; + } + if (result.Status == AsyncTaskStatus.Success) + { + if (context.SuccessAction != null) + { + context.SuccessAction(result); + } + } + else if (result.Status == AsyncTaskStatus.IOException) + { + _logger.ErrorFormat("Async task '{0}' result status is io exception, contextInfo:{1}, current retryTimes:{2}, errorMsg:{3}, try to run the async task again.", + context.AsyncActionName, + GetContextInfo(context.GetContextInfoFunc), + context.RetryTimes, + result.ErrorMessage); + ExecuteRetryAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.MainAction, + context.RetryTimes, + context.MaxRetryTimes, + context.RetryInterval); + } + else if (result.Status == AsyncTaskStatus.Failed) + { + _logger.ErrorFormat("Async task '{0}' failed, contextInfo:{1}, current retryTimes:{2}, errorMsg:{3}", + context.AsyncActionName, + GetContextInfo(context.GetContextInfoFunc), + context.RetryTimes, + result.ErrorMessage); + if (context.RetryWhenFailed) + { + ExecuteRetryAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.MainAction, + context.RetryTimes, + context.MaxRetryTimes, + context.RetryInterval); + } + else + { + ExecuteFailedAction( + context.AsyncActionName, + context.GetContextInfoFunc, + context.FailedAction, + result.ErrorMessage); + } + } + } + catch (Exception ex) + { + _logger.Error(string.Format("Failed to execute the taskContinueAction, asyncActionName:{0}, contextInfo:{1}", + context.AsyncActionName, + GetContextInfo(context.GetContextInfoFunc)), ex); + } + } + + class TaskExecutionContext + { + public string AsyncActionName; + public Action MainAction; + public Action SuccessAction; + public Func GetContextInfoFunc; + public Action FailedAction; + public int RetryTimes; + public bool RetryWhenFailed; + public int MaxRetryTimes; + public int RetryInterval; + } + + #endregion + + public void TryIOAction(Action action, string actionName) + { + Ensure.NotNull(action, "action"); + Ensure.NotNull(actionName, "actionName"); + try + { + action(); + } + catch (IOException) + { + throw; + } + catch (Exception ex) + { + throw new IOException(string.Format("{0} failed.", actionName), ex); + } + } + public Task TryIOActionAsync(Func action, string actionName) + { + Ensure.NotNull(action, "action"); + Ensure.NotNull(actionName, "actionName"); + try + { + return action(); + } + catch (IOException) + { + throw; + } + catch (Exception ex) + { + throw new IOException(string.Format("{0} failed.", actionName), ex); + } + } + public T TryIOFunc(Func func, string funcName) + { + Ensure.NotNull(func, "func"); + Ensure.NotNull(funcName, "funcName"); + try + { + return func(); + } + catch (IOException) + { + throw; + } + catch (Exception ex) + { + throw new IOException(string.Format("{0} failed.", funcName), ex); + } + } + public Task TryIOFuncAsync(Func> func, string funcName) + { + Ensure.NotNull(func, "func"); + Ensure.NotNull(funcName, "funcName"); + try + { + return func(); + } + catch (IOException) + { + throw; + } + catch (Exception ex) + { + throw new IOException(string.Format("{0} failed.", funcName), ex); + } + } + + private void TryIOActionRecursivelyInternal(string actionName, Func getContextInfo, Action, int> action, int retryTimes, int maxRetryTimes, bool continueRetryWhenRetryFailed = false, int retryInterval = 1000) + { + try + { + action(actionName, getContextInfo, retryTimes); + } + catch (IOException ex) + { + var errorMessage = string.Format("IOException raised when executing action '{0}', currentRetryTimes:{1}, maxRetryTimes:{2}, contextInfo:{3}", actionName, retryTimes, maxRetryTimes, getContextInfo()); + _logger.Error(errorMessage, ex); + if (retryTimes >= maxRetryTimes) + { + if (!continueRetryWhenRetryFailed) + { + throw; + } + else + { + Thread.Sleep(retryInterval); + } + } + retryTimes++; + TryIOActionRecursivelyInternal(actionName, getContextInfo, action, retryTimes, maxRetryTimes, continueRetryWhenRetryFailed, retryInterval); + } + catch (Exception ex) + { + var errorMessage = string.Format("Unknown exception raised when executing action '{0}', currentRetryTimes:{1}, maxRetryTimes:{2}, contextInfo:{3}", actionName, retryTimes, maxRetryTimes, getContextInfo()); + _logger.Error(errorMessage, ex); + throw; + } + } + private T TryIOFuncRecursivelyInternal(string funcName, Func getContextInfo, Func, long, T> func, int retryTimes, int maxRetryTimes, bool continueRetryWhenRetryFailed = false, int retryInterval = 1000) + { + try + { + return func(funcName, getContextInfo, retryTimes); + } + catch (IOException ex) + { + var errorMessage = string.Format("IOException raised when executing func '{0}', currentRetryTimes:{1}, maxRetryTimes:{2}, contextInfo:{3}", funcName, retryTimes, maxRetryTimes, getContextInfo()); + _logger.Error(errorMessage, ex); + if (retryTimes >= maxRetryTimes) + { + if (!continueRetryWhenRetryFailed) + { + throw; + } + else + { + Thread.Sleep(retryInterval); + } + } + retryTimes++; + return TryIOFuncRecursivelyInternal(funcName, getContextInfo, func, retryTimes, maxRetryTimes, continueRetryWhenRetryFailed, retryInterval); + } + catch (Exception ex) + { + var errorMessage = string.Format("Unknown exception raised when executing func '{0}', currentRetryTimes:{1}, maxRetryTimes:{2}, contextInfo:{3}", funcName, retryTimes, maxRetryTimes, getContextInfo()); + _logger.Error(errorMessage, ex); + throw; + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `context` last assigned on line 150 could be null and is dereferenced at line 169, column 21. + +### Severity: +ERROR + +### Procedure: +Void IOHelper.TaskContinueAction(Task`1,Object) + +### File: +src/ECommon/IO/IOHelper.cs + +### Key: +IOHelper.cs|TaskContinueAction|NULL_DEREFERENCE + +### Node Key: +52045082f0df3a0b2de3a487af64e105 + +### Hash: +d3b9f93f116fac7f98c718e9ed7e1e65 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0100/instruction.md b/inferredbugs-0100/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84dcab8b570536591661a571b8ea4a5f21fcb99f --- /dev/null +++ b/inferredbugs-0100/instruction.md @@ -0,0 +1,130 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Aspnetcore +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Configuration; +using Microsoft.IdentityModel.Tokens; +using System; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace JWTAuthentication.Controllers +{ + [Route("api/[controller]")] + [ApiController] + public class LoginController : Controller + { + private IConfiguration _config; + + public LoginController(IConfiguration config) + { + _config = config; + } + [AllowAnonymous] + [HttpPost] + public IActionResult Login([FromBody]UserModel login) + { + IActionResult response = Unauthorized(); + var user = AuthenticateUser(login); + + if (user != null) + { + var tokenString = GenerateJSONWebToken(user); + response = Ok(new { token = tokenString }); + } + + return response; + } + + private string GenerateJSONWebToken(UserModel userInfo) + { + var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); + var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256); + + var claims = new[] { + new Claim(JwtRegisteredClaimNames.Sub, userInfo.Username), + new Claim(JwtRegisteredClaimNames.Email, userInfo.EmailAddress), + new Claim("DateOfJoing", userInfo.DateOfJoing.ToString("yyyy-MM-dd")), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) + }; + + var token = new JwtSecurityToken(_config["Jwt:Issuer"], + _config["Jwt:Issuer"], + claims, + expires: DateTime.Now.AddMinutes(120), + signingCredentials: credentials); + + return new JwtSecurityTokenHandler().WriteToken(token); + } + + private UserModel AuthenticateUser(UserModel login) + { + UserModel user = null; + + //Validate the User Credentials + //Demo Purpose, I have Passed HardCoded User Information + if (user.Username == "Jignesh") + { + user = new UserModel { Username = "Jignesh Trivedi", EmailAddress = "test.btest@gmail.com", DateOfJoing = new DateTime(2010, 08, 02) }; + } + return user; + } + } +} +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`user` could be null (last assigned on line 61) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +UserModel LoginController.AuthenticateUser(UserModel) + +### File: +JWTAuthentication/JWTAuthentication/Controllers/LoginController.cs + +### Key: +LoginController.cs|AuthenticateUser|NULLPTR_DEREFERENCE + +### Hash: +1c7006d0e8f65d73bebefe2cbaebf3b0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0101/instruction.md b/inferredbugs-0101/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d85db6e033b7b6889bb2d5e4211c2853531eda63 --- /dev/null +++ b/inferredbugs-0101/instruction.md @@ -0,0 +1,206 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Mandrill-dotnet +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Mandrill.Requests; +using Mandrill.Utilities; +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Xunit; + +namespace Mandrill.Tests.UnitTests +{ + public class PostTests : IDisposable + { + public PostTests() + { + var responseMessage = new HttpResponseMessage(); + var messageHandler = new FakeHttpMessageHandler(responseMessage); + httpClient = new HttpClient(messageHandler); + } + public void Dispose() { + httpClient?.Dispose(); + } + + private void RespondWith(MandrillApi api, HttpStatusCode statusCode, string content) + { + var responseMessage = new HttpResponseMessage(statusCode); + responseMessage.Content = new FakeHttpContent(content); + var messageHandler = new FakeHttpMessageHandler(responseMessage); + api.SetHttpClient(new HttpClient(messageHandler)); + } + + private HttpClient httpClient; + + private class SampleObject + { + public string Name { get; set; } + public int Id { get; set; } + } + + private class SamplePayload : RequestBase + { + } + + [Fact] + public async Task Should_Serialize_Response_When_Json_Content_Is_Recieved() + { + string responseString = @"{ + ""Name"": ""Shawn"", + ""Id"": 1 + }"; + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + + SampleObject response = await api.Post("", new SamplePayload()); + + Assert.Equal("Shawn", response.Name); + Assert.Equal(1, response.Id); + } + + [Fact] + public async Task Should_Throw_Mandrill_Exception_When_Server_Error() + { + string responseString = @"{ + ""code"": ""501"", + ""message"": ""m1"", + ""name"": ""n1"", + ""status"": ""s1"" + }"; + + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.InternalServerError, responseString); + + var ex = await Assert.ThrowsAsync(async () => await api.Post("", new SamplePayload())); + Assert.Equal(501, ex.Error.Code); + Assert.Equal("m1", ex.Error.Message); + Assert.Equal("n1", ex.Error.Name); + Assert.Equal("s1", ex.Error.Status); + } + + [Fact] + public async Task Should_Allow_Multiple_Requests_With_Single_HttpClient() + { + string responseString = @"{ + ""Name"": ""Shawn"", + ""Id"": 1 + }"; + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + await api.Post("", new SamplePayload()); + + } + + [Fact] + public async Task Should_Throw_Mandrill_Exception_When_Serialization_Error() + { + string responseString = @""; + + var api = new MandrillApi(""); + RespondWith(api, HttpStatusCode.OK, responseString); + + var ex = await Assert.ThrowsAsync(async () => await api.Post("", new SamplePayload())); + var content = await ex.HttpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); + Assert.Equal(responseString, content); + } + public class FakeHttpMessageHandler : HttpMessageHandler + { + private HttpResponseMessage response; + + public FakeHttpMessageHandler(HttpResponseMessage response) + { + this.response = response; + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + var responseTask = new TaskCompletionSource(); + responseTask.SetResult(response); + + return responseTask.Task; + } + } + + public class FakeHttpContent : HttpContent + { + public string Content { get; set; } + + public FakeHttpContent(string content) + { + Content = content; + } + + protected async override Task SerializeToStreamAsync(Stream stream, TransportContext context) + { + byte[] byteArray = Encoding.ASCII.GetBytes(Content); + await stream.WriteAsync(byteArray, 0, Content.Length).ConfigureAwait(false); + } + + protected override bool TryComputeLength(out long length) + { + length = Content.Length; + return true; + } + } + + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource messageHandler of type Mandrill.Tests.UnitTests.PostTests$FakeHttpMessageHandler, Leaked resource responseMessage of type System.Net.Http.HttpResponseMessage, Leaked resource (output of System.Net.Http.HttpClient::.ctor() at Line 31) of type System.Net.Http.HttpClient, Leaked resource (output of Mandrill.Tests.UnitTests.PostTests$FakeHttpContent::.ctor() at Line 29) of type Mandrill.Tests.UnitTests.PostTests$FakeHttpContent in method "Void PostTests.RespondWith(MandrillApi,HttpStatusCode,String)". + +### Severity: +ERROR + +### Procedure: +Void PostTests.RespondWith(MandrillApi,HttpStatusCode,String) + +### File: +tests/Mandrill.Tests/UnitTests/PostTests.cs + +### Key: +PostTests.cs|RespondWith|DOTNET_RESOURCE_LEAK + +### Hash: +8638c9dd7f324eb9ba414ba4d985981c + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0106/instruction.md b/inferredbugs-0106/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..020b688f7c6c138f4e61523c5d74d84db6610ebd --- /dev/null +++ b/inferredbugs-0106/instruction.md @@ -0,0 +1,422 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** azure-functions-openapi-extension +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; + +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Abstractions; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Attributes; +using Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Extensions; + +using Microsoft.OpenApi.Any; +using Microsoft.OpenApi.Models; + +using Newtonsoft.Json.Serialization; + +namespace Microsoft.Azure.WebJobs.Extensions.OpenApi.Core.Visitors +{ + /// + /// This represents the visitor entity for type. This MUST be inherited. + /// + public abstract class TypeVisitor : IVisitor + { + /// + /// Initializes a new instance of the class. + /// + /// instance. + protected TypeVisitor(VisitorCollection visitorCollection) + { + this.VisitorCollection = visitorCollection.ThrowIfNullOrDefault(); + } + + /// + /// Gets the object. + /// + protected Type Type { get; private set; } + + /// + /// Gets the . + /// + protected VisitorCollection VisitorCollection { get; } + + /// + public virtual bool IsVisitable(Type type) + { + return false; + } + + /// + public virtual void Visit(IAcceptor acceptor, KeyValuePair type, NamingStrategy namingStrategy, params Attribute[] attributes) + { + return; + } + + /// + public virtual bool IsNavigatable(Type type) + { + return false; + } + + /// + public virtual bool IsParameterVisitable(Type type) + { + return false; + } + + /// + public virtual OpenApiSchema ParameterVisit(Type type, NamingStrategy namingStrategy) + { + return default; + } + + /// + public virtual bool IsPayloadVisitable(Type type) + { + return false; + } + + /// + public virtual OpenApiSchema PayloadVisit(Type type, NamingStrategy namingStrategy) + { + return default; + } + + /// + /// Checks whether the type is visitable or not. + /// + /// Type to check. + /// value. + /// Returns True, if the type is visitable; otherwise returns False. + protected bool IsVisitable(Type type, TypeCode code) + { + var @enum = Type.GetTypeCode(type); + var isVisitable = @enum == code; + + if (isVisitable) + { + this.Type = type; + } + + return isVisitable; + } + + /// + /// Checks whether the type can be referenced or not. + /// + /// Type to check. + /// Returns True, if the type can be referenced; otherwise returns False. + protected bool IsReferential(Type type) + { + var isReferential = type.IsReferentialType(); + + return isReferential; + } + + /// + /// Visits and processes the acceptor. + /// + /// instance. + /// Property name. + /// Type name. + /// Data type. + /// Data format. + /// List of attribute instances. + /// Returns the name as the schema key. + protected string Visit(IAcceptor acceptor, string name, string title, string dataType, string dataFormat, params Attribute[] attributes) + { + var instance = acceptor as OpenApiSchemaAcceptor; + if (instance.IsNullOrDefault()) + { + return null; + } + + if (instance.Schemas.ContainsKey(name)) + { + return null; + } + + var schema = new OpenApiSchema() + { + Title = title, + Type = dataType, + Format = dataFormat + }; + + // Adds the extra properties. + if (attributes.Any()) + { + Attribute attr = attributes.OfType().SingleOrDefault(); + if (!attr.IsNullOrDefault()) + { + if (dataType != "object") + { + schema.Nullable = this.GetOpenApiPropertyNullable(attr as OpenApiPropertyAttribute); + schema.Default = this.GetOpenApiPropertyDefault(attr as OpenApiPropertyAttribute); + } + schema.Description = this.GetOpenApiPropertyDescription(attr as OpenApiPropertyAttribute); + } + + attr = attributes.OfType().SingleOrDefault(); + if (!attr.IsNullOrDefault()) + { + var extension = new OpenApiString((attr as OpenApiSchemaVisibilityAttribute).Visibility.ToDisplayName()); + + schema.Extensions.Add("x-ms-visibility", extension); + } + } + + instance.Schemas.Add(name, schema); + + return name; + } + + /// + /// Visits and processes the for parameters. + /// + /// Data type. + /// Data format. + /// Returns instance. + protected OpenApiSchema ParameterVisit(string dataType, string dataFormat) + { + var schema = new OpenApiSchema() + { + Type = dataType, + Format = dataFormat + }; + + return schema; + } + + /// + /// Visits and processes the for payloads. + /// + /// Data type. + /// Data format. + /// Returns instance. + protected OpenApiSchema PayloadVisit(string dataType, string dataFormat) + { + var schema = new OpenApiSchema() + { + Type = dataType, + Format = dataFormat + }; + + return schema; + } + + /// + /// Gets the value indicating whether the property is nullable or not. + /// + /// instance. + /// Returns True, if nullable; otherwise returns False. + protected bool GetOpenApiPropertyNullable(OpenApiPropertyAttribute attr) + { + return attr.Nullable; + } + + /// + /// Gets the default value from the instance. + /// + /// instance. + /// Returns the default data. + protected IOpenApiAny GetOpenApiPropertyDefault(OpenApiPropertyAttribute attr) + { + var @default = attr.Default; + if (@default.IsNullOrDefault()) + { + return null; + } + + if (@default is bool) + { + return new OpenApiBoolean((bool) @default); + } + + if (@default is DateTime) + { + return new OpenApiDateTime((DateTime) @default); + } + + if (@default is DateTimeOffset) + { + return new OpenApiDateTime((DateTimeOffset) @default); + } + + if (@default is float) + { + return new OpenApiFloat((float) @default); + } + + if (@default is double) + { + return new OpenApiDouble((double) @default); + } + + if (@default is decimal) + { + return new OpenApiDouble(Convert.ToDouble(@default)); + } + + if (@default is short) + { + return new OpenApiInteger((short) @default); + } + + if (@default is int) + { + return new OpenApiInteger((int) @default); + } + + if (@default is long) + { + return new OpenApiLong((long) @default); + } + + if (@default is ushort) + { + return new OpenApiInteger(Convert.ToInt16(@default)); + } + + if (@default is uint) + { + return new OpenApiInteger(Convert.ToInt32(@default)); + } + + if (@default is ulong) + { + return new OpenApiLong(Convert.ToInt64(@default)); + } + + if (@default is Guid) + { + return new OpenApiString(Convert.ToString(@default)); + } + + return new OpenApiString((string) @default); + } + + /// + /// Gets the default value from the instance. + /// + /// Type to compare. + /// instance. + /// Returns the default data. + protected IOpenApiAny GetOpenApiPropertyDefault(OpenApiPropertyAttribute attr) + { + var @default = attr.Default; + if (@default.IsNullOrDefault()) + { + return null; + } + + if (typeof(T) == typeof(short)) + { + return new OpenApiInteger((short) @default); + } + + if (typeof(T) == typeof(int)) + { + return new OpenApiInteger((int) @default); + } + + if (typeof(T) == typeof(long)) + { + return new OpenApiLong((long) @default); + } + + if (@default is ushort) + { + return new OpenApiInteger(Convert.ToInt16(@default)); + } + + if (@default is uint) + { + return new OpenApiInteger(Convert.ToInt32(@default)); + } + + if (@default is ulong) + { + return new OpenApiLong(Convert.ToInt64(@default)); + } + + if (typeof(T) == typeof(string) && @default.GetType().IsEnumType()) + { + var @enum = (Enum)Convert.ChangeType(@default, typeof(Enum)); + + return new OpenApiString((string) EnumExtensions.ToDisplayName(@enum)); + } + + return new OpenApiString((string) @default); + } + + /// + /// Gets the property description. + /// + /// instance. + /// Returns the property description. + protected string GetOpenApiPropertyDescription(OpenApiPropertyAttribute attr) + { + return attr.Description; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `instance` last assigned on line 125 could be null and is dereferenced at line 131, column 13. + +### Severity: +ERROR + +### Procedure: +String TypeVisitor.Visit(IAcceptor,String,String,String,String,Attribute[]) + +### File: +src/Microsoft.Azure.WebJobs.Extensions.OpenApi.Core/Visitors/TypeVisitor.cs + +### Key: +TypeVisitor.cs|Visit|NULL_DEREFERENCE + +### Node Key: +cd898c0a5096d52146136ed94834c132 + +### Hash: +4f0543853d960e01f9c15cc682e178ad + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0107/instruction.md b/inferredbugs-0107/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e2f909dcf136bc5cc62fff114dadaf310bc9142 --- /dev/null +++ b/inferredbugs-0107/instruction.md @@ -0,0 +1,815 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Fare +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * dk.brics.automaton + * + * Copyright (c) 2001-2011 Anders Moeller + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; + +namespace NAutomaton +{ + public static class BasicOperations + { + public static Automaton Concatenate(Automaton a1, Automaton a2) + { + if (a1.IsSingleton && a2.IsSingleton) + { + return BasicAutomata.MakeString(a1.Singleton + a2.Singleton); + } + if (IsEmpty(a1) || IsEmpty(a2)) + { + return BasicAutomata.MakeEmpty(); + } + bool deterMinistic = a1.IsSingleton && a2.IsDeterministic; + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + foreach (State s in a1.AcceptStates) + { + s.Accept = false; + s.AddEpsilon(a2.InitialState); + } + a1.IsDeterministic = deterMinistic; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Concatenate(IList l) + { + if (l.Count == 0) + { + return BasicAutomata.MakeEmptyString(); + } + bool allSingleton = l.All(a => a.IsSingleton); + if (allSingleton) + { + var b = new StringBuilder(); + foreach (Automaton a in l) + { + b.Append(a.IsSingleton); + } + return BasicAutomata.MakeString(b.ToString()); + } + else + { + if (l.Any(a => a.IsEmpty)) + { + return BasicAutomata.MakeEmpty(); + } + var ids = new HashSet(); + foreach (Automaton a in l) + { + ids.Add(RuntimeHelpers.GetHashCode(a)); + } + bool hasAliases = ids.Count != l.Count; + Automaton b = l[0]; + b = hasAliases ? b.CloneExpanded() : b.CloneExpandedIfRequired(); + HashSet ac = b.AcceptStates; + bool first = true; + foreach (Automaton a in l) + { + if (first) + { + first = false; + } + else + { + if (a.IsEmptyString) + { + continue; + } + Automaton aa = a; + aa = hasAliases ? aa.CloneExpanded() : aa.CloneExpandedIfRequired(); + HashSet ns = aa.AcceptStates; + foreach (State s in ac) + { + s.Accept = false; + s.AddEpsilon(aa.InitialState); + if (s.Accept) + { + ns.Add(s); + } + } + ac = ns; + } + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + return b; + } + } + + public static Automaton Optional(Automaton a) + { + a = a.CloneExpandedIfRequired(); + var s = new State(); + s.AddEpsilon(a.InitialState); + s.Accept = true; + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a) + { + a = a.CloneExpanded(); + var s = new State(); + s.Accept = true; + s.AddEpsilon(a.InitialState); + foreach (State p in a.AcceptStates) + { + p.AddEpsilon(s); + } + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a, int min) + { + if (min == 0) + { + return Repeat(a); + } + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + @as.Add(Repeat(a)); + return Concatenate(@as); + } + + public static Automaton Repeat(Automaton a, int min, int max) + { + if (min > max) + { + return BasicAutomata.MakeEmpty(); + } + max -= min; + a.ExpandSingleton(); + Automaton b; + if (min == 0) + { + b = BasicAutomata.MakeEmptyString(); + } + else if (min == 1) + { + b = a.Clone(); + } + else + { + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + b = Concatenate(@as); + } + if (max > 0) + { + Automaton d = a.Clone(); + while (--max > 0) + { + Automaton c = a.Clone(); + foreach (State p in c.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + d = c; + } + foreach (State p in b.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + } + return b; + } + + public static Automaton Complement(Automaton a) + { + a = a.CloneExpandedIfRequired(); + a.Determinize(); + a.Totalize(); + foreach (State p in a.States) + { + p.Accept = !p.Accept; + } + a.RemoveDeadTransitions(); + return a; + } + + public static Automaton Minus(Automaton a1, Automaton a2) + { + if (a1.IsEmpty || a1 == a2) + { + return BasicAutomata.MakeEmpty(); + } + if (a2.IsEmpty) + { + return a1.CloneIfRequired(); + } + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return BasicAutomata.MakeEmpty(); + } + + return a1.CloneIfRequired(); + } + return Intersection(a1, a2.Complement()); + } + + public static Automaton Intersection(Automaton a1, Automaton a2) + { + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return a1.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a2.IsSingleton) + { + if (a1.Run(a2.Singleton)) + { + return a2.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a1 == a2) + { + return a1.CloneIfRequired(); + } + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var c = new Automaton(); + var worklist = new LinkedList(); + var newstates = new Dictionary(); + var p = new StatePair(c.InitialState, a1.InitialState, a2.InitialState); + worklist.AddLast(p); + newstates.Add(p, p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + p.S.Accept = p.S1.Accept && p.S2.Accept; + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Max >= t1[n1].Min) + { + var q = new StatePair(t1[n1].To, t2[n2].To); + StatePair r = newstates[q]; + if (r == null) + { + q.S = new State(); + worklist.AddLast(q); + newstates.Add(q, q); + r = q; + } + char min = t1[n1].Min > t2[n2].Min ? t1[n1].Min : t2[n2].Min; + char max = t1[n1].Max < t2[n2].Max ? t1[n1].Max : t2[n2].Max; + p.S.Transitions.Add(new Transition(min, max, r.S)); + } + } + } + } + c.IsDeterministic = a1.IsDeterministic && a2.IsDeterministic; + c.RemoveDeadTransitions(); + c.CheckMinimizeAlways(); + return c; + } + + public static bool SubsetOf(Automaton a1, Automaton a2) + { + if (a1 == a2) + { + return true; + } + if (a1.IsSingleton) + { + if (a2.IsSingleton) + { + return a1.Singleton.Equals(a2.Singleton); + } + return a2.Run(a1.Singleton); + } + a2.Determinize(); + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var worklist = new LinkedList(); + var visited = new HashSet(); + var p = new StatePair(a1.InitialState, a2.InitialState); + worklist.AddLast(p); + visited.Add(p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + if (p.S1.Accept && !p.S2.Accept) + { + return false; + } + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + int min1 = t1[n1].Min, max1 = t1[n1].Max; + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Min > min1) + { + return false; + } + if (t2[n2].Max < Char.MaxValue) + { + min1 = t2[n2].Max + 1; + } + else + { + min1 = Char.MaxValue; + max1 = Char.MinValue; + } + var q = new StatePair(t1[n1].To, t2[n2].To); + if (!visited.Contains(q)) + { + worklist.AddLast(q); + visited.Add(q); + } + } + if (min1 <= max1) + { + return false; + } + } + } + return true; + } + + public static Automaton Union(Automaton a1, Automaton a2) + { + if ((a1.IsSingleton && a2.IsSingleton && a1.Singleton.Equals(a2.Singleton)) || a1 == a2) + { + return a1.CloneIfRequired(); + } + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + var s = new State(); + s.AddEpsilon(a1.InitialState); + s.AddEpsilon(a2.InitialState); + a1.InitialState = s; + a1.IsDeterministic = false; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Union(ICollection l) + { + var ids = new HashSet(); + foreach (Automaton automaton in l) + { + ids.Add(RuntimeHelpers.GetHashCode(automaton)); + } + bool hasAliases = ids.Count != l.Count; + var s = new State(); + foreach (Automaton b in l) + { + if (b.IsEmpty) + { + continue; + } + Automaton bb = b; + bb = hasAliases ? bb.CloneExpanded() : bb.CloneExpandedIfRequired(); + s.AddEpsilon(bb.InitialState); + } + var a = new Automaton(); + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static void Determinize(Automaton a) + { + if (a.IsDeterministic || a.IsSingleton) + { + return; + } + var initialset = new HashSet(); + initialset.Add(a.InitialState); + Determinize(a, initialset); + } + + public static void Determinize(Automaton a, HashSet initialset) + { + char[] points = a.StartPoints; + // Subset construction. + IDictionary, HashSet> sets = new Dictionary, HashSet>(); + var worklist = new LinkedList>(); + IDictionary, State> newstate = new Dictionary, State>(); + sets.Add(initialset, initialset); + worklist.AddLast(initialset); + a.InitialState = new State(); + newstate.Add(initialset, a.InitialState); + while (worklist.Count > 0) + { + HashSet s = worklist.RemoveAndReturnFirst(); + State r = newstate[s]; + foreach (State q in s) + { + if (q.Accept) + { + r.Accept = true; + break; + } + } + for (int n = 0; n < points.Length; n++) + { + var p = new HashSet(); + foreach (State state in s) + { + foreach (Transition t in state.Transitions) + { + if (t.Min <= points[n] && points[n] <= t.Max) + { + p.Add(t.To); + } + } + } + if (!sets.ContainsKey(p)) + { + sets.Add(p, p); + worklist.AddLast(p); + newstate.Add(p, new State()); + } + State q = newstate[p]; + char min = points[n]; + char max; + if (n + 1 < points.Length) + { + max = (char) (points[n + 1] - 1); + } + else + { + max = Char.MaxValue; + } + r.Transitions.Add(new Transition(min, max, q)); + } + } + a.IsDeterministic = true; + a.RemoveDeadTransitions(); + } + + public static void AddEpsilons(Automaton a, ICollection pairs) + { + a.ExpandSingleton(); + var forward = new Dictionary>(); + var back = new Dictionary>(); + foreach (StatePair p in pairs) + { + HashSet to = forward[p.S1]; + if (to == null) + { + to = new HashSet(); + forward.Add(p.S1, to); + } + to.Add(p.S2); + HashSet from = back[p.S2]; + if (from == null) + { + from = new HashSet(); + back.Add(p.S2, from); + } + from.Add(p.S1); + } + + var worklist = new LinkedList(pairs); + var workset = new HashSet(pairs); + while (worklist.Count != 0) + { + StatePair p = worklist.RemoveAndReturnFirst(); + workset.Remove(p); + HashSet to = forward[p.S2]; + HashSet from = back[p.S1]; + if (to != null) + { + foreach (State s in to) + { + var pp = new StatePair(p.S1, s); + if (!pairs.Contains(pp)) + { + pairs.Add(pp); + forward[p.S1].Add(s); + back[s].Add(p.S1); + worklist.AddLast(pp); + workset.Add(pp); + if (from != null) + { + foreach (State q in from) + { + var qq = new StatePair(q, p.S1); + if (!workset.Contains(qq)) + { + worklist.AddLast(qq); + workset.Add(qq); + } + } + } + } + } + } + } + // Add transitions. + foreach (StatePair p in pairs) + { + p.S1.AddEpsilon(p.S2); + } + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + } + + public static bool IsEmptyString(Automaton a) + { + if (a.IsSingleton) + { + return a.Singleton.Length == 0; + } + + return a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsEmpty(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + return !a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsTotal(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + if (a.InitialState.Accept && a.InitialState.Transitions.Count == 1) + { + // Original code (Java): Transition t = a.initial.transitions.iterator().next(); + HashSet.Enumerator enumerator = a.InitialState.Transitions.GetEnumerator(); + enumerator.MoveNext(); + Transition t = enumerator.Current; + + return t.To == a.InitialState && t.Min == Char.MinValue && t.Max == Char.MaxValue; + } + return false; + } + + public static string GetShortestExample(Automaton a, bool accepted) + { + if (a.IsSingleton) + { + if (accepted) + { + return a.Singleton; + } + + if (a.Singleton.Length > 0) + { + return ""; + } + + return "\u0000"; + } + return GetShortestExample(a.InitialState, accepted); + } + + public static string GetShortestExample(State s, bool accepted) + { + IDictionary path = new Dictionary(); + var queue = new LinkedList(); + path.Add(s, ""); + queue.AddLast(s); + string best = null; + while (queue.Count != 0) + { + State q = queue.RemoveAndReturnFirst(); + string p = path[q]; + if (q.Accept == accepted) + { + if (best == null || p.Length < best.Length || (p.Length == best.Length && p.CompareTo(best) < 0)) + { + best = p; + } + } + else + { + foreach (Transition t in q.Transitions) + { + string tp = path[t.To]; + string np = p + t.Min; + if (tp == null || (tp.Length == np.Length && np.CompareTo(tp) < 0)) + { + if (tp == null) + { + queue.AddLast(t.To); + } + path.Add(t.To, np); + } + } + } + } + return best; + } + + public static bool Run(Automaton a, string s) + { + if (a.IsSingleton) + { + return s.Equals(a.IsSingleton); + } + if (a.IsDeterministic) + { + State p = a.InitialState; + foreach (char t in s) + { + State q = p.Step(t); + if (q == null) + { + return false; + } + p = q; + } + return p.Accept; + } + + HashSet states = a.States; + Automaton.StateNumbers = states; + var pp = new LinkedList(); + var ppOther = new LinkedList(); + var bb = new BitArray(states.Count); + var bbOther = new BitArray(states.Count); + pp.AddLast(a.InitialState); + var dest = new List(); + bool accept = a.InitialState.Accept; + + foreach (char c in s) + { + accept = false; + ppOther.Clear(); + bbOther.SetAll(false); + foreach (State p in pp) + { + dest.Clear(); + p.Step(c, dest); + foreach (State q in dest) + { + if (q.Accept) + { + accept = true; + } + if (!bbOther.Get(q.Number)) + { + bbOther.Set(q.Number, true); + ppOther.AddLast(q); + } + } + } + LinkedList tp = pp; + pp = ppOther; + ppOther = tp; + BitArray tb = bb; + bb = bbOther; + bbOther = tb; + } + return accept; + } + } +} +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`a->NAutomaton.Automaton.singleton` could be null (from the call to `Automaton.get_InitialState()` on line 625) and is dereferenced in call to `Automaton.get_InitialState()`. + +### Severity: +ERROR + +### Procedure: +Boolean BasicOperations.IsTotal(Automaton) + +### File: +Src/NAutomaton/BasicOperations.cs + +### Key: +BasicOperations.cs|IsTotal|NULLPTR_DEREFERENCE + +### Hash: +7dbc81631d2c345a3519fa1396f2eb44 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0108/instruction.md b/inferredbugs-0108/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89c5f18c4090bf730ae1f2084e5313dbf3dabf96 --- /dev/null +++ b/inferredbugs-0108/instruction.md @@ -0,0 +1,815 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Fare +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * dk.brics.automaton + * + * Copyright (c) 2001-2011 Anders Moeller + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; + +namespace NAutomaton +{ + public static class BasicOperations + { + public static Automaton Concatenate(Automaton a1, Automaton a2) + { + if (a1.IsSingleton && a2.IsSingleton) + { + return BasicAutomata.MakeString(a1.Singleton + a2.Singleton); + } + if (IsEmpty(a1) || IsEmpty(a2)) + { + return BasicAutomata.MakeEmpty(); + } + bool deterMinistic = a1.IsSingleton && a2.IsDeterministic; + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + foreach (State s in a1.AcceptStates) + { + s.Accept = false; + s.AddEpsilon(a2.InitialState); + } + a1.IsDeterministic = deterMinistic; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Concatenate(IList l) + { + if (l.Count == 0) + { + return BasicAutomata.MakeEmptyString(); + } + bool allSingleton = l.All(a => a.IsSingleton); + if (allSingleton) + { + var b = new StringBuilder(); + foreach (Automaton a in l) + { + b.Append(a.IsSingleton); + } + return BasicAutomata.MakeString(b.ToString()); + } + else + { + if (l.Any(a => a.IsEmpty)) + { + return BasicAutomata.MakeEmpty(); + } + var ids = new HashSet(); + foreach (Automaton a in l) + { + ids.Add(RuntimeHelpers.GetHashCode(a)); + } + bool hasAliases = ids.Count != l.Count; + Automaton b = l[0]; + b = hasAliases ? b.CloneExpanded() : b.CloneExpandedIfRequired(); + HashSet ac = b.AcceptStates; + bool first = true; + foreach (Automaton a in l) + { + if (first) + { + first = false; + } + else + { + if (a.IsEmptyString) + { + continue; + } + Automaton aa = a; + aa = hasAliases ? aa.CloneExpanded() : aa.CloneExpandedIfRequired(); + HashSet ns = aa.AcceptStates; + foreach (State s in ac) + { + s.Accept = false; + s.AddEpsilon(aa.InitialState); + if (s.Accept) + { + ns.Add(s); + } + } + ac = ns; + } + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + return b; + } + } + + public static Automaton Optional(Automaton a) + { + a = a.CloneExpandedIfRequired(); + var s = new State(); + s.AddEpsilon(a.InitialState); + s.Accept = true; + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a) + { + a = a.CloneExpanded(); + var s = new State(); + s.Accept = true; + s.AddEpsilon(a.InitialState); + foreach (State p in a.AcceptStates) + { + p.AddEpsilon(s); + } + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a, int min) + { + if (min == 0) + { + return Repeat(a); + } + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + @as.Add(Repeat(a)); + return Concatenate(@as); + } + + public static Automaton Repeat(Automaton a, int min, int max) + { + if (min > max) + { + return BasicAutomata.MakeEmpty(); + } + max -= min; + a.ExpandSingleton(); + Automaton b; + if (min == 0) + { + b = BasicAutomata.MakeEmptyString(); + } + else if (min == 1) + { + b = a.Clone(); + } + else + { + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + b = Concatenate(@as); + } + if (max > 0) + { + Automaton d = a.Clone(); + while (--max > 0) + { + Automaton c = a.Clone(); + foreach (State p in c.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + d = c; + } + foreach (State p in b.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + } + return b; + } + + public static Automaton Complement(Automaton a) + { + a = a.CloneExpandedIfRequired(); + a.Determinize(); + a.Totalize(); + foreach (State p in a.States) + { + p.Accept = !p.Accept; + } + a.RemoveDeadTransitions(); + return a; + } + + public static Automaton Minus(Automaton a1, Automaton a2) + { + if (a1.IsEmpty || a1 == a2) + { + return BasicAutomata.MakeEmpty(); + } + if (a2.IsEmpty) + { + return a1.CloneIfRequired(); + } + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return BasicAutomata.MakeEmpty(); + } + + return a1.CloneIfRequired(); + } + return Intersection(a1, a2.Complement()); + } + + public static Automaton Intersection(Automaton a1, Automaton a2) + { + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return a1.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a2.IsSingleton) + { + if (a1.Run(a2.Singleton)) + { + return a2.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a1 == a2) + { + return a1.CloneIfRequired(); + } + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var c = new Automaton(); + var worklist = new LinkedList(); + var newstates = new Dictionary(); + var p = new StatePair(c.InitialState, a1.InitialState, a2.InitialState); + worklist.AddLast(p); + newstates.Add(p, p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + p.S.Accept = p.S1.Accept && p.S2.Accept; + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Max >= t1[n1].Min) + { + var q = new StatePair(t1[n1].To, t2[n2].To); + StatePair r = newstates[q]; + if (r == null) + { + q.S = new State(); + worklist.AddLast(q); + newstates.Add(q, q); + r = q; + } + char min = t1[n1].Min > t2[n2].Min ? t1[n1].Min : t2[n2].Min; + char max = t1[n1].Max < t2[n2].Max ? t1[n1].Max : t2[n2].Max; + p.S.Transitions.Add(new Transition(min, max, r.S)); + } + } + } + } + c.IsDeterministic = a1.IsDeterministic && a2.IsDeterministic; + c.RemoveDeadTransitions(); + c.CheckMinimizeAlways(); + return c; + } + + public static bool SubsetOf(Automaton a1, Automaton a2) + { + if (a1 == a2) + { + return true; + } + if (a1.IsSingleton) + { + if (a2.IsSingleton) + { + return a1.Singleton.Equals(a2.Singleton); + } + return a2.Run(a1.Singleton); + } + a2.Determinize(); + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var worklist = new LinkedList(); + var visited = new HashSet(); + var p = new StatePair(a1.InitialState, a2.InitialState); + worklist.AddLast(p); + visited.Add(p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + if (p.S1.Accept && !p.S2.Accept) + { + return false; + } + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + int min1 = t1[n1].Min, max1 = t1[n1].Max; + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Min > min1) + { + return false; + } + if (t2[n2].Max < Char.MaxValue) + { + min1 = t2[n2].Max + 1; + } + else + { + min1 = Char.MaxValue; + max1 = Char.MinValue; + } + var q = new StatePair(t1[n1].To, t2[n2].To); + if (!visited.Contains(q)) + { + worklist.AddLast(q); + visited.Add(q); + } + } + if (min1 <= max1) + { + return false; + } + } + } + return true; + } + + public static Automaton Union(Automaton a1, Automaton a2) + { + if ((a1.IsSingleton && a2.IsSingleton && a1.Singleton.Equals(a2.Singleton)) || a1 == a2) + { + return a1.CloneIfRequired(); + } + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + var s = new State(); + s.AddEpsilon(a1.InitialState); + s.AddEpsilon(a2.InitialState); + a1.InitialState = s; + a1.IsDeterministic = false; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Union(ICollection l) + { + var ids = new HashSet(); + foreach (Automaton automaton in l) + { + ids.Add(RuntimeHelpers.GetHashCode(automaton)); + } + bool hasAliases = ids.Count != l.Count; + var s = new State(); + foreach (Automaton b in l) + { + if (b.IsEmpty) + { + continue; + } + Automaton bb = b; + bb = hasAliases ? bb.CloneExpanded() : bb.CloneExpandedIfRequired(); + s.AddEpsilon(bb.InitialState); + } + var a = new Automaton(); + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static void Determinize(Automaton a) + { + if (a.IsDeterministic || a.IsSingleton) + { + return; + } + var initialset = new HashSet(); + initialset.Add(a.InitialState); + Determinize(a, initialset); + } + + public static void Determinize(Automaton a, HashSet initialset) + { + char[] points = a.StartPoints; + // Subset construction. + IDictionary, HashSet> sets = new Dictionary, HashSet>(); + var worklist = new LinkedList>(); + IDictionary, State> newstate = new Dictionary, State>(); + sets.Add(initialset, initialset); + worklist.AddLast(initialset); + a.InitialState = new State(); + newstate.Add(initialset, a.InitialState); + while (worklist.Count > 0) + { + HashSet s = worklist.RemoveAndReturnFirst(); + State r = newstate[s]; + foreach (State q in s) + { + if (q.Accept) + { + r.Accept = true; + break; + } + } + for (int n = 0; n < points.Length; n++) + { + var p = new HashSet(); + foreach (State state in s) + { + foreach (Transition t in state.Transitions) + { + if (t.Min <= points[n] && points[n] <= t.Max) + { + p.Add(t.To); + } + } + } + if (!sets.ContainsKey(p)) + { + sets.Add(p, p); + worklist.AddLast(p); + newstate.Add(p, new State()); + } + State q = newstate[p]; + char min = points[n]; + char max; + if (n + 1 < points.Length) + { + max = (char) (points[n + 1] - 1); + } + else + { + max = Char.MaxValue; + } + r.Transitions.Add(new Transition(min, max, q)); + } + } + a.IsDeterministic = true; + a.RemoveDeadTransitions(); + } + + public static void AddEpsilons(Automaton a, ICollection pairs) + { + a.ExpandSingleton(); + var forward = new Dictionary>(); + var back = new Dictionary>(); + foreach (StatePair p in pairs) + { + HashSet to = forward[p.S1]; + if (to == null) + { + to = new HashSet(); + forward.Add(p.S1, to); + } + to.Add(p.S2); + HashSet from = back[p.S2]; + if (from == null) + { + from = new HashSet(); + back.Add(p.S2, from); + } + from.Add(p.S1); + } + + var worklist = new LinkedList(pairs); + var workset = new HashSet(pairs); + while (worklist.Count != 0) + { + StatePair p = worklist.RemoveAndReturnFirst(); + workset.Remove(p); + HashSet to = forward[p.S2]; + HashSet from = back[p.S1]; + if (to != null) + { + foreach (State s in to) + { + var pp = new StatePair(p.S1, s); + if (!pairs.Contains(pp)) + { + pairs.Add(pp); + forward[p.S1].Add(s); + back[s].Add(p.S1); + worklist.AddLast(pp); + workset.Add(pp); + if (from != null) + { + foreach (State q in from) + { + var qq = new StatePair(q, p.S1); + if (!workset.Contains(qq)) + { + worklist.AddLast(qq); + workset.Add(qq); + } + } + } + } + } + } + } + // Add transitions. + foreach (StatePair p in pairs) + { + p.S1.AddEpsilon(p.S2); + } + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + } + + public static bool IsEmptyString(Automaton a) + { + if (a.IsSingleton) + { + return a.Singleton.Length == 0; + } + + return a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsEmpty(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + return !a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsTotal(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + if (a.InitialState.Accept && a.InitialState.Transitions.Count == 1) + { + // Original code (Java): Transition t = a.initial.transitions.iterator().next(); + HashSet.Enumerator enumerator = a.InitialState.Transitions.GetEnumerator(); + enumerator.MoveNext(); + Transition t = enumerator.Current; + + return t.To == a.InitialState && t.Min == Char.MinValue && t.Max == Char.MaxValue; + } + return false; + } + + public static string GetShortestExample(Automaton a, bool accepted) + { + if (a.IsSingleton) + { + if (accepted) + { + return a.Singleton; + } + + if (a.Singleton.Length > 0) + { + return ""; + } + + return "\u0000"; + } + return GetShortestExample(a.InitialState, accepted); + } + + public static string GetShortestExample(State s, bool accepted) + { + IDictionary path = new Dictionary(); + var queue = new LinkedList(); + path.Add(s, ""); + queue.AddLast(s); + string best = null; + while (queue.Count != 0) + { + State q = queue.RemoveAndReturnFirst(); + string p = path[q]; + if (q.Accept == accepted) + { + if (best == null || p.Length < best.Length || (p.Length == best.Length && p.CompareTo(best) < 0)) + { + best = p; + } + } + else + { + foreach (Transition t in q.Transitions) + { + string tp = path[t.To]; + string np = p + t.Min; + if (tp == null || (tp.Length == np.Length && np.CompareTo(tp) < 0)) + { + if (tp == null) + { + queue.AddLast(t.To); + } + path.Add(t.To, np); + } + } + } + } + return best; + } + + public static bool Run(Automaton a, string s) + { + if (a.IsSingleton) + { + return s.Equals(a.IsSingleton); + } + if (a.IsDeterministic) + { + State p = a.InitialState; + foreach (char t in s) + { + State q = p.Step(t); + if (q == null) + { + return false; + } + p = q; + } + return p.Accept; + } + + HashSet states = a.States; + Automaton.StateNumbers = states; + var pp = new LinkedList(); + var ppOther = new LinkedList(); + var bb = new BitArray(states.Count); + var bbOther = new BitArray(states.Count); + pp.AddLast(a.InitialState); + var dest = new List(); + bool accept = a.InitialState.Accept; + + foreach (char c in s) + { + accept = false; + ppOther.Clear(); + bbOther.SetAll(false); + foreach (State p in pp) + { + dest.Clear(); + p.Step(c, dest); + foreach (State q in dest) + { + if (q.Accept) + { + accept = true; + } + if (!bbOther.Get(q.Number)) + { + bbOther.Set(q.Number, true); + ppOther.AddLast(q); + } + } + } + LinkedList tp = pp; + pp = ppOther; + ppOther = tp; + BitArray tb = bb; + bb = bbOther; + bbOther = tb; + } + return accept; + } + } +} +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`bb->NAutomaton.Automaton.singleton` could be null (from the call to `Automaton.CloneExpanded()` on line 449) and is dereferenced in call to `Automaton.get_InitialState()`. + +### Severity: +ERROR + +### Procedure: +Automaton BasicOperations.Union(ICollection`1) + +### File: +Src/NAutomaton/BasicOperations.cs + +### Key: +BasicOperations.cs|Union|NULLPTR_DEREFERENCE + +### Hash: +a6803b933fe81f0e80022390dedc99ef + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0109/instruction.md b/inferredbugs-0109/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7763695c9d2215df37bf3d85f5a41b061b5a9db --- /dev/null +++ b/inferredbugs-0109/instruction.md @@ -0,0 +1,815 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Fare +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* + * dk.brics.automaton + * + * Copyright (c) 2001-2011 Anders Moeller + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; + +namespace NAutomaton +{ + public static class BasicOperations + { + public static Automaton Concatenate(Automaton a1, Automaton a2) + { + if (a1.IsSingleton && a2.IsSingleton) + { + return BasicAutomata.MakeString(a1.Singleton + a2.Singleton); + } + if (IsEmpty(a1) || IsEmpty(a2)) + { + return BasicAutomata.MakeEmpty(); + } + bool deterMinistic = a1.IsSingleton && a2.IsDeterministic; + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + foreach (State s in a1.AcceptStates) + { + s.Accept = false; + s.AddEpsilon(a2.InitialState); + } + a1.IsDeterministic = deterMinistic; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Concatenate(IList l) + { + if (l.Count == 0) + { + return BasicAutomata.MakeEmptyString(); + } + bool allSingleton = l.All(a => a.IsSingleton); + if (allSingleton) + { + var b = new StringBuilder(); + foreach (Automaton a in l) + { + b.Append(a.IsSingleton); + } + return BasicAutomata.MakeString(b.ToString()); + } + else + { + if (l.Any(a => a.IsEmpty)) + { + return BasicAutomata.MakeEmpty(); + } + var ids = new HashSet(); + foreach (Automaton a in l) + { + ids.Add(RuntimeHelpers.GetHashCode(a)); + } + bool hasAliases = ids.Count != l.Count; + Automaton b = l[0]; + b = hasAliases ? b.CloneExpanded() : b.CloneExpandedIfRequired(); + HashSet ac = b.AcceptStates; + bool first = true; + foreach (Automaton a in l) + { + if (first) + { + first = false; + } + else + { + if (a.IsEmptyString) + { + continue; + } + Automaton aa = a; + aa = hasAliases ? aa.CloneExpanded() : aa.CloneExpandedIfRequired(); + HashSet ns = aa.AcceptStates; + foreach (State s in ac) + { + s.Accept = false; + s.AddEpsilon(aa.InitialState); + if (s.Accept) + { + ns.Add(s); + } + } + ac = ns; + } + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + return b; + } + } + + public static Automaton Optional(Automaton a) + { + a = a.CloneExpandedIfRequired(); + var s = new State(); + s.AddEpsilon(a.InitialState); + s.Accept = true; + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a) + { + a = a.CloneExpanded(); + var s = new State(); + s.Accept = true; + s.AddEpsilon(a.InitialState); + foreach (State p in a.AcceptStates) + { + p.AddEpsilon(s); + } + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static Automaton Repeat(Automaton a, int min) + { + if (min == 0) + { + return Repeat(a); + } + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + @as.Add(Repeat(a)); + return Concatenate(@as); + } + + public static Automaton Repeat(Automaton a, int min, int max) + { + if (min > max) + { + return BasicAutomata.MakeEmpty(); + } + max -= min; + a.ExpandSingleton(); + Automaton b; + if (min == 0) + { + b = BasicAutomata.MakeEmptyString(); + } + else if (min == 1) + { + b = a.Clone(); + } + else + { + IList @as = new List(); + while (min-- > 0) + { + @as.Add(a); + } + b = Concatenate(@as); + } + if (max > 0) + { + Automaton d = a.Clone(); + while (--max > 0) + { + Automaton c = a.Clone(); + foreach (State p in c.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + d = c; + } + foreach (State p in b.AcceptStates) + { + p.AddEpsilon(d.InitialState); + } + b.IsDeterministic = false; + b.ClearHashCode(); + b.CheckMinimizeAlways(); + } + return b; + } + + public static Automaton Complement(Automaton a) + { + a = a.CloneExpandedIfRequired(); + a.Determinize(); + a.Totalize(); + foreach (State p in a.States) + { + p.Accept = !p.Accept; + } + a.RemoveDeadTransitions(); + return a; + } + + public static Automaton Minus(Automaton a1, Automaton a2) + { + if (a1.IsEmpty || a1 == a2) + { + return BasicAutomata.MakeEmpty(); + } + if (a2.IsEmpty) + { + return a1.CloneIfRequired(); + } + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return BasicAutomata.MakeEmpty(); + } + + return a1.CloneIfRequired(); + } + return Intersection(a1, a2.Complement()); + } + + public static Automaton Intersection(Automaton a1, Automaton a2) + { + if (a1.IsSingleton) + { + if (a2.Run(a1.Singleton)) + { + return a1.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a2.IsSingleton) + { + if (a1.Run(a2.Singleton)) + { + return a2.CloneIfRequired(); + } + + return BasicAutomata.MakeEmpty(); + } + if (a1 == a2) + { + return a1.CloneIfRequired(); + } + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var c = new Automaton(); + var worklist = new LinkedList(); + var newstates = new Dictionary(); + var p = new StatePair(c.InitialState, a1.InitialState, a2.InitialState); + worklist.AddLast(p); + newstates.Add(p, p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + p.S.Accept = p.S1.Accept && p.S2.Accept; + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Max >= t1[n1].Min) + { + var q = new StatePair(t1[n1].To, t2[n2].To); + StatePair r = newstates[q]; + if (r == null) + { + q.S = new State(); + worklist.AddLast(q); + newstates.Add(q, q); + r = q; + } + char min = t1[n1].Min > t2[n2].Min ? t1[n1].Min : t2[n2].Min; + char max = t1[n1].Max < t2[n2].Max ? t1[n1].Max : t2[n2].Max; + p.S.Transitions.Add(new Transition(min, max, r.S)); + } + } + } + } + c.IsDeterministic = a1.IsDeterministic && a2.IsDeterministic; + c.RemoveDeadTransitions(); + c.CheckMinimizeAlways(); + return c; + } + + public static bool SubsetOf(Automaton a1, Automaton a2) + { + if (a1 == a2) + { + return true; + } + if (a1.IsSingleton) + { + if (a2.IsSingleton) + { + return a1.Singleton.Equals(a2.Singleton); + } + return a2.Run(a1.Singleton); + } + a2.Determinize(); + Transition[][] transitions1 = Automaton.GetSortedTransitions(a1.States); + Transition[][] transitions2 = Automaton.GetSortedTransitions(a2.States); + var worklist = new LinkedList(); + var visited = new HashSet(); + var p = new StatePair(a1.InitialState, a2.InitialState); + worklist.AddLast(p); + visited.Add(p); + while (worklist.Count > 0) + { + p = worklist.RemoveAndReturnFirst(); + if (p.S1.Accept && !p.S2.Accept) + { + return false; + } + Transition[] t1 = transitions1[p.S1.Number]; + Transition[] t2 = transitions2[p.S2.Number]; + for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) + { + while (b2 < t2.Length && t2[b2].Max < t1[n1].Min) + { + b2++; + } + int min1 = t1[n1].Min, max1 = t1[n1].Max; + for (int n2 = b2; n2 < t2.Length && t1[n1].Max >= t2[n2].Min; n2++) + { + if (t2[n2].Min > min1) + { + return false; + } + if (t2[n2].Max < Char.MaxValue) + { + min1 = t2[n2].Max + 1; + } + else + { + min1 = Char.MaxValue; + max1 = Char.MinValue; + } + var q = new StatePair(t1[n1].To, t2[n2].To); + if (!visited.Contains(q)) + { + worklist.AddLast(q); + visited.Add(q); + } + } + if (min1 <= max1) + { + return false; + } + } + } + return true; + } + + public static Automaton Union(Automaton a1, Automaton a2) + { + if ((a1.IsSingleton && a2.IsSingleton && a1.Singleton.Equals(a2.Singleton)) || a1 == a2) + { + return a1.CloneIfRequired(); + } + if (a1 == a2) + { + a1 = a1.CloneExpanded(); + a2 = a2.CloneExpanded(); + } + else + { + a1 = a1.CloneExpandedIfRequired(); + a2 = a2.CloneExpandedIfRequired(); + } + var s = new State(); + s.AddEpsilon(a1.InitialState); + s.AddEpsilon(a2.InitialState); + a1.InitialState = s; + a1.IsDeterministic = false; + a1.ClearHashCode(); + a1.CheckMinimizeAlways(); + return a1; + } + + public static Automaton Union(ICollection l) + { + var ids = new HashSet(); + foreach (Automaton automaton in l) + { + ids.Add(RuntimeHelpers.GetHashCode(automaton)); + } + bool hasAliases = ids.Count != l.Count; + var s = new State(); + foreach (Automaton b in l) + { + if (b.IsEmpty) + { + continue; + } + Automaton bb = b; + bb = hasAliases ? bb.CloneExpanded() : bb.CloneExpandedIfRequired(); + s.AddEpsilon(bb.InitialState); + } + var a = new Automaton(); + a.InitialState = s; + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + return a; + } + + public static void Determinize(Automaton a) + { + if (a.IsDeterministic || a.IsSingleton) + { + return; + } + var initialset = new HashSet(); + initialset.Add(a.InitialState); + Determinize(a, initialset); + } + + public static void Determinize(Automaton a, HashSet initialset) + { + char[] points = a.StartPoints; + // Subset construction. + IDictionary, HashSet> sets = new Dictionary, HashSet>(); + var worklist = new LinkedList>(); + IDictionary, State> newstate = new Dictionary, State>(); + sets.Add(initialset, initialset); + worklist.AddLast(initialset); + a.InitialState = new State(); + newstate.Add(initialset, a.InitialState); + while (worklist.Count > 0) + { + HashSet s = worklist.RemoveAndReturnFirst(); + State r = newstate[s]; + foreach (State q in s) + { + if (q.Accept) + { + r.Accept = true; + break; + } + } + for (int n = 0; n < points.Length; n++) + { + var p = new HashSet(); + foreach (State state in s) + { + foreach (Transition t in state.Transitions) + { + if (t.Min <= points[n] && points[n] <= t.Max) + { + p.Add(t.To); + } + } + } + if (!sets.ContainsKey(p)) + { + sets.Add(p, p); + worklist.AddLast(p); + newstate.Add(p, new State()); + } + State q = newstate[p]; + char min = points[n]; + char max; + if (n + 1 < points.Length) + { + max = (char) (points[n + 1] - 1); + } + else + { + max = Char.MaxValue; + } + r.Transitions.Add(new Transition(min, max, q)); + } + } + a.IsDeterministic = true; + a.RemoveDeadTransitions(); + } + + public static void AddEpsilons(Automaton a, ICollection pairs) + { + a.ExpandSingleton(); + var forward = new Dictionary>(); + var back = new Dictionary>(); + foreach (StatePair p in pairs) + { + HashSet to = forward[p.S1]; + if (to == null) + { + to = new HashSet(); + forward.Add(p.S1, to); + } + to.Add(p.S2); + HashSet from = back[p.S2]; + if (from == null) + { + from = new HashSet(); + back.Add(p.S2, from); + } + from.Add(p.S1); + } + + var worklist = new LinkedList(pairs); + var workset = new HashSet(pairs); + while (worklist.Count != 0) + { + StatePair p = worklist.RemoveAndReturnFirst(); + workset.Remove(p); + HashSet to = forward[p.S2]; + HashSet from = back[p.S1]; + if (to != null) + { + foreach (State s in to) + { + var pp = new StatePair(p.S1, s); + if (!pairs.Contains(pp)) + { + pairs.Add(pp); + forward[p.S1].Add(s); + back[s].Add(p.S1); + worklist.AddLast(pp); + workset.Add(pp); + if (from != null) + { + foreach (State q in from) + { + var qq = new StatePair(q, p.S1); + if (!workset.Contains(qq)) + { + worklist.AddLast(qq); + workset.Add(qq); + } + } + } + } + } + } + } + // Add transitions. + foreach (StatePair p in pairs) + { + p.S1.AddEpsilon(p.S2); + } + a.IsDeterministic = false; + a.ClearHashCode(); + a.CheckMinimizeAlways(); + } + + public static bool IsEmptyString(Automaton a) + { + if (a.IsSingleton) + { + return a.Singleton.Length == 0; + } + + return a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsEmpty(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + return !a.InitialState.Accept && a.InitialState.Transitions.Count == 0; + } + + public static bool IsTotal(Automaton a) + { + if (a.IsSingleton) + { + return false; + } + if (a.InitialState.Accept && a.InitialState.Transitions.Count == 1) + { + // Original code (Java): Transition t = a.initial.transitions.iterator().next(); + HashSet.Enumerator enumerator = a.InitialState.Transitions.GetEnumerator(); + enumerator.MoveNext(); + Transition t = enumerator.Current; + + return t.To == a.InitialState && t.Min == Char.MinValue && t.Max == Char.MaxValue; + } + return false; + } + + public static string GetShortestExample(Automaton a, bool accepted) + { + if (a.IsSingleton) + { + if (accepted) + { + return a.Singleton; + } + + if (a.Singleton.Length > 0) + { + return ""; + } + + return "\u0000"; + } + return GetShortestExample(a.InitialState, accepted); + } + + public static string GetShortestExample(State s, bool accepted) + { + IDictionary path = new Dictionary(); + var queue = new LinkedList(); + path.Add(s, ""); + queue.AddLast(s); + string best = null; + while (queue.Count != 0) + { + State q = queue.RemoveAndReturnFirst(); + string p = path[q]; + if (q.Accept == accepted) + { + if (best == null || p.Length < best.Length || (p.Length == best.Length && p.CompareTo(best) < 0)) + { + best = p; + } + } + else + { + foreach (Transition t in q.Transitions) + { + string tp = path[t.To]; + string np = p + t.Min; + if (tp == null || (tp.Length == np.Length && np.CompareTo(tp) < 0)) + { + if (tp == null) + { + queue.AddLast(t.To); + } + path.Add(t.To, np); + } + } + } + } + return best; + } + + public static bool Run(Automaton a, string s) + { + if (a.IsSingleton) + { + return s.Equals(a.IsSingleton); + } + if (a.IsDeterministic) + { + State p = a.InitialState; + foreach (char t in s) + { + State q = p.Step(t); + if (q == null) + { + return false; + } + p = q; + } + return p.Accept; + } + + HashSet states = a.States; + Automaton.StateNumbers = states; + var pp = new LinkedList(); + var ppOther = new LinkedList(); + var bb = new BitArray(states.Count); + var bbOther = new BitArray(states.Count); + pp.AddLast(a.InitialState); + var dest = new List(); + bool accept = a.InitialState.Accept; + + foreach (char c in s) + { + accept = false; + ppOther.Clear(); + bbOther.SetAll(false); + foreach (State p in pp) + { + dest.Clear(); + p.Step(c, dest); + foreach (State q in dest) + { + if (q.Accept) + { + accept = true; + } + if (!bbOther.Get(q.Number)) + { + bbOther.Set(q.Number, true); + ppOther.AddLast(q); + } + } + } + LinkedList tp = pp; + pp = ppOther; + ppOther = tp; + BitArray tb = bb; + bb = bbOther; + bbOther = tb; + } + return accept; + } + } +} +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`a->NAutomaton.Automaton.singleton` could be null (from the call to `Automaton.get_InitialState()` on line 607) and is dereferenced in call to `Automaton.get_InitialState()`. + +### Severity: +ERROR + +### Procedure: +Boolean BasicOperations.IsEmptyString(Automaton) + +### File: +Src/NAutomaton/BasicOperations.cs + +### Key: +BasicOperations.cs|IsEmptyString|NULLPTR_DEREFERENCE + +### Hash: +03b5e9d7c27fd1475c1c4eabd71fbf59 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0131/instruction.md b/inferredbugs-0131/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0737a91e2412eba9d2187e316af6ed18e6ee5e61 --- /dev/null +++ b/inferredbugs-0131/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Rhisis +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Rhisis.Core.Structures; +using System; +using System.IO; + +namespace Rhisis.Core.Resources +{ + /// + /// FlyFF World File structure. + /// + public class WldFile : FileStream, IDisposable + { + public WldFileInformations WorldInformations { get; private set; } + + /// + /// Creates a new instance. + /// + /// Wld file data + public WldFile(string filePath) + : base(filePath, FileMode.Open, FileAccess.Read) + { + this.Read(); + } + + /// + /// Reads the content of the Wld file. + /// + private void Read() + { + var reader = new StreamReader(this); + Vector3 size = null; + bool isIndoor = false; + bool canFly = false; + int mpu = 0; + int revivalMapId = 0; + string revivalKey = string.Empty; + + while (!reader.EndOfStream) + { + var line = reader.ReadLine().Trim().ToLower(); + + if (line.StartsWith("//") || string.IsNullOrEmpty(line)) + continue; + + string[] lineArray = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); + + switch (lineArray[0].ToLower()) + { + case "size": + size = this.ReadSize(lineArray); + break; + case "indoor": + isIndoor = lineArray[1] == "1" ? true : false; + break; + case "fly": + canFly = lineArray[1] == "1" ? true : false; + break; + case "mpu": + mpu = int.Parse(lineArray[1]); + break; + case "revival": + revivalMapId = int.Parse(lineArray[1]); + revivalKey = lineArray[2].Trim('"'); + break; + } + } + + this.WorldInformations = new WldFileInformations((int)size.X, (int)size.Z, mpu, isIndoor, canFly, revivalMapId, revivalKey); + } + + /// + /// Read the "size" field of the wld file. + /// + /// Current line array + private Vector3 ReadSize(string[] lineArray) + { + string width = lineArray[1].Replace(",", string.Empty); + string length = lineArray[2]; + + return new Vector3(int.Parse(width), 0, int.Parse(length)); + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`size` could be null (last assigned on line 30) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Void WldFile.Read() + +### File: +src/Rhisis.Core/Resources/Wld/WldFile.cs + +### Key: +WldFile.cs|Read|NULLPTR_DEREFERENCE + +### Hash: +1c02f21e9c65b381c4d00fa9db6f752e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0136/instruction.md b/inferredbugs-0136/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5f9b1876e0d4e5962a5facfcea4ae80a2acae76 --- /dev/null +++ b/inferredbugs-0136/instruction.md @@ -0,0 +1,207 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pnpframework +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SharePoint.Client; +using PnP.Core.Services; +using PnP.Framework.Utilities.PnPSdk; +using System; +using System.Threading; +using System.Runtime.CompilerServices; +using System.Collections.Concurrent; + +[assembly: InternalsVisibleTo("PnPFramework.Test")] +namespace PnP.Framework +{ + /// + /// Class that implements interop between PnP Framework and PnP Core SDK + /// + public class PnPCoreSdk + { + + private static readonly Lazy _lazyInstance = new Lazy(() => new PnPCoreSdk(), true); + private IPnPContextFactory pnpContextFactoryCache; + private ConcurrentDictionary pnpContextCached = new ConcurrentDictionary(); + private static readonly SemaphoreSlim semaphoreSlimFactory = new SemaphoreSlim(1); + internal static ILegacyAuthenticationProviderFactory AuthenticationProviderFactory { get; set; } = new PnPCoreSdkAuthenticationProviderFactory(); + internal static event EventHandler OnDIContainerBuilding; + + /// + /// Provides the singleton instance of th entity manager + /// + public static PnPCoreSdk Instance + { + get + { + return _lazyInstance.Value; + } + } + + /// + /// Private constructor since this is a singleton + /// + private PnPCoreSdk() + { + } + + /// + /// Get's a PnPContext from a CSOM ClientContext + /// + /// CSOM ClientContext + /// The equivalent PnPContext + public PnPContext GetPnPContext(ClientContext context) + { + Uri ctxUri = new Uri(context.Url); + var ctxSettings = context.GetContextSettings(); + + PnPContext cachedContext; + if (pnpContextCached.TryGetValue(ctxUri.Authority.ToLower(), out cachedContext)) + { + if (cachedContext.Uri == ctxUri) + { + return cachedContext; + } + else + { + return cachedContext.Clone(ctxUri); + } + } + else + { + var factory = BuildContextFactory(); + return factory.Create(ctxUri, AuthenticationProviderFactory.GetAuthenticationProvider(context)); + } + } + + private IPnPContextFactory BuildContextFactory() + { + try + { + // Ensure there's only one context factory building happening at any given time + semaphoreSlimFactory.Wait(); + + // Return the factory from cache if we already have one + if (pnpContextFactoryCache != null) + { + return pnpContextFactoryCache; + } + + // Build the service collection and load PnP Core SDK + IServiceCollection services = new ServiceCollection(); + + // To increase coverage of solutions providing tokens without graph scopes we turn of graphfirst for PnPContext created from PnP Framework + services = services.AddPnPCore(options => + { + options.PnPContext.GraphFirst = false; + }).Services; + + // Enables to plug in additional services into this service container + if(OnDIContainerBuilding != null) + { + OnDIContainerBuilding.Invoke(this, services); + } + + var serviceProvider = services.BuildServiceProvider(); + + // Get a PnP context factory + var pnpContextFactory = serviceProvider.GetRequiredService(); + + // Chache the factory before returning it + if (pnpContextFactoryCache == null) + { + pnpContextFactoryCache = pnpContextFactory; + } + + return pnpContextFactory; + } + finally + { + semaphoreSlimFactory.Release(); + } + + } + + /// + /// Returns a CSOM ClientContext for a given PnP Core SDK context + /// + /// The PnP Core SDK context + /// The equivalent CSOM ClientContext + public ClientContext GetClientContext(PnPContext pnpContext) + { + //shloud do only for AppOnly Context + if (!pnpContextCached.ContainsKey(pnpContext.Uri.Authority.ToLower())) + { + pnpContextCached.TryAdd(pnpContext.Uri.Authority.ToLower(),pnpContext); + } +#pragma warning disable CA2000 // Dispose objects before losing scope + AuthenticationManager authManager = AuthenticationManager.CreateWithPnPCoreSdk(pnpContext.AuthenticationProvider); +#pragma warning restore CA2000 // Dispose objects before losing scope + + var ctx = authManager.GetContext(pnpContext.Uri.ToString()); + var ctxSettings = ctx.GetContextSettings(); + ctxSettings.AuthenticationManager = authManager; //otherwise GetAccessToken would not work for example + ctx.AddContextSettings(ctxSettings); + return ctx; + } + + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ctxSettings` last assigned on line 138 could be null and is dereferenced at line 139, column 13. + +### Severity: +ERROR + +### Procedure: +ClientContext PnPCoreSdk.GetClientContext(PnPContext) + +### File: +src/lib/PnP.Framework/PnPCoreSdk.cs + +### Key: +PnPCoreSdk.cs|GetClientContext|NULL_DEREFERENCE + +### Node Key: +5f12004af86bc692e0983547f0c7b710 + +### Hash: +07e25cda3d7ee86ec286221a808c7465 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0137/instruction.md b/inferredbugs-0137/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87fa350b778b28cc643024729f5ffa8d1ad1384d --- /dev/null +++ b/inferredbugs-0137/instruction.md @@ -0,0 +1,199 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pnpframework +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SharePoint.Client; +using PnP.Core.Services; +using PnP.Framework.Utilities.PnPSdk; +using System; +using System.Threading; + +namespace PnP.Framework +{ + /// + /// Class that implements interop between PnP Framework and PnP Core SDK + /// + public class PnPCoreSdk + { + + private static readonly Lazy _lazyInstance = new Lazy(() => new PnPCoreSdk(), true); + private IPnPContextFactory pnpContextFactoryCache; + private static readonly SemaphoreSlim semaphoreSlimFactory = new SemaphoreSlim(1); + internal static ILegacyAuthenticationProviderFactory AuthenticationProviderFactory { get; set; } = new PnPCoreSdkAuthenticationProviderFactory(); + internal static event EventHandler OnDIContainerBuilding; + + /// + /// Provides the singleton instance of th entity manager + /// + public static PnPCoreSdk Instance + { + get + { + return _lazyInstance.Value; + } + } + + /// + /// Private constructor since this is a singleton + /// + private PnPCoreSdk() + { + } + + /// + /// Get's a PnPContext from a CSOM ClientContext + /// + /// CSOM ClientContext + /// The equivalent PnPContext + public PnPContext GetPnPContext(ClientContext context) + { + Uri ctxUri = new Uri(context.Url); + + var ctxSettings = context.GetContextSettings(); + + if (ctxSettings!=null && ctxSettings.Type == Utilities.Context.ClientContextType.PnPCoreSdk && ctxSettings.AuthenticationManager!=null) + { + var pnpContext = ctxSettings.AuthenticationManager.PnPCoreContext; + if (pnpContext != null) + { + return pnpContext; + } + else + { + var iAuthProvider = ctxSettings.AuthenticationManager.PnPCoreAuthenticationProvider; + if (iAuthProvider != null) + { + var factory0 = BuildContextFactory(); + return factory0.Create(ctxUri, iAuthProvider); + } + } + } + var factory = BuildContextFactory(); + return factory.Create(ctxUri, AuthenticationProviderFactory.GetAuthenticationProvider(context)); + } + + private IPnPContextFactory BuildContextFactory() + { + try + { + // Ensure there's only one context factory building happening at any given time + semaphoreSlimFactory.Wait(); + + // Return the factory from cache if we already have one + if (pnpContextFactoryCache != null) + { + return pnpContextFactoryCache; + } + + // Build the service collection and load PnP Core SDK + IServiceCollection services = new ServiceCollection(); + + // To increase coverage of solutions providing tokens without graph scopes we turn of graphfirst for PnPContext created from PnP Framework + services = services.AddPnPCore(options => + { + options.PnPContext.GraphFirst = false; + }).Services; + + // Enables to plug in additional services into this service container + if(OnDIContainerBuilding != null) + { + OnDIContainerBuilding.Invoke(this, services); + } + + var serviceProvider = services.BuildServiceProvider(); + + // Get a PnP context factory + var pnpContextFactory = serviceProvider.GetRequiredService(); + + // Chache the factory before returning it + if (pnpContextFactoryCache == null) + { + pnpContextFactoryCache = pnpContextFactory; + } + + return pnpContextFactory; + } + finally + { + semaphoreSlimFactory.Release(); + } + + } + + /// + /// Returns a CSOM ClientContext for a given PnP Core SDK context + /// + /// The PnP Core SDK context + /// The equivalent CSOM ClientContext + public ClientContext GetClientContext(PnPContext pnpContext) + { +#pragma warning disable CA2000 // Dispose objects before losing scope + AuthenticationManager authManager = AuthenticationManager.CreateWithPnPCoreSdk(pnpContext); +#pragma warning restore CA2000 // Dispose objects before losing scope + + var ctx = authManager.GetContext(pnpContext.Uri.ToString()); + var ctxSettings = ctx.GetContextSettings(); + ctxSettings.Type = Utilities.Context.ClientContextType.PnPCoreSdk; + ctxSettings.AuthenticationManager = authManager; //otherwise GetAccessToken would not work for example + ctx.AddContextSettings(ctxSettings); + return ctx; + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource authManager of type PnP.Framework.AuthenticationManager in method "ClientContext PnPCoreSdk.GetClientContext(PnPContext)". + +### Severity: +ERROR + +### Procedure: +ClientContext PnPCoreSdk.GetClientContext(PnPContext) + +### File: +src/lib/PnP.Framework/PnPCoreSdk.cs + +### Key: +PnPCoreSdk.cs|GetClientContext|DOTNET_RESOURCE_LEAK + +### Hash: +f3d511500f5cf7f282b38813b59da9d9 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0138/instruction.md b/inferredbugs-0138/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2294822f926ff54c87d6395a072e433a448147d1 --- /dev/null +++ b/inferredbugs-0138/instruction.md @@ -0,0 +1,199 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pnpframework +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SharePoint.Client; +using PnP.Core.Services; +using PnP.Framework.Utilities.PnPSdk; +using System; +using System.Threading; + +namespace PnP.Framework +{ + /// + /// Class that implements interop between PnP Framework and PnP Core SDK + /// + public class PnPCoreSdk + { + + private static readonly Lazy _lazyInstance = new Lazy(() => new PnPCoreSdk(), true); + private IPnPContextFactory pnpContextFactoryCache; + private static readonly SemaphoreSlim semaphoreSlimFactory = new SemaphoreSlim(1); + internal static ILegacyAuthenticationProviderFactory AuthenticationProviderFactory { get; set; } = new PnPCoreSdkAuthenticationProviderFactory(); + internal static event EventHandler OnDIContainerBuilding; + + /// + /// Provides the singleton instance of th entity manager + /// + public static PnPCoreSdk Instance + { + get + { + return _lazyInstance.Value; + } + } + + /// + /// Private constructor since this is a singleton + /// + private PnPCoreSdk() + { + } + + /// + /// Get's a PnPContext from a CSOM ClientContext + /// + /// CSOM ClientContext + /// The equivalent PnPContext + public PnPContext GetPnPContext(ClientContext context) + { + Uri ctxUri = new Uri(context.Url); + + var ctxSettings = context.GetContextSettings(); + + if (ctxSettings!=null && ctxSettings.Type == Utilities.Context.ClientContextType.PnPCoreSdk && ctxSettings.AuthenticationManager!=null) + { + var pnpContext = ctxSettings.AuthenticationManager.PnPCoreContext; + if (pnpContext != null) + { + return pnpContext; + } + else + { + var iAuthProvider = ctxSettings.AuthenticationManager.PnPCoreAuthenticationProvider; + if (iAuthProvider != null) + { + var factory0 = BuildContextFactory(); + return factory0.Create(ctxUri, iAuthProvider); + } + } + } + var factory = BuildContextFactory(); + return factory.Create(ctxUri, AuthenticationProviderFactory.GetAuthenticationProvider(context)); + } + + private IPnPContextFactory BuildContextFactory() + { + try + { + // Ensure there's only one context factory building happening at any given time + semaphoreSlimFactory.Wait(); + + // Return the factory from cache if we already have one + if (pnpContextFactoryCache != null) + { + return pnpContextFactoryCache; + } + + // Build the service collection and load PnP Core SDK + IServiceCollection services = new ServiceCollection(); + + // To increase coverage of solutions providing tokens without graph scopes we turn of graphfirst for PnPContext created from PnP Framework + services = services.AddPnPCore(options => + { + options.PnPContext.GraphFirst = false; + }).Services; + + // Enables to plug in additional services into this service container + if(OnDIContainerBuilding != null) + { + OnDIContainerBuilding.Invoke(this, services); + } + + var serviceProvider = services.BuildServiceProvider(); + + // Get a PnP context factory + var pnpContextFactory = serviceProvider.GetRequiredService(); + + // Chache the factory before returning it + if (pnpContextFactoryCache == null) + { + pnpContextFactoryCache = pnpContextFactory; + } + + return pnpContextFactory; + } + finally + { + semaphoreSlimFactory.Release(); + } + + } + + /// + /// Returns a CSOM ClientContext for a given PnP Core SDK context + /// + /// The PnP Core SDK context + /// The equivalent CSOM ClientContext + public ClientContext GetClientContext(PnPContext pnpContext) + { +#pragma warning disable CA2000 // Dispose objects before losing scope + AuthenticationManager authManager = AuthenticationManager.CreateWithPnPCoreSdk(pnpContext); +#pragma warning restore CA2000 // Dispose objects before losing scope + + var ctx = authManager.GetContext(pnpContext.Uri.ToString()); + var ctxSettings = ctx.GetContextSettings(); + ctxSettings.Type = Utilities.Context.ClientContextType.PnPCoreSdk; + ctxSettings.AuthenticationManager = authManager; //otherwise GetAccessToken would not work for example + ctx.AddContextSettings(ctxSettings); + return ctx; + } + + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`ctxSettings` could be null (from the call to `InternalClientContextExtensions.GetContextSettings(...)` on line 132) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +ClientContext PnPCoreSdk.GetClientContext(PnPContext) + +### File: +src/lib/PnP.Framework/PnPCoreSdk.cs + +### Key: +PnPCoreSdk.cs|GetClientContext|NULLPTR_DEREFERENCE + +### Hash: +959e9729725b08fc9a97a1f358a56ffb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0139/instruction.md b/inferredbugs-0139/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6fc915386d6396aa4a994bca831dda0c75ae7e4 --- /dev/null +++ b/inferredbugs-0139/instruction.md @@ -0,0 +1,192 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** pnpframework +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SharePoint.Client; +using PnP.Core.Services; +using PnP.Framework.Utilities.PnPSdk; +using System; +using System.Threading; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("PnPFramework.Test")] +namespace PnP.Framework +{ + /// + /// Class that implements interop between PnP Framework and PnP Core SDK + /// + public class PnPCoreSdk + { + + private static readonly Lazy _lazyInstance = new Lazy(() => new PnPCoreSdk(), true); + private IPnPContextFactory pnpContextFactoryCache; + private static readonly SemaphoreSlim semaphoreSlimFactory = new SemaphoreSlim(1); + internal static ILegacyAuthenticationProviderFactory AuthenticationProviderFactory { get; set; } = new PnPCoreSdkAuthenticationProviderFactory(); + internal static event EventHandler OnDIContainerBuilding; + + /// + /// Provides the singleton instance of th entity manager + /// + public static PnPCoreSdk Instance + { + get + { + return _lazyInstance.Value; + } + } + + /// + /// Private constructor since this is a singleton + /// + private PnPCoreSdk() + { + } + + /// + /// Get's a PnPContext from a CSOM ClientContext + /// + /// CSOM ClientContext + /// The equivalent PnPContext + public PnPContext GetPnPContext(ClientContext context) + { + Uri ctxUri = new Uri(context.Url); + var factory = BuildContextFactory(); + var ctxSettings = context.GetContextSettings(); + if(ctxSettings!=null && ctxSettings.AuthenticationManager!=null) + { + var iAuthProvider = ctxSettings.AuthenticationManager.PnPCoreAuthenticationProvider; + if(iAuthProvider!=null) + { + return factory.Create(ctxUri, iAuthProvider); + } + } + return factory.Create(ctxUri, AuthenticationProviderFactory.GetAuthenticationProvider(context)); + } + + private IPnPContextFactory BuildContextFactory() + { + try + { + // Ensure there's only one context factory building happening at any given time + semaphoreSlimFactory.Wait(); + + // Return the factory from cache if we already have one + if (pnpContextFactoryCache != null) + { + return pnpContextFactoryCache; + } + + // Build the service collection and load PnP Core SDK + IServiceCollection services = new ServiceCollection(); + + // To increase coverage of solutions providing tokens without graph scopes we turn of graphfirst for PnPContext created from PnP Framework + services = services.AddPnPCore(options => + { + options.PnPContext.GraphFirst = false; + }).Services; + + // Enables to plug in additional services into this service container + if(OnDIContainerBuilding != null) + { + OnDIContainerBuilding.Invoke(this, services); + } + + var serviceProvider = services.BuildServiceProvider(); + + // Get a PnP context factory + var pnpContextFactory = serviceProvider.GetRequiredService(); + + // Chache the factory before returning it + if (pnpContextFactoryCache == null) + { + pnpContextFactoryCache = pnpContextFactory; + } + + return pnpContextFactory; + } + finally + { + semaphoreSlimFactory.Release(); + } + + } + + /// + /// Returns a CSOM ClientContext for a given PnP Core SDK context + /// + /// The PnP Core SDK context + /// The equivalent CSOM ClientContext + public ClientContext GetClientContext(PnPContext pnpContext) + { +#pragma warning disable CA2000 // Dispose objects before losing scope + AuthenticationManager authManager = AuthenticationManager.CreateWithPnPCoreSdk(pnpContext.AuthenticationProvider); +#pragma warning restore CA2000 // Dispose objects before losing scope + + var ctx = authManager.GetContext(pnpContext.Uri.ToString()); + var ctxSettings = ctx.GetContextSettings(); + ctxSettings.AuthenticationManager = authManager; //otherwise GetAccessToken would not work for example + ctx.AddContextSettings(ctxSettings); + return ctx; + } + + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `ctxSettings` last assigned on line 123 could be null and is dereferenced at line 124, column 13. + +### Severity: +ERROR + +### Procedure: +ClientContext PnPCoreSdk.GetClientContext(PnPContext) + +### File: +src/lib/PnP.Framework/PnPCoreSdk.cs + +### Key: +PnPCoreSdk.cs|GetClientContext|NULL_DEREFERENCE + +### Node Key: +5f12004af86bc692e0983547f0c7b710 + +### Hash: +07e25cda3d7ee86ec286221a808c7465 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0152/instruction.md b/inferredbugs-0152/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b38694f01da05011293227db7aadb9d50412199d --- /dev/null +++ b/inferredbugs-0152/instruction.md @@ -0,0 +1,419 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 19 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using JetBrains.Annotations; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + public class VideoInfo: IDisposable, IVideoInfo + { + private FFMpeg _ffmpeg; + + /// + public VideoInfo(FileInfo sourceFileInfo): this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + [UsedImplicitly] + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + throw new ArgumentException($"Input file {filePath} doesn't exists."); + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + [UsedImplicitly] + public void Dispose() + { + FFmpeg.Dispose(); + } + + /// + public string FilePath { get; } + + /// + public ConversionHandler OnConversionProgress { get; set; } + + + /// + public string Extension => Path.GetExtension(FilePath); + + + /// + public TimeSpan Duration { get; internal set; } + + /// + public string AudioFormat { get; internal set; } + + + /// + public string VideoFormat { get; internal set; } + + + /// + public string Ratio { get; internal set; } + + /// + public double FrameRate { get; internal set; } + + /// + public int Height { get; internal set; } + + /// + public int Width { get; internal set; } + + /// + public double Size { get; internal set; } + + /// + public bool IsRunning => FFmpeg.IsRunning; + + + /// + [UsedImplicitly] + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath) + Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + + /// + [UsedImplicitly] + public bool ToTs(string outputPath) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB) + .SetCodec(VideoCodec.MpegTs) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToWebM(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibVpx, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToOgv(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibTheora, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToMp4(string outputPath, Speed speed = Speed.SuperFast, + string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .UseMultiThread(multithread) + .SetScale(size) + .SetVideo(VideoCodec.LibX264, 2400) + .SetSpeed(speed) + .SetAudio(AudioCodec.Aac, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ExtractVideo(string output) + { + IConversion conversion = new Conversion().SetInput(FilePath) + .StreamCopy(Channel.Both) + .DisableChannel(Channel.Audio) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + /// + [UsedImplicitly] + public bool ExtractAudio(string output) + { + IConversion conversion = new Conversion().SetInput(FilePath) + .DisableChannel(Channel.Video) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool AddAudio(FileInfo audio, string output) + { + IConversion conversion = new Conversion().SetInput(new FileInfo(FilePath), audio) + .StreamCopy(Channel.Video) + .SetAudio(AudioCodec.Aac, AudioQuality.Hd) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + string output = $"{Environment.TickCount}.png"; + + bool success = Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + + /// + [UsedImplicitly] + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + [UsedImplicitly] + public bool Snapshot(VideoInfo source, string outputPath, Size? size = null, TimeSpan? captureTime = null) + { + if(captureTime == null) + captureTime = TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3); + + size = GetSize(source, size); + + IConversion conversion = new Conversion() + .SetInput(source.FilePath) + .SetVideo(VideoCodec.Png) + .SetOutputFramesCount(1) + .SetSeek(captureTime) + .SetSize(size) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + /// + [UsedImplicitly] + public bool SaveM3U8Stream(Uri uri, string outputPath) + { + if(uri.Scheme != "http" || + uri.Scheme != "https") + throw new ArgumentException($"Invalid uri {uri.AbsolutePath}"); + + return new Conversion().SetInput(uri) + .SetOutput(outputPath) + .Start(); + } + + /// + [UsedImplicitly] + public bool JoinWith(string output, params IVideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + var pathList = new List(); + + foreach(VideoInfo video in videos) + { + string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), Extensions.Ts); + pathList.Add(tempFileName); + video.ToTs(tempFileName); + } + + IConversion conversion = new Conversion(). + Concat(pathList.ToArray()) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Audio, Filter.Aac_AdtstoAsc) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + private static Size? GetSize(VideoInfo source, Size? size) + { + if(size == null || + size.Value.Height == 0 && size.Value.Width == 0) + size = new Size(source.Width, source.Height); + + if(size.Value.Width != size.Value.Height) + { + if(size.Value.Width == 0) + { + double ratio = source.Width / (double) size.Value.Width; + + size = new Size((int) (source.Width * ratio), (int) (source.Height * ratio)); + } + + if(size.Value.Height == 0) + { + double ratio = source.Height / (double) size.Value.Height; + + size = new Size((int) (source.Width * ratio), (int) (source.Height * ratio)); + } + } + + return size; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Xabe.FFMpeg.IConversion Xabe.FFMpeg.Conversion::SetInput(System.String) at Line 200).Xabe.FFMpeg.Conversion._inputFiles.[_] of type Xabe.FFMpeg.VideoInfo in method "Boolean VideoInfo.ExtractAudio(String)". + +### Severity: +ERROR + +### Procedure: +Boolean VideoInfo.ExtractAudio(String) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ExtractAudio|DOTNET_RESOURCE_LEAK + +### Hash: +2c0a362289adc79f5120a027e89e008c + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0155/instruction.md b/inferredbugs-0155/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76b2061433eada138cdd6f21c81301cc5257f350 --- /dev/null +++ b/inferredbugs-0155/instruction.md @@ -0,0 +1,419 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 24 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using JetBrains.Annotations; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + public class VideoInfo: IDisposable, IVideoInfo + { + private FFMpeg _ffmpeg; + + /// + public VideoInfo(FileInfo sourceFileInfo): this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + [UsedImplicitly] + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + throw new ArgumentException($"Input file {filePath} doesn't exists."); + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + [UsedImplicitly] + public void Dispose() + { + FFmpeg.Dispose(); + } + + /// + public string FilePath { get; } + + /// + public ConversionHandler OnConversionProgress { get; set; } + + + /// + public string Extension => Path.GetExtension(FilePath); + + + /// + public TimeSpan Duration { get; internal set; } + + /// + public string AudioFormat { get; internal set; } + + + /// + public string VideoFormat { get; internal set; } + + + /// + public string Ratio { get; internal set; } + + /// + public double FrameRate { get; internal set; } + + /// + public int Height { get; internal set; } + + /// + public int Width { get; internal set; } + + /// + public double Size { get; internal set; } + + /// + public bool IsRunning => FFmpeg.IsRunning; + + + /// + [UsedImplicitly] + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath) + Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + + /// + [UsedImplicitly] + public bool ToTs(string outputPath) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Video, Filter.H264_Mp4ToAnnexB) + .SetCodec(VideoCodec.MpegTs) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToWebM(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibVpx, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToOgv(string outputPath, string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .SetScale(size) + .SetVideo(VideoCodec.LibTheora, 2400) + .SetSpeed(16) + .SetAudio(AudioCodec.LibVorbis, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ToMp4(string outputPath, Speed speed = Speed.SuperFast, + string size = "", AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + IConversion conversion = new Conversion() + .SetInput(FilePath) + .UseMultiThread(multithread) + .SetScale(size) + .SetVideo(VideoCodec.LibX264, 2400) + .SetSpeed(speed) + .SetAudio(AudioCodec.Aac, audioQuality) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool ExtractVideo(string output) + { + IConversion conversion = new Conversion().SetInput(FilePath) + .StreamCopy(Channel.Both) + .DisableChannel(Channel.Audio) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + /// + [UsedImplicitly] + public bool ExtractAudio(string output) + { + IConversion conversion = new Conversion().SetInput(FilePath) + .DisableChannel(Channel.Video) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public bool AddAudio(FileInfo audio, string output) + { + IConversion conversion = new Conversion().SetInput(new FileInfo(FilePath), audio) + .StreamCopy(Channel.Video) + .SetAudio(AudioCodec.Aac, AudioQuality.Hd) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + + /// + [UsedImplicitly] + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + string output = $"{Environment.TickCount}.png"; + + bool success = Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + + /// + [UsedImplicitly] + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + [UsedImplicitly] + public bool Snapshot(VideoInfo source, string outputPath, Size? size = null, TimeSpan? captureTime = null) + { + if(captureTime == null) + captureTime = TimeSpan.FromSeconds(source.Duration.TotalSeconds / 3); + + size = GetSize(source, size); + + IConversion conversion = new Conversion() + .SetInput(source.FilePath) + .SetVideo(VideoCodec.Png) + .SetOutputFramesCount(1) + .SetSeek(captureTime) + .SetSize(size) + .SetOutput(outputPath); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + /// + [UsedImplicitly] + public bool SaveM3U8Stream(Uri uri, string outputPath) + { + if(uri.Scheme != "http" || + uri.Scheme != "https") + throw new ArgumentException($"Invalid uri {uri.AbsolutePath}"); + + return new Conversion().SetInput(uri) + .SetOutput(outputPath) + .Start(); + } + + /// + [UsedImplicitly] + public bool JoinWith(string output, params IVideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + var pathList = new List(); + + foreach(VideoInfo video in videos) + { + string tempFileName = Path.ChangeExtension(Path.GetTempFileName(), Extensions.Ts); + pathList.Add(tempFileName); + video.ToTs(tempFileName); + } + + IConversion conversion = new Conversion(). + Concat(pathList.ToArray()) + .StreamCopy(Channel.Both) + .SetBitstreamFilter(Channel.Audio, Filter.Aac_AdtstoAsc) + .SetOutput(output); + + conversion.OnProgress += OnConversionProgress; + return conversion.Start(); + } + + private static Size? GetSize(VideoInfo source, Size? size) + { + if(size == null || + size.Value.Height == 0 && size.Value.Width == 0) + size = new Size(source.Width, source.Height); + + if(size.Value.Width != size.Value.Height) + { + if(size.Value.Width == 0) + { + double ratio = source.Width / (double) size.Value.Width; + + size = new Size((int) (source.Width * ratio), (int) (source.Height * ratio)); + } + + if(size.Value.Height == 0) + { + double ratio = source.Height / (double) size.Value.Height; + + size = new Size((int) (source.Width * ratio), (int) (source.Height * ratio)); + } + } + + return size; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from Xabe.FFMpeg.IConversion Xabe.FFMpeg.Conversion::SetInput(System.String) at Line 118).Xabe.FFMpeg.Conversion._inputFiles.[_] of type Xabe.FFMpeg.VideoInfo in method "Boolean VideoInfo.ToTs(String)". + +### Severity: +ERROR + +### Procedure: +Boolean VideoInfo.ToTs(String) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ToTs|DOTNET_RESOURCE_LEAK + +### Hash: +d30f04058674accc9699f12382cda9c1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0163/instruction.md b/inferredbugs-0163/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..daa12d3b8546d32001dd25b496bce44d35c60bd1 --- /dev/null +++ b/inferredbugs-0163/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Linq; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + /// Information about media file + /// + public class VideoInfo : IDisposable + { + /// + /// _sourceFile info + /// + + public readonly string FilePath; + + /// + /// Return extension of file + /// + public string Extension => Path.GetExtension(FilePath); + + private FFMpeg _ffmpeg; + + /// + /// Fires when conversion progress changed + /// + public ConversionHandler OnConversionProgress; + + /// + /// Get VideoInfo from file + /// + /// _sourceFile + public VideoInfo(FileInfo sourceFileInfo) : this(sourceFileInfo.FullName) + { + } + + /// + /// Get VideoInfo from file + /// + /// FilePath to file + public VideoInfo(string filePath) + { + if(!File.Exists(filePath)) + { + throw new ArgumentException($"Input file {filePath} doesn't exists."); + } + FilePath = filePath; + new FFProbe().ProbeDetails(this); + } + + private FFMpeg FFmpeg + { + get + { + if(_ffmpeg != null && + _ffmpeg.IsRunning) + throw new InvalidOperationException( + "Operation on this file is in progress."); + + return _ffmpeg ?? (_ffmpeg = new FFMpeg()); + } + } + + /// + /// duration of video + /// + public TimeSpan Duration { get; internal set; } + + /// + /// Audio format + /// + public string AudioFormat { get; internal set; } + + /// + /// Video format + /// + public string VideoFormat { get; internal set; } + + /// + /// Screen ratio + /// + public string Ratio { get; internal set; } + + /// + /// Frame rate + /// + public double FrameRate { get; internal set; } + + /// + /// Height + /// + public int Height { get; internal set; } + + /// + /// Width + /// + public int Width { get; internal set; } + + /// + /// size + /// + public double Size { get; internal set; } + + /// + /// Get the ffmpeg process status + /// + public bool IsRunning => FFmpeg.IsRunning; + + /// + /// Create VideoInfo from file + /// + /// _sourceFile + /// VideoInfo + public static VideoInfo FromFile(FileInfo fileInfo) + { + return new VideoInfo(fileInfo); + } + + /// + /// Get formated info about video + /// + /// Formated info about vidoe + public override string ToString() + { + return "Video FilePath : " + FilePath + Environment.NewLine + + "Video Root : " + Path.GetDirectoryName(FilePath)+ Environment.NewLine + + "Video Name: " + Path.GetFileName(FilePath) + Environment.NewLine + + "Video Extension : " + Extension + Environment.NewLine + + "Video duration : " + Duration + Environment.NewLine + + "Audio format : " + AudioFormat + Environment.NewLine + + "Video format : " + VideoFormat + Environment.NewLine + + "Aspect Ratio : " + Ratio + Environment.NewLine + + "Framerate : " + FrameRate + "fps" + Environment.NewLine + + "Resolution : " + Width + "x" + Height + Environment.NewLine + + "Size : " + Size + " MB"; + } + + /// + /// Convert file to TS + /// + /// Destination file + /// Output VideoInfo + public VideoInfo ToTs(string outputPath) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToTs(this, outputPath); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to WebM + /// + /// Destination file + /// Dimension + /// Audio quality + /// Output VideoInfo + public VideoInfo ToWebM(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToWebM(this, outputPath, size, audioQuality); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to OGV + /// + /// Destination file + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToOgv(string outputPath, VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToOgv(this, outputPath, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Convert file to MP4 + /// + /// Destination file + /// Conversion speed + /// Dimension + /// Audio quality + /// Use multithread + /// Output VideoInfo + public VideoInfo ToMp4(string outputPath, Speed speed = Speed.SuperFast, + VideoSize size = VideoSize.Original, AudioQuality audioQuality = AudioQuality.Normal, bool multithread = false) + { + FFmpeg.OnProgress += OnConversionProgress; + var success = FFmpeg.ToMp4(this, outputPath, speed, size, audioQuality, multithread); + if (!success) + throw new OperationCanceledException("The conversion process could not be completed."); + FFmpeg.OnProgress -= OnConversionProgress; + return new VideoInfo(outputPath); + } + + /// + /// Extract video from file + /// + /// Output audio stream + /// Conversion result + public bool ExtractVideo(string output) + { + return FFmpeg.ExtractVideo(this, output); + } + + /// + /// Extract audio from file + /// + /// Output video stream + /// Conversion result + public bool ExtractAudio(string output) + { + return FFmpeg.ExtractAudio(this, output); + } + + /// + /// Add audio to file + /// + /// Audio file + /// Output file + /// Conversion result + public bool AddAudio(FileInfo audio, string output) + { + return FFmpeg.AddAudio(this, audio, output); + } + + /// + /// Get snapshot of video + /// + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(Size? size = null, TimeSpan? captureTime = null) + { + var output = $"{Environment.TickCount}.png"; + + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + using(Image bmp = Image.FromFile(output)) + { + using(var ms = new MemoryStream()) + { + bmp.Save(ms, ImageFormat.Png); + + result = new Bitmap(ms); + } + } + + if(File.Exists(output)) + File.Delete(output); + + return result; + } + + /// + /// Saves snapshot of video + /// + /// Output file + /// Dimension of snapshot + /// + /// Snapshot + public Bitmap Snapshot(string output, Size? size = null, TimeSpan? captureTime = null) + { + bool success = FFmpeg.Snapshot(this, output, size, captureTime); + + if(!success) + throw new OperationCanceledException("Could not take snapshot!"); + + Bitmap result; + + + using(Image bmp = Image.FromFile(System.IO.Path.ChangeExtension(output, ".png"))) + { + result = (Bitmap) bmp.Clone(); + } + + return result; + } + + /// + /// Concat multiple videos + /// + /// Concatenated videos + /// Videos to add + /// Conversion result + public bool JoinWith(string output, params VideoInfo[] videos) + { + List queuedVideos = videos.ToList(); + + queuedVideos.Insert(0, this); + + return FFmpeg.Join(output, queuedVideos.ToArray()); + } + + /// + public void Dispose() + { + FFmpeg.Stop(); + _ffmpeg?.Dispose(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Xabe.FFMpeg.VideoInfo, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 154) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 151) of type Xabe.FFMpeg.FFMpeg, Leaked resource (returned from Xabe.FFMpeg.FFMpeg Xabe.FFMpeg.VideoInfo::get_FFmpeg() at Line 150) of type Xabe.FFMpeg.FFMpeg in method "VideoInfo VideoInfo.ToTs(String)". + +### Severity: +ERROR + +### Procedure: +VideoInfo VideoInfo.ToTs(String) + +### File: +Xabe.FFMpeg/VideoInfo.cs + +### Key: +VideoInfo.cs|ToTs|DOTNET_RESOURCE_LEAK + +### Hash: +35a500da90cfddc1cf82912270f016de + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0164/instruction.md b/inferredbugs-0164/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3c0fc422d4645c3bb11b10071bd14d80d29da92 --- /dev/null +++ b/inferredbugs-0164/instruction.md @@ -0,0 +1,397 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Xabe.FFmpeg +**Bug ID:** 14 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Text; +using Xabe.FFMpeg.Enums; + +namespace Xabe.FFMpeg +{ + /// + public class Conversion: IConversion + { + private string _audio; + private string _audioSpeed; + private string _bitsreamFilter; + private string _codec; + private string _copy; + private string _disabled; + private string _frameCount; + private string _input; + private string _loop; + private string _output; + private string _outputPath; + private string _reverse; + private string _scale; + private string _seek; + private string _shortestInput; + private string _size; + private string _speed; + private string _threads; + private string _video; + private string _videoSpeed; + + /// + public string Build() + { + var builder = new StringBuilder(); + builder.Append(_input); + builder.Append(_scale); + builder.Append(_video); + builder.Append(_speed); + builder.Append(_audio); + builder.Append(_threads); + builder.Append(_disabled); + builder.Append(_size); + builder.Append(_codec); + builder.Append(_bitsreamFilter); + builder.Append(_copy); + builder.Append(_seek); + builder.Append(_frameCount); + builder.Append(_loop); + builder.Append(_reverse); + builder.Append(_shortestInput); + builder.Append(BuildVideoFilter()); + builder.Append(BuildAudioFilter()); + builder.Append(_output); + + return builder.ToString(); + } + + /// + public bool Start() + { + return new FFMpeg().StartConversion(Build(), _outputPath); + } + + /// + public IConversion SetSpeed(Speed speed) + { + _speed = $"-preset {speed.ToString() .ToLower()} "; + return this; + } + + /// + public IConversion SetSpeed(int cpu) + { + _speed = $"-quality good -cpu-used {cpu} -deadline realtime "; + return this; + } + + /// + public IConversion SetAudio(AudioCodec codec, AudioQuality bitrate) + { + return SetAudio(codec.ToString(), bitrate); + } + + /// + public IConversion SetAudio(string codec, AudioQuality bitrate) + { + _audio = $"-codec:a {codec.ToLower()} -b:a {(int) bitrate}k -strict experimental "; + return this; + } + + /// + public IConversion SetVideo(VideoCodec codec, int bitrate = 0) + { + return SetVideo(codec.ToString(), bitrate); + } + + /// + public IConversion SetVideo(string codec, int bitrate = 0) + { + _video = $"-codec:v {codec.ToLower()} "; + + if(bitrate > 0) + _video += $"-b:v {bitrate}k "; + return this; + } + + /// + public IConversion UseMultiThread(bool multiThread) + { + string threadCount = multiThread + ? Environment.ProcessorCount.ToString() + : "1"; + + _threads = $"-threads {threadCount} "; + return this; + } + + /// + public IConversion SetInput(Uri uri) + { + _input = $"-i \"{uri.AbsoluteUri}\" "; + return this; + } + + /// + public IConversion DisableChannel(Channel type) + { + switch(type) + { + case Channel.Video: + _disabled = "-vn "; + break; + case Channel.Audio: + _disabled = "-an "; + break; + } + return this; + } + + /// + public IConversion SetInput(VideoInfo input) + { + _input = $"-i \"{input.FilePath}\" "; + return this; + } + + /// + public IConversion SetInput(params FileInfo[] inputs) + { + _input = ""; + foreach(FileInfo file in inputs) + _input += $"-i \"{file.FullName}\" "; + return this; + } + + /// + public IConversion SetOutput(string outputPath) + { + _outputPath = outputPath; + _output = $"\"{outputPath}\""; + return this; + } + + /// + public IConversion SetScale(VideoSize size) + { + return SetScale(size.Resolution); + } + + /// + public IConversion SetScale(string size) + { + if(!string.IsNullOrWhiteSpace(size)) + _scale = $"-vf scale={size} "; + return this; + } + + /// + public IConversion SetSize(Size? size) + { + if(size.HasValue) + _size = $"-s {size.Value.Width}x{size.Value.Height} "; + + return this; + } + + /// + public IConversion SetCodec(VideoCodec codec) + { + return SetCodec(codec.ToString()); + } + + /// + public IConversion SetCodec(string codec) + { + _codec = $"-f {codec.ToLower()} "; + return this; + } + + /// + public IConversion SetBitstreamFilter(Channel type, Filter filter) + { + return SetBitstreamFilter(type, filter.ToString()); + } + + /// + public IConversion SetBitstreamFilter(Channel type, string filter) + { + switch(type) + { + case Channel.Audio: + _bitsreamFilter = $"-bsf:a {filter.ToLower()} "; + break; + case Channel.Video: + _bitsreamFilter = $"-bsf:v {filter.ToLower()} "; + break; + } + return this; + } + + /// + public IConversion StreamCopy(Channel type) + { + switch(type) + { + case Channel.Audio: + _copy = "-c:a copy "; + break; + case Channel.Video: + _copy = "-c:v copy "; + break; + default: + _copy = "-c copy "; + break; + } + return this; + } + + /// + public IConversion ChangeVideoSpeed(double multiplication) + { + _videoSpeed = $"setpts={string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:N1}", multiplication)}*PTS "; + return this; + } + + /// + public IConversion ChangeAudioSpeed(double multiplication) + { + _audioSpeed = $"atempo={string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:N1}", multiplication)} "; + return this; + } + + /// + public IConversion Reverse(Channel type) + { + switch(type) + { + case Channel.Audio: + _reverse = "-af areverse "; + break; + case Channel.Video: + _reverse = "-vf reverse "; + break; + case Channel.Both: + _reverse = "-vf reverse -af areverse "; + break; + } + return this; + } + + /// + public IConversion SetSeek(TimeSpan? seek) + { + if(seek.HasValue) + _seek = $"-ss {seek} "; + + return this; + } + + /// + public IConversion SetOutputFramesCount(int number) + { + _frameCount = $"-frames:v {number} "; + return this; + } + + /// + public IConversion SetLoop(int count) + { + _loop = $"-loop {count} "; + return this; + } + + /// + public IConversion UseShortest(bool useShortest) + { + if(!useShortest) + return this; + _shortestInput = "-shortest "; + return this; + } + + /// + public IConversion Concat(params string[] paths) + { + _input = $"-i \"concat:{string.Join(@"|", paths)}\" "; + return this; + } + + private string BuildVideoFilter() + { + var builder = new StringBuilder(); + builder.Append("-filter:v "); + builder.Append(_videoSpeed); + + string filter = builder.ToString(); + if(filter == "-filter:v ") + return ""; + return filter; + } + + private string BuildAudioFilter() + { + var builder = new StringBuilder(); + builder.Append("-filter:a "); + builder.Append(_audioSpeed); + + string filter = builder.ToString(); + if(filter == "-filter:a ") + return ""; + return filter; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Xabe.FFMpeg.FFMpeg::.ctor() at Line 65) of type Xabe.FFMpeg.FFMpeg in method "Boolean Conversion.Start()". + +### Severity: +ERROR + +### Procedure: +Boolean Conversion.Start() + +### File: +Xabe.FFMpeg/Conversion.cs + +### Key: +Conversion.cs|Start|DOTNET_RESOURCE_LEAK + +### Hash: +9d04ec60243a4420128edc18131feae3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0190/instruction.md b/inferredbugs-0190/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a3d712da399005d4e1a48ce3c021cf71d266988 --- /dev/null +++ b/inferredbugs-0190/instruction.md @@ -0,0 +1,86 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** NEventStore +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +namespace EventStore.Serialization.Json +{ + using System.IO; + using Newtonsoft.Json; + + public class JsonSerializer : ISerialize + { + private readonly Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer + { + TypeNameHandling = TypeNameHandling.Auto + }; + + public void Serialize(Stream output, object graph) + { + var streamWriter = new StreamWriter(output); + var jsonWriter = new JsonTextWriter(streamWriter); + this.serializer.Serialize(jsonWriter, graph); + jsonWriter.Flush(); + streamWriter.Flush(); + } + public object Deserialize(Stream input) + { + using (var streamReader = new StreamReader(input)) + using (var jsonReader = new JsonTextReader(streamReader)) + return this.serializer.Deserialize(jsonReader); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource streamWriter of type System.IO.StreamWriter in method "Void JsonSerializer.Serialize(Stream,Object)". + +### Severity: +ERROR + +### Procedure: +Void JsonSerializer.Serialize(Stream,Object) + +### File: +src/proj/EventStore.Serialization.Json/JsonSerializer.cs + +### Key: +JsonSerializer.cs|Serialize|DOTNET_RESOURCE_LEAK + +### Hash: +144c09e8e6bc68e527dd79f9ee56af05 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0197/instruction.md b/inferredbugs-0197/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63b48d86a1286cfbc7ea7ec9dfb198dd86d1bd3d --- /dev/null +++ b/inferredbugs-0197/instruction.md @@ -0,0 +1,392 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cowboy +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Cowboy.Buffer; +using Cowboy.Logging; + +namespace Cowboy.Sockets +{ + public class TcpSocketSaeaServer + { + #region Fields + + private static readonly ILog _log = Logger.Get(); + private IBufferManager _bufferManager; + private readonly ConcurrentDictionary _sessions = new ConcurrentDictionary(); + private readonly TcpSocketSaeaServerConfiguration _configuration; + + private Socket _listener; + private SaeaPool _sessionAcceptSaeaPool; + private SaeaPool _sessionHandleSaeaPool; + + private int _state; + private const int _none = 0; + private const int _listening = 1; + private const int _disposed = 5; + + #endregion + + #region Constructors + + public TcpSocketSaeaServer(int listenedPort, TcpSocketSaeaServerConfiguration configuration = null) + : this(IPAddress.Any, listenedPort, configuration) + { + } + + public TcpSocketSaeaServer(IPAddress listenedAddress, int listenedPort, TcpSocketSaeaServerConfiguration configuration = null) + : this(new IPEndPoint(listenedAddress, listenedPort), configuration) + { + } + + public TcpSocketSaeaServer(IPEndPoint listenedEndPoint, TcpSocketSaeaServerConfiguration configuration = null) + { + if (listenedEndPoint == null) + throw new ArgumentNullException("listenedEndPoint"); + + this.ListenedEndPoint = listenedEndPoint; + _configuration = configuration ?? new TcpSocketSaeaServerConfiguration(); + + if (_configuration.FrameBuilder == null) + throw new InvalidProgramException("The frame handler in configuration cannot be null."); + + Initialize(); + } + + private void Initialize() + { + _bufferManager = new GrowingByteBufferManager(_configuration.InitialBufferAllocationCount, _configuration.ReceiveBufferSize); + + //_sessionAcceptSaeaPool = new SaeaPool(); + //_sessionHandleSaeaPool = new SaeaPool(); + //for (int i = 0; i < 10; i++) + //{ + // _sessionAcceptSaeaPool.Push(CreateSaeaForSessionAccept()); + //} + //for (int i = 0; i < 100; i++) + //{ + // _sessionHandleSaeaPool.Push(CreateSaeaForSessionHandle()); + //} + } + + #endregion + + #region Properties + + public IPEndPoint ListenedEndPoint { get; private set; } + public bool Active { get { return _state == _listening; } } + //public int SessionCount { get { return _sessions.Count; } } + + #endregion + + public void Start() + { + int origin = Interlocked.CompareExchange(ref _state, _listening, _none); + if (origin == _disposed) + { + throw new ObjectDisposedException(GetType().FullName); + } + else if (origin != _none) + { + throw new InvalidOperationException("This tcp server has already started."); + } + + try + { + _listener = new Socket(this.ListenedEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + _listener.Bind(this.ListenedEndPoint); + + ConfigureListener(); + + _listener.Listen(_configuration.PendingConnectionBacklog); + + StartAccept(); + } + catch (Exception ex) when (!ShouldThrow(ex)) { } + } + + public void Stop() + { + if (Interlocked.Exchange(ref _state, _disposed) == _disposed) + { + return; + } + + try + { + _listener.Dispose(); + + //foreach (var session in _sessions.Values) + //{ + // await session.Close(); + //} + } + catch (Exception ex) when (!ShouldThrow(ex)) { } + finally + { + _listener = null; + } + } + + private void ConfigureListener() + { + AllowNatTraversal(_configuration.AllowNatTraversal); + } + + private void AllowNatTraversal(bool allowed) + { + if (allowed) + { + _listener.SetIPProtectionLevel(IPProtectionLevel.Unrestricted); + } + else + { + _listener.SetIPProtectionLevel(IPProtectionLevel.EdgeRestricted); + } + } + + private bool ShouldThrow(Exception ex) + { + if (ex is ObjectDisposedException + || ex is InvalidOperationException + || ex is SocketException + || ex is IOException) + { + return false; + } + return true; + } + + private SocketAsyncEventArgs CreateSaeaForSessionAccept() + { + var saea = new SocketAsyncEventArgs(); + + saea.Completed += OnSessionAcceptSaeaCompleted; + + return saea; + } + + private void OnSessionAcceptSaeaCompleted(object sender, SocketAsyncEventArgs e) + { + ProcessAccept(e); + } + + private void StartAccept() + { + SocketAsyncEventArgs sessionAcceptSaea = null; + if (!_sessionAcceptSaeaPool.TryPop(out sessionAcceptSaea)) + { + _log.ErrorFormat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + throw new Exception(); + } + + bool isIoOperationPending = _listener.AcceptAsync(sessionAcceptSaea); + if (!isIoOperationPending) + { + ProcessAccept(sessionAcceptSaea); + } + } + + private void ProcessAccept(SocketAsyncEventArgs saea) + { + StartAccept(); + + if (saea.SocketError != SocketError.Success) + { + _log.ErrorFormat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + + saea.AcceptSocket.Close(); + saea.AcceptSocket = null; + _sessionAcceptSaeaPool.Push(saea); + return; + } + + SocketAsyncEventArgs sessionHandleSaea = null; + if (!_sessionHandleSaeaPool.TryPop(out sessionHandleSaea)) + { + _log.ErrorFormat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + throw new Exception(); + } + + sessionHandleSaea.AcceptSocket = saea.AcceptSocket; + saea.AcceptSocket = null; + _sessionAcceptSaeaPool.Push(saea); + + StartReceive(sessionHandleSaea); + } + + private SocketAsyncEventArgs CreateSaeaForSessionHandle() + { + var saea = new SocketAsyncEventArgs(); + + saea.Completed += OnSessionHandleSaeaCompleted; + + return saea; + } + + private void OnSessionHandleSaeaCompleted(object sender, SocketAsyncEventArgs e) + { + switch (e.LastOperation) + { + case SocketAsyncOperation.Receive: + ProcessReceive(e); + break; + case SocketAsyncOperation.Send: + ProcessSend(e); + break; + default: + throw new InvalidOperationException( + string.Format("The last operation [{0}] completed on the socket was not a receive or send.", e.LastOperation)); + } + } + + private void StartReceive(SocketAsyncEventArgs saea) + { + var buffer = _bufferManager.BorrowBuffer(); + saea.SetBuffer(buffer, 0, buffer.Length); + + bool isIoOperationPending = saea.AcceptSocket.ReceiveAsync(saea); + if (!isIoOperationPending) + { + ProcessReceive(saea); + } + } + + private void ProcessReceive(SocketAsyncEventArgs saea) + { + if (saea.SocketError != SocketError.Success) + { + _log.ErrorFormat("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); + + CloseSession(saea); + return; + } + + var receiveCount = saea.BytesTransferred; + if (receiveCount == 0) + { + CloseSession(saea); + return; + } + + var buffer = new byte[99999]; + Array.Copy(saea.Buffer, 0, buffer, 0, receiveCount); + + StartReceive(saea); + } + + private void StartSend(SocketAsyncEventArgs saea) + { + bool isIoOperationPending = saea.AcceptSocket.SendAsync(saea); + if (!isIoOperationPending) + { + ProcessSend(saea); + } + } + + private void ProcessSend(SocketAsyncEventArgs saea) + { + if (saea.SocketError == SocketError.Success) + { + //receiveSendToken.sendBytesRemainingCount = receiveSendToken.sendBytesRemainingCount - saea.BytesTransferred; + + //if (receiveSendToken.sendBytesRemainingCount == 0) + //{ + // StartReceive(saea); + //} + //else + //{ + // receiveSendToken.bytesSentAlreadyCount += saea.BytesTransferred; + // StartSend(saea); + //} + } + else + { + CloseSession(saea); + } + } + + private void CloseSession(SocketAsyncEventArgs saea) + { + try + { + saea.AcceptSocket.Shutdown(SocketShutdown.Both); + } + catch { } + + try + { + saea.AcceptSocket.Dispose(); + } + catch { } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `sessionHandleSaea` last assigned on line 210 could be null and is dereferenced at line 217, column 13. + +### Severity: +ERROR + +### Procedure: +Void TcpSocketSaeaServer.ProcessAccept(SocketAsyncEventArgs) + +### File: +Cowboy.Sockets/TcpSocketSaeaServer.cs + +### Key: +TcpSocketSaeaServer.cs|ProcessAccept|NULL_DEREFERENCE + +### Node Key: +fed63043a57b15ee86a51c8f4210d5cd + +### Hash: +6996eeb511e0a078d8699693a2979dec + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0199/instruction.md b/inferredbugs-0199/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..936226d48bbe1942a13ef7575ae9fb779ef7d39d --- /dev/null +++ b/inferredbugs-0199/instruction.md @@ -0,0 +1,321 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Cowboy +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Security.Principal; +using System.Threading; +using System.Threading.Tasks; +using Cowboy.Utilities; + +namespace Cowboy.Hosting.Self +{ + public class SelfHost + { + private IList _baseUriList; + private HttpListener _listener; + private bool _keepGoing = false; + private Engine _engine; + private SemaphoreSlim _counter = new SemaphoreSlim(8, 8); + + public SelfHost(Engine engine, params Uri[] baseUris) + { + if (engine == null) + throw new ArgumentNullException("engine"); + + _engine = engine; + _baseUriList = baseUris; + } + + public void Start() + { + StartListener(); + + _keepGoing = true; + Task.Run(async () => + { + await StartProcess(); + }) + .Forget(); + } + + public void Stop() + { + _keepGoing = false; + if (_listener != null && _listener.IsListening) + { + _listener.Stop(); + } + } + + private async Task StartProcess() + { + while (_keepGoing) + { + await _counter.WaitAsync(); + + var context = await _listener.GetContextAsync(); + Task.Run(async () => + { + try + { + await Process(context); + } + catch (Exception) + { + throw; + } + }) + .Forget(); + } + } + + private async Task Process(HttpListenerContext httpContext) + { + var cancellationToken = new CancellationToken(); + var request = ConvertRequest(httpContext.Request); + var context = await _engine.HandleRequest(request, cancellationToken); + ConvertResponse(context.Response, httpContext.Response); + _counter.Release(); + } + + private void StartListener() + { + if (TryStartListener()) + { + return; + } + + if (!TryAddUrlReservations()) + { + throw new InvalidOperationException("Unable to configure namespace reservation."); + } + + if (!TryStartListener()) + { + throw new InvalidOperationException("Unable to start listener."); + } + } + + private bool TryStartListener() + { + try + { + // if the listener fails to start, it gets disposed; + // so we need a new one, each time. + _listener = new HttpListener(); + foreach (var prefix in GetPrefixes()) + { + _listener.Prefixes.Add(prefix); + } + + _listener.Start(); + + return true; + } + catch (HttpListenerException e) + { + int ACCESS_DENIED = 5; + if (e.ErrorCode == ACCESS_DENIED) + { + return false; + } + + throw; + } + } + + private bool TryAddUrlReservations() + { + var user = WindowsIdentity.GetCurrent().Name; + + foreach (var prefix in GetPrefixes()) + { + if (!NetSh.AddUrlAcl(prefix, user)) + { + return false; + } + } + + return true; + } + + private IEnumerable GetPrefixes() + { + foreach (var baseUri in _baseUriList) + { + var prefix = new UriBuilder(baseUri).ToString(); + + bool rewriteLocalhost = true; + if (rewriteLocalhost && !baseUri.Host.Contains(".")) + { + prefix = prefix.Replace("localhost", "+"); + } + + yield return prefix; + } + } + + private Uri GetBaseUri(HttpListenerRequest request) + { + var result = _baseUriList.FirstOrDefault(uri => uri.IsCaseInsensitiveBaseOf(request.Url)); + + if (result != null) + { + return result; + } + + return new Uri(request.Url.GetLeftPart(UriPartial.Authority)); + } + + private Request ConvertRequest(HttpListenerRequest httpRequest) + { + var baseUri = GetBaseUri(httpRequest); + + if (baseUri == null) + { + throw new InvalidOperationException(string.Format("Unable to locate base URI for request: {0}", httpRequest.Url)); + } + + var expectedRequestLength = GetExpectedRequestLength(httpRequest.Headers.ToDictionary()); + + var relativeUrl = baseUri.MakeAppLocalPath(httpRequest.Url); + + var url = new Url + { + Scheme = httpRequest.Url.Scheme, + HostName = httpRequest.Url.Host, + Port = httpRequest.Url.IsDefaultPort ? null : (int?)httpRequest.Url.Port, + BasePath = baseUri.AbsolutePath.TrimEnd('/'), + Path = HttpUtility.UrlDecode(relativeUrl), + Query = httpRequest.Url.Query, + }; + + // NOTE: For HTTP/2 we want fieldCount = 1, + // otherwise (HTTP/1.0 and HTTP/1.1) we want fieldCount = 2 + var fieldCount = httpRequest.ProtocolVersion.Major == 2 ? 1 : 2; + + var protocolVersion = string.Format("HTTP/{0}", httpRequest.ProtocolVersion.ToString(fieldCount)); + + return new Request( + httpRequest.HttpMethod, + url, + RequestStream.FromStream(httpRequest.InputStream, expectedRequestLength, false), + httpRequest.Headers.ToDictionary(), + (httpRequest.RemoteEndPoint != null) ? httpRequest.RemoteEndPoint.Address.ToString() : null, + protocolVersion); + } + + private void ConvertResponse(Response response, HttpListenerResponse httpResponse) + { + foreach (var header in response.Headers) + { + if (!IgnoredHeaders.IsIgnored(header.Key)) + { + httpResponse.AddHeader(header.Key, header.Value); + } + } + + if (response.ReasonPhrase != null) + { + httpResponse.StatusDescription = response.ReasonPhrase; + } + + if (response.ContentType != null) + { + httpResponse.ContentType = response.ContentType; + } + + httpResponse.StatusCode = (int)response.StatusCode; + + using (var output = httpResponse.OutputStream) + { + response.Contents.Invoke(output); + } + } + + private static long GetExpectedRequestLength(IDictionary> incomingHeaders) + { + if (incomingHeaders == null) + { + return 0; + } + + if (!incomingHeaders.ContainsKey("Content-Length")) + { + return 0; + } + + var headerValue = incomingHeaders["Content-Length"].SingleOrDefault(); + + if (headerValue == null) + { + return 0; + } + + long contentLength; + + return !long.TryParse(headerValue, NumberStyles.Any, CultureInfo.InvariantCulture, out contentLength) ? + 0 : contentLength; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type Cowboy.Request, Leaked resource (returned from Cowboy.RequestStream Cowboy.RequestStream::FromStream(System.IO.Stream,System.Int64,System.Boolean) at Line 200) of type Cowboy.RequestStream in method "Request SelfHost.ConvertRequest(HttpListenerRequest)". + +### Severity: +ERROR + +### Procedure: +Request SelfHost.ConvertRequest(HttpListenerRequest) + +### File: +Cowboy.Hosting.Self/SelfHost.cs + +### Key: +SelfHost.cs|ConvertRequest|DOTNET_RESOURCE_LEAK + +### Hash: +9c6cfc2f7159d3381e8436416911b70d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0248/instruction.md b/inferredbugs-0248/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a53fda1f94a9e0ff72032ef1f1b48ea8f4b5b23a --- /dev/null +++ b/inferredbugs-0248/instruction.md @@ -0,0 +1,266 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** DryIoc +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using NUnit.Framework; + +namespace DryIoc.UnitTests +{ + [TestFixture] + public class CompositePatternTests + { + [Test] + public void I_should_be_able_to_resolve_composite_of_enumerable_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle)); + container.Register(typeof(IShape), typeof(Square)); + container.Register(typeof(IShape), typeof(PolygonOfEnumerable), serviceKey: "composite"); + + var composite = (PolygonOfEnumerable)container.Resolve("composite"); + + Assert.AreEqual(2, composite.Shapes.Count()); + } + + [Test] + public void I_should_be_able_to_resolve_enumerable_of_funcs_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle)); + container.Register(typeof(IShape), typeof(Square)); + container.Register(typeof(IShape), typeof(PolygonOfEnumerable)); + + var shapes = container.Resolve>>(); + + Assert.AreEqual(3, shapes.Count()); + } + + [Test] + public void I_should_be_able_to_resolve_composite_of_array_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle)); + container.Register(typeof(IShape), typeof(Square)); + container.Register(typeof(IShape), typeof(PolygonOfArray), serviceKey: "composite"); + + var composite = (PolygonOfArray)container.Resolve("composite"); + + Assert.AreEqual(2, composite.Shapes.Count()); + } + + [Test] + public void I_should_be_able_to_resolve_default_composite_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle), serviceKey: "circle"); + container.Register(typeof(IShape), typeof(Square), serviceKey: "square"); + container.Register(typeof(IShape), typeof(PolygonOfArray)); + + var composite = (PolygonOfArray)container.Resolve(); + + Assert.AreEqual(2, composite.Shapes.Count()); + } + + [Test] + public void I_should_be_able_to_resolve_composite_as_item_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle)); + container.Register(typeof(IShape), typeof(Square)); + container.Register(typeof(IShape), typeof(PolygonOfEnumerable)); + + var shapes = container.Resolve(); + + Assert.AreEqual(3, shapes.Count()); + } + + [Test] + public void I_should_be_able_to_resolve_composite_of_many_as_item_without_exception() + { + var container = new Container(); + container.Register(typeof(IShape), typeof(Circle)); + container.Register(typeof(IShape), typeof(Square)); + container.Register(typeof(IShape), typeof(PolygonOfMany), serviceKey: "composite"); + + var polygon = (PolygonOfMany)container.Resolve("composite"); + Assert.AreEqual(2, polygon.Shapes.Count()); + + var shapes = container.Resolve>().Items; + Assert.AreEqual(3, shapes.Count()); + } + + [Test] + public void No_recursion_with_required_type() + { + var container = new Container(); + container.Register(serviceKey: nameof(OperationOne)); + container.Register(serviceKey: nameof(OperationTwo)); + + container.RegisterMany( + new[] {typeof(IOperation), typeof(IAction)}, + typeof(CompositeOpertaion)); + container.Register(made: Parameters.Of.Type(typeof(IOperation))); + + var service = container.Resolve(); + Assert.IsNotNull(service); + Assert.IsInstanceOf(service.Action); + } + + [Test] + public void No_recursion_with_required_type_in_lazy_enumerable() + { + var container = new Container(rules => rules.WithResolveIEnumerableAsLazyEnumerable()); + container.Register(serviceKey: nameof(OperationOne)); + container.Register(serviceKey: nameof(OperationTwo)); + + container.RegisterMany( + new[] { typeof(IOperation), typeof(IAction) }, + typeof(CompositeOpertaion)); + container.Register(made: Parameters.Of.Type(typeof(IOperation))); + + var service = container.Resolve(); + Assert.IsNotNull(service); + Assert.IsInstanceOf(service.Action); + } + + public interface IAction + { + } + + public interface IOperation : IAction + { + } + + public class OperationOne : IOperation + { + } + + public class OperationTwo : IOperation + { + } + + public class CompositeOpertaion : IOperation + { + public readonly IEnumerable Operations; + + public CompositeOpertaion(IEnumerable operations) + { + Operations = operations.ToArray(); + } + } + + public class Service + { + public readonly IAction Action; + + public Service(IAction action) + { + Action = action; + } + } + + #region Composite pattern CUT + + public interface IShape + { + } + + public class Circle : IShape + { + } + + public class Square : IShape + { + } + + public class PolygonOfEnumerable : IShape + { + public IEnumerable Shapes { get; set; } + + public PolygonOfEnumerable(IEnumerable shapes) + { + Shapes = shapes; + } + } + + public class PolygonOfMany : IShape + { + public IEnumerable Shapes { get; set; } + + public PolygonOfMany(LazyEnumerable shapes) + { + Shapes = shapes; + } + } + + public class PolygonOfArray : IShape + { + public IShape[] Shapes { get; set; } + + public PolygonOfArray(IShape[] shapes) + { + Shapes = shapes; + } + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource container of type DryIoc.Container in method "Void CompositePatternTests.No_recursion_with_required_type()". + +### Severity: +ERROR + +### Procedure: +Void CompositePatternTests.No_recursion_with_required_type() + +### File: +DryIoc.UnitTests/CompositePatternTests.cs + +### Key: +CompositePatternTests.cs|No_recursion_with_required_type|DOTNET_RESOURCE_LEAK + +### Hash: +761410cb8d46a90871cafe9b6a3ce774 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0277/instruction.md b/inferredbugs-0277/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84b078d5619db35c8744299ebd64c9d47df80aa2 --- /dev/null +++ b/inferredbugs-0277/instruction.md @@ -0,0 +1,112 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Hyperion +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; + +namespace Wire.ValueSerializers +{ + public class ConsistentArraySerializer : ValueSerializer + { + public static readonly ConsistentArraySerializer Instance = new ConsistentArraySerializer(); + private readonly byte[] _manifest = {254}; + + public override object ReadValue(Stream stream, SerializerSession session) + { + var elementSerializer = session.Serializer.GetSerializerByManifest(stream, session); + //read the element type + var elementType = elementSerializer.GetElementType(); + //get the element type serializer + var length = (int) Int32Serializer.Instance.ReadValue(stream, session); //read the array length + var array = Array.CreateInstance(elementType, length); //create the array + for (var i = 0; i < length; i++) + { + var value = elementSerializer.ReadValue(stream, session); //read the element value + array.SetValue(value, i); //set the element value + } + return array; + } + + public override Type GetElementType() + { + throw new NotSupportedException(); + } + + public override void WriteManifest(Stream stream, Type type, SerializerSession session) + { + stream.Write(_manifest, 0, _manifest.Length); + } + + public override void WriteValue(Stream stream, object value, SerializerSession session) + { + var array = value as Array; + var elementType = value.GetType().GetElementType(); + var elementSerializer = session.Serializer.GetSerializerByType(elementType); + elementSerializer.WriteManifest(stream, elementType, session); //write array element type + Int32Serializer.Instance.WriteValue(stream, array.Length, session); //write array length + for (var i = 0; i < array.Length; i++) //write the elements + { + var elementValue = array.GetValue(i); + elementSerializer.WriteValue(stream, elementValue, session); + } + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `array` last assigned on line 39 could be null and is dereferenced at line 43, column 13. + +### Severity: +ERROR + +### Procedure: +Void ConsistentArraySerializer.WriteValue(Stream,Object,SerializerSession) + +### File: +Wire/ValueSerializers/ConsistentArraySerializer.cs + +### Key: +ConsistentArraySerializer.cs|WriteValue|NULL_DEREFERENCE + +### Node Key: +96dedd6dddaca32a2416e33dabbf5226 + +### Hash: +3f863455d4d6057f56abc3fc496730f7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0283/instruction.md b/inferredbugs-0283/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..777b7e770c2b118f5909d2377573fa34a4327387 --- /dev/null +++ b/inferredbugs-0283/instruction.md @@ -0,0 +1,517 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** dlr +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* **************************************************************************** + * + * Copyright (c) Microsoft Corporation. + * + * This source code is subject to terms and conditions of the Apache License, Version 2.0. A + * copy of the license can be found in the License.html file at the root of this distribution. If + * you cannot locate the Apache License, Version 2.0, please send an email to + * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound + * by the terms of the Apache License, Version 2.0. + * + * You must not remove this notice, or any other, from this software. + * + * + * ***************************************************************************/ +using System; +using System.Diagnostics; +using System.Diagnostics.Contracts; +using System.Security; +using System.Text; + +namespace Microsoft.Scripting.Metadata { + /// + /// Zero terminated, UTF8 encoded sequence of bytes representing a name in metadata (a type name, a member name, etc). + /// The name is bound to the module it was retrieved from. The module is kept alive until all its metadata names are collected. + /// Doesn't cache hashcode, byte or character count. + /// + public unsafe struct MetadataName : IEquatable, IEquatable { + internal readonly byte* m_data; + internal readonly object m_keepAlive; + + public static readonly MetadataName Empty = default(MetadataName); + + internal MetadataName(byte* data, object keepAlive) { + m_data = data; + m_keepAlive = keepAlive; + } + + public bool IsEmpty { + get { + bool result = m_data == null || *m_data == 0; + GC.KeepAlive(m_keepAlive); + return result; + } + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override bool Equals(object obj) { + return obj is MetadataName && Equals((MetadataName)obj) + || obj is MetadataNamePart && Equals((MetadataNamePart)obj); + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public bool Equals(MetadataName other) { + bool result = Equals(m_data, other.m_data); + GC.KeepAlive(m_keepAlive); + GC.KeepAlive(other.m_keepAlive); + return result; + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public bool Equals(MetadataNamePart other) { + return other.Equals(this); + } + + public static bool operator ==(MetadataName self, MetadataNamePart other) { + return self.Equals(other); + } + + public static bool operator ==(MetadataName self, MetadataName other) { + return self.Equals(other); + } + + public static bool operator !=(MetadataName self, MetadataNamePart other) { + return self.Equals(other); + } + + public static bool operator !=(MetadataName self, MetadataName other) { + return self.Equals(other); + } + + // safe + public bool Equals(byte[] bytes, int start, int count) { + if (bytes == null) { + throw new ArgumentNullException(nameof(bytes)); + } + if (start < 0) { + throw new ArgumentOutOfRangeException(nameof(start)); + } + if (count < 0 || count > bytes.Length - start) { + throw new ArgumentOutOfRangeException(nameof(count)); + } + + bool result; + fixed (byte* ptr = &bytes[start]) { + result = Equals(m_data, ptr, count); + } + GC.KeepAlive(m_keepAlive); + return result; + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override string ToString() { + if (m_data == null) { + return string.Empty; + } + + int byteCount = GetLength(); + int charCount = Encoding.UTF8.GetCharCount(m_data, byteCount, null); +#if CCI + string result = new string('\0', charCount); +#else + string result = String.FastAllocateString(charCount); +#endif + fixed (char* ptr = result) { + Encoding.UTF8.GetChars(m_data, byteCount, ptr, charCount, null); + } + GC.KeepAlive(m_keepAlive); + return result; + } + + // safe + internal string ToString(int byteCount) { + if (m_data == null) { + Contract.Assert(byteCount == 0); + return string.Empty; + } + + // TODO: use FastAllocateString (if we know character length we can optimize): + string result = new string((sbyte*)m_data, 0, byteCount, Encoding.UTF8); + GC.KeepAlive(m_keepAlive); + return result; + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override int GetHashCode() { + int result = GetByteHashCode(m_data); + GC.KeepAlive(m_keepAlive); + return result; + } + + // safe + internal int GetHashCode(int start, int count) { + int result = GetByteHashCode((m_data != null) ? m_data + start : null, count); + GC.KeepAlive(m_keepAlive); + return result; + } + + // safe + public int GetLength() { + int result = GetLength(m_data); + GC.KeepAlive(m_keepAlive); + return result; + } + + public MetadataNamePart GetExtent() { + return new MetadataNamePart(this, GetLength()); + } + + // safe + internal MetadataName GetSuffix(int start) { + return (m_data != null) ? new MetadataName(m_data + start, m_keepAlive) : Empty; + } + + // safe + internal int IndexOf(byte b) { + int result = IndexOf(m_data, b); + GC.KeepAlive(m_keepAlive); + return result; + } + + // safe + internal int IndexOf(byte b, int start, int count) { + int result = IndexOf(m_data, b, start, count); + GC.KeepAlive(m_keepAlive); + return result; + } + + // safe + internal int LastIndexOf(byte b, int start, int count) { + if (m_data == null) return -1; + byte* ptr = FindPrevious(m_data + start, m_data + start - count + 1, b); + GC.KeepAlive(m_keepAlive); + return ptr != null ? (int)(ptr - m_data) : -1; + } + + internal static int GetLength(byte* bytes) { + if (bytes == null) { + return 0; + } + byte* ptr = bytes; + while (*ptr != 0) { + ptr++; + } + return (int)(ptr - bytes); + } + + internal static int IndexOf(byte* bytes, byte b) { + if (bytes == null) { + return -1; + } + byte* ptr = bytes; + while (*ptr != 0 && *ptr != b) { + ptr++; + } + if (*ptr == 0) { + return -1; + } + return (int)(ptr - bytes); + } + + internal static int IndexOf(byte* bytes, byte b, int start, int count) { + if (bytes == null) { + return -1; + } + + // TODO: return Buffer.IndexOfByte(m_data, b, start, count); + byte* ptr = bytes + start; + byte* endPtr = bytes + start + count; + while (ptr < endPtr) { + if (*ptr == b) { + return (int)(ptr - bytes); + } + ptr++; + } + return -1; + } + + internal static byte* FindPrevious(byte* start, byte* last, byte b) { + Contract.Assert(start != null && last != null); + byte* ptr = start - 1; + while (true) { + if (ptr < last) { + return null; + } + if (*ptr == b) { + return ptr; + } + ptr--; + } + } + + internal static int GetByteHashCode(byte* bytes) { + int hash1 = 5381; + int hash2 = hash1; + + if (bytes != null) { + int c; + byte* s = bytes; + while ((c = s[0]) != 0) { + hash1 = ((hash1 << 5) + hash1) ^ c; + c = s[1]; + if (c == 0) { + break; + } + hash2 = ((hash2 << 5) + hash2) ^ c; + s += 2; + } + } + return hash1 + (hash2 * 1566083941); + } + + internal static int GetByteHashCode(byte* bytes, int count) { + Contract.Assert(bytes != null || count == 0); + + int hash1 = 5381; + int hash2 = hash1; + + if (bytes != null) { + byte* last = bytes + count - 1; + byte* s = bytes; + while (s < last) { + hash1 = ((hash1 << 5) + hash1) ^ (int)s[0]; + hash2 = ((hash2 << 5) + hash2) ^ (int)s[1]; + s += 2; + } + if (s < bytes + count) { + hash1 = ((hash1 << 5) + hash1) ^ (int)s[0]; + } + } + return hash1 + (hash2 * 1566083941); + } + + internal static bool Equals(byte* p, byte* q) { + if (p == q) { + return true; + } + if (p == null) { + return *q == 0; + } + if (q == null) { + return *p == 0; + } + + while (true) { + if (*p != *q) { + return false; + } + if (*p == 0) { + return true; + } + p++; + q++; + } + } + + internal static bool Equals(byte* p, byte* q, int qCount) { + if (p == null) { + return qCount == 0; + } + + byte* e = q + qCount; + while (true) { + if (*p == 0) { + return q == e; + } + if (q == e || *p != *q) { + return false; + } + p++; + q++; + } + } + + internal static bool Equals(byte* p, int pCount, byte* q, int qCount) { + if (pCount != qCount) { + return false; + } + if (p == q || pCount == 0) { + return true; + } + + byte* e = p + pCount; + while (p < e) { + if (*p != *q) { + return false; + } + p++; + q++; + } + return true; + } + } + + public struct MetadataNamePart : IEquatable, IEquatable { + private readonly MetadataName m_name; + private readonly int m_byteCount; + + public static readonly MetadataNamePart Empty = default(MetadataNamePart); + + internal MetadataNamePart(MetadataName name, int byteCount) { + m_name = name; + m_byteCount = byteCount; + } + + public int Length { + get { return m_byteCount; } + } + + public int IndexOf(byte b) { + return m_name.IndexOf(b, 0, m_byteCount); + } + + public int IndexOf(byte b, int start, int count) { + if (start < 0) { + throw new ArgumentOutOfRangeException(nameof(start)); + } + if (count < 0 || count > Length - start) { + throw new ArgumentOutOfRangeException(nameof(count)); + } + return m_name.IndexOf(b, start, count); + } + + public int LastIndexOf(byte b, int start, int count) { + if (start < 0 || start > Length) { + throw new ArgumentOutOfRangeException(nameof(start)); + } + if (count < 0 || start < count - 1) { + throw new ArgumentOutOfRangeException(nameof(count)); + } + return m_name.LastIndexOf(b, start, count); + } + + public unsafe MetadataNamePart GetPart(int start) { + if (start < 0 || start > Length) { + throw new ArgumentOutOfRangeException(nameof(start)); + } + return new MetadataNamePart(m_name.GetSuffix(start), m_byteCount - start); + } + + public unsafe MetadataNamePart GetPart(int start, int count) { + if (start < 0) { + throw new ArgumentOutOfRangeException(nameof(start)); + } + if (count < 0 || count > Length - start) { + throw new ArgumentOutOfRangeException(nameof(count)); + } + return new MetadataNamePart(m_name.GetSuffix(start), count); + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override string ToString() { + return m_name.ToString(m_byteCount); + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override int GetHashCode() { + return m_name.GetHashCode(0, m_byteCount); + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public override bool Equals(object obj) { + return obj is MetadataNamePart && Equals((MetadataNamePart)obj) + || obj is MetadataName && Equals((MetadataName)obj); + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public unsafe bool Equals(MetadataNamePart other) { + bool result = MetadataName.Equals(m_name.m_data, m_byteCount, other.m_name.m_data, other.m_byteCount); + GC.KeepAlive(m_name.m_keepAlive); + GC.KeepAlive(other.m_name.m_keepAlive); + return result; + } + + // SECURITY: The method is actually not safe. We must make sure that this object is not leaked to partially-trusted code. + [SecuritySafeCritical] + public unsafe bool Equals(MetadataName other) { + bool result = MetadataName.Equals(other.m_data, m_name.m_data, m_byteCount); + GC.KeepAlive(m_name.m_keepAlive); + GC.KeepAlive(other.m_keepAlive); + return result; + } + + public static bool operator ==(MetadataNamePart self, MetadataNamePart other) { + return self.Equals(other); + } + + public static bool operator ==(MetadataNamePart self, MetadataName other) { + return self.Equals(other); + } + + public static bool operator !=(MetadataNamePart self, MetadataNamePart other) { + return self.Equals(other); + } + + public static bool operator !=(MetadataNamePart self, MetadataName other) { + return self.Equals(other); + } + } +} + +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`this.Microsoft.Scripting.Metadata.MetadataName.m_data` is read without initialization during the call to `MetadataName.GetHashCode(...)`. + +### Severity: +ERROR + +### Procedure: +Int32 MetadataNamePart.GetHashCode() + +### File: +Src/Microsoft.Scripting.Metadata/MetadataName.cs + +### Key: +MetadataName.cs|GetHashCode|PULSE_UNINITIALIZED_VALUE + +### Hash: +d3ee861574acce8fc38cd4ec533f0016 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0302/instruction.md b/inferredbugs-0302/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3672b45a8c280f81ec68f5eaae213b083f67a1b5 --- /dev/null +++ b/inferredbugs-0302/instruction.md @@ -0,0 +1,212 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 11 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq; +using Xunit; + +namespace Kiota.Builder.Refiners.Tests { + public class RubyLanguageRefinerTests { + + private readonly CodeNamespace graphNS; + private readonly CodeClass parentClass; + private readonly CodeNamespace root = CodeNamespace.InitRootNamespace(); + public RubyLanguageRefinerTests() { + root = CodeNamespace.InitRootNamespace(); + graphNS = root.AddNamespace("graph"); + parentClass = new (graphNS) { + Name = "parentClass" + }; + graphNS.AddClass(parentClass); + } + #region CommonLanguageRefinerTests + [Fact] + public void AddsDefaultImports() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var requestBuilder = root.AddClass(new CodeClass(root) { + Name = "rb", + ClassKind = CodeClassKind.RequestBuilder, + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.NotEmpty(model.StartBlock.Usings); + Assert.NotEmpty(requestBuilder.StartBlock.Usings); + } + [Fact] + public void ReplacesImportsSubNamespace() { + var rootNS = parentClass.Parent as CodeNamespace; + rootNS.RemoveChildElement(parentClass); + graphNS.AddClass(parentClass); + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace($"{graphNS.Name}.messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsParentNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = root.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsSameNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var messageClassDef = new CodeClass(graphNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./message", declaration.Usings.First().Declaration.Name); + } + #endregion + #region RubyLanguageRefinerTests + [Fact] + public void EscapesReservedKeywords() { + var model = root.AddClass(new CodeClass (root) { + Name = "break", + ClassKind = CodeClassKind.Model + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.NotEqual("break", model.Name); + Assert.Contains("escaped", model.Name); + } + [Fact] + public void AddInheritedAndMethodTypesImports() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var declaration = model.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (parentClass){ + Name = "someInterface" + }; + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("./someInterface", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void FixInheritedEntityType() { + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + var entity = graphNS.AddClass(new CodeClass (root) { + Name = "entity", + ClassKind = CodeClassKind.Model + }).First(); + var declaration = model.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (entity){ + Name = "entity" + }; + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("Graph::Entity", declaration.Inherits.Name); + } + [Fact] + public void AddNamespaceModuleImports() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.Ruby }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + Assert.Equal("./graph", declaration.Usings.Last().Declaration.Name); + } + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 38 could be null and is dereferenced at line 43, column 13. + +### Severity: +ERROR + +### Procedure: +Void RubyLanguageRefinerTests.ReplacesImportsSubNamespace() + +### File: +tests/Kiota.Builder.Tests/Refiners/RubyLanguageRefinerTests.cs + +### Key: +RubyLanguageRefinerTests.cs|ReplacesImportsSubNamespace|NULL_DEREFERENCE + +### Node Key: +ef91c4941a914fb0bf4a21cb3664ec51 + +### Hash: +5a69b29aff4eade5c735a2550a474e91 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0303/instruction.md b/inferredbugs-0303/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c37a56885eeb6e3916207fc488832246cb723393 --- /dev/null +++ b/inferredbugs-0303/instruction.md @@ -0,0 +1,238 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq; +using Xunit; + +namespace Kiota.Builder.Refiners.Tests { + public class TypeScriptLanguageRefinerTests { + private readonly CodeNamespace root; + private readonly CodeNamespace graphNS; + private readonly CodeClass parentClass; + public TypeScriptLanguageRefinerTests() { + root = CodeNamespace.InitRootNamespace(); + graphNS = root.AddNamespace("graph"); + parentClass = new (graphNS) { + Name = "parentClass" + }; + graphNS.AddClass(parentClass); + } +#region common + [Fact] + public void ReplacesImportsSubNamespace() { + var rootNS = parentClass.Parent as CodeNamespace; + rootNS.RemoveChildElement(parentClass); + graphNS.AddClass(parentClass); + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = graphNS.AddNamespace($"{graphNS.Name}.messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("./messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsParentNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var subNS = root.AddNamespace("messages"); + var messageClassDef = new CodeClass(subNS) { + Name = "Message", + }; + subNS.AddClass(messageClassDef); + declaration.Usings.Add(new (parentClass) { + Name = "messages", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("../messages/message", declaration.Usings.First().Declaration.Name); + } + [Fact] + public void ReplacesImportsSameNamespace() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + var messageClassDef = new CodeClass(graphNS) { + Name = "Message", + }; + declaration.Usings.Add(new (parentClass) { + Name = "graph", + Declaration = new(parentClass) { + Name = "Message", + TypeDefinition = messageClassDef, + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.Equal("./message", declaration.Usings.First().Declaration.Name); + } +#endregion +#region typescript + private const string HttpCoreDefaultName = "IHttpCore"; + private const string FactoryDefaultName = "ISerializationWriterFactory"; + private const string DeserializeDefaultName = "IDictionary>"; + private const string DateTimeOffsetDefaultName = "DateTimeOffset"; + private const string AddiationalDataDefaultName = "new Dictionary()"; + private const string HandlerDefaultName = "IResponseHandler"; + [Fact] + public void EscapesReservedKeywords() { + var model = root.AddClass(new CodeClass (root) { + Name = "break", + ClassKind = CodeClassKind.Model + }).First(); + ILanguageRefiner.Refine(new GenerationConfiguration { Language = GenerationLanguage.TypeScript }, root); + Assert.NotEqual("break", model.Name); + Assert.Contains("escaped", model.Name); + } + [Fact] + public void CorrectsCoreType() { + + var model = root.AddClass(new CodeClass (root) { + Name = "model", + ClassKind = CodeClassKind.Model + }).First(); + model.AddProperty(new (model) { + Name = "core", + PropertyKind = CodePropertyKind.HttpCore, + Type = new CodeType(model) { + Name = HttpCoreDefaultName + } + }, new (model) { + Name = "someDate", + PropertyKind = CodePropertyKind.Custom, + Type = new CodeType(model) { + Name = DateTimeOffsetDefaultName, + } + }, new (model) { + Name = "additionalData", + PropertyKind = CodePropertyKind.AdditionalData, + Type = new CodeType(model) { + Name = AddiationalDataDefaultName + } + }); + var executorMethod = model.AddMethod(new CodeMethod(model) { + Name = "executor", + MethodKind = CodeMethodKind.RequestExecutor, + ReturnType = new CodeType(model) { + Name = "string" + } + }).First(); + executorMethod.AddParameter(new CodeParameter(executorMethod) { + Name = "handler", + ParameterKind = CodeParameterKind.ResponseHandler, + Type = new CodeType(executorMethod) { + Name = HandlerDefaultName, + } + }); + const string serializerDefaultName = "ISerializationWriter"; + var serializationMethod = model.AddMethod(new CodeMethod(model) { + Name = "seriailization", + MethodKind = CodeMethodKind.Serializer, + ReturnType = new CodeType(model) { + Name = "string" + } + }).First(); + serializationMethod.AddParameter(new CodeParameter(serializationMethod) { + Name = "handler", + ParameterKind = CodeParameterKind.Serializer, + Type = new CodeType(executorMethod) { + Name = serializerDefaultName, + } + }); + var responseHandlerMethod = model.AddMethod(new CodeMethod(model) { + Name = "defaultResponseHandler", + ReturnType = new CodeType(model) { + Name = "string" + } + }, new (model) { + Name = "deserializeFields", + ReturnType = new CodeType(model) { + Name = DeserializeDefaultName, + }, + MethodKind = CodeMethodKind.Deserializer + }).First(); + const string streamDefaultName = "Stream"; + responseHandlerMethod.AddParameter(new CodeParameter(responseHandlerMethod) { + Name = "param1", + Type = new CodeType(responseHandlerMethod) { + Name = streamDefaultName + } + }); + ILanguageRefiner.Refine(new GenerationConfiguration{ Language = GenerationLanguage.TypeScript }, root); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => HttpCoreDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => FactoryDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => DateTimeOffsetDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => AddiationalDataDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().Where(x => DeserializeDefaultName.Equals(x.ReturnType.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => HandlerDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => serializerDefaultName.Equals(x.Type.Name))); + Assert.Empty(model.GetChildElements(true).OfType().SelectMany(x => x.Parameters).Where(x => streamDefaultName.Equals(x.Type.Name))); + } + } +#endregion +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 23 could be null and is dereferenced at line 28, column 13. + +### Severity: +ERROR + +### Procedure: +Void TypeScriptLanguageRefinerTests.ReplacesImportsSubNamespace() + +### File: +tests/Kiota.Builder.Tests/Refiners/TypeScriptLanguageRefinerTests.cs + +### Key: +TypeScriptLanguageRefinerTests.cs|ReplacesImportsSubNamespace|NULL_DEREFERENCE + +### Node Key: +ef91c4941a914fb0bf4a21cb3664ec51 + +### Hash: +c388e163c631c1b3af917b6048067d2c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0304/instruction.md b/inferredbugs-0304/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..15e95972d44a90b8862ecfb8ab5cea8324e100be --- /dev/null +++ b/inferredbugs-0304/instruction.md @@ -0,0 +1,134 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 29 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using Xunit; + +namespace Kiota.Builder.Writers.Go.Tests { + public class CodeClassDeclarationWriterTests : IDisposable + { + private const string DefaultPath = "./"; + private const string DefaultName = "name"; + private readonly StringWriter tw; + private readonly LanguageWriter writer; + private readonly CodeClassDeclarationWriter codeElementWriter; + private readonly CodeClass parentClass; + private readonly CodeNamespace root; + + public CodeClassDeclarationWriterTests() { + codeElementWriter = new CodeClassDeclarationWriter(new GoConventionService()); + writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.Go, DefaultPath, DefaultName); + tw = new StringWriter(); + writer.SetTextWriter(tw); + root = CodeNamespace.InitRootNamespace(); + parentClass = new () { + Name = "parentClass" + }; + root.AddClass(parentClass); + } + public void Dispose() { + tw?.Dispose(); + GC.SuppressFinalize(this); + } + [Fact] + public void WritesSimpleDeclaration() { + codeElementWriter.WriteCodeElement(parentClass.StartBlock as CodeClass.Declaration, writer); + var result = tw.ToString(); + Assert.Contains("type", result); + Assert.Contains("struct", result); + Assert.Contains("package", result); + } + [Fact] + public void WritesInheritance() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.Inherits = new (){ + Name = "someParent" + }; + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("SomeParent", result); + } + [Fact] + public void WritesImports() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.AddUsings(new () { + Name = "Objects", + Declaration = new() { + Name = "Go.util", + IsExternal = true, + } + }, + new () { + Name = "project.graph", + Declaration = new() { + Name = "Message", + } + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("import (", result); + Assert.Contains("ib040b76fd8c2f056725723d35361c053f34e28d2ff1828ce830f3e00e807a59b \"project/graph\"", result); + Assert.Contains("i5bda920e7ace9d5445a4ab998b248741f78d1219c76fbec57ddf13651f485ee4 \"Go.util\"", result); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 41 could be null and is dereferenced at line 42, column 13. + +### Severity: +ERROR + +### Procedure: +Void CodeClassDeclarationWriterTests.WritesInheritance() + +### File: +tests/Kiota.Builder.Tests/Writers/Go/CodeClassDeclarationWriterTests.cs + +### Key: +CodeClassDeclarationWriterTests.cs|WritesInheritance|NULL_DEREFERENCE + +### Node Key: +7048a1dafced0623f612932e96eeeeb0 + +### Hash: +d4828fa53f2f4ab6d7f637132377396c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0305/instruction.md b/inferredbugs-0305/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb97f4bfa422a70416047b0f40f57121101695f6 --- /dev/null +++ b/inferredbugs-0305/instruction.md @@ -0,0 +1,136 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kiota +**Bug ID:** 16 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using Xunit; + +namespace Kiota.Builder.Writers.TypeScript.Tests { + public class CodeClassDeclarationWriterTests : IDisposable + { + private const string DefaultPath = "./"; + private const string DefaultName = "name"; + private readonly StringWriter tw; + private readonly LanguageWriter writer; + private readonly CodeClassDeclarationWriter codeElementWriter; + private readonly CodeClass parentClass; + + public CodeClassDeclarationWriterTests() { + writer = LanguageWriter.GetLanguageWriter(GenerationLanguage.TypeScript, DefaultPath, DefaultName); + codeElementWriter = new CodeClassDeclarationWriter(new TypeScriptConventionService(writer), "graphtests"); + tw = new StringWriter(); + writer.SetTextWriter(tw); + var root = CodeNamespace.InitRootNamespace(); + var ns = root.AddNamespace("graphtests.models"); + parentClass = new () { + Name = "parentClass" + }; + ns.AddClass(parentClass); + } + public void Dispose() { + tw?.Dispose(); + GC.SuppressFinalize(this); + } + [Fact] + public void WritesSimpleDeclaration() { + codeElementWriter.WriteCodeElement(parentClass.StartBlock as CodeClass.Declaration, writer); + var result = tw.ToString(); + Assert.Contains("export class", result); + } + [Fact] + public void WritesImplementation() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.AddImplements(new CodeType { + Name = "someInterface" + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("implements", result); + } + [Fact] + public void WritesInheritance() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.Inherits = new () { + Name = "someInterface" + }; + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("extends", result); + } + [Fact] + public void WritesImports() { + var declaration = parentClass.StartBlock as CodeClass.Declaration; + declaration.AddUsings(new CodeUsing { + Name = "Objects", + Declaration = new () { + Name = "util", + IsExternal = true, + } + }); + codeElementWriter.WriteCodeElement(declaration, writer); + var result = tw.ToString(); + Assert.Contains("import", result); + Assert.Contains("from", result); + Assert.Contains("'util'", result); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `declaration` last assigned on line 39 could be null and is dereferenced at line 40, column 13. + +### Severity: +ERROR + +### Procedure: +Void CodeClassDeclarationWriterTests.WritesImplementation() + +### File: +tests/Kiota.Builder.Tests/Writers/TypeScript/CodeClassDeclarationWriterTests.cs + +### Key: +CodeClassDeclarationWriterTests.cs|WritesImplementation|NULL_DEREFERENCE + +### Node Key: +9ff6f66912dc2a3a36e0c52dc18cdd65 + +### Hash: +20b53f0b500a6194dfb0213cd135f282 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0332/instruction.md b/inferredbugs-0332/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8e86ffe3c1ab7adaa9a4e49ca05fa978e001d18 --- /dev/null +++ b/inferredbugs-0332/instruction.md @@ -0,0 +1,321 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sentakki +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Linq; +using osu.Framework.Allocation; +using osu.Framework.Bindables; +using osu.Framework.Graphics; +using osu.Framework.Graphics.Containers; +using osu.Framework.Graphics.Pooling; +using osu.Framework.Graphics.Sprites; +using osu.Framework.Graphics.Textures; +using osu.Game.Rulesets.Objects; +using osu.Game.Rulesets.Objects.Types; +using osu.Game.Rulesets.Sentakki.Configuration; + +namespace osu.Game.Rulesets.Sentakki.Objects.Drawables.Pieces +{ + public class SlideVisual : CompositeDrawable + { + // This will be proxied, so a must. + public override bool RemoveWhenNotAlive => false; + + private int completedSegments; + public int CompletedSegments + { + get => completedSegments; + set + { + completedSegments = value; + updateProgress(completedSegments); + } + } + private SliderPath path; + + public SliderPath Path + { + get => path; + set + { + if (path == value) + return; + path = value; + updateVisuals(); + updateProgress(CompletedSegments); + } + } + + private Container segments; + private DrawablePool segmentPool; + private DrawablePool chevronPool; + + private readonly BindableBool snakingIn = new BindableBool(true); + + public int SegmentCount => segments.Count; + + public SlideVisual() + { + Anchor = Anchor.Centre; + Origin = Anchor.Centre; + } + + [BackgroundDependencyLoader(true)] + private void load(SentakkiRulesetConfigManager sentakkiConfig) + { + sentakkiConfig?.BindWith(SentakkiRulesetSettings.SnakingSlideBody, snakingIn); + + AddRangeInternal(new Drawable[]{ + segmentPool = new DrawablePool(20), + chevronPool = new DrawablePool(61), + segments = new Container(), + }); + } + + private const int chevrons_per_eith = 8; + private const double ring_radius = 297; + private const double chevrons_per_distance = (chevrons_per_eith * 8) / (2 * Math.PI * ring_radius); + private const double distance_per_chevron = 1 / chevrons_per_distance; + private const double endpoint_distance = /*r*/34; + + public static int ChevronsInPath(SliderPath path) + { + var (array, count) = splitIntoContinuousPaths(path); + var chevrons = array.Take(count).Sum(p => chevronsInContinuousPath(p)); + ArrayPool.Shared.Return(array); + return chevrons; + } + + /// A rented array which needs to be returned to + private static (SliderPath[] array, int count) splitIntoContinuousPaths(SliderPath path) + { + // first node will not split + var count = path.ControlPoints.Skip(1).Count(c => c.Type.Value == PathType.Linear) + 1; + var paths = ArrayPool.Shared.Rent(count); + int pathIndex = 0; + for (int i = 0; i < count; i++) if(paths[i] is null) paths[i] = new SliderPath(); + paths[0].ControlPoints.Clear(); + paths[0].ControlPoints.Add(path.ControlPoints[0]); + for (int i = 1; i < path.ControlPoints.Count; i++) + { + var controlPoint = path.ControlPoints[i]; + paths[pathIndex].ControlPoints.Add(controlPoint); + if (controlPoint.Type.Value == PathType.Linear) + { + // TODO test the angle here as continuous -> linear can still be smooth + pathIndex++; + paths[pathIndex].ControlPoints.Clear(); + paths[pathIndex].ControlPoints.Add(controlPoint); + } + } + return (paths, count); + } + + private static int chevronsInContinuousPath(SliderPath path) + { + return (int)Math.Ceiling((path.Distance - (2 * endpoint_distance)) * chevrons_per_distance); + } + + private void updateVisuals() + { + foreach (var segment in segments) + segment.ClearChevrons(); + segments.Clear(false); + + var reverseSegments = new List(); + void visualizePath(SliderPath path) + { + var chevronCount = chevronsInContinuousPath(path); + var totalDistance = path.Distance; + var safeDistance = totalDistance - (endpoint_distance * 2); + var distancePerChevron = safeDistance / chevronCount; + + SlideSegment currentSegment = segmentPool.Get(); + reverseSegments.Add(currentSegment); + + float lastAngle = path.PositionAt(0).GetDegreesFromPosition(path.PositionAt(0.1 / totalDistance)); + var previousPosition = path.PositionAt(0); + for (int i = 0; i < chevronCount; i++) + { + var progress = (double)i / ( chevronCount - 1 ); // from 0 to 1, both inclusive + + var position = path.PositionAt(((progress * safeDistance) + endpoint_distance) / totalDistance); + var angle = previousPosition.GetDegreesFromPosition(position); + + currentSegment.Add(chevronPool.Get().With(c => { + c.Position = position; + c.Rotation = angle; + c.ShouldHide = false; + c.Alpha = 1; + c.Depth = i; // earlier ones should remain on top + })); + + // add next segment if not last ( last segment has up to 5 chevrons while all other 3 ) + if ( i % 3 == 2 && chevronCount - 3 > i ) + { + currentSegment = segmentPool.Get(); + reverseSegments.Add(currentSegment); + } + + lastAngle = angle; + previousPosition = position; + } + } + + var (paths, count) = splitIntoContinuousPaths(path); + for (int i = 0; i < count; i++) visualizePath(paths[i]); + ArrayPool.Shared.Return(paths); + + segments.AddRange( reverseSegments.Reverse() ); + } + + private void updateProgress(int completedNodes) + { + for (int i = 1; i <= segments.Count; ++i) + { + segments[^i].Alpha = i <= completedNodes ? 0 : 1; + } + } + + public void PerformEntryAnimation(double duration) + { + if (snakingIn.Value) + { + int chevrons = (int)Math.Ceiling(Path.Distance / distance_per_chevron); + double fadeDuration = duration / chevrons; + double currentOffset = duration / 2; + for (int i = segments.Count - 1; i >= 0; i--) + { + var segment = segments[i]; + for (int j = segment.Children.Count - 1; j >= 0; j--) + { + var chevron = segment.Children[j] as SlideChevron; + if (!chevron.ShouldHide) + chevron.FadeOut().Delay(currentOffset).FadeInFromZero(fadeDuration * 2); + currentOffset += fadeDuration / 2; + } + } + } + else + { + this.FadeOut().Delay(duration / 2).FadeIn(duration / 2); + } + } + + public void PerformExitAnimation(double duration) + { + int chevronsLeft = (int)Math.Ceiling(Path.Distance / distance_per_chevron); + double fadeDuration() => duration / chevronsLeft; + double currentOffset = 0; + for (int i = segments.Count - 1; i >= 0; i--) + { + var segment = segments[i]; + if (segment.Alpha == 0) + { + chevronsLeft -= segment.ChevronCount; + continue; + } + + for (int j = segment.Children.Count - 1; j >= 0; j--) + { + var chevron = segment.Children[j] as SlideChevron; + if (!chevron.ShouldHide) + chevron.Delay(currentOffset).FadeOut(fadeDuration() * 2); + currentOffset += fadeDuration() / 2; + } + } + } + + private class SlideSegment : PoolableDrawable + { + public void ClearChevrons() => ClearInternal(false); + public void Add(Drawable drawable) => AddInternal(drawable); + public int ChevronCount => InternalChildren.Count; + + public IReadOnlyList Children => InternalChildren; + } + + private class SlideChevron : PoolableDrawable + { + public bool ShouldHide; + + public SlideChevron() + { + Anchor = Anchor.Centre; + Origin = Anchor.Centre; + } + + [BackgroundDependencyLoader] + private void load(TextureStore textures) + { + AddInternal(new Sprite + { + Anchor = Anchor.Centre, + Origin = Anchor.Centre, + Texture = textures.Get("slide"), + }); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `chevron` last assigned on line 191 could be null and is dereferenced at line 192, column 25. + +### Severity: +ERROR + +### Procedure: +Void SlideVisual.PerformEntryAnimation(Double) + +### File: +osu.Game.Rulesets.Sentakki/Objects/Drawables/Pieces/SlideVisual.cs + +### Key: +SlideVisual.cs|PerformEntryAnimation|NULL_DEREFERENCE + +### Node Key: +1ca5f3cb6750b76593061ea065f8fb1b + +### Hash: +700beeaa7502910866d867afbe9ec41d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0333/instruction.md b/inferredbugs-0333/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..85192754d409560de532e4be22efd893ff8c6d75 --- /dev/null +++ b/inferredbugs-0333/instruction.md @@ -0,0 +1,321 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** sentakki +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Linq; +using osu.Framework.Allocation; +using osu.Framework.Bindables; +using osu.Framework.Graphics; +using osu.Framework.Graphics.Containers; +using osu.Framework.Graphics.Pooling; +using osu.Framework.Graphics.Sprites; +using osu.Framework.Graphics.Textures; +using osu.Game.Rulesets.Objects; +using osu.Game.Rulesets.Objects.Types; +using osu.Game.Rulesets.Sentakki.Configuration; + +namespace osu.Game.Rulesets.Sentakki.Objects.Drawables.Pieces +{ + public class SlideVisual : CompositeDrawable + { + // This will be proxied, so a must. + public override bool RemoveWhenNotAlive => false; + + private int completedSegments; + public int CompletedSegments + { + get => completedSegments; + set + { + completedSegments = value; + updateProgress(completedSegments); + } + } + private SliderPath path; + + public SliderPath Path + { + get => path; + set + { + if (path == value) + return; + path = value; + updateVisuals(); + updateProgress(CompletedSegments); + } + } + + private Container segments; + private DrawablePool segmentPool; + private DrawablePool chevronPool; + + private readonly BindableBool snakingIn = new BindableBool(true); + + public int SegmentCount => segments.Count; + + public SlideVisual() + { + Anchor = Anchor.Centre; + Origin = Anchor.Centre; + } + + [BackgroundDependencyLoader(true)] + private void load(SentakkiRulesetConfigManager sentakkiConfig) + { + sentakkiConfig?.BindWith(SentakkiRulesetSettings.SnakingSlideBody, snakingIn); + + AddRangeInternal(new Drawable[]{ + segmentPool = new DrawablePool(20), + chevronPool = new DrawablePool(61), + segments = new Container(), + }); + } + + private const int chevrons_per_eith = 8; + private const double ring_radius = 297; + private const double chevrons_per_distance = (chevrons_per_eith * 8) / (2 * Math.PI * ring_radius); + private const double distance_per_chevron = 1 / chevrons_per_distance; + private const double endpoint_distance = /*r*/34; + + public static int ChevronsInPath(SliderPath path) + { + var (array, count) = splitIntoContinuousPaths(path); + var chevrons = array.Take(count).Sum(p => chevronsInContinuousPath(p)); + ArrayPool.Shared.Return(array); + return chevrons; + } + + /// A rented array which needs to be returned to + private static (SliderPath[] array, int count) splitIntoContinuousPaths(SliderPath path) + { + // first node will not split + var count = path.ControlPoints.Skip(1).Count(c => c.Type.Value == PathType.Linear) + 1; + var paths = ArrayPool.Shared.Rent(count); + int pathIndex = 0; + for (int i = 0; i < count; i++) if(paths[i] is null) paths[i] = new SliderPath(); + paths[0].ControlPoints.Clear(); + paths[0].ControlPoints.Add(path.ControlPoints[0]); + for (int i = 1; i < path.ControlPoints.Count; i++) + { + var controlPoint = path.ControlPoints[i]; + paths[pathIndex].ControlPoints.Add(controlPoint); + if (controlPoint.Type.Value == PathType.Linear) + { + // TODO test the angle here as continuous -> linear can still be smooth + pathIndex++; + paths[pathIndex].ControlPoints.Clear(); + paths[pathIndex].ControlPoints.Add(controlPoint); + } + } + return (paths, count); + } + + private static int chevronsInContinuousPath(SliderPath path) + { + return (int)Math.Ceiling((path.Distance - (2 * endpoint_distance)) * chevrons_per_distance); + } + + private void updateVisuals() + { + foreach (var segment in segments) + segment.ClearChevrons(); + segments.Clear(false); + + var reverseSegments = new List(); + void visualizePath(SliderPath path) + { + var chevronCount = chevronsInContinuousPath(path); + var totalDistance = path.Distance; + var safeDistance = totalDistance - (endpoint_distance * 2); + var distancePerChevron = safeDistance / chevronCount; + + SlideSegment currentSegment = segmentPool.Get(); + reverseSegments.Add(currentSegment); + + float lastAngle = path.PositionAt(0).GetDegreesFromPosition(path.PositionAt(0.1 / totalDistance)); + var previousPosition = path.PositionAt(0); + for (int i = 0; i < chevronCount; i++) + { + var progress = (double)i / ( chevronCount - 1 ); // from 0 to 1, both inclusive + + var position = path.PositionAt(((progress * safeDistance) + endpoint_distance) / totalDistance); + var angle = previousPosition.GetDegreesFromPosition(position); + + currentSegment.Add(chevronPool.Get().With(c => { + c.Position = position; + c.Rotation = angle; + c.ShouldHide = false; + c.Alpha = 1; + c.Depth = i; // earlier ones should remain on top + })); + + // add next segment if not last ( last segment has up to 5 chevrons while all other 3 ) + if ( i % 3 == 2 && chevronCount - 3 > i ) + { + currentSegment = segmentPool.Get(); + reverseSegments.Add(currentSegment); + } + + lastAngle = angle; + previousPosition = position; + } + } + + var (paths, count) = splitIntoContinuousPaths(path); + for (int i = 0; i < count; i++) visualizePath(paths[i]); + ArrayPool.Shared.Return(paths); + + segments.AddRange( reverseSegments.Reverse() ); + } + + private void updateProgress(int completedNodes) + { + for (int i = 1; i <= segments.Count; ++i) + { + segments[^i].Alpha = i <= completedNodes ? 0 : 1; + } + } + + public void PerformEntryAnimation(double duration) + { + if (snakingIn.Value) + { + int chevrons = (int)Math.Ceiling(Path.Distance / distance_per_chevron); + double fadeDuration = duration / chevrons; + double currentOffset = duration / 2; + for (int i = segments.Count - 1; i >= 0; i--) + { + var segment = segments[i]; + for (int j = segment.Children.Count - 1; j >= 0; j--) + { + var chevron = segment.Children[j] as SlideChevron; + if (!chevron.ShouldHide) + chevron.FadeOut().Delay(currentOffset).FadeInFromZero(fadeDuration * 2); + currentOffset += fadeDuration / 2; + } + } + } + else + { + this.FadeOut().Delay(duration / 2).FadeIn(duration / 2); + } + } + + public void PerformExitAnimation(double duration) + { + int chevronsLeft = (int)Math.Ceiling(Path.Distance / distance_per_chevron); + double fadeDuration() => duration / chevronsLeft; + double currentOffset = 0; + for (int i = segments.Count - 1; i >= 0; i--) + { + var segment = segments[i]; + if (segment.Alpha == 0) + { + chevronsLeft -= segment.ChevronCount; + continue; + } + + for (int j = segment.Children.Count - 1; j >= 0; j--) + { + var chevron = segment.Children[j] as SlideChevron; + if (!chevron.ShouldHide) + chevron.Delay(currentOffset).FadeOut(fadeDuration() * 2); + currentOffset += fadeDuration() / 2; + } + } + } + + private class SlideSegment : PoolableDrawable + { + public void ClearChevrons() => ClearInternal(false); + public void Add(Drawable drawable) => AddInternal(drawable); + public int ChevronCount => InternalChildren.Count; + + public IReadOnlyList Children => InternalChildren; + } + + private class SlideChevron : PoolableDrawable + { + public bool ShouldHide; + + public SlideChevron() + { + Anchor = Anchor.Centre; + Origin = Anchor.Centre; + } + + [BackgroundDependencyLoader] + private void load(TextureStore textures) + { + AddInternal(new Sprite + { + Anchor = Anchor.Centre, + Origin = Anchor.Centre, + Texture = textures.Get("slide"), + }); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `chevron` last assigned on line 220 could be null and is dereferenced at line 221, column 21. + +### Severity: +ERROR + +### Procedure: +Void SlideVisual.PerformExitAnimation(Double) + +### File: +osu.Game.Rulesets.Sentakki/Objects/Drawables/Pieces/SlideVisual.cs + +### Key: +SlideVisual.cs|PerformExitAnimation|NULL_DEREFERENCE + +### Node Key: +1ca5f3cb6750b76593061ea065f8fb1b + +### Hash: +5c9e641fa001daa9f6dc3ac9b6faf5dd + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0335/instruction.md b/inferredbugs-0335/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07426732ca1cd46635208bbe86fd2ad5713a6352 --- /dev/null +++ b/inferredbugs-0335/instruction.md @@ -0,0 +1,110 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ConvNetSharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using ConvNetSharp.Core; +using ConvNetSharp.Core.Layers.Double; +using ConvNetSharp.Core.Training.Double; +using ConvNetSharp.Volume; +using ConvNetSharp.Volume.Double; + +namespace MinimalExample +{ + internal class Program + { + private static void Main() + { + // species a 2-layer neural network with one hidden layer of 20 neurons + var net = new Net(); + + // input layer declares size of input. here: 2-D data + // ConvNetJS works on 3-Dimensional volumes (width, height, depth), but if you're not dealing with images + // then the first two dimensions (width, height) will always be kept at size 1 + net.AddLayer(new InputLayer(1, 1, 2)); + + // declare 20 neurons + net.AddLayer(new FullyConnLayer(20)); + + // declare a ReLU (rectified linear unit non-linearity) + net.AddLayer(new ReluLayer()); + + // declare a fully connected layer that will be used by the softmax layer + net.AddLayer(new FullyConnLayer(10)); + + // declare the linear classifier on top of the previous hidden layer + net.AddLayer(new SoftmaxLayer(10)); + + // forward a random data point through the network + var x = new Volume(new[] { 0.3, -0.5 }, new Shape(2)); + + var prob = net.Forward(x); + + // prob is a Volume. Volumes have a property Weights that stores the raw data, and WeightGradients that stores gradients + Console.WriteLine("probability that x is class 0: " + prob.Get(0)); // prints e.g. 0.50101 + + var trainer = new SgdTrainer(net) { LearningRate = 0.01, L2Decay = 0.001 }; + trainer.Train(x, new Volume(new[] { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, new Shape(1, 1, 10, 1))); // train the network, specifying that x is class zero + + var prob2 = net.Forward(x); + Console.WriteLine("probability that x is class 0: " + prob2.Get(0)); + // now prints 0.50374, slightly higher than previous 0.50101: the networks + // weights have been adjusted by the Trainer to give a higher probability to + // the class we trained the network with (zero) + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource trainer of type ConvNetSharp.Core.Training.Double.SgdTrainer, Leaked resource x of type ConvNetSharp.Volume.Double.Volume, Leaked resource (output of ConvNetSharp.Volume.Double.Volume::.ctor() at Line 43) of type ConvNetSharp.Volume.Double.Volume in method "Void Program.Main()". + +### Severity: +ERROR + +### Procedure: +Void Program.Main() + +### File: +Examples/MinimalExample/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +f539b2edd403b97ee57633f3c77aa260 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0351/instruction.md b/inferredbugs-0351/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6b4907fa436bcb26163df7050006c218e2193407 --- /dev/null +++ b/inferredbugs-0351/instruction.md @@ -0,0 +1,234 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** platyPS +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Markdown.MAML.Model; + +namespace Markdown.MAML.Parser +{ + /// + /// This class contain logic to render maml from the Model. + /// + public class MamlRenderer + { + private enum State + { + None, + Command, + + } + + private StringBuilder _stringBuilder = new StringBuilder(); + private DocumentNode _root; + private State _state; + private Stack _tagStack; + private IEnumerator _rootEnumerator; + + public const string XML_PREAMBULA = @" + +"; + public const string COMMAND_PREAMBULA = @""; + + private const int COMMAND_NAME_HEADING_LEVEL = 2; + private const int COMMAND_ENTRIES_HEADING_LEVEL = 3; + + public MamlRenderer(DocumentNode root) + { + _root = root; + _tagStack = new Stack(); + if (_root.Children == null) + { + // HACK: + _rootEnumerator = (new LinkedList()).GetEnumerator(); + } + else + { + _rootEnumerator = _root.Children.GetEnumerator(); + } + } + + private void PushTag(string tag) + { + _stringBuilder.AppendFormat("<{0}>\n", tag); + _tagStack.Push(tag); + } + + private void PopTag(string tag) + { + string poped = _tagStack.Pop(); + if (poped != tag) + { + throw new FormatException("Expecting pop " + tag + ", but got " + poped); + } + _stringBuilder.AppendFormat("\n", tag); + } + + private void PopAllTags() + { + PopTag(_tagStack.Count); + } + + private void PopTag(int count) + { + for (int i = 0; i < count; i++) + { + _stringBuilder.AppendFormat("\n", _tagStack.Pop()); + } + } + + public string ToMamlString() + { + _stringBuilder.Clear(); + _state = State.None; + _stringBuilder.AppendLine(XML_PREAMBULA); + + AddCommands(); + + _stringBuilder.AppendLine(""); + return _stringBuilder.ToString(); + } + + private MarkdownNode GetCurrentNode() + { + return _rootEnumerator.Current; + } + + private MarkdownNode GetNextNode() + { + if (_rootEnumerator.MoveNext()) + { + return _rootEnumerator.Current; + } + + return null; + } + + private void AddCommands() + { + MarkdownNode markdownNode; + _stringBuilder.AppendLine(COMMAND_PREAMBULA); + while ((markdownNode = GetNextNode()) != null) + { + if (markdownNode is HeadingNode) + { + var headingNode = markdownNode as HeadingNode; + switch (headingNode.HeadingLevel) + { + case COMMAND_NAME_HEADING_LEVEL : + { + PopAllTags(); + _state = State.Command; + + PushTag("command:details"); + _stringBuilder.AppendFormat("{0}", headingNode.Text); + AddDescription(); + PopTag("command:details"); + + break; + } + default: throw new HelpSchemaException("Booo, I don't know what is the heading level " + headingNode.HeadingLevel); + } + } + } + //PopAllTags(); + + _stringBuilder.AppendLine(""); + } + + private void AddDescription() + { + var node = GetNextNode(); + + // check for appropriate header + if (node.NodeType != MarkdownNodeType.Heading) + { + throw new HelpSchemaException("Expect ###DESCRIPTION"); + } + + var headingNode = node as HeadingNode; + if (headingNode.HeadingLevel != COMMAND_ENTRIES_HEADING_LEVEL) + { + throw new HelpSchemaException("Expect ###DESCRIPTION"); + } + + if (StringComparer.OrdinalIgnoreCase.Compare(headingNode.Text, "DESCRIPTION") != 0) + { + throw new HelpSchemaException("Expect ###DESCRIPTION"); + } + + node = GetNextNode(); + if (node.NodeType != MarkdownNodeType.Paragraph) + { + throw new HelpSchemaException("Expect DESCRIPTION text"); + } + + PushTag("maml:description"); + PushTag("maml:para"); + _stringBuilder.AppendLine((node as ParagraphNode).Text); + PopTag(2); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `headingNode` last assigned on line 149 could be null and is dereferenced at line 150, column 13. + +### Severity: +ERROR + +### Procedure: +Void MamlRenderer.AddDescription() + +### File: +src/Markdown.MAML/Parser/MamlRenderer.cs + +### Key: +MamlRenderer.cs|AddDescription|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +cd5342b3a32f6f4f780de9cf797101ce + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0356/instruction.md b/inferredbugs-0356/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21895c82f0d325701f540ccfbc3386e81fd73ba4 --- /dev/null +++ b/inferredbugs-0356/instruction.md @@ -0,0 +1,459 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** StackExchange.Metrics +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +using StackExchange.Metrics; +using StackExchange.Metrics.Handlers; +using StackExchange.Metrics.Metrics; + +namespace Scratch +{ + class Program + { + static Task s_samplerTask; + static CancellationTokenSource s_cancellationTokenSource; + + static async Task Main(string[] args) + { + //BenchmarkRunner.Run(); + //var x = 1; + //if (x == 1) + //{ + // return; + //} + + s_cancellationTokenSource = new CancellationTokenSource(); + + Debug.AutoFlush = true; + + const string LocalEndpointKey = "Local"; + + var localHandler = new LocalMetricHandler(); + var options = new MetricsCollectorOptions(exception => + { + Console.WriteLine("Hey, there was an exception."); + Console.WriteLine(exception); + }) + { + Endpoints = new MetricEndpoint[] { + new MetricEndpoint(LocalEndpointKey, localHandler), + new MetricEndpoint("Test HTTP 1", new TestBosunMetricHandler(new Uri("http://127.0.0.1/"))), + new MetricEndpoint("Test HTTP 2", new TestSignalFxHandler(new Uri("http://127.0.0.1/"))), + //new MetricEndpoint("Test UDP", new TestUdpMetricHandler(s_cancellationTokenSource.Token) { MaxPayloadSize = 320 }), + //new MetricEndpoint("Bosun (no URL)", new BosunMetricHandler(null)), + //new MetricEndpoint("Bosun", new BosunMetricHandler(new Uri("http://devbosun.ds.stackexchange.com/"))), + //new MetricEndpoint("DataDog Agent", new DataDogStatsdMetricHandler("dogstatsd.datadog.svc.ny-intkube.k8s", 8125)), + //new MetricEndpoint("SignalFx Agent", new SignalFxMetricHandler(new Uri("http://sfxgateway.signalfx.svc.ny-intkube.k8s:18080"))), + //new MetricEndpoint("DataDog Cloud", new DataDogMetricHandler(new Uri("https://api.datadoghq.com/"), "{API_KEY}", "{APP_KEY}")), + //new MetricEndpoint("DataDog Cloud (no URL)", new DataDogMetricHandler(null, "{API_KEY}", "{APP_KEY}")), + //new MetricEndpoint("SignalFx Cloud", new SignalFxMetricHandler(new Uri("https://ingest.us1.signalfx.com/"), "{API_KEY}")), + //new MetricEndpoint("SignalFx Cloud (no URL)", new SignalFxMetricHandler(null, "{API_KEY}")), + }, + MetricsNamePrefix = "bosun.reporter.", + ThrowOnPostFail = true, + ThrowOnQueueFull = false, + SnapshotInterval = TimeSpan.FromSeconds(10), + PropertyToTagName = NameTransformers.CamelToLowerSnakeCase, + TagValueConverter = (name, value) => name == "converted" ? value.ToLowerInvariant() : value, + DefaultTags = new Dictionary { {"host", NameTransformers.Sanitize(Environment.MachineName.ToLower())} } + }; + + var collector = new MetricsCollector(options); + + collector.BeforeSerialization += () => Console.WriteLine("BosunReporter: Running metrics snapshot."); + collector.AfterSerialization += info => Console.WriteLine($"BosunReporter: Metric Snapshot wrote {info.Count} metrics ({info.BytesWritten} bytes) to {info.Endpoint} in {info.Duration.TotalMilliseconds.ToString("0.##")}ms"); + collector.AfterSend += info => + { + if (info.Endpoint == LocalEndpointKey) + { + foreach (var reading in localHandler.GetReadings()) + { + Console.WriteLine($"{reading.Name}{reading.Suffix}@{reading.Timestamp:s} {reading.Value}"); + } + } + Console.WriteLine($"BosunReporter: Payload {info.PayloadType} - {info.BytesWritten} bytes posted to endpoint {info.Endpoint} in {info.Duration.TotalMilliseconds.ToString("0.##")}ms ({(info.Successful ? "SUCCESS" : "FAILED")})"); + }; + + collector.BindMetric("my_counter", "increments", typeof(TestCounter)); + var counter = collector.GetMetric("my_counter", "increments", "This is meaningless."); + counter.Increment(); + counter.Increment(); + + var gauge = collector.CreateMetric("gauge", "watts", "Some description of a gauge.", new TestAggregateGauge("1")); + if (gauge != collector.GetMetric("gauge", "watts", null, new TestAggregateGauge("1"))) + throw new Exception("WAT?"); + + try + { + collector.CreateMetric("gauge", "watts", "Some description of a gauge.", new TestAggregateGauge("1")); + } + catch(Exception) + { + goto SKIP_EXCEPTION; + } + + throw new Exception("CreateMetric should have failed for duplicate metric."); + + SKIP_EXCEPTION: + + var gauge2 = collector.GetMetric("gauge2", "newtons", "Number of newtons currently applied."); + for (var i = 0; i < 6; i++) + { + new Thread(Run).Start(new Tuple(gauge, gauge2, i)); + } + + var enumCounter = collector.GetMetricGroup("some_enum", "things", "Some of something"); + enumCounter.PopulateFromEnum(); + + Type t; + string u; + if (collector.TryGetMetricInfo("gauge2", out t, out u)) + { + Console.WriteLine(t); + Console.WriteLine(u); + } + else + { + Console.WriteLine("NOOOOO!!!!!"); + } + + var si = 0; + var snapshot = collector.GetMetric("my_snapshot", "snappys", "Snap snap snap.", new SnapshotGauge(() => ++si % 5)); + + var group = collector.GetMetricGroup("test_group", "tests", "These gauges are for testing."); + group.Add("low").Description = "Low testing."; + group.Add("medium").Description = "Medium testing."; + group.Add("high").Description = "High testing."; + var sampler = collector.GetMetric("sampler", "french fries", "Collect them all.", new SamplingGauge()); + var eventGauge = collector.GetMetric("event", "count", "How many last time.", new EventGauge()); + var converted = collector.CreateMetric("convert_test", "units", "Checking to see if the tag value converter works.", new ConvertedTagsTestCounter("ThingsAndStuff")); + var noHost = collector.CreateMetric("no_host", "units", "Shouldn't have a host tag."); + + var externalCounter = collector.GetMetricGroup("external.test", "units", "Should aggregate externally."); + externalCounter.PopulateFromEnum(); + // var externalNoTags = collector.CreateMetric("external.no_tags", "units", "Shouldn't have any tags except relay."); + + var lotsOfCounters = new List(); + for (var i = 0; i < 400; i++) + { + lotsOfCounters.Add(collector.GetMetric("counter_" + i, "counts", "Testing lots of counters", new Counter())); + } + + var sai = 0; + var random = new Random(); + + s_samplerTask = Task.Run(async () => + { + while (true) + { + await Task.Delay(100); + + sampler.Record(++sai % 35); + eventGauge.Record(sai % 35); + group["low"].Record(random.Next(0, 10)); + group["medium"].Record(random.Next(10, 20)); + group["high"].Record(random.Next(20, 30)); + + enumCounter[SomeEnum.One].Increment(); + enumCounter[SomeEnum.Two].Increment(2); + enumCounter[SomeEnum.Three].Increment(3); + enumCounter[SomeEnum.Four].Increment(4); + + externalCounter[SomeEnum.One].Increment(); + if (sai % 2 == 0) + externalCounter[SomeEnum.Two].Increment(); + if (sai % 3 == 0) + externalCounter[SomeEnum.Three].Increment(); + if (sai % 4 == 0) + externalCounter[SomeEnum.Four].Increment(); + + foreach (var lotsOfCounter in lotsOfCounters) + { + lotsOfCounter.Increment(random.Next(0, 5)); + } + + // externalNoTags.Increment(); + + converted.Increment(); + noHost.Increment(); + + if (sai == 1000 || s_cancellationTokenSource.IsCancellationRequested) + { + collector.Shutdown(); + break; + } + } + }); + + Console.CancelKeyPress += (object sender, ConsoleCancelEventArgs e) => + { + s_cancellationTokenSource.Cancel(); + }; + + try + { + await s_samplerTask; + } + catch (TaskCanceledException) + { + // meh, ignore + } + } + + static void Run(object obj) + { + var tup = (Tuple)obj; + var gauge1 = tup.Item1; + var gauge2 = tup.Item2; + + if (gauge1 == gauge2) + throw new Exception("These weren't supposed to be the same... they have different tags."); + + var rand = new Random(tup.Item3); + int i; + while (!s_cancellationTokenSource.IsCancellationRequested) + { + for (i = 0; i < 20; i++) + { + gauge1.Record(rand.NextDouble()); + gauge2.Record(rand.NextDouble()); + } + + Thread.Sleep(1); + } + } + } + + + class TestHttpHandler : HttpMessageHandler + { + readonly TimeSpan _timeout; + + public TestHttpHandler(TimeSpan timeout) + { + this._timeout = timeout; + } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + await Task.Delay(_timeout); + var json = await request.Content.ReadAsStringAsync(); + //Console.WriteLine($"Sending metrics to {request.RequestUri}. JSON = {json}"); + return new HttpResponseMessage + { + StatusCode = HttpStatusCode.OK + }; + } + } + + class TestBosunMetricHandler : BosunMetricHandler + { + public TestBosunMetricHandler(Uri baseUri) : base(baseUri) + { + } + + protected override HttpClient CreateHttpClient() => new HttpClient(new TestHttpHandler(TimeSpan.FromMilliseconds(300))); + } + + class TestSignalFxHandler : SignalFxMetricHandler + { + public TestSignalFxHandler(Uri baseUri) : base(baseUri) + { + } + + protected override HttpClient CreateHttpClient() => new HttpClient(new TestHttpHandler(TimeSpan.FromMilliseconds(10))); + } + + class TestUdpMetricHandler : DataDogStatsdMetricHandler + { + public TestUdpMetricHandler(CancellationToken cancellationToken) : base(IPAddress.Loopback.ToString(), 1234) + { + Task.Run( + () => + { + var udpClient = new UdpClient(1234); + var ipEndpoint = new IPEndPoint(IPAddress.Loopback, 0); + cancellationToken.Register(() => udpClient.Dispose()); + while (!cancellationToken.IsCancellationRequested) + { + try + { + udpClient.Receive(ref ipEndpoint); + } + catch { } + } + }); + } + } + + [GaugeAggregator(AggregateMode.Count)] + public class CountGauge : AggregateGauge + { + } + + [GaugeAggregator(AggregateMode.Count)] + [GaugeAggregator(AggregateMode.Average)] + [GaugeAggregator(AggregateMode.Max)] + [GaugeAggregator(AggregateMode.Min)] + [GaugeAggregator(AggregateMode.Median)] + [GaugeAggregator(AggregateMode.Percentile, 0.95)] + [GaugeAggregator(AggregateMode.Percentile, 0.25)] + public class TestAggregateGauge : AggregateGauge + { + // [MetricTag] public readonly string Host; + [MetricTag] public readonly string SomeTagName; + + public TestAggregateGauge(string something) + { +// Host = "bret-host"; + SomeTagName = something; + } + } + + public class TestCounter : Counter + { +// [MetricTag] public readonly string Host; + + public TestCounter() + { +// Host = "bret-host"; + } + } + + public class TestSnapshotGauge : SnapshotGauge + { + [MetricTag] public readonly string Thing; + + public TestSnapshotGauge(Func getValue) : base(() => getValue()) + { + Thing = "nothing"; + } + } + + public class TestGroupGauge : EventGauge + { + [MetricTag] + public readonly string Range; + + public TestGroupGauge(string range) + { + Range = range; + } + } + + public enum SomeEnum + { + One = 1, + Two = 2, + Three = 3, + Four = 4, + } + + public class EnumCounter : Counter + { + [MetricTag] public readonly SomeEnum TagName; + + public EnumCounter(SomeEnum val) + { + TagName = val; + } + } + + public class ConvertedTagsTestCounter : Counter + { + [MetricTag] public readonly string Converted; + + public ConvertedTagsTestCounter(string toConvert) + { + Converted = toConvert; + } + } + + [ExcludeDefaultTags("host")] + public class ExcludeHostCounter : Counter + { + [MetricTag] public readonly string Other; + + public ExcludeHostCounter() + { + Other = "true"; + } + } + + public class TestExternalCounter : CumulativeCounter + { + [MetricTag] public readonly SomeEnum Something; + + public TestExternalCounter(SomeEnum something) + { + Something = something; + } + } + + public class ExternalNoTagsCounter : CumulativeCounter + { + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource return of type System.Net.Http.HttpClient, Leaked resource (output of Scratch.TestHttpHandler::.ctor() at Line 268) of type Scratch.TestHttpHandler in method "HttpClient TestSignalFxHandler.CreateHttpClient()". + +### Severity: +ERROR + +### Procedure: +HttpClient TestSignalFxHandler.CreateHttpClient() + +### File: +tests/Scratch/Program.cs + +### Key: +Program.cs|CreateHttpClient|DOTNET_RESOURCE_LEAK + +### Hash: +3903f094dc594061581c643bb4067c0d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0358/instruction.md b/inferredbugs-0358/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6d5cec6c835a619bc9ff66c61909f354a37477c --- /dev/null +++ b/inferredbugs-0358/instruction.md @@ -0,0 +1,335 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kafka-streams-dotnet +**Bug ID:** 11 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Confluent.Kafka; +using Streamiz.Kafka.Net.Kafka; +using Streamiz.Kafka.Net.Mock.Pipes; +using Streamiz.Kafka.Net.Mock.Sync; +using Streamiz.Kafka.Net.Processors; +using Streamiz.Kafka.Net.Processors.Internal; +using Streamiz.Kafka.Net.SerDes; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data.SqlTypes; +using System.IO; +using System.Linq; +using System.Threading; +using Streamiz.Kafka.Net.Crosscutting; +using Streamiz.Kafka.Net.Kafka.Internal; +using Streamiz.Kafka.Net.Metrics; +using Streamiz.Kafka.Net.Stream.Internal; + +namespace Streamiz.Kafka.Net.Mock +{ + internal sealed class TaskSynchronousTopologyDriver : IBehaviorTopologyTestDriver + { + private readonly IStreamConfig configuration; + private readonly IStreamConfig topicConfiguration; + private readonly InternalTopologyBuilder builder; + private readonly CancellationToken token; + private readonly IKafkaSupplier supplier; + private readonly IDictionary tasks = new Dictionary(); + private readonly GlobalStateUpdateTask globalTask = null; + private readonly GlobalProcessorContext globalProcessorContext = null; + private readonly StreamMetricsRegistry metricsRegistry; + + private readonly IDictionary> partitionsByTaskId = + new Dictionary>(); + + private readonly SyncProducer producer = null; + private readonly bool hasGlobalTopology = false; + private ITopicManager internalTopicManager; + + public bool IsRunning { get; private set; } + + public bool IsStopped => !IsRunning; + + public bool IsError { get; private set; } = false; + + public TaskSynchronousTopologyDriver(string clientId, InternalTopologyBuilder topologyBuilder, + IStreamConfig configuration, IStreamConfig topicConfiguration, CancellationToken token) + : this(clientId, topologyBuilder, configuration, topicConfiguration, null, token) + { + } + + public TaskSynchronousTopologyDriver(string clientId, InternalTopologyBuilder topologyBuilder, + IStreamConfig configuration, IStreamConfig topicConfiguration, IKafkaSupplier supplier, + CancellationToken token) + { + this.configuration = configuration; + this.configuration.ClientId = clientId; + this.topicConfiguration = topicConfiguration; + metricsRegistry = new StreamMetricsRegistry(clientId, MetricsRecordingLevel.DEBUG); + + this.token = token; + builder = topologyBuilder; + this.supplier = supplier ?? new SyncKafkaSupplier(); + this.supplier.MetricsRegistry = metricsRegistry; + producer = this.supplier.GetProducer(configuration.ToProducerConfig()) as SyncProducer; + + foreach (var sourceTopic in builder + .GetSourceTopics()) + { + var part = new TopicPartition(sourceTopic, 0); + var taskId = builder.GetTaskIdFromPartition(part); + if (partitionsByTaskId.ContainsKey(taskId)) + partitionsByTaskId[taskId].Add(part); + else + partitionsByTaskId.Add(taskId, new List {part}); + } + + ProcessorTopology globalTaskTopology = topologyBuilder.BuildGlobalStateTopology(); + hasGlobalTopology = globalTaskTopology != null; + if (hasGlobalTopology) + { + var globalConsumer = + this.supplier.GetGlobalConsumer(configuration.ToGlobalConsumerConfig($"{clientId}-global-consumer")); + var adminClient = this.supplier.GetAdmin(configuration.ToAdminConfig($"{clientId}-admin")); + var stateManager = + new GlobalStateManager(globalConsumer, globalTaskTopology, adminClient, configuration); + globalProcessorContext = new GlobalProcessorContext(configuration, stateManager, metricsRegistry); + stateManager.SetGlobalProcessorContext(globalProcessorContext); + globalTask = new GlobalStateUpdateTask(stateManager, globalTaskTopology, globalProcessorContext); + + globalTask.Initialize(); + } + } + + internal StreamTask GetTask(string topicName) + { + StreamTask task = null; + var id = builder.GetTaskIdFromPartition(new Confluent.Kafka.TopicPartition(topicName, 0)); + if (tasks.ContainsKey(id)) + task = tasks[id]; + else + { + if (!builder.GetGlobalTopics().Contains(topicName)) + { + task = new StreamTask("thread-0", + id, + partitionsByTaskId[id], + builder.BuildTopology(id), + supplier.GetConsumer(configuration.ToConsumerConfig(), null), + configuration, + supplier, + producer, + new MockChangelogRegister(), + metricsRegistry); + task.InitializeStateStores(); + task.InitializeTopology(); + task.RestorationIfNeeded(); + task.CompleteRestoration(); + tasks.Add(id, task); + } + } + + return task; + } + + private void InitializeInternalTopicManager() + { + // Create internal topics (changelogs & repartition) if need + var adminClientInternalTopicManager = supplier.GetAdmin(configuration.ToAdminConfig( + StreamThread.GetSharedAdminClientId( + $"{configuration.ApplicationId.ToLower()}-admin-internal-topic-manager"))); + internalTopicManager = new DefaultTopicManager(configuration, adminClientInternalTopicManager); + + InternalTopicManagerUtils + .New() + .CreateSourceTopics(builder, supplier) + .CreateInternalTopicsAsync(internalTopicManager, builder) + .GetAwaiter() + .GetResult(); + } + + private void ForwardRepartitionTopic(IConsumer consumer, string topic) + { + var records = new List>(); + consumer.Subscribe(topic); + ConsumeResult record = null; + do + { + record = consumer.Consume(); + if (record != null) + records.Add(record); + } while (record != null); + + + if (records.Any()) + { + long now = DateTime.Now.GetMilliseconds(); + var task = GetTask(topic); + task.AddRecords(records); + while (task.CanProcess(now)) + task.Process(); + + consumer.Commit(records.Last()); + } + + consumer.Unsubscribe(); + } + + private SyncPipeBuilder CreateBuilder(string topicName) + { + var task = GetTask(topicName); + if (task == null && hasGlobalTopology) + { + return new SyncPipeBuilder(globalTask); + } + + return new SyncPipeBuilder(task); + } + + #region IBehaviorTopologyTestDriver + + public TestMultiInputTopic CreateMultiInputTopic(string[] topics, ISerDes keySerdes = null, + ISerDes valueSerdes = null) + { + Dictionary pipes = new Dictionary(); + + foreach (var topic in topics) + { + var builder = CreateBuilder(topic); + var pipeInput = builder.Input(topic, configuration); + + var topicsLink = new List(); + this.builder.GetLinkTopics(topic, topicsLink); + var consumer = + supplier.GetConsumer(topicConfiguration.ToConsumerConfig("consumer-repartition-forwarder"), + null); + + foreach (var topicLink in topicsLink) + pipeInput.Flushed += () => ForwardRepartitionTopic(consumer, topicLink); + + pipes.Add(topic, pipeInput); + } + + return new TestMultiInputTopic(pipes, configuration, keySerdes, valueSerdes); + } + + public TestInputTopic CreateInputTopic(string topicName, ISerDes keySerdes, + ISerDes valueSerdes) + { + var pipeBuilder = CreateBuilder(topicName); + var pipeInput = pipeBuilder.Input(topicName, configuration); + + var topicsLink = new List(); + builder.GetLinkTopics(topicName, topicsLink); + var consumer = supplier.GetConsumer(topicConfiguration.ToConsumerConfig("consumer-repartition-forwarder"), + null); + + foreach (var topic in topicsLink) + pipeInput.Flushed += () => ForwardRepartitionTopic(consumer, topic); + + return new TestInputTopic(pipeInput, configuration, keySerdes, valueSerdes); + } + + public TestOutputTopic CreateOutputTopic(string topicName, TimeSpan consumeTimeout, + ISerDes keySerdes = null, ISerDes valueSerdes = null) + { + var pipeBuilder = new SyncPipeBuilder(producer); + var pipeOutput = pipeBuilder.Output(topicName, consumeTimeout, configuration, token); + return new TestOutputTopic(pipeOutput, topicConfiguration, keySerdes, valueSerdes); + } + + public void Dispose() + { + internalTopicManager?.Dispose(); + + foreach (var t in tasks.Values) + { + t.Close(); + + // Remove local state store for this task + if (t.IsPersistent) + Directory.Delete(t.Context.StateDir, true); + } + + if (hasGlobalTopology) + { + globalTask.FlushState(); + globalTask.Close(); + } + + IsRunning = false; + } + + public void StartDriver() + { + InitializeInternalTopicManager(); + + IsRunning = true; + } + + public IStateStore GetStateStore(string name) + { + var task = tasks.Values.FirstOrDefault(t => t.Context.GetStateStore(name) != null); + + if(task != null) + return task.Context.GetStateStore(name); + + return hasGlobalTopology ? globalProcessorContext.GetStateStore(name) : null; + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `task` last assigned on line 159 could be null and is dereferenced at line 160, column 17. + +### Severity: +ERROR + +### Procedure: +Void TaskSynchronousTopologyDriver.ForwardRepartitionTopic(IConsumer`2,String) + +### File: +core/Mock/TaskSynchronousTopologyDriver.cs + +### Key: +TaskSynchronousTopologyDriver.cs|ForwardRepartitionTopic|NULL_DEREFERENCE + +### Node Key: +5f12004af86bc692e0983547f0c7b710 + +### Hash: +e91b9b0e93bfeb816f23aabec3d91977 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0360/instruction.md b/inferredbugs-0360/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af793de45ec132969e431e1ab00c9765daddaa87 --- /dev/null +++ b/inferredbugs-0360/instruction.md @@ -0,0 +1,269 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kafka-streams-dotnet +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Confluent.Kafka; +using Moq; +using NUnit.Framework; +using Streamiz.Kafka.Net.Crosscutting; +using Streamiz.Kafka.Net.Errors; +using Streamiz.Kafka.Net.Mock.Sync; +using Streamiz.Kafka.Net.Processors; +using Streamiz.Kafka.Net.Processors.Internal; +using Streamiz.Kafka.Net.SerDes; +using Streamiz.Kafka.Net.State; +using Streamiz.Kafka.Net.State.RocksDb; +using static Streamiz.Kafka.Net.Processors.Internal.StoreChangelogReader; + +namespace Streamiz.Kafka.Net.Tests.Private +{ + public class StoreChangelogReaderTests + { + private string stateDir; + private string changelogTopic; + private IStreamConfig config; + private SyncKafkaSupplier supplier; + private RocksDbKeyValueStore store; + private StoreChangelogReader storeChangelogReader; + private ProcessorStateManager stateMgr; + private ProcessorContext context; + private IConsumer restoreConsumer; + + private Message CreateMessage(string topic, string key, string value) + { + StringSerDes stringSerDes = new StringSerDes(); + return new Message + { + Key = stringSerDes.Serialize(key, new SerializationContext(MessageComponentType.Key, topic)), + Value = stringSerDes.Serialize(value, new SerializationContext(MessageComponentType.Key, topic)) + }; + } + + [SetUp] + public void Init() + { + stateDir = Path.Combine(".", Guid.NewGuid().ToString()); + config = new StreamConfig(); + config.ApplicationId = "test-storechangelog-app"; + config.StateDir = stateDir; + config.PollMs = 100; + + supplier = new SyncKafkaSupplier(); + var producer = supplier.GetProducer(config.ToProducerConfig()); + restoreConsumer = supplier.GetRestoreConsumer(config.ToConsumerConfig()); + + var topicPart = new TopicPartition("topic", 0); + changelogTopic = "store-changelog-topic"; + var changelogsTopics = new Dictionary(); + changelogsTopics.Add("store", changelogTopic); + var id = new TaskId + { + Id = 0, + Partition = 0 + }; + + store = new RocksDbKeyValueStore("store"); + storeChangelogReader = new StoreChangelogReader(config, restoreConsumer); + stateMgr = new ProcessorStateManager( + id, + topicPart.ToSingle(), + changelogsTopics, + storeChangelogReader, + new OffsetCheckpointFile(Path.Combine(config.StateDir, config.ApplicationId, $"{id.Id}-{id.Partition}")) + ); + + Mock moq = new Mock(); + moq.Setup(t => t.Id).Returns(new TaskId { Id = 0, Partition = 0 }); + + context = new ProcessorContext(moq.Object, config, stateMgr); + store.Init(context, store); + + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key1", "value1")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key2", "value2")); + } + + [TearDown] + public void Dispose() + { + stateMgr.Close(); + storeChangelogReader.Clear(); + Directory.Delete(config.StateDir, true); + } + + [Test] + public void RestoreComplete() + { + storeChangelogReader.Restore(); + + Assert.AreEqual(2, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(2, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RestoreFromRecovery() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + var producer = supplier.GetProducer(config.ToProducerConfig()); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key3", "value3")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key4", "value4")); + + restoreConsumer.Resume(restoreConsumer.Assignment); + + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + File.Delete(Path.Combine(config.StateDir, config.ApplicationId, "0-0", ".checkpoint")); + + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + restoreConsumer.Resume(restoreConsumer.Assignment); + + storeChangelogReader.Restore(); + + Assert.AreEqual(4, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(4, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RestoreFromScratch() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + var producer = supplier.GetProducer(config.ToProducerConfig()); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key3", "value3")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key4", "value4")); + + // delete state dir rocksdb + Directory.Delete(Path.Combine(config.StateDir), true); + + restoreConsumer.Resume(restoreConsumer.Assignment); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + storeChangelogReader.Restore(); + + Assert.AreEqual(4, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(4, metadata.RestoreEndOffset); + Assert.AreEqual(4, metadata.TotalRestored); + } + + [Test] + public void RestoreFromInvalidOffset() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + // set an invalid offset in checkpoint file + StringBuilder sb = new StringBuilder(); + sb.AppendLine("0").AppendLine("1").AppendLine("store-changelog-topic 0 -100"); + File.WriteAllText(Path.Combine(config.StateDir, config.ApplicationId, "0-0", ".checkpoint"), sb.ToString()); + + restoreConsumer.Resume(restoreConsumer.Assignment); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + storeChangelogReader.Restore(); + + Assert.AreEqual(2, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(2, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RegisterFailed() + { + Assert.Throws(() => storeChangelogReader.Register(new TopicPartition("test", 0), stateMgr)); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `metadata` last assigned on line 101 could be null and is dereferenced at line 103, column 13. + +### Severity: +ERROR + +### Procedure: +Void StoreChangelogReaderTests.RestoreComplete() + +### File: +test/Streamiz.Kafka.Net.Tests/Private/StoreChangelogReaderTests.cs + +### Key: +StoreChangelogReaderTests.cs|RestoreComplete|NULL_DEREFERENCE + +### Node Key: +c6749c0eea2f60af0918298ee5b3577c + +### Hash: +c541346c087ce3a0ad81b876221c4ca3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0367/instruction.md b/inferredbugs-0367/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3d93e3c66f6cd648aa740ee3d864a00466b89a6 --- /dev/null +++ b/inferredbugs-0367/instruction.md @@ -0,0 +1,269 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** kafka-streams-dotnet +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using Confluent.Kafka; +using Moq; +using NUnit.Framework; +using Streamiz.Kafka.Net.Crosscutting; +using Streamiz.Kafka.Net.Errors; +using Streamiz.Kafka.Net.Mock.Sync; +using Streamiz.Kafka.Net.Processors; +using Streamiz.Kafka.Net.Processors.Internal; +using Streamiz.Kafka.Net.SerDes; +using Streamiz.Kafka.Net.State; +using Streamiz.Kafka.Net.State.RocksDb; +using static Streamiz.Kafka.Net.Processors.Internal.StoreChangelogReader; + +namespace Streamiz.Kafka.Net.Tests.Private +{ + public class StoreChangelogReaderTests + { + private string stateDir; + private string changelogTopic; + private IStreamConfig config; + private SyncKafkaSupplier supplier; + private RocksDbKeyValueStore store; + private StoreChangelogReader storeChangelogReader; + private ProcessorStateManager stateMgr; + private ProcessorContext context; + private IConsumer restoreConsumer; + + private Message CreateMessage(string topic, string key, string value) + { + StringSerDes stringSerDes = new StringSerDes(); + return new Message + { + Key = stringSerDes.Serialize(key, new SerializationContext(MessageComponentType.Key, topic)), + Value = stringSerDes.Serialize(value, new SerializationContext(MessageComponentType.Key, topic)) + }; + } + + [SetUp] + public void Init() + { + stateDir = Path.Combine(".", Guid.NewGuid().ToString()); + config = new StreamConfig(); + config.ApplicationId = "test-storechangelog-app"; + config.StateDir = stateDir; + config.PollMs = 100; + + supplier = new SyncKafkaSupplier(); + var producer = supplier.GetProducer(config.ToProducerConfig()); + restoreConsumer = supplier.GetRestoreConsumer(config.ToConsumerConfig()); + + var topicPart = new TopicPartition("topic", 0); + changelogTopic = "store-changelog-topic"; + var changelogsTopics = new Dictionary(); + changelogsTopics.Add("store", changelogTopic); + var id = new TaskId + { + Id = 0, + Partition = 0 + }; + + store = new RocksDbKeyValueStore("store"); + storeChangelogReader = new StoreChangelogReader(config, restoreConsumer); + stateMgr = new ProcessorStateManager( + id, + topicPart.ToSingle(), + changelogsTopics, + storeChangelogReader, + new OffsetCheckpointFile(Path.Combine(config.StateDir, config.ApplicationId, $"{id.Id}-{id.Partition}")) + ); + + Mock moq = new Mock(); + moq.Setup(t => t.Id).Returns(new TaskId { Id = 0, Partition = 0 }); + + context = new ProcessorContext(moq.Object, config, stateMgr); + store.Init(context, store); + + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key1", "value1")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key2", "value2")); + } + + [TearDown] + public void Dispose() + { + stateMgr.Close(); + storeChangelogReader.Clear(); + Directory.Delete(config.StateDir, true); + } + + [Test] + public void RestoreComplete() + { + storeChangelogReader.Restore(); + + Assert.AreEqual(2, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(2, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RestoreFromRecovery() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + var producer = supplier.GetProducer(config.ToProducerConfig()); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key3", "value3")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key4", "value4")); + + restoreConsumer.Resume(restoreConsumer.Assignment); + + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + File.Delete(Path.Combine(config.StateDir, config.ApplicationId, "0-0", ".checkpoint")); + + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + restoreConsumer.Resume(restoreConsumer.Assignment); + + storeChangelogReader.Restore(); + + Assert.AreEqual(4, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(4, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RestoreFromScratch() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + var producer = supplier.GetProducer(config.ToProducerConfig()); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key3", "value3")); + producer.Produce(changelogTopic, CreateMessage(changelogTopic, "key4", "value4")); + + // delete state dir rocksdb + Directory.Delete(Path.Combine(config.StateDir), true); + + restoreConsumer.Resume(restoreConsumer.Assignment); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + storeChangelogReader.Restore(); + + Assert.AreEqual(4, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(4, metadata.RestoreEndOffset); + Assert.AreEqual(4, metadata.TotalRestored); + } + + [Test] + public void RestoreFromInvalidOffset() + { + storeChangelogReader.Restore(); + stateMgr.Checkpoint(); + stateMgr.Close(); + + // set an invalid offset in checkpoint file + StringBuilder sb = new StringBuilder(); + sb.AppendLine("0").AppendLine("1").AppendLine("store-changelog-topic 0 -100"); + File.WriteAllText(Path.Combine(config.StateDir, config.ApplicationId, "0-0", ".checkpoint"), sb.ToString()); + + restoreConsumer.Resume(restoreConsumer.Assignment); + store.Init(context, store); + stateMgr.InitializeOffsetsFromCheckpoint(); + + storeChangelogReader.Restore(); + + Assert.AreEqual(2, store.All().ToList().Count); + + var metadata = storeChangelogReader.GetMetadata(new TopicPartition(changelogTopic, 0)); + Assert.IsNotNull(metadata); + Assert.AreEqual(ChangelogState.COMPLETED, metadata.ChangelogState); + Assert.AreEqual(2, metadata.RestoreEndOffset); + Assert.AreEqual(2, metadata.TotalRestored); + } + + [Test] + public void RegisterFailed() + { + Assert.Throws(() => storeChangelogReader.Register(new TopicPartition("test", 0), stateMgr)); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `metadata` last assigned on line 138 could be null and is dereferenced at line 140, column 13. + +### Severity: +ERROR + +### Procedure: +Void StoreChangelogReaderTests.RestoreFromRecovery() + +### File: +test/Streamiz.Kafka.Net.Tests/Private/StoreChangelogReaderTests.cs + +### Key: +StoreChangelogReaderTests.cs|RestoreFromRecovery|NULL_DEREFERENCE + +### Node Key: +c6749c0eea2f60af0918298ee5b3577c + +### Hash: +050a879e21e946688cdd6edc9d0428dd + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0368/instruction.md b/inferredbugs-0368/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ce792a3879770a8bbf8404cb67032f534aacb62 --- /dev/null +++ b/inferredbugs-0368/instruction.md @@ -0,0 +1,330 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** DotNetCore.SKIT.FlurlHttpClient.Wechat +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +using Org.BouncyCastle.Crypto; +using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.OpenSsl; +using Org.BouncyCastle.Security; +using Org.BouncyCastle.X509; + +namespace SKIT.FlurlHttpClient.Wechat.TenpayV3.Utilities +{ + /// + /// RSA 算法工具类。 + /// + public static class RSAUtility + { + // REF: https://github.com/bcgit/bc-csharp/blob/master/crypto/src/security/CipherUtilities.cs + private const string RSA_CIPHER_ALG = "RSA/ECB/OAEPWITHSHA1ANDMGF1PADDING"; + // REF: https://github.com/bcgit/bc-csharp/blob/master/crypto/src/security/SignerUtilities.cs + private const string RSA_SIGNER_ALG = "SHA-256withRSA"; + + /// + /// 使用私钥基于 SHA-256 算法生成签名。 + /// + /// PKCS#8 私钥字节数组。 + /// 待签名的数据字节数组。 + /// 签名字节数组。 + public static byte[] SignWithSHA256(byte[] privateKeyBytes, byte[] plainBytes) + { + if (privateKeyBytes == null) throw new ArgumentNullException(nameof(privateKeyBytes)); + if (plainBytes == null) throw new ArgumentNullException(nameof(plainBytes)); + + RsaKeyParameters rsaKeyParams = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes); + return SignWithSHA256(rsaKeyParams, plainBytes); + } + + /// + /// 使用私钥基于 SHA-256 算法生成签名。 + /// + /// PKCS#8 私钥(pem 格式)。 + /// 待签名的文本数据。 + /// 经 Base64 编码的签名。 + public static string SignWithSHA256(string privateKey, string plainText) + { + if (privateKey == null) throw new ArgumentNullException(nameof(privateKey)); + if (plainText == null) throw new ArgumentNullException(nameof(plainText)); + + byte[] privateKeyBytes = ConvertPkcs8PrivateKeyToByteArray(privateKey); + byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); + byte[] signBytes = SignWithSHA256(privateKeyBytes, plainBytes); + return Convert.ToBase64String(signBytes); + } + + /// + /// 使用公钥基于 SHA-256 算法验证签名。 + /// + /// PKCS#8 公钥字节数据。 + /// 待验证的数据字节数据。 + /// 待验证的签名字节数据。 + /// 验证结果。 + public static bool VerifyWithSHA256(byte[] publicKeyBytes, byte[] plainBytes, byte[] signBytes) + { + if (publicKeyBytes == null) throw new ArgumentNullException(nameof(publicKeyBytes)); + if (plainBytes == null) throw new ArgumentNullException(nameof(plainBytes)); + if (signBytes == null) throw new ArgumentNullException(nameof(signBytes)); + + RsaKeyParameters rsaKeyParams = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes); + return VerifyWithSHA256(rsaKeyParams, plainBytes, signBytes); + } + + /// + /// 使用公钥基于 SHA-256 算法验证签名。 + /// + /// PKCS#8 公钥(pem 格式)。 + /// 待验证的文本数据。 + /// 经 Base64 编码的待验证的签名。 + /// 验证结果。 + public static bool VerifyWithSHA256(string publicKey, string plainText, string signature) + { + if (publicKey == null) throw new ArgumentNullException(nameof(publicKey)); + if (plainText == null) throw new ArgumentNullException(nameof(plainText)); + if (signature == null) throw new ArgumentNullException(nameof(signature)); + + byte[] publicKeyBytes = ConvertPkcs8PublicKeyToByteArray(publicKey); + byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); + byte[] signBytes = Convert.FromBase64String(signature); + return VerifyWithSHA256(publicKeyBytes, plainBytes, signBytes); + } + + /// + /// 使用证书基于 SHA-256 算法验证签名。 + /// + /// 证书(cer 格式)。 + /// 待验证的文本数据。 + /// 经 Base64 编码的待验证的签名。 + /// 验证结果。 + public static bool VerifyWithSHA256ByCertificate(string certificate, string plainText, string signature) + { + if (certificate == null) throw new ArgumentNullException(nameof(certificate)); + if (plainText == null) throw new ArgumentNullException(nameof(plainText)); + if (signature == null) throw new ArgumentNullException(nameof(signature)); + + RsaKeyParameters rsaKeyParams = ConvertCertificateToPublicKeyParams(certificate); + byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); + byte[] signBytes = Convert.FromBase64String(signature); + return VerifyWithSHA256(rsaKeyParams, plainBytes, signBytes); + } + + /// + /// 使用私钥基于 ECB 模式解密数据。 + /// + /// PKCS#8 私钥字节数据。 + /// 待解密的数据字节数据。 + /// 解密后的数据字节数组。 + public static byte[] DecryptWithECB(byte[] privateKeyBytes, byte[] cipherBytes) + { + if (privateKeyBytes == null) throw new ArgumentNullException(nameof(privateKeyBytes)); + if (cipherBytes == null) throw new ArgumentNullException(nameof(cipherBytes)); + + RsaKeyParameters rsaKeyParams = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privateKeyBytes); + return DecryptWithECB(rsaKeyParams, cipherBytes); + } + + /// + /// 使用私钥基于 ECB 模式解密数据。 + /// + /// PKCS#8 私钥(pem 格式)。 + /// 经 Base64 编码的待解密数据。 + /// 解密后的文本数据。 + public static string DecryptWithECB(string privateKey, string cipherText) + { + if (privateKey == null) throw new ArgumentNullException(nameof(privateKey)); + if (cipherText == null) throw new ArgumentNullException(nameof(cipherText)); + + byte[] privateKeyBytes = ConvertPkcs8PrivateKeyToByteArray(privateKey); + byte[] cipherBytes = Convert.FromBase64String(cipherText); + byte[] plainBytes = DecryptWithECB(privateKeyBytes, cipherBytes); + return Encoding.UTF8.GetString(plainBytes); + } + + /// + /// 使用公钥基于 ECB 模式加密数据。 + /// + /// PKCS#8 公钥字节数据。 + /// 待加密的数据字节数据。 + /// 加密后的数据字节数组。 + public static byte[] EncryptWithECB(byte[] publicKeyBytes, byte[] plainBytes) + { + if (publicKeyBytes == null) throw new ArgumentNullException(nameof(publicKeyBytes)); + if (plainBytes == null) throw new ArgumentNullException(nameof(plainBytes)); + + RsaKeyParameters rsaKeyParams = (RsaKeyParameters)PublicKeyFactory.CreateKey(publicKeyBytes); + return EncryptWithECB(rsaKeyParams, plainBytes); + } + + /// + /// 使用公钥基于 ECB 模式加密数据。 + /// + /// PKCS#8 公钥(pem 格式)。 + /// 待加密的文本数据。 + /// 经 Base64 编码的加密数据。 + public static string EncryptWithECB(string publicKey, string plainText) + { + if (publicKey == null) throw new ArgumentNullException(nameof(publicKey)); + if (plainText == null) throw new ArgumentNullException(nameof(plainText)); + + byte[] publicKeyBytes = ConvertPkcs8PublicKeyToByteArray(publicKey); + byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); + byte[] cipherBytes = EncryptWithECB(publicKeyBytes, plainBytes); + return Convert.ToBase64String(cipherBytes); + } + + /// + /// 使用证书基于 ECB 模式加密数据。 + /// + /// 证书(cer 格式)。 + /// 待加密的文本数据。 + /// 经 Base64 编码的加密数据。 + public static string EncryptWithECBByCertificate(string certificate, string plainText) + { + if (certificate == null) throw new ArgumentNullException(nameof(certificate)); + if (plainText == null) throw new ArgumentNullException(nameof(plainText)); + + RsaKeyParameters rsaKeyParams = ConvertCertificateToPublicKeyParams(certificate); + byte[] plainBytes = Encoding.UTF8.GetBytes(plainText); + byte[] cipherBytes = EncryptWithECB(rsaKeyParams, plainBytes); + return Convert.ToBase64String(cipherBytes); + } + + /// + /// 从 CRT/CER 证书中提取 PKCS#8 公钥。 + /// + /// 即从 -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE----- + /// 转为 -----BEGIN PUBLIC KEY----- ..... -----END PUBLIC KEY----- + /// + /// + /// 证书(cer 格式)。 + /// PKCS#8 公钥(pem 格式)。 + public static string ExportPublicKey(string certificate) + { + using (TextWriter swriter = new StringWriter()) + { + RsaKeyParameters rsaKeyParams = ConvertCertificateToPublicKeyParams(certificate); + PemWriter pemWriter = new PemWriter(swriter); + pemWriter.WriteObject(rsaKeyParams); + pemWriter.Writer.Flush(); + return swriter.ToString()!; + } + } + + private static byte[] ConvertPkcs8PrivateKeyToByteArray(string privateKey) + { + privateKey = privateKey + .Replace("-----BEGIN PRIVATE KEY-----", "") + .Replace("-----END PRIVATE KEY-----", ""); + privateKey = Regex.Replace(privateKey, "\\s+", ""); + return Convert.FromBase64String(privateKey); + } + + private static byte[] ConvertPkcs8PublicKeyToByteArray(string publicKey) + { + publicKey = publicKey + .Replace("-----BEGIN PUBLIC KEY-----", "") + .Replace("-----END PUBLIC KEY-----", ""); + publicKey = Regex.Replace(publicKey, "\\s+", ""); + return Convert.FromBase64String(publicKey); + } + + private static RsaKeyParameters ConvertCertificateToPublicKeyParams(string certificate) + { + using (TextReader sreader = new StringReader(certificate)) + { + PemReader pemReader = new PemReader(sreader); + X509Certificate cert = (X509Certificate)pemReader.ReadObject(); + return (RsaKeyParameters)cert.GetPublicKey(); + } + } + + private static byte[] SignWithSHA256(RsaKeyParameters rsaKeyParams, byte[] plainBytes) + { + ISigner signer = SignerUtilities.GetSigner(RSA_SIGNER_ALG); + signer.Init(true, rsaKeyParams); + signer.BlockUpdate(plainBytes, 0, plainBytes.Length); + return signer.GenerateSignature(); + } + + private static bool VerifyWithSHA256(RsaKeyParameters rsaKeyParams, byte[] plainBytes, byte[] signBytes) + { + ISigner signer = SignerUtilities.GetSigner(RSA_SIGNER_ALG); + signer.Init(false, rsaKeyParams); + signer.BlockUpdate(plainBytes, 0, plainBytes.Length); + return signer.VerifySignature(signBytes); + } + + private static byte[] EncryptWithECB(RsaKeyParameters rsaKeyParams, byte[] plainBytes) + { + IBufferedCipher cipher = CipherUtilities.GetCipher(RSA_CIPHER_ALG); + cipher.Init(true, rsaKeyParams); + return cipher.DoFinal(plainBytes); + } + + private static byte[] DecryptWithECB(RsaKeyParameters rsaKeyParams, byte[] cipherBytes) + { + IBufferedCipher cipher = CipherUtilities.GetCipher(RSA_CIPHER_ALG); + cipher.Init(false, rsaKeyParams); + return cipher.DoFinal(cipherBytes); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource pemReader.Org.BouncyCastle.Utilities.IO.Pem.PemReader.textBuffer of type System.IO.StreamWriter, Leaked resource pemReader.Org.BouncyCastle.Utilities.IO.Pem.PemReader.buffer of type System.IO.MemoryStream in method "RsaKeyParameters RSAUtility.ConvertCertificateToPublicKeyParams(String)". + +### Severity: +ERROR + +### Procedure: +RsaKeyParameters RSAUtility.ConvertCertificateToPublicKeyParams(String) + +### File: +src/SKIT.FlurlHttpClient.Wechat.TenpayV3/Utilities/RSAUtility.cs + +### Key: +RSAUtility.cs|ConvertCertificateToPublicKeyParams|DOTNET_RESOURCE_LEAK + +### Hash: +097c64dfdb14749aec9e91dab9fd42cb + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0369/instruction.md b/inferredbugs-0369/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1f77bb64899203680120ff6c3747d93860521ff --- /dev/null +++ b/inferredbugs-0369/instruction.md @@ -0,0 +1,315 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** html2openxml +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved + * + * This source is subject to the Microsoft Permissive License. + * Please see the License.txt file for more information. + * All other rights reserved. + * + * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A + * PARTICULAR PURPOSE. + */ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace HtmlToOpenXml +{ + using w = DocumentFormat.OpenXml.Wordprocessing; + + + /// + /// Represents the collection of attributes present in the current html tag. + /// + sealed class HtmlAttributeCollection + { + // This regex split the attributes. This line is valid and all the attributes are well discovered: + // + // RegexOptions.Singleline stands for dealing with attributes that contain newline (typically for base64 image, see issue #8) + private static Regex stripAttributesRegex = new Regex(@" +#tag and its value surrounded by "" or ' +((?\w+)=(?""|')\s*(?\#?.*?)(\k|>)) +| +# tag whereas the value is not delimited: cellspacing=0 +(?\w+)=(?\w+) +| +# single tag (with no value): contenteditable +\b(?\w+)\b", RegexOptions.IgnorePatternWhitespace| RegexOptions.Singleline); + + private static Regex stripStyleAttributesRegex = new Regex(@"(?.+?):\s*(?[^;]+);*\s*"); + + private Dictionary attributes; + + + + private HtmlAttributeCollection() + { + this.attributes = new Dictionary(); + } + + public static HtmlAttributeCollection Parse(String htmlTag) + { + HtmlAttributeCollection collection = new HtmlAttributeCollection(); + if (String.IsNullOrEmpty(htmlTag)) return collection; + + // We remove the name of the tag (due to our regex) and ensure there are at least one parameter + int startIndex; + for (startIndex = 0; startIndex < htmlTag.Length; startIndex++) + { + if (Char.IsWhiteSpace(htmlTag[startIndex])) + { + startIndex++; + break; + } + else if (htmlTag[startIndex] == '>' || htmlTag[startIndex] == '/') + { + // no attribute in this tag + return collection; + } + } + + MatchCollection matches = stripAttributesRegex.Matches(htmlTag, startIndex); + foreach (Match m in matches) + { + collection.attributes[m.Groups["tag"].Value] = m.Groups["val"].Value; + } + + return collection; + } + + public static HtmlAttributeCollection ParseStyle(String htmlTag) + { + HtmlAttributeCollection collection = new HtmlAttributeCollection(); + if (String.IsNullOrEmpty(htmlTag)) return collection; + + // Encoded ':' and ';' characters are valid for browser but not handled by the regex (bug #13812 reported by robin391) + // ex= + MatchCollection matches = stripStyleAttributesRegex.Matches(HttpUtility.HtmlDecode(htmlTag)); + foreach (Match m in matches) + collection.attributes[m.Groups["name"].Value] = m.Groups["val"].Value; + + return collection; + } + + /// + /// Gets the number of attributes for this tag. + /// + public int Count + { + get { return attributes.Count; } + } + + /// + /// Gets the named attribute. + /// + public String this[String name] + { + get + { + string value; + return attributes.TryGetValue(name, out value)? value : null; + } + } + + /// + /// Gets an attribute representing an integer. + /// + public Int32? GetAsInt(String name) + { + string attrValue = this[name]; + int val; + if (attrValue != null && Int32.TryParse(attrValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + return val; + + return null; + } + + /// + /// Gets an attribute representing a color (named color, hexadecimal or hexadecimal + /// without the preceding # character). + /// + public HtmlColor GetAsColor(String name) + { + return HtmlColor.Parse(this[name]); + } + + /// + /// Gets an attribute representing an unit: 120px, 10pt, 5em, 20%, ... + /// + /// If the attribute is misformed, the property is set to false. + public Unit GetAsUnit(String name) + { + return Unit.Parse(this[name]); + } + + /// + /// Gets an attribute representing the 4 unit sides. + /// If a side has been specified individually, it will override the grouped definition. + /// + /// If the attribute is misformed, the property is set to false. + public Margin GetAsMargin(String name) + { + Margin margin = Margin.Parse(this[name]); + Unit u; + + u = GetAsUnit(name + "-top"); + if (u.IsValid) margin.Top = u; + u = GetAsUnit(name + "-right"); + if (u.IsValid) margin.Right = u; + u = GetAsUnit(name + "-bottom"); + if (u.IsValid) margin.Bottom = u; + u = GetAsUnit(name + "-left"); + if (u.IsValid) margin.Left = u; + + return margin; + } + + /// + /// Gets an attribute representing the 4 border sides. + /// If a border style/color/width has been specified individually, it will override the grouped definition. + /// + /// If the attribute is misformed, the property is set to false. + public HtmlBorder GetAsBorder(String name) + { + HtmlBorder border = new HtmlBorder(GetAsSideBorder(name)); + SideBorder sb; + + sb = GetAsSideBorder(name + "-top"); + if (sb.IsValid) border.Top = sb; + sb = GetAsSideBorder(name + "-right"); + if (sb.IsValid) border.Right = sb; + sb = GetAsSideBorder(name + "-bottom"); + if (sb.IsValid) border.Bottom = sb; + sb = GetAsSideBorder(name + "-left"); + if (sb.IsValid) border.Left = sb; + + return border; + } + + /// + /// Gets an attribute representing a single border side. + /// If a border style/color/width has been specified individually, it will override the grouped definition. + /// + /// If the attribute is misformed, the property is set to false. + public SideBorder GetAsSideBorder(String name) + { + string attrValue = this[name]; + SideBorder border = SideBorder.Parse(attrValue); + + // handle attributes specified individually. + Unit width = SideBorder.ParseWidth(this[name + "-width"]); + if (width.IsValid) border.Width = width; + + var color = GetAsColor(name + "-color"); + if (!color.IsEmpty) border.Color = color; + + var style = ConverterUtility.ConvertToBorderStyle(this[name + "-style"]); + if (style != w.BorderValues.Nil) border.Style = style; + + return border; + } + + /// + /// Gets the class attribute that specify one or more classnames. + /// + public String[] GetAsClass() + { + string attrValue = this["class"]; + if (attrValue == null) return null; + return attrValue.Split(HttpUtility.WhiteSpaces, StringSplitOptions.RemoveEmptyEntries); + } + + /// + /// Gets the font attribute and combine with the style, size and family. + /// + public HtmlFont GetAsFont(String name) + { + HtmlFont font = HtmlFont.Parse(this[name]); + string attrValue = this[name + "-style"]; + if (attrValue != null) + { + var style = ConverterUtility.ConvertToFontStyle(attrValue); + if (style.HasValue) font.Style = style.Value; + } + attrValue = this[name + "-variant"]; + if (attrValue != null) + { + var variant = ConverterUtility.ConvertToFontVariant(attrValue); + if (variant.HasValue) font.Variant = variant.Value; + } + attrValue = this[name + "-weight"]; + if (attrValue != null) + { + var weight = ConverterUtility.ConvertToFontWeight(attrValue); + if (weight.HasValue) font.Weight = weight.Value; + } + attrValue = this[name + "-family"]; + if (attrValue != null) + { + font.Family = ConverterUtility.ConvertToFontFamily(attrValue); + } + Unit unit = this.GetAsUnit(name + "-size"); + if (unit.IsValid) font.Size = unit; + return font; + } + } +} +``` + +### Bug Type: +PULSE_UNINITIALIZED_VALUE + +### Qualifier: +`this.HtmlToOpenXml.HtmlColor.k__BackingField` is read without initialization during the call to `SideBorder.Parse(...)`. + +### Severity: +ERROR + +### Procedure: +SideBorder HtmlAttributeCollection.GetAsSideBorder(String) + +### File: +src/Html2OpenXml/Collections/HtmlAttributeCollection.cs + +### Key: +HtmlAttributeCollection.cs|GetAsSideBorder|PULSE_UNINITIALIZED_VALUE + +### Hash: +9702d83476f0d09134d4192f86efa9b9 + +### Bug Type Hum: +Uninitialized Value + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0393/instruction.md b/inferredbugs-0393/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2ee8b041027683a8358b8fabaf7ff34da0ceba2 --- /dev/null +++ b/inferredbugs-0393/instruction.md @@ -0,0 +1,119 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** openmod +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.CompilerServices; +using SDG.Unturned; + +#if NUGET_BOOTSTRAP +using OpenMod.Bootstrapper; +using OpenMod.NuGet; +#else +using System.Reflection; +using Microsoft.Extensions.Hosting; +using OpenMod.API; +#endif + + +namespace OpenMod.Unturned.Module +{ + public class OpenModInitializer + { + [MethodImpl(MethodImplOptions.NoInlining)] + public static void Initialize() + { + string openModDirectory = Path.GetFullPath($"Servers/{Dedicator.serverID}/OpenMod/"); + if (!Directory.Exists(openModDirectory)) + { + Directory.CreateDirectory(openModDirectory); + } + +#if NUGET_BOOTSTRAP + Console.WriteLine("Bootstrapping OpenMod for Unturned, this might take a while..."); + + var bootrapper = new OpenModDynamicBootstrapper(); + + bootrapper.Bootstrap( + openModDirectory, + Environment.GetCommandLineArgs(), + new List { "OpenMod.Unturned" }, + false, + new NuGetConsoleLogger()); + +#else + var hostBuilder = new HostBuilder(); + var parameters = new RuntimeInitParameters + { + CommandlineArgs = Environment.GetCommandLineArgs(), + WorkingDirectory = openModDirectory + }; + + var assemblies = new List + { + typeof(OpenMod.UnityEngine.UnityMainThreadDispatcher).Assembly, + typeof(OpenMod.Unturned.OpenModUnturnedHost).Assembly + }; + + var runtime = new Runtime.Runtime(); + runtime.Init(assemblies, hostBuilder, parameters); +#endif + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource runtime.OpenMod.Runtime.Runtime.m_HostReadyEventHandle of type System.Threading.ManualResetEvent in method "Void OpenModInitializer.Initialize()". + +### Severity: +ERROR + +### Procedure: +Void OpenModInitializer.Initialize() + +### File: +unturned/OpenMod.Unturned.Module/OpenModInitializer.cs + +### Key: +OpenModInitializer.cs|Initialize|DOTNET_RESOURCE_LEAK + +### Hash: +810c6f376fe76f379c988c9f66bc5c1b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0394/instruction.md b/inferredbugs-0394/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68aa1da26f1b0e988f0687483f27135f4807fe0e --- /dev/null +++ b/inferredbugs-0394/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ConsoleTableExt +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using ConsoleTableExt; +using System; +using System.Collections.Generic; +using System.Data; + +namespace ConsoleTableApp +{ + class Program + { + static void Main(string[] args) + { + DataTable table = new DataTable(); + table.Columns.Add(null, typeof(int)); + table.Columns.Add("Drug", typeof(string)); + table.Columns.Add("Patient", typeof(string)); + table.Columns.Add("Date", typeof(string)); + + DataRow row = table.NewRow(); + row[0] = 999; + row[1] = "y"; + row[2] = "str"; + row[3] = "x"; + + ConsoleTableBuilder + .From(GetTable()) + .WithColumn(new List {"1", null, null}) + .AddRow(null, null, "3", null, "5", "6", "7") + .AddRow(new List{ null, 1, "2" }) + .AddRow(row) + .AddRow(new List> + { + new List{"1",2,3,4}, + new List{"x", "y", 999} + }) + .WithFormat(ConsoleTableBuilderFormat.Alternative) + .WithOptions(new ConsoleTableBuilderOption {TrimColumn = true}) + .ExportAndWriteLine(); + + ConsoleTableBuilder.From(new List + { + new object[] {"1", "2", 3, null}, + new object[] {"1", null, 2}, + new object[] {"122"} + }) + .WithColumn(new List {null, "1", null}) + .AddColumn("helo") + .AddColumn("helo 1") + .AddColumn("helo 2") + .AddColumn("1","2","3","4","5") + .WithColumn("hello", "co", "ba") + .WithFormat(ConsoleTableBuilderFormat.Alternative) + .WithOptions(new ConsoleTableBuilderOption{TrimColumn = true}) + .ExportAndWrite(); + + Console.WriteLine(); + + ConsoleTableBuilder.From(new List> + { + new List {"1", 2, null, 4}, + new List {null, "luong son ba chuc", "anh dai"}, + new List {"133 f afa faf as",} + }) + .WithFormat(ConsoleTableBuilderFormat.Minimal) + .ExportAndWriteLine(); + + ConsoleTableBuilder + .From(new List {new[] {"1", null}, new[] {null, "4"}}) + .WithFormat(ConsoleTableBuilderFormat.Alternative) + .ExportAndWriteLine(); + + var builder = ConsoleTableBuilder.From(GetTable()); + builder.Export().ToString(); + builder.WithFormat(ConsoleTableBuilderFormat.Default).ExportAndWriteLine(); + builder.WithFormat(ConsoleTableBuilderFormat.Alternative).ExportAndWriteLine(); + builder.WithFormat(ConsoleTableBuilderFormat.MarkDown).ExportAndWriteLine(); + builder.WithFormat(ConsoleTableBuilderFormat.Minimal).ExportAndWriteLine(); + + Console.ReadKey(); + } + + static DataTable GetTable() + { + // Here we create a DataTable with four columns. + DataTable table = new DataTable(); + table.Columns.Add(null, typeof(int)); + table.Columns.Add("Drug", typeof(string)); + table.Columns.Add("Patient", typeof(string)); + table.Columns.Add("Date", typeof(DateTime)); + + // Here we add five DataRows. + table.Rows.Add(null, "Indocin", "David", DateTime.Now); + table.Rows.Add(50, null, "Sam", DateTime.Now); + table.Rows.Add(10, "Hydralazine", null, DateTime.Now); + table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); + table.Rows.Add(100, "Dilantin", "Melanie", null); + return table; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource table of type System.Data.DataTable, Leaked resource (returned from System.Data.DataTable ConsoleTableApp.Program::GetTable() at Line 71) of type System.Data.DataTable, Leaked resource (returned from System.Data.DataTable ConsoleTableApp.Program::GetTable() at Line 24) of type System.Data.DataTable in method "Void Program.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void Program.Main(String[]) + +### File: +Src/ConsoleTableApp/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +e34bd0593933df0dddd82bfc44c7b73b + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0419/instruction.md b/inferredbugs-0419/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4997b88bcbe2d563378ed81bed03970ef1ede5a3 --- /dev/null +++ b/inferredbugs-0419/instruction.md @@ -0,0 +1,322 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** apm-agent-dotnet +**Bug ID:** 33 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq; +using System.Threading; +using Elastic.Apm.Config; +using Elastic.Apm.Logging; +using Elastic.Apm.Tests.Mocks; +using FluentAssertions; +using Xunit; + +namespace Elastic.Apm.Tests +{ + /// + /// Tests the configuration through environment variables + /// + public class EnvVarConfigTest : IDisposable + { + [Fact] + public void ServerUrlsSimpleTest() + { + var serverUrl = "http://myServer.com:1234"; + var agent = new ApmAgent(new TestAgentComponents(serverUrls: serverUrl)); + agent.ConfigurationReader.ServerUrls[0].OriginalString.Should().Be(serverUrl); + var rootedUrl = serverUrl + "/"; + rootedUrl.Should().BeEquivalentTo(agent.ConfigurationReader.ServerUrls[0].AbsoluteUri); + } + + [Fact] + public void ServerUrlsInvalidUrlTest() + { + var serverUrl = "InvalidUrl"; + var agent = new ApmAgent(new TestAgentComponents(serverUrls: serverUrl)); + agent.ConfigurationReader.ServerUrls[0].Should().Be(ConfigConsts.DefaultServerUri); + } + + [Fact] + public void ServerUrlInvalidUrlLogTest() + { + var serverUrl = "InvalidUrl"; + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrl)); + agent.ConfigurationReader.ServerUrls[0].Should().Be(ConfigConsts.DefaultServerUri); + + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0].Should() + .StartWith($"{{{nameof(TestAgentConfigurationReader)}}}") + .And.ContainAll( + "Failed parsing server URL from", + TestAgentConfigurationReader.Origin, + ConfigConsts.ConfigKeys.Urls, + serverUrl + ); + } + + /// + /// Sets 2 servers and makes sure that they are all parsed + /// + [Fact] + public void ServerUrlsMultipleUrlsTest() + { + var serverUrl1 = "http://myServer1.com:1234"; + var serverUrl2 = "http://myServer2.com:1234"; + var serverUrls = $"{serverUrl1},{serverUrl2}"; + + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrls)); + + var parsedUrls = agent.ConfigurationReader.ServerUrls; + parsedUrls[0].OriginalString.Should().Be(serverUrl1); + parsedUrls[0].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl1}/"); + + parsedUrls[1].OriginalString.Should().Be(serverUrl2); + parsedUrls[1].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl2}/"); + } + + /// + /// Sets 3 server urls, 2 of them are valid, 1 is invalid + /// Makes sure that the 2 valid urls are parsed and there is a log line for the invalid server url + /// + [Fact] + public void ServerUrlsMultipleUrlsWith1InvalidUrlTest() + { + var serverUrl1 = "http://myServer1.com:1234"; + var serverUrl2 = "invalidUrl"; + var serverUrl3 = "http://myServer2.com:1234"; + var serverUrls = $"{serverUrl1},{serverUrl2},{serverUrl3}"; + var logger = new TestLogger(); + var agent = new ApmAgent(new TestAgentComponents(logger, serverUrls)); + + var parsedUrls = agent.ConfigurationReader.ServerUrls; + parsedUrls.Should().NotBeEmpty().And.HaveCount(2, "seeded 3 but one was invalid"); + parsedUrls[0].OriginalString.Should().Be(serverUrl1); + parsedUrls[0].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl1}/"); + + parsedUrls[1].OriginalString.Should().Be(serverUrl3); + parsedUrls[1].AbsoluteUri.Should().BeEquivalentTo($"{serverUrl3}/"); + + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0].Should() + .StartWith($"{{{nameof(TestAgentConfigurationReader)}}}") + .And.ContainAll( + "Failed parsing server URL from", + TestAgentConfigurationReader.Origin, + ConfigConsts.ConfigKeys.Urls, + serverUrl2 + ); + } + + [Fact] + public void SecretTokenSimpleTest() + { + var secretToken = "secretToken"; + var agent = new ApmAgent(new TestAgentComponents(secretToken: secretToken)); + agent.ConfigurationReader.SecretToken.Should().Be(secretToken); + } + + [Fact] + public void DefaultLogLevelTest() => Agent.Config.LogLevel.Should().Be(LogLevel.Error); + + [Fact] + public void SetDebugLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Debug")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Debug); + } + + [Fact] + public void SetErrorLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Error")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Error); + } + + [Fact] + public void SetInfoLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Information")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Information); + } + + [Fact] + public void SetWarningLogLevelTest() + { + var agent = new ApmAgent(new TestAgentComponents("Warning")); + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Warning); + } + + [Fact] + public void SetInvalidLogLevelTest() + { + var logLevelValue = "InvalidLogLevel"; + var agent = new ApmAgent(new TestAgentComponents(logLevelValue)); + var logger = agent.Logger as TestLogger; + + agent.ConfigurationReader.LogLevel.Should().Be(LogLevel.Error); + logger.Lines.Should().NotBeEmpty(); + logger.Lines[0].Should() + .StartWith($"{{{nameof(TestAgentConfigurationReader)}}}") + .And.ContainAll( + "Failed parsing log level from", + TestAgentConfigurationReader.Origin, + ConfigConsts.ConfigKeys.Level, + "Defaulting to " + ); + } + + /// + /// The server doesn't accept services with '.' in it. + /// This test makes sure we don't have '.' in the default service name. + /// + [Fact] + public void DefaultServiceNameTest() + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + //By default XUnit uses 'testhost' as the entry assembly, and that is what the + //agent reports if we don't set it to anything: + var serviceName = payloadSender.Payloads[0].Service.Name; + serviceName.Should().NotBeNullOrWhiteSpace(); + serviceName.Should().NotContain("."); + } + + /// + /// Sets the ELASTIC_APM_SERVICE_NAME environment variable and makes sure that + /// when the agent sends data to the server it has the value from the + /// ELASTIC_APM_SERVICE_NAME environment variable as service name. + /// + [Fact] + public void ReadServiceNameViaEnvironmentVariable() + { + var serviceName = "MyService123"; + Environment.SetEnvironmentVariable(ConfigConsts.ConfigKeys.ServiceName, serviceName); + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + payloadSender.Payloads[0].Service.Name.Should().Be(serviceName); + } + + /// + /// Sets the ELASTIC_APM_SERVICE_NAME environment variable to a value that contains a '.' + /// Makes sure that when the agent sends data to the server it has the value from the + /// ELASTIC_APM_SERVICE_NAME environment variable as service name and also makes sure that + /// the '.' is replaced. + /// + [Fact] + public void ReadServiceNameWithDotViaEnvironmentVariable() + { + var serviceName = "My.Service.Test"; + Environment.SetEnvironmentVariable(ConfigConsts.ConfigKeys.ServiceName, serviceName); + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new AgentComponents(payloadSender: payloadSender)); + agent.Tracer.CaptureTransaction("TestTransactionName", "TestTransactionType", t => { Thread.Sleep(2); }); + + + payloadSender.Payloads[0].Service.Name.Should().Be(serviceName.Replace('.', '_')); + payloadSender.Payloads[0].Service.Name.Should().NotContain("."); + } + + /// + /// In case the user does not provide us a service name we try to calculate it based on the callstack. + /// This test makes sure we recognize mscorlib and our own assemblies correctly in the + /// method. + /// + [Fact] + public void TestAbstractConfigurationReaderIsMsOrElastic() + { + var elasticToken = new byte[] { 174, 116, 0, 210, 193, 137, 207, 34 }; + var mscorlibToken = new byte[] { 183, 122, 92, 86, 25, 52, 224, 137 }; + + AbstractConfigurationReader.IsMsOrElastic(elasticToken).Should().BeTrue(); + + AbstractConfigurationReader.IsMsOrElastic(new byte[] { 0 }).Should().BeFalse(); + AbstractConfigurationReader.IsMsOrElastic(new byte[] { }).Should().BeFalse(); + + AbstractConfigurationReader + .IsMsOrElastic(new[] + { + elasticToken[0], mscorlibToken[1], elasticToken[2], + mscorlibToken[3], elasticToken[4], mscorlibToken[5], elasticToken[6], mscorlibToken[7] + }).Should().BeFalse(); + } + + /// + /// Makes sure that the logs + /// in case it reads an invalid URL. + /// + [Fact] + public void LoggerNotNull() + { + Environment.SetEnvironmentVariable(ConfigConsts.ConfigKeys.Urls, "localhost"); //invalid, it should be "http://localhost" + var testLogger = new TestLogger(); + var config = new EnvironmentConfigurationReader(testLogger); + var serverUrl = config.ServerUrls.FirstOrDefault(); + + serverUrl.Should().NotBeNull(); + testLogger.Lines.Should().NotBeEmpty(); + } + + public void Dispose() => Environment.SetEnvironmentVariable(ConfigConsts.ConfigKeys.Urls, null); + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource agent of type Elastic.Apm.ApmAgent in method "Void EnvVarConfigTest.ServerUrlInvalidUrlLogTest()". + +### Severity: +ERROR + +### Procedure: +Void EnvVarConfigTest.ServerUrlInvalidUrlLogTest() + +### File: +test/Elastic.Apm.Tests/ConfigTest.cs + +### Key: +ConfigTest.cs|ServerUrlInvalidUrlLogTest|DOTNET_RESOURCE_LEAK + +### Hash: +3025b8845c05fdb80fa2d1a9eedb27e5 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0421/instruction.md b/inferredbugs-0421/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc79aaa0565680cab8ab0d94f6182cefc57240cd --- /dev/null +++ b/inferredbugs-0421/instruction.md @@ -0,0 +1,625 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** apm-agent-dotnet +**Bug ID:** 18 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Threading; +using System.Threading.Tasks; +using Elastic.Apm.Api; +using Elastic.Apm.Model.Payload; +using Elastic.Apm.Tests.Mocks; +using Xunit; + +namespace Elastic.Apm.Tests.ApiTests +{ + /// + /// Tests the API for manual instrumentation. + /// Only tests scenarios when using the convenient API and only test transactions. + /// Spans are covered by . + /// Scenarios with manually calling , + /// , + /// are covered by + /// Very similar to . The test cases are the same, + /// but this one tests the CaptureTransaction method - including every single overload. + /// + public class ConvenientApiTransactionTests + { + private const string ExceptionMessage = "Foo"; + private const int SleepLength = 450; + private const string TransactionName = "ConvenientApiTest"; + private const string TransactionType = "Test"; + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent. + /// + [Fact] + public void SimpleAction() => AssertWith1Transaction(agent => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + () => { Thread.Sleep(SleepLength); }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) that throws an exception into the CaptureTransaction method + /// and it makes sure that the transaction and the exception are captured by the agent. + /// + [Fact] + public void SimpleActionWithException() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, new Action(() => + { + Thread.Sleep(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + })); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the parameter + /// is not null + /// + [Fact] + public void SimpleActionWithParameter() => AssertWith1Transaction(agent => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) that throws an exception into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction and the error are captured by the agent and the + /// parameter is not null + /// + [Fact] + public void SimpleActionWithExceptionAndParameter() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + agent.Tracer.CaptureTransaction(TransactionName, TransactionType, new Action(t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + })); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) with a return value into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent and the return value is correct. + /// + [Fact] + public void SimpleActionWithReturnType() => AssertWith1Transaction(agent => + { + var res = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, () => + { + Thread.Sleep(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method. + /// It wraps a fake transaction (Thread.Sleep) with a return value into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public void SimpleActionWithReturnTypeAndParameter() => AssertWith1Transaction(agent => + { + var res = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake transaction (Thread.Sleep) with a return value that throws an exception into the CaptureTransaction + /// method with an parameter + /// and it makes sure that the transaction and the error are captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public void SimpleActionWithReturnTypeAndExceptionAndParameter() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + var result = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, t => + { + Assert.NotNull(t); + Thread.Sleep(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake transaction (Thread.Sleep) with a return value that throws an exception into the CaptureTransaction + /// method + /// and it makes sure that the transaction and the error are captured by the agent. + /// + [Fact] + public void SimpleActionWithReturnTypeAndException() => AssertWith1TransactionAnd1Error(agent => + { + Assert.Throws(() => + { + var result = agent.Tracer.CaptureTransaction(TransactionName, TransactionType, () => + { + Thread.Sleep(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) into the CaptureTransaction method + /// and it makes sure that the transaction is captured. + /// + [Fact] + public async Task AsyncTask() => await AssertWith1TransactionAsync(async agent => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async () => { await Task.Delay(SleepLength); }); + }); + + /// + /// Tests the method with an exception + /// It wraps a fake async transaction (Task.Delay) that throws an exception into the CaptureTransaction method + /// and it makes sure that the transaction and the error are captured. + /// + [Fact] + public async Task AsyncTaskWithException() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured and the parameter is not null. + /// + [Fact] + public async Task AsyncTaskWithParameter() => await AssertWith1TransactionAsync(async agent => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + }); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake async transaction (Task.Delay) that throws an exception into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction and the error are captured and the parameter + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithExceptionAndParameter() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) with a return value into the CaptureTransaction method + /// and it makes sure that the transaction is captured by the agent and the return value is correct. + /// + [Fact] + public async Task AsyncTaskWithReturnType() => await AssertWith1TransactionAsync(async agent => + { + var res = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + return 42; + }); + Assert.Equal(42, res); + }); + + /// + /// Tests the method. + /// It wraps a fake async transaction (Task.Delay) with a return value into the CaptureTransaction method with an + /// parameter + /// and it makes sure that the transaction is captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndParameter() => await AssertWith1TransactionAsync(async agent => + { + var res = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + return 42; + }); + + Assert.Equal(42, res); + }); + + /// + /// Tests the method with an + /// exception. + /// It wraps a fake async transaction (Task.Delay) with a return value that throws an exception into the CaptureTransaction + /// method with an parameter + /// and it makes sure that the transaction and the error are captured by the agent and the return value is correct and the + /// is not null. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndExceptionAndParameter() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + var result = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async t => + { + Assert.NotNull(t); + await Task.Delay(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Tests the method with an exception. + /// It wraps a fake async transaction (Task.Delay) with a return value that throws an exception into the CaptureTransaction + /// method + /// and it makes sure that the transaction and the error are captured by the agent. + /// + [Fact] + public async Task AsyncTaskWithReturnTypeAndException() => await AssertWith1TransactionAnd1ErrorAsync(async agent => + { + await Assert.ThrowsAsync(async () => + { + var result = await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, async () => + { + await Task.Delay(SleepLength); + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + + return 42; + }); + + Assert.True(false); //Should not be executed because the agent isn't allowed to catch an exception. + Assert.Equal(42, result); //But if it'd not throw it'd be 42. + }); + }); + + /// + /// Wraps a cancelled task into the CaptureTransaction method and + /// makes sure that the cancelled task is captured by the agent. + /// + [Fact] + public async Task CancelledAsyncTask() + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + var cancellationTokenSource = new CancellationTokenSource(); + var token = cancellationTokenSource.Token; + cancellationTokenSource.Cancel(); + + await Assert.ThrowsAsync(async () => + { + await agent.Tracer.CaptureTransaction(TransactionName, TransactionType, + async () => + { + // ReSharper disable once MethodSupportsCancellation, we want to delay before we throw the exception + await Task.Delay(SleepLength); + token.ThrowIfCancellationRequested(); + }); + }); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + Assert.True(payloadSender.Payloads[0].Transactions[0].Duration >= SleepLength); + + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal("A task was canceled", payloadSender.Errors[0].Errors[0].Culprit); + Assert.Equal("Task canceled", payloadSender.Errors[0].Errors[0].Exception.Message); + } + + /// + /// Creates a custom transaction and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public void TagsOnTransaction() + { + var payloadSender = AssertWith1Transaction( + t => + { + t.Tracer.CaptureTransaction(TransactionName, TransactionType, transaction => + { + Thread.Sleep(SleepLength); + transaction.Tags["foo"] = "bar"; + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Creates a custom async transaction and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public async Task TagsOnTransactionAsync() + { + var payloadSender = await AssertWith1TransactionAsync( + async t => + { + await t.Tracer.CaptureTransaction(TransactionName, TransactionType, async transaction => + { + await Task.Delay(SleepLength); + transaction.Tags["foo"] = "bar"; + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Creates a custom async Transaction that ends with an error and adds a tag to it. + /// Makes sure that the tag is stored on Transaction.Context. + /// + [Fact] + public async Task TagsOnTransactionAsyncError() + { + var payloadSender = await AssertWith1TransactionAnd1ErrorAsync( + async t => + { + await Assert.ThrowsAsync(async () => + { + await t.Tracer.CaptureTransaction(TransactionName, TransactionType, async transaction => + { + await Task.Delay(SleepLength); + transaction.Tags["foo"] = "bar"; + + if (new Random().Next(1) == 0) //avoid unreachable code warning. + throw new InvalidOperationException(ExceptionMessage); + }); + }); + }); + + //According to the Intake API tags are stored on the Context (and not on Transaction.Tags directly). + Assert.Equal("bar", payloadSender.FirstTransaction.Context.Tags["foo"]); + + //Also make sure the tag is visible directly on Transaction.Tags. + Assert.Equal("bar", payloadSender.Payloads[0].Transactions[0].Tags["foo"]); + } + + /// + /// Asserts on 1 transaction with async code + /// + private async Task AssertWith1TransactionAsync(Func func) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + await func(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + var duration = payloadSender.FirstTransaction.Duration; + Assert.True(duration >= SleepLength, $"Expected {duration} to be greater or equal to: {SleepLength}"); + return payloadSender; + } + + /// + /// Asserts on 1 async transaction and 1 error + /// + private async Task AssertWith1TransactionAnd1ErrorAsync(Func func) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + await func(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= SleepLength, $"Expected {duration} to be greater or equal to: {SleepLength}"); + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal(typeof(InvalidOperationException).FullName, payloadSender.Errors[0].Errors[0].Exception.Type); + Assert.Equal(ExceptionMessage, payloadSender.Errors[0].Errors[0].Exception.Message); + return payloadSender; + } + + /// + /// Asserts on 1 transaction + /// + private MockPayloadSender AssertWith1Transaction(Action action) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + action(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + var duration = payloadSender.Payloads[0].Transactions[0].Duration; + Assert.True(duration >= SleepLength, $"Expected {duration} to be greater or equal to: {SleepLength}"); + + return payloadSender; + } + + /// + /// Asserts on 1 transaction and 1 error + /// + private void AssertWith1TransactionAnd1Error(Action action) + { + var payloadSender = new MockPayloadSender(); + var agent = new ApmAgent(new TestAgentComponents(payloadSender: payloadSender)); + + action(agent); + + Assert.NotEmpty(payloadSender.Payloads); + Assert.NotEmpty(payloadSender.Payloads[0].Transactions); + + Assert.Equal(TransactionName, payloadSender.Payloads[0].Transactions[0].Name); + Assert.Equal(TransactionType, payloadSender.Payloads[0].Transactions[0].Type); + + Assert.True(payloadSender.Payloads[0].Transactions[0].Duration >= SleepLength); + + + Assert.NotEmpty(payloadSender.Errors); + Assert.NotEmpty(payloadSender.Errors[0].Errors); + + Assert.Equal(typeof(InvalidOperationException).FullName, payloadSender.Errors[0].Errors[0].Exception.Type); + Assert.Equal(ExceptionMessage, payloadSender.Errors[0].Errors[0].Exception.Message); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource agent of type Elastic.Apm.ApmAgent, Leaked resource (output of Elastic.Apm.Tests.Mocks.TestAgentComponents::.ctor() at Line 524) of type Elastic.Apm.AgentComponents in method "MockPayloadSender ConvenientApiTransactionTests.AssertWith1Transaction(Action`1)". + +### Severity: +ERROR + +### Procedure: +MockPayloadSender ConvenientApiTransactionTests.AssertWith1Transaction(Action`1) + +### File: +test/Elastic.Apm.Tests/ApiTests/ConvenientApiTransactionTests.cs + +### Key: +ConvenientApiTransactionTests.cs|AssertWith1Transaction|DOTNET_RESOURCE_LEAK + +### Hash: +90850b0928d21b123521ccec4af878e1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0500/instruction.md b/inferredbugs-0500/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c51384122b45f7f8f7c273739d0afc2cef57b44 --- /dev/null +++ b/inferredbugs-0500/instruction.md @@ -0,0 +1,300 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** speckle-sharp +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Data.SQLite; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Timers; + +namespace Speckle.Transports +{ + // TODO: Investigate partitioning the object tables by the first two hash charaters. + public class SqlLiteObjectTransport : IDisposable, ITransport + { + public string TransportName { get; set; } = "LocalTransport"; + + public string RootPath { get; set; } + public string ConnectionString { get; set; } + + private SQLiteConnection Connection { get; set; } + + private Dictionary Buffer = new Dictionary(); + private System.Timers.Timer WriteTimer; + private int TotalElapsed = 0, PollInterval = 100; + private bool IsWriting = false; + + private int MAX_BUFFER_SIZE = 5000000; // 5 mb + private int CURR_BUFFER_SIZE = 0; + + public SqlLiteObjectTransport(string basePath = null, string applicationName = "Speckle", string scope = "Objects") + { + if (basePath == null) + basePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + + RootPath = Path.Combine(basePath, applicationName, $"{scope}.db"); + ConnectionString = $@"URI=file:{RootPath};"; + + InitializeTables(); + + WriteTimer = new System.Timers.Timer() { AutoReset = true, Enabled = false, Interval = PollInterval }; + WriteTimer.Elapsed += WriteTimerElapsed; + } + + private void InitializeTables() + { + + // NOTE: used for creating partioned object tables. + //string[] HexChars = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" }; + //var cart = new List(); + //foreach (var str in HexChars) + // foreach (var str2 in HexChars) + // cart.Add(str + str2); + + Connection = new SQLiteConnection(ConnectionString); + Connection.Open(); + using (var command = new SQLiteCommand(Connection)) + { + command.CommandText = @" + CREATE TABLE IF NOT EXISTS objects( + hash TEXT PRIMARY KEY, + content TEXT + ) WITHOUT ROWID; + "; + command.ExecuteNonQuery(); + } + + // Insert Optimisations + + SQLiteCommand cmd; + cmd = new SQLiteCommand("PRAGMA journal_mode=MEMORY;", Connection); + cmd.ExecuteNonQuery(); + + cmd = new SQLiteCommand("PRAGMA synchronous=OFF;", Connection); + cmd.ExecuteNonQuery(); + + cmd = new SQLiteCommand("PRAGMA count_changes=OFF;", Connection); + cmd.ExecuteNonQuery(); + + cmd = new SQLiteCommand("PRAGMA temp_store=MEMORY;", Connection); + cmd.ExecuteNonQuery(); + } + + #region Writes + + public async Task WriteComplete() + { + await Utilities.WaitUntil(() => { return CURR_BUFFER_SIZE == 0; }, 100); + } + + private void WriteTimerElapsed(object sender, ElapsedEventArgs e) + { + TotalElapsed += PollInterval; + if (TotalElapsed > 500) + { + TotalElapsed = 0; + WriteTimer.Enabled = false; + WriteBuffer(); + } + } + + private void WriteBuffer() + { + lock (Buffer) + { + if (Buffer.Count == 0) return; + IsWriting = true; + using (var t = Connection.BeginTransaction()) + { + using (var command = new SQLiteCommand(Connection)) + { + command.CommandText = $"INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; + foreach (var kvp in Buffer) + { + command.Parameters.AddWithValue("@hash", kvp.Key); + command.Parameters.AddWithValue("@content", Utilities.CompressString(kvp.Value)); + command.ExecuteNonQuery(); + } + } + t.Commit(); + } + Buffer.Clear(); + TotalElapsed = 0; + CURR_BUFFER_SIZE = 0; + IsWriting = false; + } + } + + /// + /// Adds the object into a buffer that will be written to the db later. + /// + /// + /// + /// + public void SaveObject(string hash, string serializedObject, bool owerite = false) + { + CURR_BUFFER_SIZE += System.Text.Encoding.UTF8.GetByteCount(serializedObject); + + lock (Buffer) + { + Buffer.Add(hash, serializedObject); + } + + if (CURR_BUFFER_SIZE > MAX_BUFFER_SIZE) + { + WriteBuffer(); + } + else + { + WriteTimer.Enabled = true; + WriteTimer.Start(); + } + } + + /// + /// Directly saves the object in the db. + /// + /// + /// + public void SaveObjectSync(string hash, string serializedObject) + { + using (var command = new SQLiteCommand(Connection)) + { + command.CommandText = $"INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; + command.Parameters.AddWithValue("@hash", hash); + command.Parameters.AddWithValue("@content", Utilities.CompressString(serializedObject)); + command.ExecuteNonQuery(); + } + } + + /// + /// Directly saves the objects into the db. + /// + /// + /// + public async Task SaveObjects(IEnumerable<(string, string)> objects) + { + using (var t = Connection.BeginTransaction()) + { + using (var command = new SQLiteCommand(Connection)) + { + foreach (var (hash, content) in objects) + { + command.CommandText = $"INSERT OR IGNORE INTO objects(hash, content) VALUES(@hash, @content)"; + command.Parameters.AddWithValue("@hash", hash); + command.Parameters.AddWithValue("@content", Utilities.CompressString(content)); + command.ExecuteNonQuery(); + } + } + await t.CommitAsync(); + return; + } + } + + #endregion + + #region Reads + + public string GetObject(string hash) + { + using (var command = new SQLiteCommand(Connection)) + { + command.CommandText = "SELECT * FROM objects WHERE hash = @hash LIMIT 1 "; + command.Parameters.AddWithValue("@hash", hash); + var reader = command.ExecuteReader(); + while (reader.Read()) + { + return Utilities.DecompressString(reader.GetString(1)); + + } + throw new Exception("No object found"); + } + } + + public IEnumerable GetObjects(IEnumerable hashes) + { + //using (var command = new SQLiteCommand(Connection)) + //{ + // command.CommandText = "SELECT * FROM objects WHERE hash = @hash LIMIT 1 "; + // command.Parameters.AddWithValue("@hash", hash); + // var reader = command.ExecuteReader(); + // while (reader.Read()) + // { + // yield return Utilities.DecompressString(reader.GetString(1)); + // } + // throw new Exception("No object found"); + //} + throw new NotImplementedException(); + } + + #endregion + + public void Dispose() + { + lock (Buffer) // wait for a lock on the buffer, in case the timer is now executing + { + Connection.Close(); + Connection.Dispose(); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource cmd of type System.Data.SQLite.SQLiteCommand, Leaked resource (output of System.Data.SQLite.SQLiteConnection::.ctor() at Line 54) of type System.Data.SQLite.SQLiteConnection in method "Void SqlLiteObjectTransport.InitializeTables()". + +### Severity: +ERROR + +### Procedure: +Void SqlLiteObjectTransport.InitializeTables() + +### File: +Speckle/Transports/SQLiteTransport.cs + +### Key: +SQLiteTransport.cs|InitializeTables|DOTNET_RESOURCE_LEAK + +### Hash: +f475e5e92468b34ec35a6e5936c697e1 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0507/instruction.md b/inferredbugs-0507/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d79db6d33b7e7b2c25c2e84c64149937adbb737 --- /dev/null +++ b/inferredbugs-0507/instruction.md @@ -0,0 +1,956 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** R2API +**Bug ID:** 5 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using Mono.Cecil.Cil; +using MonoMod.Utils; + +namespace R2API.Utils { + public static class Reflection { + + private const BindingFlags AllFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | + BindingFlags.Instance | BindingFlags.DeclaredOnly; + + private delegate T GetDelegate(object instance); + + private delegate void SetDelegate(object instance, T value); + + //private delegate object CallDelegate(object instance, object[] arguments); + + private delegate void SetDelegateRef(ref TInstance instance, TValue value) where TInstance : struct; + + private delegate T GetDelegateRef(ref TInstance instance) where TInstance : struct; + + #region Caches + + // Field + private static readonly ConcurrentDictionary<(Type T, string name), FieldInfo> FieldCache = + new ConcurrentDictionary<(Type T, string name), FieldInfo>(); + + private static readonly ConcurrentDictionary FieldGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary FieldSetDelegateCache = + new ConcurrentDictionary(); + + + // Property + private static readonly ConcurrentDictionary<(Type T, string name), PropertyInfo> PropertyCache = + new ConcurrentDictionary<(Type T, string name), PropertyInfo>(); + + private static readonly ConcurrentDictionary PropertyGetDelegateCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary PropertySetDelegateCache = + new ConcurrentDictionary(); + + + // Method + private static readonly ConcurrentDictionary<(Type T, string name), MethodInfo> MethodCache = + new ConcurrentDictionary<(Type T, string name), MethodInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo> + OverloadedMethodCache = + new ConcurrentDictionary<(Type T, string name, Type[] argumentTypes), MethodInfo>(); + + private static readonly ConcurrentDictionary DelegateCache = + new ConcurrentDictionary(); + + + // Class + private static readonly ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo> ConstructorCache = + new ConcurrentDictionary<(Type T, Type[] argumentTypes), ConstructorInfo>(); + + private static readonly ConcurrentDictionary<(Type T, string name), Type> NestedTypeCache = + new ConcurrentDictionary<(Type T, string name), Type>(); + + + // Helper methods + private static TValue GetOrAddOnNull(this ConcurrentDictionary dict, TKey key, + Func factory) { + if (dict.TryGetValue(key, out var val) && val != null) + return val; + + return dict[key] = factory(key); + } + + #endregion + + #region Field + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(string name) => + typeof(T).GetFieldCached(name); + + /// + /// Gets the of the type by name and caches it + /// + /// The type to search + /// The name of the field to find + /// + public static FieldInfo GetFieldCached(this Type T, string name) => + FieldCache.GetOrAddOnNull((T, name), x => x.T.GetFieldFull(x.name) + ?? throw new Exception($"Could not find {nameof(FieldInfo)} on {T.FullName} with the name {name}")); + + + /// + /// Gets the value of the field on the object + /// + /// The type of the return value + /// The name of the field to get the value of + /// The object to get the field's value from + /// + public static TReturn GetFieldValue(this object instance, string fieldName) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (instance); + + /// + /// Gets the value of the specified static field on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static field's value on + /// + public static TReturn GetFieldValue(this Type staticType, string fieldName) => + staticType + .GetFieldCached(fieldName) + .GetFieldGetDelegate() + (null); + + /// + /// Sets the value of the specified field on the specified object; if the object is a struct use + /// instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set + /// + public static void SetFieldValue(this object instance, string fieldName, TValue value) => + instance.GetType() + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (instance, value); + + /// + /// Sets the value of the specified static field on the specified static type + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static field's value on + /// The value to set + /// + public static void SetFieldValue(this Type staticType, string fieldName, TValue value) => + staticType + .GetFieldCached(fieldName) + .GetFieldSetDelegate() + (null, value); + + /// + /// Sets the value of the specified field on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified field's value on + /// The value to set the field to + /// + public static void SetStructFieldValue(this ref TInstance instance, string fieldName, TValue value) + where TInstance : struct => + typeof(TInstance) + .GetFieldCached(fieldName) + .GetFieldSetDelegateRef() + (ref instance, value); + + + /// + /// Gets the on the specified and searches base types if not found. + /// + /// The to search and get base types from + /// The name of the property to search for. + /// + private static FieldInfo GetFieldFull(this Type T, string name) { + while (T != null) { + var fieldInfo = T.GetField(name, AllFlags); + if (fieldInfo != null) { + return fieldInfo; + } + + T = T.BaseType; + } + + return null; + } + + private static T GetMemberFull(this Type type, string name) where T : MemberInfo { + while (type != null) { + var fieldInfo = type.GetMember(name, AllFlags); + if (fieldInfo != null) { + return (T)fieldInfo.First(); + } + + type = type.BaseType; + } + + return null; + } + + private static GetDelegate GetFieldGetDelegate(this FieldInfo field) => + FieldGetDelegateCache.GetOrAdd(field, x => x.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetFieldSetDelegate(this FieldInfo field) => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetFieldSetDelegateRef(this FieldInfo field) where TInstance : struct => + FieldSetDelegateCache.GetOrAdd(field, x => x.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Property + + /// + /// Gets the of the type by name + /// + /// The type on which to find the property + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(string name) => + typeof(T).GetPropertyCached(name); + + /// + /// Gets the of the type by name + /// + /// The type to get the from + /// The name of the property to get + /// + public static PropertyInfo GetPropertyCached(this Type T, string name) => + PropertyCache.GetOrAddOnNull((T, name), x => x.T.GetProperty(x.name, AllFlags)); + + /// + /// Gets the value of the property on the specified object; if the object is a struct use + /// instead + /// + /// The type of the return value + /// The object to get the property's value from + /// The name of the field to get the value of + /// + public static TReturn GetPropertyValue(this object instance, string propName) => + instance.GetType() + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (instance); + + /// + /// Gets the value of the static property on the specified static type + /// + /// The return type + /// The name of the static field to get the value of + /// The type to get the specified static property's value on + /// + public static TReturn GetPropertyValue(this Type staticType, string propName) => + staticType + .GetPropertyCached(propName) + .GetPropertyGetDelegate() + (null); + + /// + /// Sets the value of the property on the specified class; if you're setting the property on a + /// struct use instead + /// + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set + /// + public static void SetPropertyValue(this object instance, string propName, TValue value) => + instance.GetType() + .GetPropertyCached(propName)? + .GetPropertySetDelegate() + (instance, value); + + /// + /// Sets the value of the static property on the specified static class + /// + /// The type of the value to set + /// The name of the static field to set the value of + /// The type to set the specified static property's value on + /// The value to set the property to + /// + public static void SetPropertyValue(this Type staticType, string propName, TValue value) => + staticType.GetPropertyCached(propName)? + .GetPropertySetDelegate() + (null, value); + + /// + /// Sets the value of the specified property on the specified struct + /// + /// The type of the instance of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// The value to set the property to + /// + public static void SetStructPropertyValue(this ref TInstance instance, string propName, + TValue value) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertySetDelegateRef() + (ref instance, value); + + /// + /// Gets the value of the specified property on the specified struct + /// + /// The type of the struct + /// The type of the value to set + /// The name of the field to set the value of + /// The type to set the specified property's value on + /// + public static TValue GetStructPropertyValue(this ref TInstance instance, string propName) + where TInstance : struct => + typeof(TInstance) + .GetPropertyCached(propName) + .GetPropertyGetDelegateRef() + (ref instance); + + private static GetDelegate GetPropertyGetDelegate(this PropertyInfo property) => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static GetDelegateRef GetPropertyGetDelegateRef(this PropertyInfo property) + where TInstance : struct => + PropertyGetDelegateCache.GetOrAdd(property, prop => prop.CreateGetDelegate()) + .CastDelegate>(); + + private static SetDelegate GetPropertySetDelegate(this PropertyInfo property) => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegate()) + .CastDelegate>(); + + private static SetDelegateRef GetPropertySetDelegateRef( + this PropertyInfo property) + where TInstance : struct => + PropertySetDelegateCache.GetOrAdd(property, prop => prop.CreateSetDelegateRef()) + .CastDelegate>(); + + #endregion + + #region Method + + /// + /// Gets the method on the specified type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(string name) => + typeof(T).GetMethodCached(name); + + /// + /// Gets the method on the specified static type and caches it + /// + /// The type to search + /// The name of the method to find + /// + public static MethodInfo GetMethodCached(this Type T, string name) => + MethodCache.GetOrAddOnNull((T, name), x => x.T.GetMethod(x.name, AllFlags) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name}")); + + /// + /// Gets the method on the specified type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + /// + public static MethodInfo GetMethodCached(string name, Type[] argumentTypes) => + typeof(T).GetMethodCached(name, argumentTypes); + + /// + /// Gets the method on the specified static type and caches it. This overload is used when the method is ambiguous + /// + /// The type to search + /// The name of the method to find + /// The types of the argument + public static MethodInfo GetMethodCached(this Type T, string name, Type[] argumentTypes) => + OverloadedMethodCache.GetOrAddOnNull((T, name, argumentTypes), + x => x.T.GetMethod(x.name, AllFlags, null, x.argumentTypes, null) + ?? throw new Exception($"Could not find {nameof(MethodInfo)} on {T.FullName} with the name {name} and arguments: " + + $"{string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Invoke a method on the specified object by name + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName, null); + + /// + /// Invoke a static method on the specified type by name + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// + public static TReturn InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName, null); + + /// + /// Invoke a method on the specified object by name + /// + /// The object to invoke the method on + /// The name of the method to invoke + public static void InvokeMethod(this object instance, string methodName) => + instance.InvokeMethod(methodName); + + /// + /// Invoke a static method on the specified type by name + /// + /// The static type to search + /// The name of the method to invoke + public static void InvokeMethod(this Type staticType, string methodName) => + staticType.InvokeMethod(methodName); + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The return type of the method + /// The object to invoke the method on + /// The name of the method to invoke + /// + /// + public static TReturn InvokeMethod(this object instance, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? instance.GetType() + .GetMethodCached(methodName) + : instance.GetType() + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray()) + ) ?? throw new Exception($"Could not find method on type {instance.GetType()} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(instance, methodParams); + } + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The return type of the method + /// The static type to search + /// The name of the method to invoke + /// The method parameters + /// + public static TReturn InvokeMethod(this Type staticType, string methodName, + params object[] methodParams) { + var methodInfo = (methodParams == null + ? staticType + .GetMethodCached(methodName) + : staticType + .GetMethodCached(methodName, methodParams.Select(x => x.GetType()).ToArray())) + ?? throw new Exception($"Could not find method on type {staticType} with the name of {methodName} with the arguments specified."); + + return (TReturn)methodInfo.GetMethodDelegateCached()(null, methodParams); + } + + /// + /// Invoke a method on the specified object by name with parameters + /// + /// The object to invoke the method on + /// The name of the method to invoke + /// + public static void InvokeMethod(this object instance, string methodName, params object[] methodParams) => + instance.InvokeMethod(methodName, methodParams); + + /// + /// Invoke a static method on the specified type by name with parameters + /// + /// The static type to search + /// The name of the method to invoke + /// + public static void InvokeMethod(this Type staticType, string methodName, params object[] methodParams) => + staticType.InvokeMethod(methodName, methodParams); + + + private static FastReflectionDelegate GetMethodDelegateCached(this MethodInfo methodInfo) => + DelegateCache.GetOrAdd(methodInfo, method => method.CreateFastDelegate()); + + #endregion + + #region Class + + /// + /// Gets the constructor on the specified type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(Type[] argumentTypes) => + GetConstructorCached(typeof(T), argumentTypes); + + /// + /// Gets the constructor on the specified static type with specified arguments and caches it + /// + /// The type to search + /// The types of the arguments on the constructor to find + /// + public static ConstructorInfo GetConstructorCached(this Type T, Type[] argumentTypes) => + ConstructorCache.GetOrAddOnNull((T, argumentTypes), x => x.T.GetConstructor(x.argumentTypes) + ?? throw new Exception($"Could not find {nameof(ConstructorInfo)} on {T.FullName} with the arguments {string.Join(",", argumentTypes.Select(a => a.FullName))}")); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedType(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified type + /// + /// The type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(string name) => + typeof(T).GetNestedTypeCached(name); + + /// + /// Gets the nested type on the specified static type + /// + /// The static type to search + /// The name of the nested type to find + /// + public static Type GetNestedTypeCached(this Type T, string name) => + NestedTypeCache.GetOrAddOnNull((T, name), x => x.T.GetNestedType(x.name, AllFlags) + ?? throw new Exception($"Could not find nested {nameof(Type)} on {T.FullName} with the name {name}")); + + /// + /// Instatiates the specified type + /// + /// The type to instantiate + /// + public static object Instantiate(this Type type) => + Activator.CreateInstance(type, true); + + /// + /// Instatiates the specified type with specified constructor arguments + /// + /// The type to instantiate + /// The constructor arguments + /// + public static object Instantiate(this Type type, params object[] constructorArguments) => + type.GetConstructorCached(constructorArguments.Select(x => x.GetType()).ToArray()) + .Invoke(constructorArguments); + + /// + /// Instantiates the specified generic type + /// + /// The type to instantiate + /// The type of the generic type argument + /// + public static object InstantiateGeneric(this Type typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates the specified generic types + /// + /// The type to instantiate + /// The types of the generic type arguments + /// + public static object InstantiateGeneric(this Type[] typeArgument) => + typeof(TClass).MakeGenericType(typeArgument).Instantiate(); + + /// + /// Instantiates a list of the specified generic type + /// + /// + /// + public static IList InstantiateList(this Type type) => + (IList)typeof(List<>).MakeGenericType(type).Instantiate(); + + #endregion + + #region Fast Reflection + + private static GetDelegate CreateGetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!typeof(TReturn).IsAssignableFrom(field.FieldType)) { + throw new Exception($"Field type {field.FieldType} does not match the requested type {typeof(TReturn)}."); + } + + + var method = new DynamicMethodDefinition($"{field} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + if (field.DeclaringType.GetTypeInfo().IsValueType) { + il.Emit(OpCodes.Unbox_Any, field.DeclaringType); + } + } + + il.Emit(!field.IsStatic ? OpCodes.Ldfld : OpCodes.Ldsfld, field); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static SetDelegate CreateSetDelegate(this FieldInfo field) { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (!field.FieldType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this FieldInfo field) where TInstance : struct { + if (field == null) { + throw new ArgumentException("Field cannot be null.", nameof(field)); + } + + if (field.FieldType != typeof(TValue)) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {field.FieldType}."); + } + + var method = new DynamicMethodDefinition($"{field} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + if (!field.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(!field.IsStatic ? OpCodes.Stfld : OpCodes.Stsfld, field); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + private static GetDelegate CreateGetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(object) }); + var il = method.GetILProcessor(); + + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegate)method.Generate().CreateDelegate(typeof(GetDelegate)); + } + + private static GetDelegateRef CreateGetDelegate(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!typeof(TReturn).IsAssignableFrom(property.PropertyType)) { + throw new Exception($"Field type {property.PropertyType} does not match the requested type {typeof(TReturn)}."); + } + + var method = new DynamicMethodDefinition($"{property} Getter", typeof(TReturn), new[] { typeof(TInstance).MakeByRefType() }); + var il = method.GetILProcessor(); + + // Cache this as well? + var getMethod = property.GetGetMethod(nonPublic: true); + + if (!getMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Call, getMethod); + il.Emit(OpCodes.Ret); + + return (GetDelegateRef)method.Generate().CreateDelegate(typeof(GetDelegateRef)); + } + + + private static SetDelegate CreateSetDelegate(this PropertyInfo property) { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} Setter", typeof(void), + new[] { typeof(object), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegate)method.Generate().CreateDelegate(typeof(SetDelegate)); + } + + private static SetDelegateRef CreateSetDelegateRef(this PropertyInfo property) where TInstance : struct { + if (property == null) { + throw new ArgumentException("Property cannot be null.", nameof(property)); + } + + if (!property.PropertyType.IsAssignableFrom(typeof(TValue))) { + throw new Exception($"Value type type {typeof(TValue)} does not match the requested type {property.PropertyType}."); + } + + var method = new DynamicMethodDefinition($"{property} SetterByRef", typeof(void), + new[] { typeof(TInstance).MakeByRefType(), typeof(TValue) }); + var il = method.GetILProcessor(); + + var setMethod = property.GetSetMethod(true); + + if (!setMethod.IsStatic) { + il.Emit(OpCodes.Ldarg_0); + } + + il.Emit(OpCodes.Ldarg_1); + il.Emit(OpCodes.Call, setMethod); + il.Emit(OpCodes.Ret); + + return (SetDelegateRef)method.Generate().CreateDelegate(typeof(SetDelegateRef)); + } + + // Partial hack from https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + // to get fast call delegates + //private static CallDelegate GenerateCallDelegate(this MethodInfo method) { + // if (method == null) { + // throw new ArgumentException("Method cannot be null.", nameof(method)); + // } + + // var dmd = new DynamicMethodDefinition( + // $"CallDelegate<{method.Name}>", typeof(object), new[] { typeof(object), typeof(object[]) }); + // var il = dmd.GetILProcessor(); + + // var args = method.GetParameters(); + + // if (!method.IsStatic) { + // il.Emit(OpCodes.Ldarg_0); + // if (method.DeclaringType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Unbox_Any, method.DeclaringType); + // } + // } + + // for (var i = 0; i < args.Length; i++) { + // var argType = args[i].ParameterType; + // var argIsByRef = argType.IsByRef; + // if (argIsByRef) + // argType = argType.GetElementType(); + // var argIsValueType = argType.GetTypeInfo().IsValueType; + + // if (argIsByRef && argIsValueType) { + // // Used later when storing back the reference to the new box in the array. + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + // } + + // il.Emit(OpCodes.Ldarg_1); + // il.EmitFast_Ldc_I4(i); + + // if (argIsByRef && !argIsValueType) { + // il.Emit(OpCodes.Ldelema, typeof(object)); + // } + // else { + // il.Emit(OpCodes.Ldelem_Ref); + // if (!argIsValueType) continue; + // il.Emit(!argIsByRef ? OpCodes.Unbox_Any : OpCodes.Unbox, argType); + // } + // } + + // if (method.IsFinal || !method.IsVirtual) { + // il.Emit(OpCodes.Call, method); + // } + // else { + // il.Emit(OpCodes.Callvirt, method); + // } + + // var returnType = method.IsConstructor ? method.DeclaringType : method.ReturnType; + // if (returnType != typeof(void)) { + // if (returnType.GetTypeInfo().IsValueType) { + // il.Emit(OpCodes.Box, returnType); + // } + // } + // else { + // il.Emit(OpCodes.Ldnull); + // } + + // il.Emit(OpCodes.Ret); + + // return (CallDelegate) dmd.Generate().CreateDelegate(typeof(CallDelegate)); + //} + + // https://github.com/0x0ade/MonoMod/blob/master/MonoMod.Utils/FastReflectionHelper.cs + public static void EmitFast_Ldc_I4(this ILProcessor il, int value) { + switch (value) { + case -1: + il.Emit(OpCodes.Ldc_I4_M1); + return; + case 0: + il.Emit(OpCodes.Ldc_I4_0); + return; + case 1: + il.Emit(OpCodes.Ldc_I4_1); + return; + case 2: + il.Emit(OpCodes.Ldc_I4_2); + return; + case 3: + il.Emit(OpCodes.Ldc_I4_3); + return; + case 4: + il.Emit(OpCodes.Ldc_I4_4); + return; + case 5: + il.Emit(OpCodes.Ldc_I4_5); + return; + case 6: + il.Emit(OpCodes.Ldc_I4_6); + return; + case 7: + il.Emit(OpCodes.Ldc_I4_7); + return; + case 8: + il.Emit(OpCodes.Ldc_I4_8); + return; + } + + if (value > -129 && value < 128) + il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); + else + il.Emit(OpCodes.Ldc_I4, value); + } + + public static byte ReadLocalIndex(OpCode opCode, object operand) { + if (opCode == OpCodes.Ldloc_0 || opCode == OpCodes.Stloc_0) { + return 0; + } + if (opCode == OpCodes.Ldloc_1 || opCode == OpCodes.Stloc_1) { + return 1; + } + if (opCode == OpCodes.Ldloc_2 || opCode == OpCodes.Stloc_2) { + return 2; + } + if (opCode == OpCodes.Ldloc_3 || opCode == OpCodes.Stloc_3) { + return 3; + } + if (opCode == OpCodes.Ldloc_S || opCode == OpCodes.Stloc_S) { + return (byte)operand; + } + + throw new Exception($"Could not read index for opcode and operand: {opCode} - {operand}"); + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource method of type MonoMod.Utils.DynamicMethodDefinition in method "Reflection$SetDelegateRef`2 Reflection.CreateSetDelegateRef(FieldInfo)". + +### Severity: +ERROR + +### Procedure: +Reflection$SetDelegateRef`2 Reflection.CreateSetDelegateRef(FieldInfo) + +### File: +R2API/Utils/Reflection.cs + +### Key: +Reflection.cs|CreateSetDelegateRef|DOTNET_RESOURCE_LEAK + +### Hash: +7d013c8b9d63c2c37da5e5eea60a4e48 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0509/instruction.md b/inferredbugs-0509/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b563e68a981eab9cfc11eadf5381fb4ac18486b3 --- /dev/null +++ b/inferredbugs-0509/instruction.md @@ -0,0 +1,181 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Mongo2Go +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Diagnostics; +using System.Globalization; +using System.Threading; + +namespace Mongo2Go.Helper +{ + public class MongoDbProcess : IMongoDbProcess + { + private const string ProcessReadyIdentifier = "waiting for connections"; + private Process _process; + + public bool Disposed { get; private set; } + + internal MongoDbProcess(Process process) + { + _process = process; + } + + public IMongoDbProcess Start(string binariesDirectory, string dataDirectory, int port) + { + string fileName = @"{0}\{1}".Formatted(binariesDirectory, MongoDbDefaults.MongodExecutable); + string arguments = @"--dbpath ""{0}"" --port {1} --nohttpinterface --nojournal".Formatted(dataDirectory, port); + + ProcessStartInfo startInfo = new ProcessStartInfo + { + FileName = fileName, + Arguments = arguments, + //CreateNoWindow = true, + UseShellExecute = false, + RedirectStandardOutput = true, + }; + + Process process = new Process { StartInfo = startInfo }; + + StartAndBlockUntilReady(process, 5); + + return new MongoDbProcess(process); + } + + /// + /// Reads from Output stream to determine if MongoDB is ready + /// + private static void StartAndBlockUntilReady(Process process, int timeoutInSeconds) + { + bool processReady = false; + process.OutputDataReceived += (sender, args) => + { + if (!string.IsNullOrEmpty(args.Data) && + args.Data.Contains(ProcessReadyIdentifier)) + { + processReady = true; + } + }; + + process.Start(); + process.BeginOutputReadLine(); + + int lastResortCounter = 0; + int timeOut = timeoutInSeconds*10; + while (!processReady) + { + Thread.Sleep(100); + if (++lastResortCounter > timeOut) + { + // we waited X seconds. + // for any reason the detection did not worked, eg. the identifier changed + // lets assume everything is still ok + break; + } + } + + process.CancelOutputRead(); + } + + #region IDisposable and friends + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (Disposed) { return; } + if (disposing) + { + // we have no "managed resources" - but we leave this switch to avoid an FxCop CA1801 warnig + } + Kill(); + + // wait a bit to be sure + Thread.Sleep(500); + + Disposed = true; + } + + ~MongoDbProcess() + { + Dispose(false); + } + + private void Kill() + { + if (_process == null) + { + return; + } + + if (!_process.HasExited) + { + _process.Kill(); + } + + _process.Dispose(); + _process = null; + } + + #endregion + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource process of type System.Diagnostics.Process, Leaked resource return of type Mongo2Go.Helper.MongoDbProcess in method "IMongoDbProcess MongoDbProcess.Start(String,String,Int32)". + +### Severity: +ERROR + +### Procedure: +IMongoDbProcess MongoDbProcess.Start(String,String,Int32) + +### File: +Mongo2Go/Mongo2Go/Helper/MongoDbProcess.cs + +### Key: +MongoDbProcess.cs|Start|DOTNET_RESOURCE_LEAK + +### Hash: +4cd426fe69612e9962db815d7feacfba + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0531/instruction.md b/inferredbugs-0531/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27625bf6d149cce75bf94c209ccc7b23b47728fd --- /dev/null +++ b/inferredbugs-0531/instruction.md @@ -0,0 +1,191 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** MIMS +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using MIMS.Entity.Model; +using System; +using System.Collections.Generic; +using System.Collections; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Dapper; +using MIMS.Entity.Dtos; + +namespace MIMS.Service +{ + public class PSS_InWarehouseDetailDAL + { + + #region init dbconnection + private static readonly string connString = ConfigurationManager.ConnectionStrings["PharmacySystem"].ConnectionString; + private IDbConnection _conn; + public IDbConnection Conn + { + get + { + _conn = new SqlConnection(connString); + _conn.Open(); + return _conn; + } + } + #endregion + + /// + /// 获取一个list的数据 + /// + /// + public IList GetList(Dictionary prams, string where = null) + { + using (Conn) + { + string query = "SELECT * FROM PSS_InWarehouseDetail WHERE 1=1 "; + if (!string.IsNullOrEmpty(where)) + query += where; + return Conn.Query(query, prams).ToList(); + } + + } + /// + /// 分页获取数据列表(带条件) + /// + /// 条件 + /// 排序字段 + /// 参数 + /// 排序类型 + /// 当前页 + /// 页大小 + /// 总条数 + /// + public IList GetPageListWhere(StringBuilder where, Dictionary prams, string orderField, string orderType, int pageIndex, int pageSize, ref int count) + { + int num = (pageIndex - 1) * pageSize; + int num1 = pageIndex * pageSize; + using (Conn) + { + StringBuilder strSql = new StringBuilder(); + StringBuilder sql = new StringBuilder(); + sql.Append(@"SELECT * FROM (SELECT I.*, + B.PinyinCode, + A.Stock, + B.PhaName, + B.Spec, + B.Unit, + O.OrginName, + C.CompanyName + FROM PSS_InWarehouseDetail I + LEFT JOIN PHA_Accounts A ON I.PhaCode = A.PhaCode AND I.OrginID = A.OrginID + LEFT JOIN PHA_BaseInfo B ON I.PhaCode = B.PhaCode + LEFT JOIN PHA_Orgin O ON I.OrginID = O.OrginID + LEFT JOIN PSS_PurchaseCompany C ON A.CompanyID = C.CompanyID) A WHERE 1=1 "); + sql.Append(where); + strSql.Append("Select * From (Select ROW_NUMBER() Over (Order By " + orderField + " " + orderType + ""); + strSql.Append(") As rowNum, * From (" + sql + ") As T ) As N Where rowNum > " + num + " And rowNum <= " + num1 + ""); + count = Conn.Query("Select Count(1) From (" + sql + ") As t", prams).Single(); + return Conn.Query(strSql.ToString(), prams).ToList(); + } + } + + /// + /// 根据主键值获得一个对象 + /// + /// + /// + public PSS_InWarehouseDetail GetEntity(string id) + { + using (Conn) + { + string query = "SELECT * FROM PSS_InWarehouseDetail WHERE ID=@ID"; + return Conn.Query(query, new { ID = id }).SingleOrDefault(); + } + } + + // public int Update(PSS_InWarehouseDetail obj) + // { + // using (Conn) + // { + // string query = @"UPDATE PSS_InWarehouseDetail + // SET PurchaseNo=@PurchaseNo,PurchaseDate=@PurchaseDate, + // Remark=@Remark,OperateNo=@OperateNo,OperateDate=@OperateDate,PurchaseStatus=@PurchaseStatus + // WHERE PurchaseNo =@PurchaseNo"; + // return Conn.Execute(query, obj); + // } + // } + public int Insert(PSS_InWarehouseDetail obj) + { + obj.InWarehouseSum = obj.InWarehousePrice * obj.InWarehouseCount; + using (Conn) + { + string query = @"INSERT INTO PSS_InWarehouseDetail + VALUES(@IWID,@IWWay,@PhaCode,@OrginID,@PhaNo,@PhaExpiry,@InWarehouseCount,@InWarehousePrice,@InWarehouseSum)"; + return Conn.Execute(query, obj); + } + } + public int Delete(PSS_InWarehouseDetail obj) + { + using (Conn) + { + string query = @"DELETE FROM PSS_InWarehouseDetail WHERE ID = @ID"; + return Conn.Execute(query, obj); + } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Data.IDbConnection MIMS.Service.PSS_InWarehouseDetailDAL::get_Conn() at Line 44) of type System.Data.SqlClient.SqlConnection in method "IList PSS_InWarehouseDetailDAL.GetList(Dictionary`2,String)". + +### Severity: +ERROR + +### Procedure: +IList PSS_InWarehouseDetailDAL.GetList(Dictionary`2,String) + +### File: +MIMS.Service/PSS_InWarehouseDetailDAL.cs + +### Key: +PSS_InWarehouseDetailDAL.cs|GetList|DOTNET_RESOURCE_LEAK + +### Hash: +7d124964dbdbb29a4ac576286d6b90c3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0536/instruction.md b/inferredbugs-0536/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6f69e49ef0a40b91fad9f4535efc180138adae4 --- /dev/null +++ b/inferredbugs-0536/instruction.md @@ -0,0 +1,217 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** USharp +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace UnrealEngine.Runtime +{ + public partial class CodeGenerator + { + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module, StructInfo structInfo) + { + AppendAttribute(builder, field, module); + //if (field.IsA() && structInfo.StructAsClass) + //{ + // builder.AppendLine("[" + Names.UStructAsClassAttributeShort + "]"); + //} + } + + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module) + { + AppendAttribute(builder, field, module, false); + } + + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module, bool isCollapsedMember) + { + UnrealModuleType moduleType; + UnrealModuleType moduleAssetType; + string moduleName = GetModuleName(field, out moduleType, out moduleAssetType); + if (string.IsNullOrEmpty(moduleName)) + { + moduleName = module.Name; + } + + List attributes = new List(); + + // TODO: Combine all of this into EPropertyType (add some TypeCode into UField?) + bool isInterface = false; + UEnum unrealEnum = field as UEnum; + UClass unrealClass = field as UClass; + UScriptStruct unrealStruct = field as UScriptStruct; + + UFunction unrealFunction = field as UFunction; + if (unrealFunction != null) + { + if (unrealFunction.HasAnyFunctionFlags(EFunctionFlags.Delegate)) + { + attributes.Add("UDelegate"); + } + else + { + string additionalFunctionInfo = string.Empty; + if (unrealFunction.GetName().StartsWith("K2_") && unrealFunction.GetOwnerClass().HasAnyClassFlags(EClassFlags.Native)) + { + additionalFunctionInfo = ", K2=true"; + } + + if (isCollapsedMember) + { + // The Flags here might not contain too useful information if there is both a get/set function. + // Maybe include a second flags var? + attributes.Add("UFunctionAsProp(Flags=0x" + ((uint)unrealFunction.FunctionFlags).ToString("X8") + additionalFunctionInfo + ")"); + } + else + { + attributes.Add("UFunction(Flags=0x" + ((uint)unrealFunction.FunctionFlags).ToString("X8") + additionalFunctionInfo + ")"); + } + } + } + + UProperty unrealProperty = field as UProperty; + if (unrealProperty != null) + { + attributes.Add("UProperty(Flags=(PropFlags)0x" + ((ulong)unrealProperty.PropertyFlags).ToString("X16") + ")"); + } + + if (unrealStruct != null) + { + attributes.Add("UStruct(Flags=0x" + ((uint)unrealStruct.StructFlags).ToString("X8") + ")"); + } + else if (unrealClass != null) + { + // Abstract isn't really required but might help with code browsing to know what is abstract + // and what isn't. Therefore put it at the start of the attributes list. + if (unrealClass.HasAnyClassFlags(EClassFlags.Abstract)) + { + attributes.Add("Abstract"); + } + + isInterface = unrealClass.IsChildOf(); + if (isInterface) + { + attributes.Add("UInterface(Flags=0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + ")"); + } + else + { + // Should we skip "inherit" config name? + string configNameStr = string.Empty; + if (unrealClass.ClassConfigName != FName.None && + !unrealClass.ClassConfigName.ToString().Equals("inherit", StringComparison.InvariantCultureIgnoreCase)) + { + configNameStr = ", Config=\"" + unrealClass.ClassConfigName + "\""; + } + + attributes.Add("UClass(Flags=(ClassFlags)0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + + configNameStr + ")"); + } + } + + if (unrealEnum != null) + { + attributes.Add("UEnum"); + } + + if (unrealEnum != null || unrealClass != null || unrealStruct != null) + { + bool blueprintType = false; + bool blueprintable = false; + if (unrealEnum != null) + { + blueprintType = field.GetBoolMetaData(MDClass.BlueprintType); + } + else + { + GetBlueprintability(field as UStruct, out blueprintType, out blueprintable); + } + if (blueprintType) + { + attributes.Add(UMeta.GetKey(MDClass.BlueprintType)); + } + if (unrealClass != null && blueprintable) + { + attributes.Add(UMeta.GetKey(MDClass.Blueprintable)); + } + + if (isInterface) + { + } + + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\", \"" + moduleName + + "\", UnrealModuleType." + GetUnrealModuleTypeString(moduleType, moduleAssetType) + + (isInterface ? ", InterfaceImpl=typeof(" + GetTypeName(unrealClass, null) + "Impl" + ")" : string.Empty) + ")"); + + } + else + { + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\")"); + } + + if (attributes.Count > 0) + { + builder.AppendLine("[" + string.Join(", ", attributes) + "]"); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `null` is dereferenced by call to `GetPathName(...)` at line 130, column 17. + +### Severity: +ERROR + +### Procedure: +Void CodeGenerator.AppendAttribute(CSharpTextBuilder,UField,CodeGenerator$UnrealModuleInfo,Boolean) + +### File: +Managed/UnrealEngine.Runtime/UnrealEngine.Runtime/Internal/CodeGenerator/CodeGenerator.Attributes.cs + +### Key: +CodeGenerator.Attributes.cs|AppendAttribute|NULL_DEREFERENCE + +### Node Key: +3a2147135192b9867938f06f06ce66ee + +### Hash: +c698cc1f6c94a76b74ab8dfce284dd93 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0538/instruction.md b/inferredbugs-0538/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24f7e41e7f25013640b8490ecb332fb0917c2974 --- /dev/null +++ b/inferredbugs-0538/instruction.md @@ -0,0 +1,190 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** USharp +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace UnrealEngine.Runtime +{ + public partial class CodeGenerator + { + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module, StructInfo structInfo) + { + AppendAttribute(builder, field, module); + //if (field.IsA() && structInfo.StructAsClass) + //{ + // builder.AppendLine("[" + Names.UStructAsClassAttributeShort + "]"); + //} + } + + private void AppendAttribute(CSharpTextBuilder builder, UField field, UnrealModuleInfo module) + { + UnrealModuleType moduleType; + UnrealModuleType moduleAssetType; + string moduleName = GetModuleName(field, out moduleType, out moduleAssetType); + if (string.IsNullOrEmpty(moduleName)) + { + moduleName = module.Name; + } + + List attributes = new List(); + + // TODO: Combine all of this into EPropertyType (add some TypeCode into UField?) + bool isInterface = false; + UEnum unrealEnum = field as UEnum; + UClass unrealClass = field as UClass; + UScriptStruct unrealStruct = field as UScriptStruct; + + UFunction unrealFunction = field as UFunction; + if (unrealFunction != null) + { + attributes.Add("UFunction(Flags=0x" + ((uint)unrealFunction.FunctionFlags).ToString("X8") + ")"); + } + + UProperty unrealProperty = field as UProperty; + if (unrealProperty != null) + { + attributes.Add("UProperty(Flags=(PropFlags)0x" + ((ulong)unrealProperty.PropertyFlags).ToString("X16") + ")"); + } + + if (unrealStruct != null) + { + attributes.Add("UStruct(Flags=0x" + ((uint)unrealStruct.StructFlags).ToString("X8") + ")"); + } + else if (unrealClass != null) + { + // Abstract isn't really required but might help with code browsing to know what is abstract + // and what isn't. Therefore put it at the start of the attributes list. + if (unrealClass.HasAnyClassFlags(EClassFlags.Abstract)) + { + attributes.Add("Abstract"); + } + + isInterface = unrealClass.IsChildOf(); + if (isInterface) + { + attributes.Add("UInterface(Flags=0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + ")"); + } + else + { + // Should we skip "inherit" config name? + string configNameStr = string.Empty; + if (unrealClass.ClassConfigName != FName.None && + !unrealClass.ClassConfigName.ToString().Equals("inherit", StringComparison.InvariantCultureIgnoreCase)) + { + configNameStr = ", Config=\"" + unrealClass.ClassConfigName + "\""; + } + + attributes.Add("UClass(Flags=(ClassFlags)0x" + ((uint)unrealClass.ClassFlags).ToString("X8") + + configNameStr + ")"); + } + } + + if (unrealEnum != null) + { + attributes.Add("UEnum"); + } + + if (unrealEnum != null || unrealClass != null || unrealStruct != null) + { + bool blueprintType = false; + bool blueprintable = false; + if (unrealEnum != null) + { + blueprintType = field.GetBoolMetaData(MDClass.BlueprintType); + } + else + { + GetBlueprintability(field as UStruct, out blueprintType, out blueprintable); + } + if (blueprintType) + { + attributes.Add(UMeta.GetKey(MDClass.BlueprintType)); + } + if (blueprintable) + { + attributes.Add(UMeta.GetKey(MDClass.Blueprintable)); + } + + if (isInterface) + { + } + + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\", \"" + moduleName + + "\", UnrealModuleType." + GetUnrealModuleTypeString(moduleType, moduleAssetType) + + (isInterface ? ", InterfaceImpl=typeof(" + GetTypeName(unrealClass) + "Impl" + ")" : string.Empty) + ")"); + + } + else + { + attributes.Add("UMetaPath(\"" + field.GetPathName() + "\")"); + } + + if (attributes.Count > 0) + { + builder.AppendLine("[" + string.Join(", ", attributes) + "]"); + } + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `null` is dereferenced by call to `GetPathName(...)` at line 130, column 17. + +### Severity: +ERROR + +### Procedure: +Void CodeGenerator.AppendAttribute(CSharpTextBuilder,UField,CodeGenerator$UnrealModuleInfo,Boolean) + +### File: +Managed/UnrealEngine.Runtime/UnrealEngine.Runtime/Internal/CodeGenerator/CodeGenerator.Attributes.cs + +### Key: +CodeGenerator.Attributes.cs|AppendAttribute|NULL_DEREFERENCE + +### Node Key: +3a2147135192b9867938f06f06ce66ee + +### Hash: +c698cc1f6c94a76b74ab8dfce284dd93 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0552/instruction.md b/inferredbugs-0552/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2c5b93eb4362affc80a7711f039b681a49ad461 --- /dev/null +++ b/inferredbugs-0552/instruction.md @@ -0,0 +1,629 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 20 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Data; +using System.Linq.Expressions; +using System.Collections.Generic; + +namespace TZM.XFramework.Data +{ + /// + /// 选择列表达式解析器 + /// + public class ColumnExpressionVisitor : ExpressionVisitorBase + { + private static IDictionary _statisMethods = null; + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + private IDbQueryableInfo_Select _qQuery = null; + private DbExpression _groupBy = null; + private List _include = null; + + private ColumnCollection _pickColumns = null; + private NavigationCollection _navigations = null; + private List _navChainHopper = null; + private int _startLength = 0; + private string _pickColumnText = null; + + /// + /// 选中字段,Column 对应实体的原始属性 + /// + public ColumnCollection PickColumns + { + get { return _pickColumns; } + } + + /// + /// 选中字段的文本,给 Contains 表达式用 + /// + public string PickColumnText + { + get + { + if (_pickColumnText == null) + { + int count = _builder.Length - _startLength; + if (count > 0) + { + char[] chars = new char[count]; + _builder.CopyTo(_startLength, chars, 0, count); + _pickColumnText = new String(chars); + } + } + + return _pickColumnText; + } + } + + /// + /// 导航属性描述信息 + /// + /// 从 到实体的映射需要使用这些信息来给导航属性赋值 + /// + /// + public NavigationCollection Navigations + { + get { return _navigations; } + } + + static ColumnExpressionVisitor() + { + _statisMethods = new Dictionary + { + { DbExpressionType.Count,"COUNT" }, + { DbExpressionType.Max,"MAX" }, + { DbExpressionType.Min,"MIN" }, + { DbExpressionType.Average,"AVG" }, + { DbExpressionType.Sum,"SUM" } + }; + } + + /// + /// 初始化 类的新实例 + /// + public ColumnExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, IDbQueryableInfo_Select qQuery) + : base(provider, aliases, qQuery.SelectExpression.Expressions != null ? qQuery.SelectExpression.Expressions[0] : null) + { + _provider = provider; + _aliases = aliases; + _qQuery = qQuery; + _groupBy = qQuery.GroupByExpression; + _include = qQuery.Includes; + + if (_pickColumns == null) _pickColumns = new ColumnCollection(); + _navigations = new NavigationCollection(); + _navChainHopper = new List(10); + } + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + public override void Write(ISqlBuilder builder) + { + if (base.Expression != null) + { + base._builder = builder; + _builder.AppendNewLine(); + _startLength = _builder.Length; + if (base._methodVisitor == null) base._methodVisitor = _provider.CreateMethodVisitor(this); + + // SELECT 表达式解析 + if (base.Expression.NodeType != ExpressionType.Constant) base.Write(builder); + else + { + // if have no select syntax + Type type = (base.Expression as ConstantExpression).Value as Type; + this.VisitAllMember(type, "t0"); + } + // Include 表达式解析<导航属性> + this.VisitInclude(); + // 去掉空白字符 + _builder.TrimEnd(' ', ','); + } + } + + // p=>p p=>p.t p=>p.Id + protected override Expression VisitLambda(Expression node) + { + LambdaExpression lambda = node as LambdaExpression; + if (lambda.Body.NodeType == ExpressionType.Parameter) + { + // 例: a=> a + Type type = lambda.Body.Type; + string alias = _aliases.GetTableAlias(lambda); + this.VisitAllMember(type, alias); + return node; + } + else if (lambda.Body.CanEvaluate()) + { + // 例:a=>1 + base.Visit(lambda.Body.Evaluate()); + + // 选择字段 + string newName = _pickColumns.Add(Constant.CONSTANTNAME); + // 添加字段别名 + _builder.AppendAs(newName); + return node; + } + else if (lambda.Body.NodeType == ExpressionType.MemberAccess) + { + // 例: t=> t.a + // => SELECT a.ClientId + Type type = lambda.Body.Type; + if (!TypeUtils.IsPrimitiveType(type)) return this.VisitAllMember(type, _aliases.GetTableAlias(lambda.Body), node); + else + { + var newNode = this.VisitWithoutRemark(x => base.VisitLambda(node)); + string newName = _pickColumns.Add((lambda.Body as MemberExpression).Member.Name); + return newNode; + } + } + else + { + return base.VisitLambda(node); + } + } + + // => new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + {// 如果有一对多的导航属性会产生嵌套的SQL,这时需要强制主表选择的列里面必须包含导航外键 + // TODO #对 Bindings 进行排序,保证导航属性的赋值一定要最后面# + // 未实现,在书写表达式时人工保证 ## + + if (node.NewExpression != null) this.VisitNewImpl(node.NewExpression); + if (_navChainHopper.Count == 0) _navChainHopper.Add(node.Type.Name); + + for (int i = 0; i < node.Bindings.Count; i++) + { + MemberAssignment binding = node.Bindings[i] as MemberAssignment; + if (binding == null) throw new XFrameworkException("Only 'MemberAssignment' binding supported."); + + Type propertyType = (node.Bindings[i].Member as System.Reflection.PropertyInfo).PropertyType; + bool isNavigation = !TypeUtils.IsPrimitiveType(propertyType); + + #region 一般属性 + + // 非导航属性 + if (!isNavigation) + { + if (binding.Expression.CanEvaluate()) + _builder.Append(binding.Expression.Evaluate().Value, binding.Member, node.Type); + else + this.VisitWithoutRemark(x => this.VisitMemberBinding(binding)); + + // 选择字段 + string newName = _pickColumns.Add(binding.Member.Name); + // 添加字段别名 + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + #endregion 一般属性 + + #region 导航属性 + + else + { + // 非显式指定的导航属性需要有 ForeignKeyAttribute + if (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable()) + { + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(binding.Member.DeclaringType); + var attribute = typeRuntime.GetInvokerAttribute(binding.Member.Name); + if (attribute == null) throw new XFrameworkException("Complex property {{{0}}} must mark 'ForeignKeyAttribute' ", binding.Member.Name); + } + + // 生成导航属性描述集合,以类名.属性名做为键值 + int n = _navChainHopper.Count; + string keyName = _navChainHopper.Count > 0 ? _navChainHopper[_navChainHopper.Count - 1] : string.Empty; + keyName = !string.IsNullOrEmpty(keyName) ? keyName + "." + binding.Member.Name : binding.Member.Name; + Navigation nav = new Navigation(keyName, binding.Member); + if (!_navigations.ContainsKey(keyName)) + { + // fix issue# XC 列占一个位 + nav.Start = _pickColumns.Count; + nav.FieldCount = GetFieldCount(binding.Expression) + (binding.Expression.NodeType == ExpressionType.MemberAccess && binding.Expression.Acceptable() ? 1 : 0); + _navigations.Add(keyName, nav); + _navChainHopper.Add(keyName); + } + + // 1.不显式指定导航属性,例:a.Client.ClientList + // 2.表达式里显式指定导航属性,例:b + if (binding.Expression.NodeType == ExpressionType.MemberAccess) this.VisitNavigation(binding.Expression as MemberExpression, binding.Expression.Acceptable()); + else if (binding.Expression.NodeType == ExpressionType.New) this.VisitNewImpl(binding.Expression as NewExpression); + else if (binding.Expression.NodeType == ExpressionType.MemberInit) this.VisitMemberInit(binding.Expression as MemberInitExpression); + + // 恢复访问链 + // 在访问导航属性时可能是 Client.CloudServer,这时要恢复为 Client,以保证能访问 Client 的下一个导航属性 + if (_navChainHopper.Count != n) _navChainHopper.RemoveAt(_navChainHopper.Count - 1); + } + + #endregion 导航属性 + } + + return node; + } + + // => Client = a.Client.CloudServer + private Expression VisitNavigation(MemberExpression node, bool visitNavigation) + { + string alias = string.Empty; + Type type = node.Type; + + if (node.Acceptable()) + { + // 例: Client = a.Client.CloudServer + // fix issue# Join 表达式显式指定导航属性时时,alias 为空 + // fix issue# 多个导航属性时 AppendNullColumn 只解析当前表达式的 + int index = 0; + int num = this.NavMembers != null ? this.NavMembers.Count : 0; + alias = this.VisitNavMember(node); + + if (num != this.NavMembers.Count) + { + foreach (var kvp in NavMembers) + { + index += 1; + if (index < NavMembers.Count && index > num) alias = _aliases.GetNavigationTableAlias(kvp.Key); + else + { + alias = _aliases.GetNavigationTableAlias(kvp.Key); + type = kvp.Value.Type; + } + } + } + else + { + } + } + else + { + // 例: Client = b + alias = _aliases.GetTableAlias(node); + type = node.Type; + } + + if (type.IsGenericType) type = type.GetGenericArguments()[0]; + this.VisitAllMember(type, alias); + if (visitNavigation) AddSplitOnColumn(node.Member, alias); + + return node; + } + + // => new {Id = p.Id} + protected override Expression VisitNew(NewExpression node) + { + // TODO 未支持匿名类的导航属性 + // MemberInit的New + // 匿名类的New + if (node == null) return node; + if (node.Arguments == null || node.Arguments.Count == 0) + throw new XFrameworkException("'NewExpression' do not have any argument."); + + this.VisitNewImpl(node); + + return node; + } + + // 遍历New表达式的参数集 + private Expression VisitNewImpl(NewExpression node) + { + for (int i = 0; i < node.Arguments.Count; i++) + { + Expression expression = node.Arguments[i]; + Type type = expression.Type; + int visitedQty = _visitedMark.Count; + + if (expression.NodeType == ExpressionType.Parameter) + { + //例: new Client(a) + string alias = _aliases.GetTableAlias(expression); + this.VisitAllMember(type, alias); + } + else if (expression.CanEvaluate()) + { + //例: DateTime.Now + _builder.Append(expression.Evaluate().Value, node.Members[i], node.Type); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + else if (expression.NodeType == ExpressionType.MemberAccess || expression.NodeType == ExpressionType.Call) + { + bool isNavigation = !type.IsEnum && !TypeUtils.IsPrimitiveType(type); + if (isNavigation) this.VisitNavigation(expression as MemberExpression, false); + else + { + // new Client(a.ClientId) + this.Visit(expression); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + } + else + { + base.Visit(expression); + this.VisitNewImpl_AddNewName(node.Members != null ? node.Members[i].Name : (expression as MemberExpression).Member.Name); + } + + // 删除本次访问的成员痕迹 + if (_visitedMark.Count != visitedQty) _visitedMark.Remove(_visitedMark.Count - visitedQty); + } + + return node; + } + + private void VisitNewImpl_AddNewName(string memberName) + { + string newName = _pickColumns.Add(memberName); + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + // g.Key.CompanyName & g.Max(a) + protected override Expression VisitMember(MemberExpression node) + { + if (node == null) return node; + else if (_groupBy == null || !node.IsGrouping()) return base.VisitMember(node); + else + { + // Group By 解析 CompanyName = g.Key.Name + LambdaExpression keySelector = _groupBy.Expressions[0] as LambdaExpression; + Expression exp = null; + Expression body = keySelector.Body; + + if (body.NodeType == ExpressionType.MemberAccess) + { + // group xx by a.CompanyName + exp = body; + + // + // + // + // + } + else if (body.NodeType == ExpressionType.New) + { + // group xx by new { Name = a.CompanyName } + + string memberName = node.Member.Name; + NewExpression newExp = body as NewExpression; + int index = newExp.Members.IndexOf(x => x.Name == memberName); + exp = newExp.Arguments[index]; + } + + return this.Visit(exp); + } + } + + // 选择所有的字段 + private Expression VisitAllMember(Type type, string alias, Expression node = null) + { + if (_groupBy != null && node != null && node.IsGrouping()) + { + // select g.Key + LambdaExpression keySelector = _groupBy.Expressions[0] as LambdaExpression; + return this.Visit(keySelector.Body); + } + else + { + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + MemberInvokerCollection invokers = typeRuntime.Invokers; + + foreach (var invoker in invokers) + { + if (invoker != null && invoker.Column != null && invoker.Column.NoMapped) continue; + if (invoker != null && invoker.ForeignKey != null) continue; // 不加载导航属性 + if (invoker.Member.MemberType == System.Reflection.MemberTypes.Method) continue; + + _builder.AppendMember(alias, invoker.Member.Name); + + // 选择字段 + string newName = _pickColumns.Add(invoker.Member.Name); + _builder.AppendAs(newName); + _builder.Append(","); + _builder.AppendNewLine(); + } + } + + return node; + } + + // g.Max(a=>a.Level) + protected override Expression VisitMethodCall(MethodCallExpression node) + { + if (_groupBy != null && node.IsGrouping()) + { + DbExpressionType dbExpressionType = DbExpressionType.None; + Enum.TryParse(node.Method.Name, out dbExpressionType); + Expression exp = dbExpressionType == DbExpressionType.Count + ? Expression.Constant(1) + : (node.Arguments.Count == 1 ? null : node.Arguments[1]); + if (exp.NodeType == ExpressionType.Lambda) exp = (exp as LambdaExpression).Body; + + // 如果是 a=> a 这种表达式,那么一定会指定 elementSelector + if (exp.NodeType == ExpressionType.Parameter) exp = _groupBy.Expressions[1]; + + _builder.Append(_statisMethods[dbExpressionType]); + _builder.Append("("); + this.Visit(exp); + _builder.Append(")"); + + return node; + } + + return base.VisitMethodCall(node); + } + + // 遍历 Include 包含的导航属性 + private void VisitInclude() + { + if (_include == null || _include.Count == 0) return; + + foreach (var dbExpression in _include) + { + Expression exp = dbExpression.Expressions[0]; + if (exp == null) continue; + + if (exp.NodeType == ExpressionType.Lambda) exp = (exp as LambdaExpression).Body; + MemberExpression memberExpression = exp as MemberExpression; + if (memberExpression == null) throw new XFrameworkException("Include expression body must be 'MemberExpression'."); + + // 例:Include(a => a.Client.AccountList[0].Client) + // 解析导航属性链 + List chain = new List(); + while (memberExpression != null) + { + // a.Client 要求 必须标明 ForeignKeyAttribute + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(memberExpression.Expression.Type); + ForeignKeyAttribute attribute = typeRuntime.GetInvokerAttribute(memberExpression.Member.Name); + if (attribute == null) throw new XFrameworkException("Include member {{{0}}} must mark 'ForeignKeyAttribute'.", memberExpression); + + MemberExpression m = null; + chain.Add(memberExpression); + if (memberExpression.Expression.NodeType == ExpressionType.MemberAccess) m = (MemberExpression)memberExpression.Expression; + else if (memberExpression.Expression.NodeType == ExpressionType.Call) m = (memberExpression.Expression as MethodCallExpression).Object as MemberExpression; + + //var m = memberExpression.Expression as MemberExpression; + if (m == null) chain.Add(memberExpression.Expression); + memberExpression = m; + } + + // 生成导航属性描述信息 + string keyName = string.Empty; + for (int i = chain.Count - 1; i >= 0; i--) + { + Expression expression = chain[i]; + memberExpression = expression as MemberExpression; + if (memberExpression == null) continue; + + keyName = memberExpression.GetKeyWidthoutAnonymous(true); + if (!_navigations.ContainsKey(keyName)) + { + // fix issue# XC 列占一个位 + Navigation descriptor = new Navigation(keyName, memberExpression.Member); + descriptor.Start = i == 0 ? _pickColumns.Count : -1;//_columns.Count; + descriptor.FieldCount = i == 0 ? (GetFieldCount(exp) + 1) : -1; //i == 0 ? (GetFieldCount(exp) + 1) : 1;//-1; + _navigations.Add(keyName, descriptor); + } + } + + this.VisitNavigation(memberExpression, true); + } + } + + // 添加额外列,用来判断整个(左)连接记录是否为空 + private void AddSplitOnColumn(System.Reflection.MemberInfo member, string alias) + { + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(member.DeclaringType); + var foreignKey = typeRuntime.GetInvokerAttribute(member.Name); + string keyName = foreignKey.OuterKeys[0]; + + _builder.Append("CASE WHEN "); + _builder.AppendMember(alias, keyName); + _builder.Append(" IS NULL THEN NULL ELSE "); + _builder.AppendMember(alias, keyName); + _builder.Append(" END"); + + // 选择字段 + string newName = _pickColumns.Add(Constant.NAVIGATIONSPLITONNAME); + //_builder.Append(caseWhen); + _builder.AppendAs(newName); + _builder.Append(','); + _builder.AppendNewLine(); + } + + // 计算数据库字段数量 + private static int GetFieldCount(Expression node) + { + int num = 0; + + switch (node.NodeType) + { + case ExpressionType.MemberInit: + MemberInitExpression m = node as MemberInitExpression; + foreach (var exp in m.NewExpression.Arguments) num += _typeFieldAggregator(exp); + foreach (MemberAssignment ma in m.Bindings) num += _primitiveAggregator((ma.Member as System.Reflection.PropertyInfo).PropertyType); + + break; + + case ExpressionType.MemberAccess: + MemberExpression m1 = node as MemberExpression; + num += _typeFieldAggregator(m1); + + break; + + case ExpressionType.New: + NewExpression m2 = node as NewExpression; + foreach (var exp in m2.Arguments) num += _typeFieldAggregator(exp); + if (m2.Members != null) foreach (var member in m2.Members) num += _primitiveAggregator((member as System.Reflection.PropertyInfo).PropertyType); + + break; + } + + return num; + } + + private static Func _typeFieldAggregator = exp => + exp.NodeType == ExpressionType.MemberAccess && TypeUtils.IsPrimitiveType(exp.Type) ? 1 : TypeRuntimeInfoCache.GetRuntimeInfo(exp.Type.IsGenericType ? exp.Type.GetGenericArguments()[0] : exp.Type).DataFieldCount; + + private static Func _primitiveAggregator = type => TypeUtils.IsPrimitiveType(type) ? 1 : 0; + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `m2` last assigned on line 564 could be null and is dereferenced at line 565, column 41. + +### Severity: +ERROR + +### Procedure: +Int32 ColumnExpressionVisitor.GetFieldCount(Expression) + +### File: +net45/TZM.XFramework/Data/ExpressionVisitor/ColumnExpressionVisitor.cs + +### Key: +ColumnExpressionVisitor.cs|GetFieldCount|NULL_DEREFERENCE + +### Node Key: +277c5e4fc7793eba679254e42372b233 + +### Hash: +95fab2d3444e3daf281008ab1e1c06d0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0553/instruction.md b/inferredbugs-0553/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e867f697517647ed2191318a9eeef38a3be2871 --- /dev/null +++ b/inferredbugs-0553/instruction.md @@ -0,0 +1,111 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 18 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// UPDATE 表达式解析器 + /// + public class OracleUpdateExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + + /// + /// 初始化 类的新实例 + /// + public OracleUpdateExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, Expression exp) + : base(provider, aliases, exp) + { + _provider = provider; + _aliases = aliases; + } + + //{new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + { + if (node.Bindings == null || node.Bindings.Count == 0) + throw new XFrameworkException("Update at least update one member."); + + for (int index = 0; index < node.Bindings.Count; ++index) + { + MemberAssignment member = node.Bindings[index] as MemberAssignment; + _builder.AppendMember(member.Member.Name); + _builder.Append(" = "); + + if (member.Expression.CanEvaluate()) + _builder.Append(member.Expression.Evaluate().Value, member.Member, node.Type); + else + base.Visit(member.Expression); + + if (index < node.Bindings.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + return node; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 30 could be null and is dereferenced at line 31, column 17. + +### Severity: +ERROR + +### Procedure: +Expression OracleUpdateExpressionVisitor.VisitMemberInit(MemberInitExpression) + +### File: +net45/TZM.XFramework.Oracle/Data/ExpressionVisitor/OracleUpdateExpressionVisitor.cs + +### Key: +OracleUpdateExpressionVisitor.cs|VisitMemberInit|NULL_DEREFERENCE + +### Node Key: +91b8c216590cdce695b1f86e7c48e6c5 + +### Hash: +df850f02c125984bc4602ac8f5e79e05 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0554/instruction.md b/inferredbugs-0554/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26234b52c6a4a945b6380dc5adb78fd2e0517046 --- /dev/null +++ b/inferredbugs-0554/instruction.md @@ -0,0 +1,647 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 27 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace Riz.XFramework.Data +{ + /// + /// 表达式解析器基类,提供公共的表达式处理方式 + /// + public class LinqExpressionVisitor : ExpressionVisitor + { + #region 私有字段 + + private TableAliasResolver _aliasResolver = null; + private Expression _expression = null; + private HashCollection _navMembers = null; + + /// + /// SQL 构造器 + /// + protected ISqlBuilder _builder = null; + + /// + /// 方法解析器 + /// + protected MethodCallExpressionVisitor _methodVisitor = null; + + /// + /// 成员访问痕迹 + /// + protected MemberVisitedStack _visitedStack = null; + + //防SQL注入字符 + //private static readonly Regex RegSystemThreats = + //new Regex(@"\s?or\s*|\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|" + + // @"\s?sysobjects\s?|\s?xp_.*?|\s?syslogins\s?|\s?sysremote\s?|\s?sysusers\s?|\s?sysxlogins\s?|\s?sysdatabases\s?|\s?aspnet_.*?|\s?exec\s?", + // RegexOptions.Compiled | RegexOptions.IgnoreCase); + + #endregion + + #region 公开属性 + + /// + /// 即将解析的表达式 + /// + public Expression Expression + { + get { return _expression; } + } + + /// + /// 即将解析的表达式 + /// + public ISqlBuilder SqlBuilder + { + get { return _builder; } + } + + /// + /// 导航属性表达式列表 + /// + public HashCollection NavMembers + { + get { return _navMembers; } + } + + /// + /// 成员访问痕迹 + /// + public MemberVisitedStack VisitedStack { get { return _visitedStack; } } + + #endregion + + #region 构造函数 + + /// + /// 初始化 类的新实例 + /// + /// 表别名解析器 + /// 将访问的表达式 + public LinqExpressionVisitor(TableAliasResolver aliasResolver, Expression expression) + { + _aliasResolver = aliasResolver; + _expression = expression; + _visitedStack = new MemberVisitedStack(); + _navMembers = new HashCollection(); + } + + #endregion + + #region 重写方法 + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + /// SQL 语句生成器 + public virtual void Write(ISqlBuilder builder) + { + this.Initialize(builder); + if (_expression != null) this.Visit(_expression); + } + + /// + /// 访问二元表达式 + /// + /// 二元表达式 + /// + protected override Expression VisitBinary(BinaryExpression node) + { + return this.VisitWithoutRemark(a => this.VisitBinaryImpl(node)); + } + + // 访问二元表达式 + Expression VisitBinaryImpl(BinaryExpression b) + { + if (b == null) return b; + + // array[0] + if (b.NodeType == ExpressionType.ArrayIndex) return this.Visit(b.Evaluate()); + + Expression left = b.Left.ReduceUnary(); + Expression right = b.Right.ReduceUnary(); + if (b.NodeType == ExpressionType.AndAlso || b.NodeType == ExpressionType.OrElse) + { + // expression maybe a.Name == "TAN" && a.Allowused + left = TryMakeBinary(b.Left); + right = TryMakeBinary(b.Right); + + if (left != b.Left || right != b.Right) + { + b = Expression.MakeBinary(b.NodeType, left, right); + return this.Visit(b); + } + } + + // 例: a.Name ?? "TAN" + if (b.NodeType == ExpressionType.Coalesce) return _methodVisitor.Visit(b, MethodCall.Coalesce); + + // 例: a.Name == null + var constExpression = left as ConstantExpression ?? right as ConstantExpression; + if (constExpression != null && constExpression.Value == null) return _methodVisitor.Visit(b, MethodCall.EqualNull); + + // 例: a.Name == a.FullName or like a.Name == "TAN" + return this.VisitBinary_Condition(b); + } + + /// + /// 访问包含条件运算符的表达式 + /// + /// 要访问的表达式 + /// + protected override Expression VisitConditional(ConditionalExpression node) + { + // 例: a.Name == null ? "TAN" : a.Name => CASE WHEN a.Name IS NULL THEN 'TAN' ELSE a.Name End + + Expression testExpression = this.TryMakeBinary(node.Test); + + _builder.Append("(CASE WHEN "); + this.Visit(testExpression); + _builder.Append(" THEN "); + this.Visit(node.IfTrue); + _builder.Append(" ELSE "); + this.Visit(node.IfFalse); + _builder.Append(" END)"); + + return node; + } + + /// + /// 访问常量表达式 + /// + /// 常量表达式 + /// + protected override Expression VisitConstant(ConstantExpression c) + { + //fix# char ~~,because expression tree converted char type 2 int. + if (c != null && c.Value != null) + { + var m = _visitedStack.Current; + bool isChar = m != null && (m.DataType == typeof(char) || m.DataType == typeof(char?)) && c.Type == typeof(int); + if (isChar) + { + char @char = Convert.ToChar(c.Value); + c = Expression.Constant(@char, typeof(char)); + } + } + + _builder.Append(c.Value, _visitedStack.Current); + return c; + } + + /// + /// 访问字段或者属性表达式 + /// + /// 字段或者成员表达式 + /// + protected override Expression VisitMember(MemberExpression node) + { + // 1.<>h__TransparentIdentifier3.b.Client.ClientName + // 2.<>h__TransparentIdentifier3.b.Client.ClientName.Length + // 3.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 4.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 5.b.ClientName + + + if (node == null) return node; + // => a.ActiveDate == DateTime.Now => a.State == (byte)state + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + // => DateTime.Now + if (node.Type == typeof(DateTime) && node.Expression == null) return _methodVisitor.Visit(node, MethodCall.MemberMember); + // => a.Nullable.Value + bool isNullable = node.Expression.Type.IsGenericType && node.Member.Name == "Value" && node.Expression.Type.GetGenericTypeDefinition() == typeof(Nullable<>); + if (isNullable) + { + this.Visit(node.Expression); + return node; + } + + // 记录访问成员栈 + _visitedStack.Add(node); + + // => a.Name.Length + if (TypeUtils.IsPrimitiveType(node.Expression.Type)) return _methodVisitor.Visit(node, MethodCall.MemberMember); + // => <>h__3.b.ClientName + if (!node.Expression.Visitable()) + { + _builder.AppendMember(_aliasResolver, node); + return node; + } + // => a.Accounts[0].Markets[0].MarketId + // => b.Client.Address.AddressName + Expression objExpression = node.Expression; + bool isMethodCall = objExpression != null && objExpression.NodeType == ExpressionType.Call; + if (isMethodCall) + { + MethodCallExpression methodExpression = objExpression as MethodCallExpression; + bool isIndex = methodExpression.IsCollectionIndex(); + if (isIndex) objExpression = methodExpression.Object; + } + // => b.Client.Address.AddressName + this.VisitNavMember(objExpression, TypeUtils.GetFieldName(node.Member, node.Expression.Type)); + + return node; + } + + /// + /// 访问方法表达式 + /// + /// 方法表达式 + /// + protected override Expression VisitMethodCall(MethodCallExpression node) + { + // => List[] + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + return _methodVisitor.Visit(node, MethodCall.MethodCall); + } + + /// + /// 访问一元表达式 + /// + /// 一元表达式 + /// + protected override Expression VisitUnary(UnaryExpression u) + { + return _methodVisitor.Visit(u, MethodCall.Unary); + } + + /// + /// 访问表达式树后自动删掉访问的成员痕迹 + /// + /// 访问委托 + protected void VisitWithoutRemark(Action visit) + { + int visitedQty = _visitedStack.Count; + visit(null); + if (_visitedStack.Count != visitedQty) _visitedStack.Remove(_visitedStack.Count - visitedQty); + } + + /// + /// 访问表达式树后自动删掉访问的成员痕迹 + /// + /// 访问实现 + /// + public Expression VisitWithoutRemark(Func visit) + { + int visitedQty = _visitedStack.Count; + var newNode = visit(null); + if (_visitedStack.Count != visitedQty) _visitedStack.Remove(_visitedStack.Count - visitedQty); + return newNode; + } + + #endregion + + #region 私有函数 + + /// + /// 访问二元表达式 + /// + /// 二元表达式 + /// + protected virtual Expression VisitBinary_Condition(BinaryExpression b) + { + // 例: a.Name == a.FullName + // or like a.Name == "TAN" + + if (b == null) return b; + // 取模运算 + else if (b.NodeType == ExpressionType.Modulo) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + // 除法运算 + else if (b.NodeType == ExpressionType.Divide) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + // 字符相加 + else if (b.NodeType == ExpressionType.Add && b.Type == typeof(string)) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + else + { + // 常量表达式放在右边,以充分利用 MemberVisitedMark + string oper = this.GetOperator(b); + bool use = this.UseBracket(b, b.Left); + + if (use) _builder.Append('('); + this.Visit(b.Left); + if (use) _builder.Append(')'); + + _builder.Append(oper); + + bool use2 = this.UseBracket(b, b.Right); + if (use2) _builder.Append('('); + this.Visit(b.Right); + if (use2) _builder.Append(')'); + + return b; + } + } + + /// + /// 访问导航属性 + /// + /// 导航属性表达式 + /// 成员名称 + /// + protected virtual string VisitNavMember(Expression expression, string memberName = null) + { + // 表达式 => b.Client.Address.AddressName + Expression node = expression; + Stack stack = null; + string alias = string.Empty; + while (node != null && node.Visitable()) + { + if (node.NodeType != ExpressionType.MemberAccess) break; + + if (stack == null) stack = new Stack(); + var member = node as MemberExpression; + + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(member.Expression.Type); + ForeignKeyAttribute attribute = typeRuntime.GetMemberAttribute(member.Member.Name); + if (attribute == null) + { + + } + + string key = member.GetKeyWidthoutAnonymous(); + stack.Push(new NavMember(key, member)); + node = member.Expression; + if (node.NodeType == ExpressionType.Call) node = (node as MethodCallExpression).Object; + } + + if (stack != null && stack.Count > 0) + { + while (stack != null && stack.Count > 0) + { + NavMember nav = stack.Pop(); + Type type = nav.Expression.Type; + if (type.IsGenericType) type = type.GetGenericArguments()[0]; + + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + // 检查表达式是否由 GetTable<,>(path) 显式指定过别名 + alias = _aliasResolver.GetGetTableAlias(nav.Key); + if (string.IsNullOrEmpty(alias)) + { + // 如果没有,检查查询表达式是否显示指定该表关联 + alias = _aliasResolver.GetJoinTableAlias(typeRuntime.TableName); + } + if (string.IsNullOrEmpty(alias)) + { + // 如果没有,则使用导航属性别名 + alias = _aliasResolver.GetNavTableAlias(nav.Key); + if (!_navMembers.Contains(nav.Key)) _navMembers.Add(nav); + } + + // 例: a.Client.ClientId + if (stack.Count == 0 && !string.IsNullOrEmpty(memberName)) _builder.AppendMember(alias, memberName); + } + } + else + { + // => SelectMany 也会产生类似 'b.Client.Address.AddressName' 这样的表达式 + alias = _aliasResolver.GetTableAlias(expression); + _builder.AppendMember(alias, memberName); + } + + // Fix issue# Join 表达式显式指定导航属性时时,alias 为空 + return alias; + } + + /// + /// 尝试将一元表达式转换成二元表达式,如 TRUE=>1 == 1 + /// + /// 将要转换的表达式 + /// + protected virtual Expression TryMakeBinary(Expression expression) + { + if (expression.Type != typeof(bool)) return expression; + //else if (expression.NodeType == ExpressionType.Constant && ignoreConst) return expression; + + Expression left = null; + Expression right = null; + + if (expression.NodeType == ExpressionType.Constant) + { + // true => 1=2 + left = Expression.Constant(1); + right = Expression.Constant(Convert.ToBoolean(((ConstantExpression)expression).Value) ? 1 : 2); + } + else if (expression.NodeType == ExpressionType.MemberAccess) + { + // a.FieldName => a.FieldName = 1 + left = expression; + right = Expression.Constant(true); + } + else if (expression.NodeType == ExpressionType.Not) + { + var unaryExpression = expression as UnaryExpression; + if (unaryExpression.Operand.NodeType == ExpressionType.MemberAccess) + { + // !a.FieldName => a.FieldName = 0 + left = ((UnaryExpression)expression).Operand; + right = Expression.Constant(false); + } + } + + if (left != null) + expression = Expression.MakeBinary(ExpressionType.Equal, left, right); + return expression; + } + + /// + /// 使用 SqlBuilder 初始化 + /// + /// + protected virtual void Initialize(ISqlBuilder builder) + { + _builder = builder; + var context = _builder.TranslateContext.DbContext; + if (_methodVisitor == null) + _methodVisitor = context.Provider.CreateMethodCallVisitor(this); + } + + // 获取二元表达式对应的操作符 + string GetOperator(BinaryExpression b) + { + string opr = string.Empty; + switch (b.NodeType) + { + case ExpressionType.Equal: + opr = " = "; + break; + case ExpressionType.NotEqual: + opr = " <> "; + break; + case ExpressionType.GreaterThan: + opr = " > "; + break; + case ExpressionType.GreaterThanOrEqual: + opr = " >= "; + break; + case ExpressionType.LessThan: + opr = " < "; + break; + case ExpressionType.LessThanOrEqual: + opr = " <= "; + break; + case ExpressionType.And: + case ExpressionType.AndAlso: + opr = b.Type == typeof(bool) ? " AND " : " & "; + break; + case ExpressionType.Or: + case ExpressionType.OrElse: + opr = b.Type == typeof(bool) ? " OR " : " | "; + break; + case ExpressionType.Add: + case ExpressionType.AddChecked: + opr = " + "; + break; + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + opr = " - "; + break; + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + opr = " * "; + break; + case ExpressionType.Divide: + opr = " / "; + break; + case ExpressionType.Modulo: + opr = " % "; + break; + case ExpressionType.Coalesce: + opr = "ISNULL"; + break; + default: + throw new NotSupportedException(string.Format("{0} is not supported.", b.NodeType)); + } + + return opr; + } + + // 判断是否需要括号 + bool UseBracket(Expression expression, Expression subExpression = null) + { + if (subExpression != null) + { + var unary = subExpression as UnaryExpression; + if (unary != null) return this.UseBracket(expression, unary.Operand); + + var invocation = subExpression as InvocationExpression; + if (invocation != null) return this.UseBracket(expression, invocation.Expression); + + var lambda = subExpression as LambdaExpression; + if (lambda != null) return this.UseBracket(expression, lambda.Body); + + var b = subExpression as BinaryExpression; + if (b != null) + { + if (expression.NodeType == ExpressionType.OrElse) + return true; + } + } + + return this.GetPriority(expression) < this.GetPriority(subExpression); + } + + // 获取表达式优先级 + int GetPriority(Expression expression) + { + switch (expression.NodeType) + { + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.ExclusiveOr: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + return 3; + case ExpressionType.And: + return expression.Type == typeof(bool) ? 6 : 3; + case ExpressionType.AndAlso: + return 6; + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + return 2; + case ExpressionType.Equal: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.NotEqual: + return 4; + case ExpressionType.Not: + return expression.Type == typeof(bool) ? 5 : 1; + case ExpressionType.Or: + return expression.Type == typeof(bool) ? 7 : 3; + case ExpressionType.OrElse: + return 7; + default: + return 0; + } + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 355 could be null and is dereferenced at line 357, column 17. + +### Severity: +ERROR + +### Procedure: +String LinqExpressionVisitor.VisitNavMember(Expression,String) + +### File: +net45/Riz.XFramework/Data/ExpressionVisitor/LinqExpressionVisitor.cs + +### Key: +LinqExpressionVisitor.cs|VisitNavMember|NULL_DEREFERENCE + +### Node Key: +5f6bc9a45b87a0bd98569135266c4d99 + +### Hash: +bc94f6de1ace235e65d0388ef1bc0077 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0555/instruction.md b/inferredbugs-0555/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f33708a5a658d1d475c597a6544df94468105322 --- /dev/null +++ b/inferredbugs-0555/instruction.md @@ -0,0 +1,390 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp + +using System; +using System.Data; +using System.Linq; +using System.Linq.Expressions; +using System.Collections.Generic; + +namespace TZM.XFramework +{ + /// + /// 扩展帮助类 + /// + public static class XFrameworkExtensions + { + #region 表达式树 + + private static readonly string _anonymousName = "<>h__TransparentIdentifier"; + private static Func _isGrouping = t => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IGrouping<,>); + private static Func _isAnonymous = name => !string.IsNullOrEmpty(name) && name.StartsWith(_anonymousName, StringComparison.Ordinal); + + /// + /// 返回真表达式 + /// + public static Expression> True() + where T : class + { + return f => true; + } + + /// + /// 返回假表达式 + /// + public static Expression> False() + where T : class + { + return f => false; + } + + /// + /// 拼接真表达式 + /// + public static Expression> AndAlso(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.AndAlso(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 拼接假表达式 + /// + public static Expression> OrElse(this Expression> TExp1, + Expression> TExp2) where T : class + { + if (TExp1 == null) return TExp2; + if (TExp2 == null) return TExp1; + + var invokeExp = System.Linq.Expressions.Expression.Invoke(TExp2, TExp1.Parameters.Cast()); + return System.Linq.Expressions.Expression.Lambda> + (System.Linq.Expressions.Expression.OrElse(TExp1.Body, invokeExp), TExp1.Parameters); + } + + /// + /// 去掉一元表达式的操作符 + /// + /// + public static Expression ReduceUnary(this Expression exp) + { + UnaryExpression unaryExpression = exp as UnaryExpression; + return unaryExpression != null + ? unaryExpression.Operand.ReduceUnary() + : exp; + } + + /// + /// 判断表达式链是否能通过动态计算,计算出它的值 + /// + public static bool CanEvaluate(this Expression node) + { + // => 5 + // => a.ActiveDate == DateTime.Now + // => a.State == (byte)state + + if (node == null) return false; + if (node.NodeType == ExpressionType.Constant) return true; + if (node.NodeType == ExpressionType.ArrayIndex) return true; + if (node.NodeType == ExpressionType.Call) + { + // List{0}[] + MethodCallExpression methodCallExpression = node as MethodCallExpression; + Expression expression = methodCallExpression.Object; + if (expression != null && Data.TypeUtils.IsCollectionType(expression.Type) && methodCallExpression.Method.Name == "get_Item") + { + return true; + } + } + + var member = node as MemberExpression; + if (member == null) return false; + if (member.Expression == null) return true; + if (member.Expression.NodeType == ExpressionType.Constant) return true; + + return member.Expression.CanEvaluate(); + } + + /// + /// 计算表达式的值 + /// + public static ConstantExpression Evaluate(this Expression e) + { + ConstantExpression node = null; + if (e.NodeType == ExpressionType.Constant) + { + node = e as ConstantExpression; + } + else + { + LambdaExpression lambda = e is LambdaExpression ? Expression.Lambda(((LambdaExpression)e).Body) : Expression.Lambda(e); + Delegate fn = lambda.Compile(); + + node = Expression.Constant(fn.DynamicInvoke(null), e is LambdaExpression ? ((LambdaExpression)e).Body.Type : e.Type); + } + + // 枚举要转成 INT + if (node.Type.IsEnum) node = Expression.Constant(Convert.ToInt32(node.Value)); + + // 返回最终处理的常量表达式s + return node; + } + + /// + /// 判断属性访问表达式是否有系统动态生成前缀 + /// + /// h__TransparentIdentifier.a.CompanyName + /// + /// + public static bool IsAnonymous(this Expression node) + { + // <>h__TransparentIdentifier => h__TransparentIdentifier.a.CompanyName + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isAnonymous(paramExp.Name); + + if (exp.NodeType == ExpressionType.MemberAccess) // <>h__TransparentIdentifier.a.CompanyName + { + MemberExpression memExp = exp as MemberExpression; + if (_isAnonymous(memExp.Member.Name)) return true; + + return IsAnonymous(memExp.Expression); + } + + return false; + } + + /// + /// 判断是否是分组表达式 + /// + public static bool IsGrouping(this Expression node) + { + //g.Key + //g.Key.CompanyName + //g.Max() + //g=>g.xxx + //g.Key.CompanyId.Length + //g.Key.Length + + // g | g=>g.xx + Expression exp = node; + ParameterExpression paramExp = exp.NodeType == ExpressionType.Lambda + ? (node as LambdaExpression).Parameters[0] + : exp as ParameterExpression; + if (paramExp != null) return _isGrouping(paramExp.Type); + + // g.Max + MethodCallExpression callExp = exp as MethodCallExpression; + if (callExp != null) return _isGrouping(callExp.Arguments[0].Type); + + + MemberExpression memExp = exp as MemberExpression; + if (memExp != null) + { + // g.Key + var g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type); + if (g1) return g1; + + // g.Key.Length | g.Key.Company | g.Key.CompanyId.Length + memExp = memExp.Expression as MemberExpression; + if (memExp != null) + { + g1 = memExp.Member.Name == "Key" && _isGrouping(memExp.Expression.Type) && memExp.Type.Namespace == null; //匿名类没有命令空间 + if (g1) return g1; + } + } + + return false; + } + + /// + /// 在递归访问 MemberAccess 表达式时,判定节点是否能够被继续递归访问 + /// + public static bool Acceptable(this Expression node) + { + // a + // <>h__TransparentIdentifier.a + // <>h__TransparentIdentifier0.<>h__TransparentIdentifier1.a + + if (node.NodeType == ExpressionType.Parameter) return false; + + if (node.NodeType == ExpressionType.MemberAccess) + { + MemberExpression m = node as MemberExpression; + if (m.Expression.NodeType == ExpressionType.Parameter) + { + string name = (m.Expression as ParameterExpression).Name; + if (_isAnonymous(name)) return false; + } + + if (m.Expression.NodeType == ExpressionType.MemberAccess) + { + string name = (m.Expression as MemberExpression).Member.Name; + if (_isAnonymous(name)) return false; + } + } + + return true; + } + + /// + /// 取剔除掉系统动态生成前缀后的表达式 + /// + public static string GetKeyWidthoutAnonymous(this MemberExpression node, bool isDesciptor = false) + { + List segs = new List(); + segs.Add(node.Member.Name); + + Expression expression = node.Expression; + while (expression.Acceptable()) + { + MemberExpression memberExpression = null; + if (expression.NodeType == ExpressionType.MemberAccess) memberExpression = (MemberExpression)expression; + else if (expression.NodeType == ExpressionType.Call) memberExpression = (expression as MethodCallExpression).Object as MemberExpression; + + segs.Add(memberExpression.Member.Name); + expression = memberExpression.Expression; + } + + // 如果读取 + if (expression.NodeType == ExpressionType.Parameter) segs.Add(isDesciptor ? expression.Type.Name : (expression as ParameterExpression).Name); + if (expression.NodeType == ExpressionType.MemberAccess) segs.Add((expression as MemberExpression).Member.Name); + + segs.Reverse(); + string result = string.Join(".", segs); + return result; + } + + #endregion + + #region 列表扩展 + + /// + /// 取指定列表中符合条件的元素索引 + /// + public static int IndexOf(this IEnumerable collection, Func predicate) + { + int i = -1; + foreach (T value in collection) + { + i++; + if (predicate(value)) return i; + } + + return -1; + } + + /// + /// 创建一个集合 + /// + public static List ToList(this IEnumerable collection, Func selector) + { + return collection.Select(selector).ToList(); + } + + /// + /// 列表转换扩展 + /// + public static List ToList(this IEnumerable source, Func selector, Func predicate = null) + { + if (predicate != null) source = source.Where(predicate); + return source.Select(selector).ToList(); + } + + /// + /// 根据页长计算总页码 + /// + /// 数据集合 + /// 页码 + /// + public static int Page(this IEnumerable collection, int pageSize) + { + int count = 0; + if ((collection as ICollection) != null) count = (collection as ICollection).Count; + else if ((collection as T[]) != null) count = (collection as T[]).Length; + else count = collection.Count(); + + int page = (count + pageSize - 1) / pageSize; + return page; + } + + /// + /// 批量添加命令参数 + /// + public static void AddRange(this IDataParameterCollection source, IEnumerable parameters) + { + if (parameters != null) + { + foreach (var p in parameters) source.Add(p); + } + } + + #endregion + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `memExp` last assigned on line 152 could be null and is dereferenced at line 153, column 17. + +### Severity: +ERROR + +### Procedure: +Boolean XFrameworkExtensions.IsAnonymous(Expression) + +### File: +net45/TZM.XFramework/Common/XFrameworkExtensions.cs + +### Key: +XFrameworkExtensions.cs|IsAnonymous|NULL_DEREFERENCE + +### Node Key: +5f6bc9a45b87a0bd98569135266c4d99 + +### Hash: +3acc963fad65cb093fd72241a905dd68 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0562/instruction.md b/inferredbugs-0562/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a9951e0df4b52e86b6c37869c087442d8098176 --- /dev/null +++ b/inferredbugs-0562/instruction.md @@ -0,0 +1,643 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 28 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace Riz.XFramework.Data +{ + /// + /// 表达式解析器基类,提供公共的表达式处理方式 + /// + public class LinqExpressionVisitor : ExpressionVisitor + { + #region 私有字段 + + private AliasGenerator _aliasGenerator = null; + private Expression _expression = null; + private HashCollection _navMembers = null; + + /// + /// SQL 构造器 + /// + protected ISqlBuilder _builder = null; + + /// + /// 方法解析器 + /// + protected MethodCallExpressionVisitor _methodVisitor = null; + + /// + /// 成员访问痕迹 + /// + protected MemberVisitedStack _visitedStack = null; + + //防SQL注入字符 + //private static readonly Regex RegSystemThreats = + //new Regex(@"\s?or\s*|\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|" + + // @"\s?sysobjects\s?|\s?xp_.*?|\s?syslogins\s?|\s?sysremote\s?|\s?sysusers\s?|\s?sysxlogins\s?|\s?sysdatabases\s?|\s?aspnet_.*?|\s?exec\s?", + // RegexOptions.Compiled | RegexOptions.IgnoreCase); + + #endregion + + #region 公开属性 + + /// + /// 即将解析的表达式 + /// + public Expression Expression + { + get { return _expression; } + } + + /// + /// 即将解析的表达式 + /// + public ISqlBuilder SqlBuilder + { + get { return _builder; } + } + + /// + /// 导航属性表达式列表 + /// + public HashCollection NavMembers + { + get { return _navMembers; } + } + + /// + /// 成员访问痕迹 + /// + public MemberVisitedStack VisitedStack { get { return _visitedStack; } } + + #endregion + + #region 构造函数 + + /// + /// 初始化 类的新实例 + /// + /// 表别名解析器 + /// 将访问的表达式 + public LinqExpressionVisitor(AliasGenerator aliasGenerator, Expression expression) + { + _aliasGenerator = aliasGenerator; + _expression = expression; + _visitedStack = new MemberVisitedStack(); + _navMembers = new HashCollection(); + } + + #endregion + + #region 重写方法 + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + /// SQL 语句生成器 + public virtual void Write(ISqlBuilder builder) + { + this.Initialize(builder); + if (_expression != null) this.Visit(_expression); + } + + /// + /// 访问二元表达式 + /// + /// 二元表达式 + /// + protected override Expression VisitBinary(BinaryExpression node) + { + return this.VisitWithoutRemark(a => this.VisitBinaryImpl(node)); + } + + // 访问二元表达式 + Expression VisitBinaryImpl(BinaryExpression b) + { + if (b == null) return b; + + // array[0] + if (b.NodeType == ExpressionType.ArrayIndex) return this.Visit(b.Evaluate()); + + Expression left = b.Left.ReduceUnary(); + Expression right = b.Right.ReduceUnary(); + if (b.NodeType == ExpressionType.AndAlso || b.NodeType == ExpressionType.OrElse) + { + // expression maybe a.Name == "TAN" && a.Allowused + left = TryMakeBinary(b.Left); + right = TryMakeBinary(b.Right); + + if (left != b.Left || right != b.Right) + { + b = Expression.MakeBinary(b.NodeType, left, right); + return this.Visit(b); + } + } + + // 例: a.Name ?? "TAN" + if (b.NodeType == ExpressionType.Coalesce) return _methodVisitor.Visit(b, MethodCall.Coalesce); + + // 例: a.Name == null + var constExpression = left as ConstantExpression ?? right as ConstantExpression; + if (constExpression != null && constExpression.Value == null) return _methodVisitor.Visit(b, MethodCall.EqualNull); + + // 例: a.Name == a.FullName or like a.Name == "TAN" + return this.VisitBinary_Condition(b); + } + + /// + /// 访问包含条件运算符的表达式 + /// + /// 要访问的表达式 + /// + protected override Expression VisitConditional(ConditionalExpression node) + { + // 例: a.Name == null ? "TAN" : a.Name => CASE WHEN a.Name IS NULL THEN 'TAN' ELSE a.Name End + + Expression testExpression = this.TryMakeBinary(node.Test); + + _builder.Append("(CASE WHEN "); + this.Visit(testExpression); + _builder.Append(" THEN "); + this.Visit(node.IfTrue); + _builder.Append(" ELSE "); + this.Visit(node.IfFalse); + _builder.Append(" END)"); + + return node; + } + + /// + /// 访问常量表达式 + /// + /// 常量表达式 + /// + protected override Expression VisitConstant(ConstantExpression c) + { + //fix# char ~~,because expression tree converted char type 2 int. + if (c != null && c.Value != null) + { + var m = _visitedStack.Current; + bool isChar = m != null && (m.DataType == typeof(char) || m.DataType == typeof(char?)) && c.Type == typeof(int); + if (isChar) + { + char @char = Convert.ToChar(c.Value); + c = Expression.Constant(@char, typeof(char)); + } + } + + _builder.Append(c.Value, _visitedStack.Current); + return c; + } + + /// + /// 访问字段或者属性表达式 + /// + /// 字段或者成员表达式 + /// + protected override Expression VisitMember(MemberExpression node) + { + // 1.<>h__TransparentIdentifier3.b.Client.ClientName + // 2.<>h__TransparentIdentifier3.b.Client.ClientName.Length + // 3.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 4.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 5.b.ClientName + + + if (node == null) return node; + // => a.ActiveDate == DateTime.Now => a.State == (byte)state + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + // => DateTime.Now + if (node.Type == typeof(DateTime) && node.Expression == null) return _methodVisitor.Visit(node, MethodCall.MemberMember); + // => a.Nullable.Value + bool isNullable = node.Expression.Type.IsGenericType && node.Member.Name == "Value" && node.Expression.Type.GetGenericTypeDefinition() == typeof(Nullable<>); + if (isNullable) + { + this.Visit(node.Expression); + return node; + } + + // 记录访问成员栈 + _visitedStack.Add(node); + + // => a.Name.Length + if (TypeUtils.IsPrimitiveType(node.Expression.Type)) return _methodVisitor.Visit(node, MethodCall.MemberMember); + // => <>h__3.b.ClientName + if (!node.Expression.Visitable()) + { + _builder.AppendMember(_aliasGenerator, node); + return node; + } + // => a.Accounts[0].Markets[0].MarketId + // => b.Client.Address.AddressName + Expression objExpression = node.Expression; + bool isMethodCall = objExpression != null && objExpression.NodeType == ExpressionType.Call; + if (isMethodCall) + { + MethodCallExpression methodExpression = objExpression as MethodCallExpression; + bool isIndex = methodExpression.IsCollectionIndex(); + if (isIndex) objExpression = methodExpression.Object; + } + // => b.Client.Address.AddressName + this.VisitNavMember(objExpression, TypeUtils.GetFieldName(node.Member, node.Expression.Type)); + + return node; + } + + /// + /// 访问方法表达式 + /// + /// 方法表达式 + /// + protected override Expression VisitMethodCall(MethodCallExpression node) + { + // => List[] + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + return _methodVisitor.Visit(node, MethodCall.MethodCall); + } + + /// + /// 访问一元表达式 + /// + /// 一元表达式 + /// + protected override Expression VisitUnary(UnaryExpression u) + { + return _methodVisitor.Visit(u, MethodCall.Unary); + } + + /// + /// 访问表达式树后自动删掉访问的成员痕迹 + /// + /// 访问委托 + protected void VisitWithoutRemark(Action visit) + { + int visitedQty = _visitedStack.Count; + visit(null); + if (_visitedStack.Count != visitedQty) _visitedStack.Remove(_visitedStack.Count - visitedQty); + } + + /// + /// 访问表达式树后自动删掉访问的成员痕迹 + /// + /// 访问实现 + /// + public Expression VisitWithoutRemark(Func visit) + { + int visitedQty = _visitedStack.Count; + var newNode = visit(null); + if (_visitedStack.Count != visitedQty) _visitedStack.Remove(_visitedStack.Count - visitedQty); + return newNode; + } + + #endregion + + #region 私有函数 + + /// + /// 访问二元表达式 + /// + /// 二元表达式 + /// + protected virtual Expression VisitBinary_Condition(BinaryExpression b) + { + // 例: a.Name == a.FullName + // or like a.Name == "TAN" + + if (b == null) return b; + // 取模运算 + else if (b.NodeType == ExpressionType.Modulo) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + // 除法运算 + else if (b.NodeType == ExpressionType.Divide) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + // 字符相加 + else if (b.NodeType == ExpressionType.Add && b.Type == typeof(string)) return _methodVisitor.Visit(b, MethodCall.BinaryCall); + else + { + // 常量表达式放在右边,以充分利用 MemberVisitedMark + string oper = this.GetOperator(b); + bool use = this.UseBracket(b, b.Left); + + if (use) _builder.Append('('); + this.Visit(b.Left); + if (use) _builder.Append(')'); + + _builder.Append(oper); + + bool use2 = this.UseBracket(b, b.Right); + if (use2) _builder.Append('('); + this.Visit(b.Right); + if (use2) _builder.Append(')'); + + return b; + } + } + + /// + /// 访问导航属性 + /// + /// 导航属性表达式 + /// 成员名称 + /// + protected virtual string VisitNavMember(Expression expression, string memberName = null) + { + // 表达式 => b.Client.Address.AddressName + Expression node = expression; + Stack stack = null; + string alias = string.Empty; + while (node != null && node.Visitable()) + { + if (node.NodeType != ExpressionType.MemberAccess) break; + + if (stack == null) stack = new Stack(); + var member = node as MemberExpression; + + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(member.Expression.Type); + ForeignKeyAttribute attribute = typeRuntime.GetMemberAttribute(member.Member.Name); + + string key = member.GetKeyWidthoutAnonymous(); + stack.Push(new NavMember(key, member)); + node = member.Expression; + if (node.NodeType == ExpressionType.Call) node = (node as MethodCallExpression).Object; + } + + if (stack != null && stack.Count > 0) + { + while (stack != null && stack.Count > 0) + { + NavMember nav = stack.Pop(); + Type type = nav.Expression.Type; + if (type.IsGenericType) type = type.GetGenericArguments()[0]; + + var typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + // 检查表达式是否由 GetTable<,>(path) 显式指定过别名 + alias = _aliasGenerator.GetGetTableAlias(nav.Key); + if (string.IsNullOrEmpty(alias)) + { + // 如果没有,检查查询表达式是否显示指定该表关联 + alias = _aliasGenerator.GetJoinTableAlias(typeRuntime.TableName); + } + if (string.IsNullOrEmpty(alias)) + { + // 如果没有,则使用导航属性别名 + alias = _aliasGenerator.GetNavTableAlias(nav.Key); + if (!_navMembers.Contains(nav.Key)) _navMembers.Add(nav); + } + + // 例: a.Client.ClientId + if (stack.Count == 0 && !string.IsNullOrEmpty(memberName)) _builder.AppendMember(alias, memberName); + } + } + else + { + // => SelectMany 也会产生类似 'b.Client.Address.AddressName' 这样的表达式 + alias = _aliasGenerator.GetTableAlias(expression); + _builder.AppendMember(alias, memberName); + } + + // Fix issue# Join 表达式显式指定导航属性时时,alias 为空 + return alias; + } + + /// + /// 尝试将一元表达式转换成二元表达式,如 TRUE=>1 == 1 + /// + /// 将要转换的表达式 + /// + protected virtual Expression TryMakeBinary(Expression expression) + { + if (expression.Type != typeof(bool)) return expression; + //else if (expression.NodeType == ExpressionType.Constant && ignoreConst) return expression; + + Expression left = null; + Expression right = null; + + if (expression.NodeType == ExpressionType.Constant) + { + // true => 1=2 + left = Expression.Constant(1); + right = Expression.Constant(Convert.ToBoolean(((ConstantExpression)expression).Value) ? 1 : 2); + } + else if (expression.NodeType == ExpressionType.MemberAccess) + { + // a.FieldName => a.FieldName = 1 + left = expression; + right = Expression.Constant(true); + } + else if (expression.NodeType == ExpressionType.Not) + { + var unaryExpression = expression as UnaryExpression; + if (unaryExpression.Operand.NodeType == ExpressionType.MemberAccess) + { + // !a.FieldName => a.FieldName = 0 + left = ((UnaryExpression)expression).Operand; + right = Expression.Constant(false); + } + } + + if (left != null) + expression = Expression.MakeBinary(ExpressionType.Equal, left, right); + return expression; + } + + /// + /// 使用 SqlBuilder 初始化 + /// + /// + protected virtual void Initialize(ISqlBuilder builder) + { + _builder = builder; + var context = _builder.TranslateContext.DbContext; + if (_methodVisitor == null) + _methodVisitor = context.Provider.CreateMethodCallVisitor(this); + } + + // 获取二元表达式对应的操作符 + string GetOperator(BinaryExpression b) + { + string opr = string.Empty; + switch (b.NodeType) + { + case ExpressionType.Equal: + opr = " = "; + break; + case ExpressionType.NotEqual: + opr = " <> "; + break; + case ExpressionType.GreaterThan: + opr = " > "; + break; + case ExpressionType.GreaterThanOrEqual: + opr = " >= "; + break; + case ExpressionType.LessThan: + opr = " < "; + break; + case ExpressionType.LessThanOrEqual: + opr = " <= "; + break; + case ExpressionType.And: + case ExpressionType.AndAlso: + opr = b.Type == typeof(bool) ? " AND " : " & "; + break; + case ExpressionType.Or: + case ExpressionType.OrElse: + opr = b.Type == typeof(bool) ? " OR " : " | "; + break; + case ExpressionType.Add: + case ExpressionType.AddChecked: + opr = " + "; + break; + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + opr = " - "; + break; + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + opr = " * "; + break; + case ExpressionType.Divide: + opr = " / "; + break; + case ExpressionType.Modulo: + opr = " % "; + break; + case ExpressionType.Coalesce: + opr = "ISNULL"; + break; + default: + throw new NotSupportedException(string.Format("{0} is not supported.", b.NodeType)); + } + + return opr; + } + + // 判断是否需要括号 + bool UseBracket(Expression expression, Expression subExpression = null) + { + if (subExpression != null) + { + var unary = subExpression as UnaryExpression; + if (unary != null) return this.UseBracket(expression, unary.Operand); + + var invocation = subExpression as InvocationExpression; + if (invocation != null) return this.UseBracket(expression, invocation.Expression); + + var lambda = subExpression as LambdaExpression; + if (lambda != null) return this.UseBracket(expression, lambda.Body); + + var b = subExpression as BinaryExpression; + if (b != null) + { + if (expression.NodeType == ExpressionType.OrElse) + return true; + } + } + + return this.GetPriority(expression) < this.GetPriority(subExpression); + } + + // 获取表达式优先级 + int GetPriority(Expression expression) + { + switch (expression.NodeType) + { + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.ExclusiveOr: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + return 3; + case ExpressionType.And: + return expression.Type == typeof(bool) ? 6 : 3; + case ExpressionType.AndAlso: + return 6; + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + return 2; + case ExpressionType.Equal: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.NotEqual: + return 4; + case ExpressionType.Not: + return expression.Type == typeof(bool) ? 5 : 1; + case ExpressionType.Or: + return expression.Type == typeof(bool) ? 7 : 3; + case ExpressionType.OrElse: + return 7; + default: + return 0; + } + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 355 could be null and is dereferenced at line 357, column 17. + +### Severity: +ERROR + +### Procedure: +String LinqExpressionVisitor.VisitNavMember(Expression,String) + +### File: +src/Riz.XFramework/Data/ExpressionVisitor/LinqExpressionVisitor.cs + +### Key: +LinqExpressionVisitor.cs|VisitNavMember|NULL_DEREFERENCE + +### Node Key: +5f6bc9a45b87a0bd98569135266c4d99 + +### Hash: +bc94f6de1ace235e65d0388ef1bc0077 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0563/instruction.md b/inferredbugs-0563/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..301837635fa83138bbe81885e9e8c7a885e0b322 --- /dev/null +++ b/inferredbugs-0563/instruction.md @@ -0,0 +1,110 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 17 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// UPDATE 表达式解析器 + /// + public class OracleUpdateExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + + /// + /// 初始化 类的新实例 + /// + public OracleUpdateExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, Expression exp) + : base(provider, aliases, exp) + { + _provider = provider; + _aliases = aliases; + } + + //{new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + { + if (node.Bindings.Count == 0) throw new XFrameworkException("Update(Expression> action, Expression> predicate) at least update one member."); + + for (int index = 0; index < node.Bindings.Count; ++index) + { + MemberAssignment member = node.Bindings[index] as MemberAssignment; + _builder.AppendMember(member.Member.Name); + _builder.Append(" = "); + + if (member.Expression.CanEvaluate()) + _builder.Append(member.Expression.Evaluate().Value, member.Member, node.Type); + else + base.Visit(member.Expression); + + if (index < node.Bindings.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + return node; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 30 could be null and is dereferenced at line 31, column 17. + +### Severity: +ERROR + +### Procedure: +Expression OracleUpdateExpressionVisitor.VisitMemberInit(MemberInitExpression) + +### File: +net45/TZM.XFramework.Oracle/Data/ExpressionVisitor/OracleUpdateExpressionVisitor.cs + +### Key: +OracleUpdateExpressionVisitor.cs|VisitMemberInit|NULL_DEREFERENCE + +### Node Key: +91b8c216590cdce695b1f86e7c48e6c5 + +### Hash: +df850f02c125984bc4602ac8f5e79e05 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0564/instruction.md b/inferredbugs-0564/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..544fc8a367fab75036335a9561ff771519bcd8e2 --- /dev/null +++ b/inferredbugs-0564/instruction.md @@ -0,0 +1,143 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Linq.Expressions; + +namespace ICS.XFramework.Data +{ + /// + /// UPDATE 表达式解析器 + /// + public class UpdateExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + + /// + /// 初始化 类的新实例 + /// + public UpdateExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, Expression exp) + : base(provider, aliases, exp) + { + _provider = provider; + _aliases = aliases; + } + + //{new App() {Id = p.Id}} + protected override Expression VisitMemberInit(MemberInitExpression node) + { + if (node.Bindings.Count == 0) throw new XFrameworkException("Update(Expression> action, Expression> predicate) at least update one member."); + + for (int index = 0; index < node.Bindings.Count; ++index) + { + MemberAssignment member = node.Bindings[index] as MemberAssignment; + _builder.AppendMember("t0", member.Member.Name); + _builder.Append(" = "); + + if (member.Expression.CanEvaluate()) + _builder.Append(member.Expression.Evaluate().Value, member.Member, node.Type); + //base.VisitConstant(member.Expression.Evaluate(), member.Member); + else + base.Visit(member.Expression); + + if (index < node.Bindings.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + return node; + } + + protected override Expression VisitNew(NewExpression node) + { + // 匿名类的New + if (node == null) return node; + if (node.Arguments == null || node.Arguments.Count == 0) + throw new XFrameworkException("'NewExpression' do not have any argument."); + + for (int index = 0; index < node.Arguments.Count; index++) + { + Expression argument = node.Arguments[index]; + Type type = argument.Type; + + var member = node.Members[index]; + _builder.AppendMember("t0", member.Name); + _builder.Append(" = "); + + if (node.Arguments[index].CanEvaluate()) + _builder.Append(node.Arguments[index].Evaluate().Value, member, node.Type); + else + base.Visit(node.Arguments[index]); + + if (index < node.Arguments.Count - 1) + { + _builder.Append(","); + _builder.AppendNewLine(); + } + } + + return node; + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 31 could be null and is dereferenced at line 32, column 17. + +### Severity: +ERROR + +### Procedure: +Expression UpdateExpressionVisitor.VisitMemberInit(MemberInitExpression) + +### File: +net45/ICS.XFramework/Data/ExpressionVisitor/UpdateExpressionVisitor.cs + +### Key: +UpdateExpressionVisitor.cs|VisitMemberInit|NULL_DEREFERENCE + +### Node Key: +91b8c216590cdce695b1f86e7c48e6c5 + +### Hash: +ca68bae44360dc2f736535b6624c50e9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0565/instruction.md b/inferredbugs-0565/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c5d3d8ee7ce8fb5b3197b945cfd31591efaaf6a --- /dev/null +++ b/inferredbugs-0565/instruction.md @@ -0,0 +1,553 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 10 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// 表达式解析器基类,提供公共的表达式处理方式 + /// + public class ExpressionVisitorBase : ExpressionVisitor + { + #region 私有字段 + + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + private Expression _expression = null; + private IDictionary _navMembers = null; + + /// + /// SQL 构造器 + /// + protected ISqlBuilder _builder = null; + + /// + /// 方法解析器 + /// + protected IMethodCallExressionVisitor _methodVisitor = null; + + /// + /// 成员访问痕迹 + /// + protected MemberVisitedMark _visitedMark = null; + + //防SQL注入字符 + //private static readonly Regex RegSystemThreats = + //new Regex(@"\s?or\s*|\s?;\s?|\s?drop\s|\s?grant\s|^'|\s?--|\s?union\s|\s?delete\s|\s?truncate\s|" + + // @"\s?sysobjects\s?|\s?xp_.*?|\s?syslogins\s?|\s?sysremote\s?|\s?sysusers\s?|\s?sysxlogins\s?|\s?sysdatabases\s?|\s?aspnet_.*?|\s?exec\s?", + // RegexOptions.Compiled | RegexOptions.IgnoreCase); + + #endregion + + #region 公开属性 + + /// + /// 即将解析的表达式 + /// + public Expression Expression + { + get { return _expression; } + } + + /// + /// 即将解析的表达式 + /// + public ISqlBuilder SqlBuilder + { + get { return _builder; } + } + + /// + /// 表别名域 + /// + public TableAliasCache TableAlias + { + get { return _aliases; } + } + + /// + /// 导航属性表达式列表 + /// + public IDictionary NavMembers + { + get { return _navMembers; } + } + + /// + /// 成员访问痕迹 + /// + public MemberVisitedMark VisitedMark { get { return _visitedMark; } } + + #endregion + + #region 构造函数 + + /// + /// 初始化 类的新实例 + /// + public ExpressionVisitorBase(IDbQueryProvider provider, TableAliasCache aliases, Expression exp, bool useNominate = true) + { + _provider = provider; + _aliases = aliases; + _expression = exp; + _visitedMark = new MemberVisitedMark(); + _navMembers = new Dictionary(); + } + + #endregion + + #region 重写方法 + + /// + /// 将表达式所表示的SQL片断写入SQL构造器 + /// + public virtual void Write(ISqlBuilder builder) + { + _builder = builder; + if (_methodVisitor == null) _methodVisitor = _provider.CreateMethodCallVisitor(this); + this.Visit(_expression); + } + + protected override Expression VisitBinary(BinaryExpression b) + { + if (b == null) return b; + + if (b.NodeType == ExpressionType.ArrayIndex) return this.Visit(b.Evaluate()); + + Expression left = b.Left.ReduceUnary(); + Expression right = b.Right.ReduceUnary(); + if (b.NodeType == ExpressionType.AndAlso || b.NodeType == ExpressionType.OrElse) + { + // expression maybe a.Name == "TAN" && a.Allowused + left = TryMakeBinary(b.Left); + right = TryMakeBinary(b.Right); + + if (left != b.Left || right != b.Right) + { + b = Expression.MakeBinary(b.NodeType, left, right); + return this.Visit(b); + } + } + + // 例: a.Name ?? "TAN" + if (b.NodeType == ExpressionType.Coalesce) return _methodVisitor.VisitCoalesce(b); + + // 例: a.Name == null + ConstantExpression constExpression = left as ConstantExpression ?? right as ConstantExpression; + if (constExpression != null && constExpression.Value == null) return _methodVisitor.VisitEqualNull(b); + + // 例: a.Name == a.FullName or like a.Name == "TAN" + return this.VisitBinary_Condition(b); + } + + protected override Expression VisitConditional(ConditionalExpression node) + { + // 例: a.Name == null ? "TAN" : a.Name => CASE WHEN a.Name IS NULL THEN 'TAN' ELSE a.Name End + + Expression testExpression = this.TryMakeBinary(node.Test, true); + Expression ifTrueExpression = this.TryMakeBinary(node.IfTrue, true); + Expression ifFalseExpression = this.TryMakeBinary(node.IfFalse, true); + + _visitedMark.ClearImmediately = false; + _builder.Append("(CASE WHEN "); + this.Visit(testExpression); + _builder.Append(" THEN "); + this.Visit(ifTrueExpression); + _builder.Append(" ELSE "); + this.Visit(ifFalseExpression); + _builder.Append(" END)"); + _visitedMark.ClearImmediately = true; + + return node; + } + + protected override Expression VisitConstant(ConstantExpression c) + { + //fix# char ~~ + Func isChar = t => t == typeof(char) || t == typeof(char?); + if (_visitedMark.Current != null && c != null && c.Value != null && isChar(_visitedMark.Current.Type) && !isChar(c.Type)) + { + char @char = Convert.ToChar(c.Value); + c = Expression.Constant(@char, typeof(char)); + } + + _builder.Append(c.Value, _visitedMark.Current); + _visitedMark.Clear(); + return c; + } + + protected override Expression VisitMember(MemberExpression node) + { + // 1.<>h__TransparentIdentifier3.b.Client.ClientName + // 2.<>h__TransparentIdentifier3.b.Client.ClientName.Length + // 3.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 4.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.ClientName + // <>h__TransparentIdentifier2.<>h__TransparentIdentifier3.b.Client.Address.AddressName + // 5.b.ClientName + + _visitedMark.Add(node); + + if (node == null) return node; + // => a.ActiveDate == DateTime.Now => a.State == (byte)state + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + // => a.Nullable.Value + bool isNullable = node.Expression.Type.IsGenericType && node.Member.Name == "Value" && node.Expression.Type.GetGenericTypeDefinition() == typeof(Nullable<>); + if (isNullable) return this.Visit(node.Expression); + // => a.Name.Length + if (TypeUtils.IsPrimitiveType(node.Expression.Type)) return _methodVisitor.VisitMemberMember(node); + // => <>h__3.b.ClientName + if (!node.Expression.Acceptable()) return _builder.AppendMember(node, _aliases); + // => a.Accounts[0].Markets[0].MarketId + // => b.Client.Address.AddressName + Expression objExpression = node.Expression; + bool isMethodCall = objExpression != null && objExpression.NodeType == ExpressionType.Call; + if (isMethodCall) + { + MethodCallExpression methodExpression = objExpression as MethodCallExpression; + var expr = methodExpression.Object; + bool isGetItem = expr != null && Data.TypeUtils.IsCollectionType(expr.Type) && methodExpression.Method.Name == "get_Item"; + if (isGetItem) objExpression = expr; + } + // => b.Client.Address.AddressName + this.VisitNavMember(objExpression, node.Member.Name); + + return node; + } + + protected override Expression VisitMethodCall(MethodCallExpression node) + { + // => List[] + if (node.CanEvaluate()) return this.VisitConstant(node.Evaluate()); + return _methodVisitor.VisitMethodCall(node); + } + + protected override Expression VisitUnary(UnaryExpression u) + { + return _methodVisitor.VisitUnary(u); + } + + #endregion + + #region 私有函数 + + protected virtual Expression VisitBinary_Condition(BinaryExpression b) + { + // 例: a.Name == a.FullName + // or like a.Name == "TAN" + + if (b != null) + { + string oper = this.GetOperator(b); + Expression left = b.Left.CanEvaluate() ? b.Right : b.Left; + Expression right = b.Left.CanEvaluate() ? b.Left : b.Right; + + bool use = this.TakeParenthese(b, b.Left); + if (use) _builder.Append('('); + this.Visit(left); + if (use) _builder.Append(')'); + + _builder.Append(oper); + + bool use2 = this.TakeParenthese(b, b.Right); + if (use2) _builder.Append('('); + this.Visit(right); + if (use2) _builder.Append(')'); + + _visitedMark.Clear(); + } + + return b; + } + + // 访问导航属性 + protected virtual string VisitNavMember(Expression expression, string memberName = null) + { + // 表达式 => b.Client.Address.AddressName + Expression node = expression; + Stack> stack = null; + string alias = string.Empty; + while (node != null && node.Acceptable()) + { + if (node.NodeType != ExpressionType.MemberAccess) break; + + if (stack == null) stack = new Stack>(); + MemberExpression memberExpression = node as MemberExpression; + + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(memberExpression.Expression.Type); + ForeignKeyAttribute attribute = typeRuntime.GetInvokerAttribute(memberExpression.Member.Name); + if (attribute == null) break; + + string key = memberExpression.GetKeyWidthoutAnonymous(); + stack.Push(new KeyValuePair(key, memberExpression)); + node = memberExpression.Expression; + if (node.NodeType == ExpressionType.Call) node = (node as MethodCallExpression).Object; + } + + if (stack != null && stack.Count > 0) + { + while (stack != null && stack.Count > 0) + { + KeyValuePair kvp = stack.Pop(); + string key = kvp.Key; + MemberExpression m = kvp.Value; + Type type = m.Type; + if (type.IsGenericType) type = type.GetGenericArguments()[0]; + + TypeRuntimeInfo typeRuntime = TypeRuntimeInfoCache.GetRuntimeInfo(type); + // 检查查询表达式是否显示指定该表关联 + alias = _aliases.GetJoinTableAlias(typeRuntime.TableName); + if (string.IsNullOrEmpty(alias)) + { + // 如果没有,则使用导航属性别名 + alias = _aliases.GetNavigationTableAlias(key); + if (!_navMembers.ContainsKey(kvp.Key)) _navMembers.Add(kvp); + } + + // 例: a.Client.ClientId + if (stack.Count == 0 && !string.IsNullOrEmpty(memberName)) _builder.AppendMember(alias, memberName); + } + } + else + { + // => SelectMany 也会产生类似 'b.Client.Address.AddressName' 这样的表达式 + alias = _aliases.GetTableAlias(expression); + _builder.AppendMember(alias, memberName); + } + + // fix issue# Join 表达式显式指定导航属性时时,alias 为空 + return alias; + } + + protected Expression TryMakeBinary(Expression exp, bool skipConstant = false) + { + if (exp.Type != typeof(bool)) return exp; + + Expression left = null; + Expression right = null; + + switch (exp.NodeType) + { + //True should be translate to 1==1 and Flase should be 1==2 + case ExpressionType.Constant: + if (!skipConstant) + { + ConstantExpression constExp = exp as ConstantExpression; + bool value = Convert.ToBoolean(constExp.Value); + left = Expression.Constant(1); + right = Expression.Constant(value ? 1 : 2); + } + + break; + + //x.MemberName(Boolean) + case ExpressionType.MemberAccess: + left = exp; + right = Expression.Constant(true); + + break; + + //!x.MemberName(Boolean) + case ExpressionType.Not: + UnaryExpression unaryExp = exp as UnaryExpression; + if (unaryExp.Operand.NodeType == ExpressionType.MemberAccess) + { + left = unaryExp.Operand; + right = Expression.Constant(false); + } + + break; + } + + if (left != null) exp = Expression.MakeBinary(ExpressionType.Equal, left, right); + + return exp; + } + + protected virtual string GetOperator(BinaryExpression b) + { + string opr = string.Empty; + switch (b.NodeType) + { + case ExpressionType.Equal: + opr = " = "; + break; + case ExpressionType.NotEqual: + opr = " <> "; + break; + case ExpressionType.GreaterThan: + opr = " > "; + break; + case ExpressionType.GreaterThanOrEqual: + opr = " >= "; + break; + case ExpressionType.LessThan: + opr = " < "; + break; + case ExpressionType.LessThanOrEqual: + opr = " <= "; + break; + case ExpressionType.And: + case ExpressionType.AndAlso: + opr = b.Type == typeof(bool) ? " AND " : " & "; + break; + case ExpressionType.Or: + case ExpressionType.OrElse: + opr = b.Type == typeof(bool) ? " OR " : " | "; + break; + case ExpressionType.Add: + case ExpressionType.AddChecked: + opr = " + "; + break; + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + opr = " - "; + break; + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + opr = " * "; + break; + case ExpressionType.Divide: + opr = " / "; + break; + case ExpressionType.Modulo: + opr = " % "; + break; + case ExpressionType.Coalesce: + opr = "ISNULL"; + break; + default: + throw new NotSupportedException(string.Format("{0} is not supported.", b.NodeType)); + } + + return opr; + } + + // 判断是否需要括号 + protected bool TakeParenthese(Expression expression, Expression subExp = null) + { + if (subExp != null) + { + UnaryExpression unaryExpression = subExp as UnaryExpression; + if (unaryExpression != null) return TakeParenthese(expression, unaryExpression.Operand); + + InvocationExpression invokeExpression = subExp as InvocationExpression; + if (invokeExpression != null) return TakeParenthese(expression, invokeExpression.Expression); + + LambdaExpression lambdaExpression = subExp as LambdaExpression; + if (lambdaExpression != null) return TakeParenthese(expression, lambdaExpression.Body); + + BinaryExpression b = subExp as BinaryExpression; + if (b != null) + { + if (expression.NodeType == ExpressionType.OrElse) + return true; + } + } + + return this.GetPriority(expression) < this.GetPriority(subExp); + } + + protected int GetPriority(Expression expression) + { + switch (expression.NodeType) + { + case ExpressionType.Add: + case ExpressionType.AddChecked: + case ExpressionType.ExclusiveOr: + case ExpressionType.Subtract: + case ExpressionType.SubtractChecked: + return 3; + case ExpressionType.And: + return expression.Type == typeof(bool) ? 6 : 3; + case ExpressionType.AndAlso: + return 6; + case ExpressionType.Divide: + case ExpressionType.Modulo: + case ExpressionType.Multiply: + case ExpressionType.MultiplyChecked: + return 2; + case ExpressionType.Equal: + case ExpressionType.GreaterThan: + case ExpressionType.GreaterThanOrEqual: + case ExpressionType.LessThan: + case ExpressionType.LessThanOrEqual: + case ExpressionType.NotEqual: + return 4; + case ExpressionType.Not: + return expression.Type == typeof(bool) ? 5 : 1; + case ExpressionType.Or: + return expression.Type == typeof(bool) ? 7 : 3; + case ExpressionType.OrElse: + return 7; + default: + return 0; + } + } + + #endregion + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `methodExpression` last assigned on line 209 could be null and is dereferenced at line 210, column 17. + +### Severity: +ERROR + +### Procedure: +Expression ExpressionVisitorBase.VisitMember(MemberExpression) + +### File: +net45/TZM.XFramework/Data/ExpressionVisitor/ExpressionVisitorBase.cs + +### Key: +ExpressionVisitorBase.cs|VisitMember|NULL_DEREFERENCE + +### Node Key: +90535029835413c6e5d1bdebbf52bdf9 + +### Hash: +40909e960c19392ca1d9db8b5f7a8424 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0590/instruction.md b/inferredbugs-0590/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..182c4f678649e36a6b5f1addcf853214d72d64c6 --- /dev/null +++ b/inferredbugs-0590/instruction.md @@ -0,0 +1,150 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Riz.XFramework +**Bug ID:** 25 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Linq.Expressions; + +namespace TZM.XFramework.Data +{ + /// + /// UPDATE 表达式解析器 + /// + public class UpdateExpressionVisitor : ExpressionVisitorBase + { + private IDbQueryProvider _provider = null; + private TableAliasCache _aliases = null; + + /// + /// 初始化 类的新实例 + /// + /// 查询语义提供者 + /// 表别名集合 + /// 要访问的表达式 + public UpdateExpressionVisitor(IDbQueryProvider provider, TableAliasCache aliases, Expression expression) + : base(provider, aliases, expression) + { + _provider = provider; + _aliases = aliases; + } + + /// + /// 访问成员初始化表达式,如 => new App() {Id = p.Id} + /// + /// 要访问的成员初始化表达式 + /// + protected override Expression VisitMemberInit(MemberInitExpression node) + { + if (node.Bindings == null || node.Bindings.Count == 0) + throw new XFrameworkException("Update at least update one member."); + + for (int index = 0; index < node.Bindings.Count; ++index) + { + //MemberAssignment member = node.Bindings[index] as MemberAssignment; + //_builder.AppendMember("t0", member.Member.Name); + //_builder.Append(" = "); + + //if (member.Expression.CanEvaluate()) + // _builder.Append(member.Expression.Evaluate().Value, member.Member); + //else + // this.VisitWithoutRemark(x => base.Visit(member.Expression)); + + //if (index < node.Bindings.Count - 1) + //{ + // _builder.Append(","); + // _builder.AppendNewLine(); + //} + } + return node; + } + + /// + /// 访问构造函数表达式,如 =>new {Id = p.Id}} + /// + /// 构造函数调用的表达式 + /// + protected override Expression VisitNew(NewExpression node) + { + // 匿名类的New + if (node == null) return node; + if (node.Arguments == null || node.Arguments.Count == 0) + throw new XFrameworkException("Update at least update one member."); + + for (int index = 0; index < node.Arguments.Count; index++) + { + //var member = node.Members[index]; + //_builder.AppendMember("t0", member.Name); + //_builder.Append(" = "); + + //if (node.Arguments[index].CanEvaluate()) + // _builder.Append(node.Arguments[index].Evaluate().Value, member); + //else + // base.Visit(node.Arguments[index]); + + //if (index < node.Arguments.Count - 1) + //{ + // _builder.Append(','); + // _builder.AppendNewLine(); + //} + } + + return node; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `member` last assigned on line 32 could be null and is dereferenced at line 33, column 17. + +### Severity: +ERROR + +### Procedure: +Expression UpdateExpressionVisitor.VisitMemberInit(MemberInitExpression) + +### File: +net45/TZM.XFramework/Data/ExpressionVisitor/UpdateExpressionVisitor.cs + +### Key: +UpdateExpressionVisitor.cs|VisitMemberInit|NULL_DEREFERENCE + +### Node Key: +91b8c216590cdce695b1f86e7c48e6c5 + +### Hash: +ca68bae44360dc2f736535b6624c50e9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0591/instruction.md b/inferredbugs-0591/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74089d2c740e8f835aa260d2915220b69a4066a6 --- /dev/null +++ b/inferredbugs-0591/instruction.md @@ -0,0 +1,331 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** socket.io-client-csharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; +using SocketIOClient.Messages; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; + +namespace SocketIOClient.UnitTest.ConverterTests +{ + [TestClass] + public class ConverterReadTest + { + [TestMethod] + public void Opened() + { + var msg = MessageFactory.CreateMessage("0{\"sid\":\"6lV4Ef7YOyGF-5dCBvKy\",\"upgrades\":[],\"pingInterval\":10000,\"pingTimeout\":5000}"); + Assert.AreEqual(MessageType.Opened, msg.Type); + + var openedMsg = msg as OpenedMessage; + + Assert.AreEqual("6lV4Ef7YOyGF-5dCBvKy", openedMsg.Sid); + Assert.AreEqual(10000, openedMsg.PingInterval); + Assert.AreEqual(5000, openedMsg.PingTimeout); + } + + [TestMethod] + public void Ping() + { + var msg = MessageFactory.CreateMessage("2"); + Assert.AreEqual(MessageType.Ping, msg.Type); + } + + [TestMethod] + public void Pong() + { + var msg = MessageFactory.CreateMessage("3"); + Assert.AreEqual(MessageType.Pong, msg.Type); + } + + [TestMethod] + public void Eio4Connected() + { + var msg = MessageFactory.CreateMessage("40{\"sid\":\"aMA_EmVTuzpgR16PAc4w\"}"); + Assert.AreEqual(MessageType.Connected, msg.Type); + + var connectedMsg = msg as ConnectedMessage; + + Assert.AreEqual(string.Empty, connectedMsg.Namespace); + Assert.AreEqual("aMA_EmVTuzpgR16PAc4w", connectedMsg.Sid); + } + + [TestMethod] + public void Eio4NamespaceConnected() + { + var msg = MessageFactory.CreateMessage("40/nsp,{\"sid\":\"xO_jp2_xrGtXUveLAc4y\"}"); + Assert.AreEqual(MessageType.Connected, msg.Type); + + var connectedMsg = msg as ConnectedMessage; + + Assert.AreEqual("/nsp", connectedMsg.Namespace); + Assert.AreEqual("xO_jp2_xrGtXUveLAc4y", connectedMsg.Sid); + } + + [TestMethod] + public void Disconnected() + { + var msg = MessageFactory.CreateMessage("41"); + Assert.AreEqual(MessageType.Disconnected, msg.Type); + + var realMsg = msg as DisconnectedMessage; + + Assert.AreEqual(string.Empty, realMsg.Namespace); + } + + [TestMethod] + public void NamespaceDisconnected() + { + var msg = MessageFactory.CreateMessage("41/github,"); + Assert.AreEqual(MessageType.Disconnected, msg.Type); + + var realMsg = msg as DisconnectedMessage; + + Assert.AreEqual("/github", realMsg.Namespace); + } + + [TestMethod] + public void Event0Param() + { + var msg = MessageFactory.CreateMessage("42[\"hi\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + + Assert.AreEqual("hi", realMsg.Event); + Assert.AreEqual(0, realMsg.JsonElements.Count); + } + + [TestMethod] + public void Event1Param() + { + var msg = MessageFactory.CreateMessage("42[\"hi\",\"V3: onAny\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + + Assert.AreEqual("hi", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("V3: onAny", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void NamespaceEvent0Param() + { + var msg = MessageFactory.CreateMessage("42/nsp,[\"234\"]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.AreEqual("/nsp", realMsg.Namespace); + + Assert.AreEqual("234", realMsg.Event); + Assert.AreEqual(0, realMsg.JsonElements.Count); + } + + [TestMethod] + public void NamespaceEvent1Param() + { + var msg = MessageFactory.CreateMessage("42/nsp,[\"qww\",true]"); + Assert.AreEqual(MessageType.EventMessage, msg.Type); + + var realMsg = msg as EventMessage; + + Assert.AreEqual("/nsp", realMsg.Namespace); + + Assert.AreEqual("qww", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.IsTrue(realMsg.JsonElements[0].GetBoolean()); + } + + [TestMethod] + public void Ack() + { + var msg = MessageFactory.CreateMessage("431[\"doghappy\"]"); + Assert.AreEqual(MessageType.AckMessage, msg.Type); + + var realMsg = msg as ClientAckMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + Assert.AreEqual(1, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("doghappy", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void NamespaceAck() + { + var msg = MessageFactory.CreateMessage("43/google,15[\"doghappy\"]"); + Assert.AreEqual(MessageType.AckMessage, msg.Type); + + var realMsg = msg as ClientAckMessage; + + Assert.AreEqual("/google", realMsg.Namespace); + Assert.AreEqual(15, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual("doghappy", realMsg.JsonElements[0].GetString()); + } + + [TestMethod] + public void Error() + { + var msg = MessageFactory.CreateMessage("44{\"message\":\"Authentication error2\"}"); + Assert.AreEqual(MessageType.ErrorMessage, msg.Type); + + var result = msg as ErrorMessage; + + Assert.AreEqual("Authentication error2", result.Message); + } + + [TestMethod] + public void Binary() + { + var msg = MessageFactory.CreateMessage("451-[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.IsTrue(string.IsNullOrEmpty(realMsg.Namespace)); + Assert.AreEqual(1, realMsg.BinaryCount); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinary() + { + var msg = MessageFactory.CreateMessage("451-/why-ve,[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.AreEqual("/why-ve", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinaryWithId() + { + var msg = MessageFactory.CreateMessage("451-/why-ve,30[\"1 params\",{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryMessage, msg.Type); + + var realMsg = msg as BinaryMessage; + + Assert.AreEqual("/why-ve", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(30, realMsg.Id); + + Assert.AreEqual("1 params", realMsg.Event); + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void BinaryAck() + { + var msg = MessageFactory.CreateMessage("461-6[{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryAckMessage, msg.Type); + + var realMsg = msg as ServerBinaryAckMessage; + + Assert.IsNull(realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(6, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + + [TestMethod] + public void NamespaceBinaryAck() + { + var msg = MessageFactory.CreateMessage("461-/name-space,6[{\"_placeholder\":true,\"num\":0}]"); + Assert.AreEqual(MessageType.BinaryAckMessage, msg.Type); + + var realMsg = msg as ServerBinaryAckMessage; + + Assert.AreEqual("/name-space", realMsg.Namespace); + Assert.AreEqual(1, realMsg.BinaryCount); + Assert.AreEqual(6, realMsg.Id); + + Assert.AreEqual(1, realMsg.JsonElements.Count); + Assert.AreEqual(JsonValueKind.Object, realMsg.JsonElements[0].ValueKind); + } + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `realMsg` last assigned on line 259 could be null and is dereferenced at line 261, column 13. + +### Severity: +ERROR + +### Procedure: +Void ConverterReadTest.NamespaceBinaryAck() + +### File: +src/SocketIOClient.UnitTest/ConverterTests/ConverterReadTest.cs + +### Key: +ConverterReadTest.cs|NamespaceBinaryAck|NULL_DEREFERENCE + +### Node Key: +a35c6d97ccef7486c04c7fb208054b5b + +### Hash: +16ff83dccb4ca5ef941dc8bea796f9d1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0596/instruction.md b/inferredbugs-0596/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12fc7e6d204eca4b940731a8f3ca124824e20d54 --- /dev/null +++ b/inferredbugs-0596/instruction.md @@ -0,0 +1,255 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ExpressiveAnnotations +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +namespace ExpressiveAnnotations.Analysis +{ + /* EBNF GRAMMAR: + * + * expression => or-exp + * or-exp => and-exp [ "||" or-exp ] + * and-exp => not-exp [ "&&" and-exp ] + * not-exp => [ "!" ] rel-exp + * rel-exp => val [ rel-op val ] + * rel-op => "==" | "!=" | ">" | ">=" | "<" | "<=" + * val => "null" | int | float | bool | string | prop | "(" or-exp ")" + */ + + /// + /// Performs syntactic analysis of provided logical expression within given context. + /// + public sealed class Parser + { + private Stack Tokens { get; set; } + private Type ContextType { get; set; } + private Expression ContextExpression { get; set; } + + /// + /// Parses the specified logical expression into expression tree within given object context. + /// + /// The type identifier of the context within which the expression is interpreted. + /// The logical expression. + /// A delegate containing the compiled version of the lambda expression described by created expression tree. + public Func Parse(string expression) + { + ContextType = typeof(Context); + var param = Expression.Parameter(typeof(Context)); + ContextExpression = param; + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + /// + /// Parses the specified logical expression and builds expression tree. + /// + /// The type instance of the context within which the expression is interpreted. + /// The logical expression. + /// A delegate containing the compiled version of the lambda expression described by produced expression tree. + public Func Parse(Type context, string expression) + { + ContextType = context; + var param = Expression.Parameter(typeof(object)); + ContextExpression = Expression.Convert(param, context); + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + private void InitTokenizer(string expression) + { + var lexer = new Lexer(); + Tokens = new Stack(lexer.Analyze(expression).Reverse()); + } + + private bool PeekToken(out Token token) + { + token = Tokens.Any() ? Tokens.Peek() : null; + return token != null; + } + + private void CrushToken() + { + Tokens.Pop(); + } + + private Expression ParseExpression() + { + return ParseOrExp(); + } + + private Expression ParseOrExp() + { + var arg1 = ParseAndExp(); + Token token; + if (!PeekToken(out token) || token.Id != TokenId.OR) + return arg1; + CrushToken(); + var arg2 = ParseOrExp(); + return Expression.Or(arg1, arg2); + } + + private Expression ParseAndExp() + { + var arg1 = ParseNotExp(); + Token token; + if (!PeekToken(out token) || token.Id != TokenId.AND) + return arg1; + CrushToken(); + var arg2 = ParseAndExp(); + return Expression.And(arg1, arg2); + } + + private Expression ParseNotExp() + { + Token token; + if (!PeekToken(out token) || token.Id != TokenId.NOT) + return ParseRelExp(); + CrushToken(); + return Expression.Not(ParseRelExp()); + } + + private Expression ParseRelExp() + { + var arg1 = ParseVal(); + Token token; + if (!PeekToken(out token) || !new[] { TokenId.LT, TokenId.LE, TokenId.GT, TokenId.GE, TokenId.EQ, TokenId.NEQ }.Contains(token.Id)) + return arg1; + CrushToken(); + var arg2 = ParseVal(); + + Helper.MakeTypesCompatible(arg1, arg2, out arg1, out arg2); + switch (token.Id) + { + case TokenId.LT: + return Expression.LessThan(arg1, arg2); + case TokenId.LE: + return Expression.LessThanOrEqual(arg1, arg2); + case TokenId.GT: + return Expression.GreaterThan(arg1, arg2); + case TokenId.GE: + return Expression.GreaterThanOrEqual(arg1, arg2); + case TokenId.EQ: + return Expression.Equal(arg1, arg2); + case TokenId.NEQ: + return Expression.NotEqual(arg1, arg2); + default: + throw new InvalidOperationException(); + } + } + + private Expression ParseVal() + { + Token token; + if (!PeekToken(out token)) + throw new InvalidOperationException(); + + if (token.Id == TokenId.LEFT_BRACKET) + { + CrushToken(); + var arg = ParseOrExp(); + if (!PeekToken(out token) || token.Id != TokenId.RIGHT_BRACKET) + throw new InvalidOperationException(); + CrushToken(); + return arg; + } + + CrushToken(); + switch (token.Id) + { + case TokenId.NULL: + return Expression.Constant(null); + case TokenId.INT: + return Expression.Constant(token.Value, typeof(int)); + case TokenId.FLOAT: + return Expression.Constant(token.Value, typeof(float)); + case TokenId.BOOL: + return Expression.Constant(token.Value, typeof(bool)); + case TokenId.STRING: + return Expression.Constant(token.Value, typeof(string)); + case TokenId.PROPERTY: + return ExtractProperty(token.Value.ToString()); + default: + throw new InvalidOperationException(); + } + } + + private Expression ExtractProperty(string name) + { + var props = name.Split('.'); + var type = ContextType; + var expr = ContextExpression; + foreach (var prop in props) + { + var pi = type.GetProperty(prop); + if (pi == null) + throw new ArgumentException(string.Format("Dynamic extraction interrupted. Field {0} not found.", prop), name); + expr = Expression.Property(expr, pi); + type = pi.PropertyType; + } + return expr; + } + } +} + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +`token` could be null (from the call to `Parser.PeekToken(...)` on line 109) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Expression Parser.ParseNotExp() + +### File: +src/ExpressiveAnnotations/Analysis/Parser.cs + +### Key: +Parser.cs|ParseNotExp|NULLPTR_DEREFERENCE + +### Hash: +c910391f39601484374e83567ae274fc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0597/instruction.md b/inferredbugs-0597/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e97e8a15ad840c14e17fefa595938d435410e77e --- /dev/null +++ b/inferredbugs-0597/instruction.md @@ -0,0 +1,284 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ExpressiveAnnotations +**Bug ID:** 6 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using ExpressiveAnnotations.LogicalExpressionsAnalysis.LexicalAnalysis; +using ExpressiveAnnotations.Misc; + +namespace ExpressiveAnnotations.LogicalExpressionsAnalysis.SyntacticAnalysis +{ + /* EBNF GRAMMAR: + * + * expression => or-exp + * or-exp => and-exp [ "||" or-exp ] + * and-exp => not-exp [ "&&" and-exp ] + * not-exp => [ "!" ] rel-exp + * rel-exp => val [ rel-op val ] + * rel-op => "==" | "!=" | ">" | ">=" | "<" | "<=" + * val => "null" | int | float | bool | string | prop | "(" or-exp ")" + */ + + internal sealed class Parser + { + private Stack Tokens { get; set; } + private Type ModelType { get; set; } + private Expression ModelExpression { get; set; } + + public Func Parse(string expression) + { + ModelType = typeof(ObjectType); + var param = Expression.Parameter(typeof(ObjectType)); + ModelExpression = param; + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + public Func Parse(Type objectType, string expression) + { + ModelType = objectType; + var param = Expression.Parameter(typeof(object)); + ModelExpression = Expression.Convert(param, objectType); + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + private void InitTokenizer(string expression) + { + var lexer = new Lexer(); + Tokens = new Stack(lexer.Analyze(expression).Reverse()); + } + + private TokenOutput PeekToken() + { + if (Tokens.Any()) + return Tokens.Peek(); + return null; + } + + private void CrushToken() + { + Tokens.Pop(); + } + + private Expression ParseExpression() + { + return ParseOrExp(); + } + + private Expression ParseOrExp() + { + var arg1 = ParseAndExp(); + if (PeekToken().Token != Token.OR) + return arg1; + CrushToken(); + var arg2 = ParseOrExp(); + return Expression.Or(arg1, arg2); + } + + private Expression ParseAndExp() + { + var arg1 = ParseNotExp(); + if (PeekToken().Token != Token.AND) + return arg1; + CrushToken(); + var arg2 = ParseAndExp(); + return Expression.And(arg1, arg2); + } + + private Expression ParseNotExp() + { + var isNot = PeekToken().Token == Token.NOT; + if (isNot) + CrushToken(); + var arg = ParseRelExp(); + + if (isNot) + return Expression.Not(arg); + return arg; + } + + private Expression ParseRelExp() + { + var arg1 = ParseVal(); + var token = PeekToken(); + if (!new[] { Token.LT, Token.LE, Token.GT, Token.GE, Token.EQ, Token.NEQ }.Contains(token.Token)) + return arg1; + CrushToken(); + var arg2 = ParseVal(); + + Helper.MakeTypesCompatible(arg1, arg2, out arg1, out arg2); + switch (token.Token) + { + case Token.LT: + return Expression.LessThan(arg1, arg2); + case Token.LE: + return Expression.LessThanOrEqual(arg1, arg2); + case Token.GT: + return Expression.GreaterThan(arg1, arg2); + case Token.GE: + return Expression.GreaterThanOrEqual(arg1, arg2); + case Token.EQ: + return Expression.Equal(arg1, arg2); + case Token.NEQ: + return Expression.NotEqual(arg1, arg2); + default: + throw new InvalidOperationException(); + } + } + + private Expression ParseVal() + { + if (PeekToken().Token == Token.LEFT_BRACKET) + { + CrushToken(); + var arg = ParseOrExp(); + if (PeekToken().Token != Token.RIGHT_BRACKET) + throw new InvalidOperationException(); + CrushToken(); + return arg; + } + + if (PeekToken().Token == Token.NULL) + { + CrushToken(); + return Expression.Constant(null); + } + + var value = ParseIntLiteral() ?? ParseFloatLiteral() ?? ParseBoolLiteral() ?? ParseStringLiteral() ?? ParseProp(); + if (value == null) + throw new InvalidOperationException(); + return value; + } + + private Expression ParseIntLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.INT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(int)); + } + return null; + } + + private Expression ParseFloatLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.FLOAT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(float)); + } + return null; + } + + private Expression ParseBoolLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.BOOL) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(bool)); + } + return null; + } + + private Expression ParseStringLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.INT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(string)); + } + return null; + } + + private Expression ParseProp() + { + var token = PeekToken(); + if (PeekToken().Token == Token.PROPERTY) + { + CrushToken(); + var propName = token.Value.ToString(); + var props = propName.Split('.'); + var type = ModelType; + var expr = ModelExpression; + foreach (var prop in props) + { + var pi = type.GetProperty(prop); + if (pi == null) + throw new ArgumentException(string.Format("Dynamic extraction interrupted. Field {0} not found.", prop), propName); + expr = Expression.Property(expr, pi); + type = pi.PropertyType; + } + return expr; + } + return null; + } + } +} + + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +``TokenOutput Parser.PeekToken()`` could be null (from the call to `Parser.PeekToken()` on line 75) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Expression Parser.ParseOrExp() + +### File: +src/ExpressiveAnnotations/Analysis/Parser.cs + +### Key: +Parser.cs|ParseOrExp|NULLPTR_DEREFERENCE + +### Hash: +7730e3ed4c281d72a26920c0276c1d7f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0598/instruction.md b/inferredbugs-0598/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69bcb155d58976bb0a0b8f11a56b1d3baaa8c272 --- /dev/null +++ b/inferredbugs-0598/instruction.md @@ -0,0 +1,284 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** ExpressiveAnnotations +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; +using ExpressiveAnnotations.LogicalExpressionsAnalysis.LexicalAnalysis; +using ExpressiveAnnotations.Misc; + +namespace ExpressiveAnnotations.LogicalExpressionsAnalysis.SyntacticAnalysis +{ + /* EBNF GRAMMAR: + * + * expression => or-exp + * or-exp => and-exp [ "||" or-exp ] + * and-exp => not-exp [ "&&" and-exp ] + * not-exp => [ "!" ] rel-exp + * rel-exp => val [ rel-op val ] + * rel-op => "==" | "!=" | ">" | ">=" | "<" | "<=" + * val => "null" | int | float | bool | string | prop | "(" or-exp ")" + */ + + internal sealed class Parser + { + private Stack Tokens { get; set; } + private Type ModelType { get; set; } + private Expression ModelExpression { get; set; } + + public Func Parse(string expression) + { + ModelType = typeof(ObjectType); + var param = Expression.Parameter(typeof(ObjectType)); + ModelExpression = param; + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + public Func Parse(Type objectType, string expression) + { + ModelType = objectType; + var param = Expression.Parameter(typeof(object)); + ModelExpression = Expression.Convert(param, objectType); + InitTokenizer(expression); + var expressionTree = ParseExpression(); + var lambda = Expression.Lambda>(expressionTree, param); + return lambda.Compile(); + } + + private void InitTokenizer(string expression) + { + var lexer = new Lexer(); + Tokens = new Stack(lexer.Analyze(expression).Reverse()); + } + + private TokenOutput PeekToken() + { + if (Tokens.Any()) + return Tokens.Peek(); + return null; + } + + private void CrushToken() + { + Tokens.Pop(); + } + + private Expression ParseExpression() + { + return ParseOrExp(); + } + + private Expression ParseOrExp() + { + var arg1 = ParseAndExp(); + if (PeekToken().Token != Token.OR) + return arg1; + CrushToken(); + var arg2 = ParseOrExp(); + return Expression.Or(arg1, arg2); + } + + private Expression ParseAndExp() + { + var arg1 = ParseNotExp(); + if (PeekToken().Token != Token.AND) + return arg1; + CrushToken(); + var arg2 = ParseAndExp(); + return Expression.And(arg1, arg2); + } + + private Expression ParseNotExp() + { + var isNot = PeekToken().Token == Token.NOT; + if (isNot) + CrushToken(); + var arg = ParseRelExp(); + + if (isNot) + return Expression.Not(arg); + return arg; + } + + private Expression ParseRelExp() + { + var arg1 = ParseVal(); + var token = PeekToken(); + if (!new[] { Token.LT, Token.LE, Token.GT, Token.GE, Token.EQ, Token.NEQ }.Contains(token.Token)) + return arg1; + CrushToken(); + var arg2 = ParseVal(); + + Helper.MakeTypesCompatible(arg1, arg2, out arg1, out arg2); + switch (token.Token) + { + case Token.LT: + return Expression.LessThan(arg1, arg2); + case Token.LE: + return Expression.LessThanOrEqual(arg1, arg2); + case Token.GT: + return Expression.GreaterThan(arg1, arg2); + case Token.GE: + return Expression.GreaterThanOrEqual(arg1, arg2); + case Token.EQ: + return Expression.Equal(arg1, arg2); + case Token.NEQ: + return Expression.NotEqual(arg1, arg2); + default: + throw new InvalidOperationException(); + } + } + + private Expression ParseVal() + { + if (PeekToken().Token == Token.LEFT_BRACKET) + { + CrushToken(); + var arg = ParseOrExp(); + if (PeekToken().Token != Token.RIGHT_BRACKET) + throw new InvalidOperationException(); + CrushToken(); + return arg; + } + + if (PeekToken().Token == Token.NULL) + { + CrushToken(); + return Expression.Constant(null); + } + + var value = ParseIntLiteral() ?? ParseFloatLiteral() ?? ParseBoolLiteral() ?? ParseStringLiteral() ?? ParseProp(); + if (value == null) + throw new InvalidOperationException(); + return value; + } + + private Expression ParseIntLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.INT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(int)); + } + return null; + } + + private Expression ParseFloatLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.FLOAT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(float)); + } + return null; + } + + private Expression ParseBoolLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.BOOL) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(bool)); + } + return null; + } + + private Expression ParseStringLiteral() + { + var token = PeekToken(); + if (PeekToken().Token == Token.INT) + { + CrushToken(); + return Expression.Constant(token.Value, typeof(string)); + } + return null; + } + + private Expression ParseProp() + { + var token = PeekToken(); + if (PeekToken().Token == Token.PROPERTY) + { + CrushToken(); + var propName = token.Value.ToString(); + var props = propName.Split('.'); + var type = ModelType; + var expr = ModelExpression; + foreach (var prop in props) + { + var pi = type.GetProperty(prop); + if (pi == null) + throw new ArgumentException(string.Format("Dynamic extraction interrupted. Field {0} not found.", prop), propName); + expr = Expression.Property(expr, pi); + type = pi.PropertyType; + } + return expr; + } + return null; + } + } +} + + +``` + +### Bug Type: +NULLPTR_DEREFERENCE + +### Qualifier: +``TokenOutput Parser.PeekToken()`` could be null (from the call to `Parser.PeekToken()` on line 145) and is dereferenced. + +### Severity: +ERROR + +### Procedure: +Expression Parser.ParseVal() + +### File: +src/ExpressiveAnnotations/Analysis/Parser.cs + +### Key: +Parser.cs|ParseVal|NULLPTR_DEREFERENCE + +### Hash: +78378aa1f177c9371012ab652e040da9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0613/instruction.md b/inferredbugs-0613/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c69a99a28239d7f146f17e1ec7c344de9735e015 --- /dev/null +++ b/inferredbugs-0613/instruction.md @@ -0,0 +1,144 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** net-ipfs-http-client +**Bug ID:** 9 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Net; +using System.Reflection; +using System.Web; +using Newtonsoft.Json; + +namespace Ipfs.Api +{ + /// + /// A client that allows access to the InterPlanetary File System (IPFS). + /// + /// + /// The API is based on the IPFS commands. + /// + /// IPFS API + /// IPFS commands + public partial class IpfsClient + { + /// + /// Creates a new instance of the class and sets the + /// default values; + /// + public IpfsClient() + { + ApiAddress = new Uri("http://localhost:5001"); + var version = Assembly.GetExecutingAssembly().GetName().Version; + UserAgent = string.Format("net-ipfs/{0}.{1}", version.Major, version.Minor); + TrustedPeers = new TruestedPeerCollection(this); + } + + /// + /// The URL to the IPFS API server. The default is "http://localhost:5001"; + /// + public Uri ApiAddress { get; set; } + + /// + /// The value of HTTP User-Agent header sent to the API server. + /// + /// + /// The default value is "net-ipfs/M.N", where M is the major and N is minor version + /// numbers of the assembly. + /// + public string UserAgent { get; set; } + + /// + /// The list of peers that are initially trusted by IPFS. + /// + /// + /// This is equilivent to ipfs bootstrap list. + /// + public TruestedPeerCollection TrustedPeers { get; private set; } + + Uri BuildCommand(string command, string arg = null) + { + var url = "/api/v0/" + command; + if (arg != null) + url += "?arg=" + HttpUtility.UrlEncode(arg); + return new Uri(ApiAddress, url); + } + + WebClient Api() + { + var api = new WebClient + { + Encoding = Encoding.UTF8 + }; + api.Headers["User-Agent"] = UserAgent; + return api; + } + + protected internal string DoCommand(string command, string arg = null) + { + return Api().DownloadString(BuildCommand(command, arg)); + } + + protected internal T DoCommand(string command, string arg = null) + { + var json = Api().DownloadString(BuildCommand(command, arg)); + return JsonConvert.DeserializeObject(json); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Net.WebClient Ipfs.Api.IpfsClient::Api() at Line 76) of type System.Net.WebClient in method "String IpfsClient.DoCommand(String,String)". + +### Severity: +ERROR + +### Procedure: +String IpfsClient.DoCommand(String,String) + +### File: +src/IpfsClient.cs + +### Key: +IpfsClient.cs|DoCommand|DOTNET_RESOURCE_LEAK + +### Hash: +362ca155805fa8ae0fe764cc760765d6 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0703/instruction.md b/inferredbugs-0703/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c9686739021f7b531c1c80b0980876046beef6b --- /dev/null +++ b/inferredbugs-0703/instruction.md @@ -0,0 +1,1157 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +// Python Tools for Visual Studio +// Copyright(c) Microsoft Corporation +// All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the License); you may not use +// this file except in compliance with the License. You may obtain a copy of the +// License at http://www.apache.org/licenses/LICENSE-2.0 +// +// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS +// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY +// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +// MERCHANTABLITY OR NON-INFRINGEMENT. +// +// See the Apache Version 2.0 License for specific language governing +// permissions and limitations under the License. + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using FluentAssertions; +using Microsoft.Python.LanguageServer; +using Microsoft.Python.LanguageServer.Implementation; +using Microsoft.Python.Tests.Utilities; +using Microsoft.Python.Tests.Utilities.FluentAssertions; +using Microsoft.PythonTools.Analysis; +using Microsoft.PythonTools.Analysis.FluentAssertions; +using Microsoft.PythonTools.Analysis.Values; +using Microsoft.PythonTools.Interpreter; +using Microsoft.PythonTools.Interpreter.Ast; +using Microsoft.PythonTools.Parsing; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestUtilities; +using static Microsoft.PythonTools.Analysis.Infrastructure.StringExtensions; +using Ast = Microsoft.PythonTools.Parsing.Ast; + +namespace AnalysisTests { + [TestClass] + public class AstAnalysisTests { + public TestContext TestContext { get; set; } + + [TestInitialize] + public void TestInitialize() => TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}"); + + private string _analysisLog; + private string _moduleCache; + + public AstAnalysisTests() { + _moduleCache = null; + } + + [TestCleanup] + public void Cleanup() { + if (TestContext.CurrentTestOutcome != UnitTestOutcome.Passed) { + if (_analysisLog != null) { + Console.WriteLine("Analysis log:"); + Console.WriteLine(_analysisLog); + } + + if (_moduleCache != null) { + Console.WriteLine("Module cache:"); + Console.WriteLine(_moduleCache); + } + } + + TestEnvironmentImpl.TestCleanup(); + } + + private static AstPythonInterpreterFactory CreateInterpreterFactory(InterpreterConfiguration configuration) { + configuration.AssertInstalled(); + var opts = new InterpreterFactoryCreationOptions { + DatabasePath = TestData.GetAstAnalysisCachePath(configuration.Version, true), + UseExistingCache = false + }; + + Trace.TraceInformation("Cache Path: " + opts.DatabasePath); + + return new AstPythonInterpreterFactory(configuration, opts); + } + + private static Task CreateServerAsync(InterpreterConfiguration configuration = null, string searchPath = null) + => new Server().InitializeAsync( + configuration ?? PythonVersions.LatestAvailable, + searchPaths: new [] { searchPath ?? TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }); + + private static AstPythonInterpreterFactory CreateInterpreterFactory() => CreateInterpreterFactory(PythonVersions.LatestAvailable); + + private static readonly Lazy _typeShedPath = new Lazy(FindTypeShedForTest); + private static string TypeShedPath => _typeShedPath.Value; + private static string FindTypeShedForTest() { + var candidate = Path.Combine(PathUtils.GetParent(typeof(AstPythonInterpreterFactory).Assembly.Location), "Typeshed"); + if (Directory.Exists(candidate) && Directory.Exists(Path.Combine(candidate, "stdlib", "2and3"))) { + return candidate; + } + + var root = TestData.GetPath(); + + for (string previousRoot = null; root != previousRoot; previousRoot = root, root = PathUtils.GetParent(root)) { + candidate = Path.Combine(root, "typeshed"); + if (Directory.Exists(Path.Combine(candidate, "stdlib", "2and3"))) { + return candidate; + } + } + + return null; + } + + + #region Test cases + + [TestMethod, Priority(0)] + public void AstClasses() { + var mod = Parse("Classes.py", PythonLanguageVersion.V35); + mod.GetMemberNames(null).Should().OnlyContain("C1", "C2", "C3", "C4", "C5", + "D", "E", + "F1", + "f" + ); + + mod.GetMember(null, "C1").Should().BeOfType() + .Which.Documentation.Should().Be("C1"); + mod.GetMember(null, "C2").Should().BeOfType(); + mod.GetMember(null, "C3").Should().BeOfType(); + mod.GetMember(null, "C4").Should().BeOfType(); + mod.GetMember(null, "C5").Should().BeOfType() + .Which.Documentation.Should().Be("C1"); + mod.GetMember(null, "D").Should().BeOfType(); + mod.GetMember(null, "E").Should().BeOfType(); + mod.GetMember(null, "f").Should().BeOfType(); + + var f1 = mod.GetMember(null, "F1").Should().BeOfType().Which; + f1.GetMemberNames(null).Should().OnlyContain("F2", "F3", "F6", "__class__", "__bases__"); + f1.GetMember(null, "F6").Should().BeOfType() + .Which.Documentation.Should().Be("C1"); + f1.GetMember(null, "F2").Should().BeOfType(); + f1.GetMember(null, "F3").Should().BeOfType(); + f1.GetMember(null, "__class__").Should().BeOfType(); + f1.GetMember(null, "__bases__").Should().BeOfType(); + } + + [TestMethod, Priority(0)] + public void AstFunctions() { + var mod = Parse("Functions.py", PythonLanguageVersion.V35); + mod.GetMemberNames(null).Should().OnlyContain("f", "f2", "g", "h", "C"); + + mod.GetMember(null, "f").Should().BeOfType() + .Which.Documentation.Should().Be("f"); + + mod.GetMember(null, "f2").Should().BeOfType() + .Which.Documentation.Should().Be("f"); + + mod.GetMember(null, "g").Should().BeOfType(); + mod.GetMember(null, "h").Should().BeOfType(); + + var c = mod.GetMember(null, "C").Should().BeOfType().Which; + c.GetMemberNames(null).Should().OnlyContain("i", "j", "C2", "__class__", "__bases__"); + c.GetMember(null, "i").Should().BeOfType(); + c.GetMember(null, "j").Should().BeOfType(); + c.GetMember(null, "__class__").Should().BeOfType(); + c.GetMember(null, "__bases__").Should().BeOfType(); + + var c2 = c.GetMember(null, "C2").Should().BeOfType().Which; + c2.GetMemberNames(null).Should().OnlyContain("k", "__class__", "__bases__"); + c2.GetMember(null, "k").Should().BeOfType(); + c2.GetMember(null, "__class__").Should().BeOfType(); + c2.GetMember(null, "__bases__").Should().BeOfType(); + } + + [TestMethod, Priority(0)] + public async Task AstValues() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("from Values import *"); + + analysis.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("y").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("z").OfTypes(BuiltinTypeId.Bytes) + .And.HaveVariable("pi").OfTypes(BuiltinTypeId.Float) + .And.HaveVariable("l").OfTypes(BuiltinTypeId.List) + .And.HaveVariable("t").OfTypes(BuiltinTypeId.Tuple) + .And.HaveVariable("d").OfTypes(BuiltinTypeId.Dict) + .And.HaveVariable("s").OfTypes(BuiltinTypeId.Set) + .And.HaveVariable("X").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("Y").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("Z").OfTypes(BuiltinTypeId.Bytes) + .And.HaveVariable("PI").OfTypes(BuiltinTypeId.Float) + .And.HaveVariable("L").OfTypes(BuiltinTypeId.List) + .And.HaveVariable("T").OfTypes(BuiltinTypeId.Tuple) + .And.HaveVariable("D").OfTypes(BuiltinTypeId.Dict) + .And.HaveVariable("S").OfTypes(BuiltinTypeId.Set); + } + } + + [TestMethod, Priority(0)] + public async Task AstMultiValues() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("from MultiValues import *"); + + analysis.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("y").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("z").OfTypes(BuiltinTypeId.Bytes) + .And.HaveVariable("l").OfTypes(BuiltinTypeId.List) + .And.HaveVariable("t").OfTypes(BuiltinTypeId.Tuple) + .And.HaveVariable("s").OfTypes(BuiltinTypeId.Set) + .And.HaveVariable("XY").OfTypes(BuiltinTypeId.Int, BuiltinTypeId.Str) + .And.HaveVariable("XYZ").OfTypes(BuiltinTypeId.Int, BuiltinTypeId.Str, BuiltinTypeId.Bytes) + .And.HaveVariable("D").OfTypes(BuiltinTypeId.List, BuiltinTypeId.Tuple, BuiltinTypeId.Dict, BuiltinTypeId.Set); + } + } + + [TestMethod, Priority(0)] + public void AstImports() { + var mod = Parse("Imports.py", PythonLanguageVersion.V35); + mod.GetMemberNames(null).Should().OnlyContain("version_info", "a_made_up_module"); + } + + [TestMethod, Priority(0)] + public async Task AstReturnTypes() { + using (var server = await CreateServerAsync()) { + var code = @"from ReturnValues import * +R_str = r_str() +R_object = r_object() +R_A1 = A() +R_A2 = A().r_A() +R_A3 = R_A1.r_A()"; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveFunctionVariables("r_a", "r_b", "r_str", "r_object") + .And.HaveClassVariables("A") + .And.HaveVariable("R_str").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("R_object").OfTypes(BuiltinTypeId.Object) + .And.HaveVariable("R_A1").OfTypes("A").WithDescription("A") + .And.HaveVariable("R_A2").OfTypes("A").WithDescription("A") + .And.HaveVariable("R_A3").OfTypes("A").WithDescription("A"); + } + } + + [TestMethod, Priority(0)] + public async Task AstInstanceMembers() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("from InstanceMethod import f1, f2"); + + analysis.Should().HaveVariable("f1").OfType(BuiltinTypeId.BuiltinFunction).WithValue() + .And.HaveVariable("f2").OfType(BuiltinTypeId.BuiltinMethodDescriptor).WithValue(); + } + } + + [TestMethod, Priority(0)] + public async Task AstInstanceMembers_Random() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("from random import *"); + + foreach (var fnName in new[] { "seed", "randrange", "gauss" }) { + analysis.Should().HaveVariable(fnName) + .OfType(BuiltinTypeId.BuiltinMethodDescriptor) + .WithValue() + .Which.Should().HaveOverloadWithParametersAt(0); + } + } + } + + [TestMethod, Priority(0)] + public async Task AstLibraryMembers_Datetime() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("import datetime"); + + var datetimeType = analysis.Should().HavePythonModuleVariable("datetime") + .Which.Should().HaveClass("datetime") + .Which; + + datetimeType.Should().HaveReadOnlyProperty("day").And.HaveMethod("now") + .Which.Should().BeClassMethod().And.HaveSingleOverload() + .Which.Should().HaveSingleReturnType() + .Which.Should().BeSameAs(datetimeType); + } + } + + [TestMethod, Priority(0)] + public async Task AstComparisonTypeInference() { + var code = @" +class BankAccount(object): + def __init__(self, initial_balance=0): + self.balance = initial_balance + def withdraw(self, amount): + self.balance -= amount + def overdrawn(self): + return self.balance < 0 +"; + + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveClass("BankAccount") + .Which.Should().HaveVariable("overdrawn").WithValue() + .Which.Should().HaveOverloadAt(0) + .Which.Should().HaveSingleReturnType("bool"); + } + } + + [TestMethod, Priority(0)] + public async Task AstSearchPathsThroughFactory() { + using (var factory = CreateInterpreterFactory()) + using (var analyzer = await PythonAnalyzer.CreateAsync(factory)) { + try { + var interpreter = (AstPythonInterpreter)analyzer.Interpreter; + + var moduleNamesChanged = EventTaskSources.AstPythonInterpreter.ModuleNamesChanged.Create(interpreter, new CancellationTokenSource(1000).Token); + factory.SetCurrentSearchPaths(new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }); + await moduleNamesChanged; + + interpreter.GetModuleNames().Should().Contain("Values"); + interpreter.ImportModule("Values").Should().NotBeNull("module should be available"); + + moduleNamesChanged = EventTaskSources.AstPythonInterpreter.ModuleNamesChanged.Create(interpreter, new CancellationTokenSource(1000).Token); + factory.SetCurrentSearchPaths(Enumerable.Empty()); + await moduleNamesChanged; + + interpreter.GetModuleNames().Should().NotContain("Values"); + interpreter.ImportModule("Values").Should().BeNull("module should be removed"); + } finally { + _analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture); + } + } + } + + [TestMethod, Priority(0)] + public async Task AstSearchPathsThroughAnalyzer() { + using (var factory = CreateInterpreterFactory()) + using (var analyzer = await PythonAnalyzer.CreateAsync(factory)) { + try { + var interpreter = (AstPythonInterpreter)analyzer.Interpreter; + + var moduleNamesChanged = EventTaskSources.AstPythonInterpreter.ModuleNamesChanged.Create(interpreter, new CancellationTokenSource(1000).Token); + analyzer.SetSearchPaths(new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }); + await moduleNamesChanged; + + interpreter.GetModuleNames().Should().Contain("Values"); + interpreter.ImportModule("Values").Should().NotBeNull("module should be available"); + + moduleNamesChanged = EventTaskSources.AstPythonInterpreter.ModuleNamesChanged.Create(interpreter, new CancellationTokenSource(1000).Token); + analyzer.SetSearchPaths(Enumerable.Empty()); + await moduleNamesChanged; + + interpreter.GetModuleNames().Should().NotContain("Values"); + interpreter.ImportModule("Values").Should().BeNull("module should be removed"); + } finally { + _analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture); + } + } + } + + [TestMethod, Priority(0)] + public async Task AstTypeStubPaths_NoStubs() { + using (var server = await CreateServerAsync()) { + var analysis = await GetStubBasedAnalysis( + server, + "import Package.Module\n\nc = Package.Module.Class()", + new AnalysisLimits { UseTypeStubPackages = false }, + searchPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }, + stubPaths: Enumerable.Empty()); + + analysis.Should().HavePythonModuleVariable("Package"); + + analysis.Should().HaveVariable("c") + .WithValue() + .Which.Should().HaveMembers("untyped_method", "inferred_method") + .And.NotHaveMembers("typed_method", "typed_method_2"); + } + } + + [TestMethod, Priority(0)] + public async Task AstTypeStubPaths_MergeStubs() { + using (var server = await CreateServerAsync()) { + var analysis = await GetStubBasedAnalysis(server, + "import Package.Module\n\nc = Package.Module.Class()", + new AnalysisLimits { + UseTypeStubPackages = true, + UseTypeStubPackagesExclusively = false + }, + searchPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }, + stubPaths: Enumerable.Empty()); + + analysis.Should().HavePythonModuleVariable("Package"); + + analysis.Should().HaveVariable("c") + .WithValue() + .Which.Should().HaveMembers("untyped_method", "inferred_method", "typed_method") + .And.NotHaveMembers("typed_method_2"); + } + } + + [TestMethod, Priority(0)] + + public async Task AstTypeStubPaths_MergeStubsPath() { + using (var server = await CreateServerAsync()) { + var analysis = await GetStubBasedAnalysis( + server, + "import Package.Module\n\nc = Package.Module.Class()", + null, + searchPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }, + stubPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis", "Stubs")) }); + + analysis.Should().HavePythonModuleVariable("Package"); // member information comes from multiple sources + + analysis.Should().HaveVariable("c") + .WithValue() + .Which.Should().HaveMembers("untyped_method", "inferred_method", "typed_method_2") + .And.NotHaveMembers("typed_method"); + } + } + + [TestMethod, Priority(0)] + public async Task AstTypeStubPaths_ExclusiveStubs() { + using (var server = await CreateServerAsync()) { + var analysis = await GetStubBasedAnalysis( + server, + "import Package.Module\n\nc = Package.Module.Class()", + new AnalysisLimits { + UseTypeStubPackages = true, + UseTypeStubPackagesExclusively = true + }, + searchPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis")) }, + stubPaths: new[] { TestData.GetPath(Path.Combine("TestData", "AstAnalysis", "Stubs")) }); + + analysis.Should().HavePythonModuleVariable("Package"); + + analysis.Should().HaveVariable("c") + .WithValue() + .Which.Should().HaveMembers("typed_method_2") + .And.NotHaveMembers("untyped_method", "inferred_method", "typed_method"); + } + } + + private async Task GetStubBasedAnalysis( + Server server, + string code, + AnalysisLimits limits, + IEnumerable searchPaths, + IEnumerable stubPaths) { + + if (limits != null) { + server.Analyzer.Limits = limits; + } + server.Analyzer.SetSearchPaths(searchPaths); + server.Analyzer.SetTypeStubPaths(stubPaths); + + var uri = await server.OpenDefaultDocumentAndGetUriAsync(code); + return await server.GetAnalysisAsync(uri); + } + + [TestMethod, Priority(0)] + public void AstMro() { + var O = new AstPythonType("O"); + var A = new AstPythonType("A"); + var B = new AstPythonType("B"); + var C = new AstPythonType("C"); + var D = new AstPythonType("D"); + var E = new AstPythonType("E"); + var F = new AstPythonType("F"); + + F.SetBases(null, new[] { O }); + E.SetBases(null, new[] { O }); + D.SetBases(null, new[] { O }); + C.SetBases(null, new[] { D, F }); + B.SetBases(null, new[] { D, E }); + A.SetBases(null, new[] { B, C }); + + AstPythonType.CalculateMro(A).Should().Equal(new[] { "A", "B", "C", "D", "E", "F", "O" }, (p, n) => p.Name == n); + AstPythonType.CalculateMro(B).Should().Equal(new[] { "B", "D", "E", "O" }, (p, n) => p.Name == n); + AstPythonType.CalculateMro(C).Should().Equal(new[] { "C", "D", "F", "O" }, (p, n) => p.Name == n); + } + + private static IPythonModule Parse(string path, PythonLanguageVersion version) { + var interpreter = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(version.ToVersion()).CreateInterpreter(); + if (!Path.IsPathRooted(path)) { + path = TestData.GetPath(Path.Combine("TestData", "AstAnalysis", path)); + } + return PythonModuleLoader.FromFile(interpreter, path, version); + } + + [TestMethod, Priority(0)] + public async Task ScrapedTypeWithWrongModule() { + var version = PythonVersions.Versions + .Concat(PythonVersions.AnacondaVersions) + .LastOrDefault(v => Directory.Exists(Path.Combine(v.PrefixPath, "Lib", "site-packages", "numpy"))); + version.AssertInstalled(); + + Console.WriteLine("Using {0}", version.PrefixPath); + using (var server = await CreateServerAsync(version)) { + var uri = await server.OpenDefaultDocumentAndGetUriAsync("import numpy.core.numeric as NP; ndarray = NP.ndarray"); + await server.WaitForCompleteAnalysisAsync(CancellationToken.None); + var hover = await server.SendHover(uri, 0, 34); + hover.Should().HaveTypeName("numpy.core.multiarray.ndarray"); + } + } + + [TestMethod, Priority(0)] + public async Task ScrapedSpecialFloats() { + using (var server = await CreateServerAsync()) { + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync("import math; inf = math.inf; nan = math.nan"); + + analysis.Should().HaveVariable("math") + .And.HaveVariable("inf").OfType(BuiltinTypeId.Float).WithValue() + .And.HaveVariable("nan").OfType(BuiltinTypeId.Float).WithValue(); + } + } + + #endregion + + #region Black-box sanity tests + // "Do we crash?" + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV37() => AstBuiltinScrape(PythonVersions.Python37_x64 ?? PythonVersions.Python37); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV36() => AstBuiltinScrape(PythonVersions.Python36_x64 ?? PythonVersions.Python36); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV35() => AstBuiltinScrape(PythonVersions.Python35_x64 ?? PythonVersions.Python35); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV34() => AstBuiltinScrape(PythonVersions.Python34_x64 ?? PythonVersions.Python34); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV33() => AstBuiltinScrape(PythonVersions.Python33_x64 ?? PythonVersions.Python33); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV32() => AstBuiltinScrape(PythonVersions.Python32_x64 ?? PythonVersions.Python32); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV31() => AstBuiltinScrape(PythonVersions.Python31_x64 ?? PythonVersions.Python31); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV27() => AstBuiltinScrape(PythonVersions.Python27_x64 ?? PythonVersions.Python27); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeV26() => AstBuiltinScrape(PythonVersions.Python26_x64 ?? PythonVersions.Python26); + + [TestMethod, Priority(0)] + public void AstBuiltinScrapeIPy27() => AstBuiltinScrape(PythonVersions.IronPython27_x64 ?? PythonVersions.IronPython27); + + + private void AstBuiltinScrape(InterpreterConfiguration configuration) { + AstScrapedPythonModule.KeepAst = true; + configuration.AssertInstalled(); + using (var factory = CreateInterpreterFactory(configuration)) + using (var analyzer = PythonAnalyzer.CreateSynchronously(factory)) { + try { + var interp = (AstPythonInterpreter)analyzer.Interpreter; + var ctxt = interp.CreateModuleContext(); + + var mod = interp.ImportModule(interp.BuiltinModuleName); + Assert.IsInstanceOfType(mod, typeof(AstBuiltinsPythonModule)); + mod.Imported(ctxt); + + var modPath = factory.ModuleCache.GetCacheFilePath(factory.Configuration.InterpreterPath); + if (File.Exists(modPath)) { + _moduleCache = File.ReadAllText(modPath); + } + + var errors = ((AstScrapedPythonModule)mod).ParseErrors ?? Enumerable.Empty(); + foreach (var err in errors) { + Console.WriteLine(err); + } + Assert.AreEqual(0, errors.Count(), "Parse errors occurred"); + + var seen = new HashSet(); + foreach (var stmt in ((Ast.SuiteStatement)((AstScrapedPythonModule)mod).Ast.Body).Statements) { + if (stmt is Ast.ClassDefinition cd) { + Assert.IsTrue(seen.Add(cd.Name), $"Repeated use of {cd.Name} at index {cd.StartIndex} in {modPath}"); + } else if (stmt is Ast.FunctionDefinition fd) { + Assert.IsTrue(seen.Add(fd.Name), $"Repeated use of {fd.Name} at index {fd.StartIndex} in {modPath}"); + } else if (stmt is Ast.AssignmentStatement assign && assign.Left.FirstOrDefault() is Ast.NameExpression n) { + Assert.IsTrue(seen.Add(n.Name), $"Repeated use of {n.Name} at index {n.StartIndex} in {modPath}"); + } + } + + // Ensure we can get all the builtin types + foreach (BuiltinTypeId v in Enum.GetValues(typeof(BuiltinTypeId))) { + var type = interp.GetBuiltinType(v); + type.Should().NotBeNull().And.BeOfType($"Did not find {v}"); + } + + // Ensure we cannot see or get builtin types directly + mod.GetMemberNames(null).Should().NotContain(Enum.GetNames(typeof(BuiltinTypeId)).Select(n => $"__{n}")); + + foreach (var id in Enum.GetNames(typeof(BuiltinTypeId))) { + mod.GetMember(null, $"__{id}").Should().BeNull(id); + } + } finally { + AstScrapedPythonModule.KeepAst = false; + _analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture); + } + } + } + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV37x64() => AstNativeBuiltinScrape(PythonVersions.Python37_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV36x64() => AstNativeBuiltinScrape(PythonVersions.Python36_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV35x64() => AstNativeBuiltinScrape(PythonVersions.Python35_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV34x64() => AstNativeBuiltinScrape(PythonVersions.Python34_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV33x64() => AstNativeBuiltinScrape(PythonVersions.Python33_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV32x64() => AstNativeBuiltinScrape(PythonVersions.Python32_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV31x64() => AstNativeBuiltinScrape(PythonVersions.Python31_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV27x64() => AstNativeBuiltinScrape(PythonVersions.Python27_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV26x64() => AstNativeBuiltinScrape(PythonVersions.Python26_x64); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV37x86() => AstNativeBuiltinScrape(PythonVersions.Python37); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV36x86() => AstNativeBuiltinScrape(PythonVersions.Python36); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV35x86() => AstNativeBuiltinScrape(PythonVersions.Python35); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV34x86() => AstNativeBuiltinScrape(PythonVersions.Python34); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV33x86() => AstNativeBuiltinScrape(PythonVersions.Python33); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV32x86() => AstNativeBuiltinScrape(PythonVersions.Python32); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV31x86() => AstNativeBuiltinScrape(PythonVersions.Python31); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV27x86() => AstNativeBuiltinScrape(PythonVersions.Python27); + + [TestMethod, Priority(0)] + public void AstNativeBuiltinScrapeV26x86() => AstNativeBuiltinScrape(PythonVersions.Python26); + + + private void AstNativeBuiltinScrape(InterpreterConfiguration configuration) { + configuration.AssertInstalled(); + AstScrapedPythonModule.KeepAst = true; + using (var factory = CreateInterpreterFactory(configuration)) + using (var analyzer = PythonAnalyzer.CreateSynchronously(factory)) { + try { + var interpreter = (AstPythonInterpreter)analyzer.Interpreter; + var ctxt = interpreter.CreateModuleContext(); + + var dllsDir = PathUtils.GetAbsoluteDirectoryPath(factory.Configuration.PrefixPath, "DLLs"); + if (!Directory.Exists(dllsDir)) { + Assert.Inconclusive("Configuration does not have DLLs"); + } + + var report = new List(); + var permittedImports = factory.GetLanguageVersion().Is2x() ? + new[] { interpreter.BuiltinModuleName, "exceptions" } : + new[] { interpreter.BuiltinModuleName }; + + foreach (var pyd in Microsoft.PythonTools.Analysis.Infrastructure.PathUtils.EnumerateFiles(dllsDir, "*", recurse: false).Where(ModulePath.IsPythonFile)) { + var mp = ModulePath.FromFullPath(pyd); + if (mp.IsDebug) { + continue; + } + + Console.WriteLine("Importing {0} from {1}", mp.ModuleName, mp.SourceFile); + var mod = interpreter.ImportModule(mp.ModuleName); + Assert.IsInstanceOfType(mod, typeof(AstScrapedPythonModule)); + mod.Imported(ctxt); + + var modPath = factory.ModuleCache.GetCacheFilePath(pyd); + Assert.IsTrue(File.Exists(modPath), "No cache file created"); + _moduleCache = File.ReadAllText(modPath); + + var errors = ((AstScrapedPythonModule)mod).ParseErrors ?? Enumerable.Empty(); + foreach (var err in errors) { + Console.WriteLine(err); + } + Assert.AreEqual(0, errors.Count(), "Parse errors occurred"); + + var ast = ((AstScrapedPythonModule)mod).Ast; + + + var imports = ((Ast.SuiteStatement)ast.Body).Statements + .OfType() + .SelectMany(s => s.Names) + .Select(n => n.MakeString()) + .Except(permittedImports) + .ToArray(); + + // We expect no imports (after excluding builtins) + report.AddRange(imports.Select(n => $"{mp.ModuleName} imported {n}")); + + _moduleCache = null; + } + + report.Should().BeEmpty(); + } finally { + AstScrapedPythonModule.KeepAst = false; + _analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture); + } + } + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV37() { + var v = PythonVersions.Python37 ?? PythonVersions.Python37_x64; + await FullStdLibTest(v); + } + + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV36() { + var v = PythonVersions.Python36 ?? PythonVersions.Python36_x64; + await FullStdLibTest(v); + } + + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV35() { + var v = PythonVersions.Python35 ?? PythonVersions.Python35_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV34() { + var v = PythonVersions.Python34 ?? PythonVersions.Python34_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV33() { + var v = PythonVersions.Python33 ?? PythonVersions.Python33_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV32() { + var v = PythonVersions.Python31 ?? PythonVersions.Python32_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV31() { + var v = PythonVersions.Python31 ?? PythonVersions.Python32_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV27() { + var v = PythonVersions.Python27 ?? PythonVersions.Python27_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibV26() { + var v = PythonVersions.Python26 ?? PythonVersions.Python26_x64; + await FullStdLibTest(v); + } + + [TestMethod, TestCategory("60s"), Priority(1)] + [Timeout(10 * 60 * 1000)] + public async Task FullStdLibAnaconda3() { + var v = PythonVersions.Anaconda36_x64 ?? PythonVersions.Anaconda36; + await FullStdLibTest(v, + // Crashes Python on import + "sklearn.linear_model.cd_fast", + // Crashes Python on import + "sklearn.cluster._k_means_elkan" + ); + } + + [TestMethod, TestCategory("60s"), Priority(1)] + [Timeout(10 * 60 * 1000)] + public async Task FullStdLibAnaconda2() { + var v = PythonVersions.Anaconda27_x64 ?? PythonVersions.Anaconda27; + await FullStdLibTest(v, + // Fails to import due to SxS manifest issues + "dde", + "win32ui" + ); + } + + [TestMethod, TestCategory("60s"), Priority(0)] + public async Task FullStdLibIPy27() { + var v = PythonVersions.IronPython27 ?? PythonVersions.IronPython27_x64; + await FullStdLibTest(v); + } + + + private async Task FullStdLibTest(InterpreterConfiguration configuration, params string[] skipModules) { + configuration.AssertInstalled(); + var factory = new AstPythonInterpreterFactory(configuration, new InterpreterFactoryCreationOptions { + DatabasePath = TestData.GetAstAnalysisCachePath(configuration.Version, true), + UseExistingCache = false + }); + var modules = ModulePath.GetModulesInLib(configuration.PrefixPath).ToList(); + + var skip = new HashSet(skipModules); + skip.UnionWith(new[] { + "matplotlib.backends._backend_gdk", + "matplotlib.backends._backend_gtkagg", + "matplotlib.backends._gtkagg", + "test.test_pep3131", + "test.test_unicode_identifiers" + }); + skip.UnionWith(modules.Select(m => m.FullName).Where(n => n.StartsWith("test.badsyntax") || n.StartsWith("test.bad_coding"))); + + var anySuccess = false; + var anyExtensionSuccess = false; + var anyExtensionSeen = false; + var anyParseError = false; + + using (var analyzer = await PythonAnalyzer.CreateAsync(factory)) { + try { + PythonModuleLoader.KeepParseErrors = true; + var tasks = new List>>(); + var interp = (AstPythonInterpreter)analyzer.Interpreter; + foreach (var m in skip) { + interp.AddUnimportableModule(m); + } + + foreach (var r in modules + .Where(m => !skip.Contains(m.ModuleName)) + .GroupBy(m => { + int i = m.FullName.IndexOf('.'); + return i <= 0 ? m.FullName : m.FullName.Remove(i); + }) + .AsParallel() + .SelectMany(g => g.Select(m => Tuple.Create(m, interp.ImportModule(m.ModuleName)))) + ) { + var modName = r.Item1; + var mod = r.Item2; + + anyExtensionSeen |= modName.IsNativeExtension; + if (mod == null) { + Trace.TraceWarning("failed to import {0} from {1}", modName.ModuleName, modName.SourceFile); + } else if (mod is AstScrapedPythonModule aspm) { + var errors = aspm.ParseErrors.ToArray(); + if (errors.Any()) { + anyParseError = true; + Trace.TraceError("Parse errors in {0}", modName.SourceFile); + foreach (var e in errors) { + Trace.TraceError(e); + } + } else { + anySuccess = true; + anyExtensionSuccess |= modName.IsNativeExtension; + mod.GetMemberNames(null).ToList(); + } + } else if (mod is AstPythonModule apm) { + var filteredErrors = apm.ParseErrors.Where(e => !e.Contains("encoding problem")).ToArray(); + if (filteredErrors.Any()) { + // Do not fail due to errors in installed packages + if (!apm.FilePath.Contains("site-packages")) { + anyParseError = true; + } + Trace.TraceError("Parse errors in {0}", modName.SourceFile); + foreach (var e in filteredErrors) { + Trace.TraceError(e); + } + } else { + anySuccess = true; + anyExtensionSuccess |= modName.IsNativeExtension; + mod.GetMemberNames(null).ToList(); + } + } else { + Trace.TraceError("imported {0} as type {1}", modName.ModuleName, mod.GetType().FullName); + } + } + } finally { + _analysisLog = factory.GetAnalysisLogContent(CultureInfo.InvariantCulture); + PythonModuleLoader.KeepParseErrors = false; + } + } + Assert.IsTrue(anySuccess, "failed to import any modules at all"); + Assert.IsTrue(anyExtensionSuccess || !anyExtensionSeen, "failed to import all extension modules"); + Assert.IsFalse(anyParseError, "parse errors occurred"); + } + + #endregion + #region Type Annotation tests + [TestMethod, Priority(0)] + public async Task AstTypeAnnotationConversion() { + using (var server = await CreateServerAsync()) { + var code = @"from ReturnAnnotations import * +x = f() +y = g()"; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveVariable("x").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("y").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("f").WithValue() + .Which.Should().HaveSingleOverload() + .Which.Should().HaveSingleParameter() + .Which.Should().HaveName("p").And.HaveType("int").And.HaveNoDefaultValue(); + } + } + #endregion + + #region Type Shed tests + [TestMethod, Priority(0)] + public async Task TypeShedElementTree() { + using (var server = await CreateServerAsync()) { + var code = @"import xml.etree.ElementTree as ET + +e = ET.Element() +e2 = e.makeelement() +iterfind = e.iterfind +l = iterfind()"; + var uri = await server.OpenDefaultDocumentAndGetUriAsync(code); + var analysis = await server.GetAnalysisAsync(uri); + var elementSignatures = await server.SendSignatureHelp(uri, 2, 15); + var makeelementSignatures = await server.SendSignatureHelp(uri, 3, 19); + var iterfindSignatures = await server.SendSignatureHelp(uri, 5, 13); + + analysis.Should().HaveVariable("l").OfTypes(BuiltinTypeId.List); + elementSignatures.Should().HaveSingleSignature() + .Which.Should().OnlyHaveParameterLabels("tag", "attrib", "**extra"); + makeelementSignatures.Should().HaveSingleSignature() + .Which.Should().OnlyHaveParameterLabels("tag", "attrib"); + iterfindSignatures.Should().HaveSingleSignature() + .Which.Should().OnlyHaveParameterLabels("path", "namespaces"); + } + } + + [TestMethod, Priority(0)] + public async Task TypeShedChildModules() { + string[] firstMembers; + + using (var server = await CreateServerAsync()) { + server.Analyzer.Limits = new AnalysisLimits { UseTypeStubPackages = false }; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(@"import urllib"); + + firstMembers = server.Analyzer.GetModuleMembers(analysis.InterpreterContext, new[] { "urllib" }) + .Select(m => m.Name) + .ToArray(); + + firstMembers.Should().NotBeEmpty().And.Contain(new[] { "parse", "request" }); + } + + using (var server = await CreateServerAsync()) { + server.Analyzer.SetTypeStubPaths(new[] { TypeShedPath }); + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(@"import urllib"); + + var secondMembers = server.Analyzer.GetModuleMembers(analysis.InterpreterContext, new[] { "urllib" }) + .Select(m => m.Name) + .ToArray(); + + secondMembers.Should().OnlyContain(firstMembers); + } + } + + [TestMethod, Priority(0)] + public async Task TypeShedSysExcInfo() { + using (var server = await CreateServerAsync()) { + server.Analyzer.SetTypeStubPaths(new[] { TypeShedPath }); + var code = @"import sys + +e1, e2, e3 = sys.exc_info()"; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveVariable("e1").OfTypes(BuiltinTypeId.Type) + .And.HaveVariable("e2").OfTypes("BaseException") + .And.HaveVariable("e3").OfTypes(BuiltinTypeId.NoneType) + .And.HaveVariable("sys").WithValue() + .Which.Should().HaveMember("exc_info") + .Which.Should().HaveOverloadCount(2) + .And.HaveOverloadAt(0).WithSingleReturnType("tuple") + .And.HaveOverloadAt(1).WithSingleReturnType("tuple[type, BaseException, None]"); + } + } + + [TestMethod, Priority(0)] + public async Task TypeShedJsonMakeScanner() { + using (var server = await CreateServerAsync()) { + server.Analyzer.SetTypeStubPaths(new[] { TypeShedPath }); + var code = @"import _json + +scanner = _json.make_scanner()"; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveVariable("scanner").WithValue() + .Which.Should().HaveSingleOverload() + .Which.Should().HaveName("__call__") + .And.HaveParameters("string", "index") + .And.HaveParameterAt(0).WithName("string").WithType("str").WithNoDefaultValue() + .And.HaveParameterAt(1).WithName("index").WithType("int").WithNoDefaultValue() + .And.HaveSingleReturnType("tuple[None, int]"); + } + } + + [TestMethod, Priority(0)] + public async Task TypeShedSysInfo() { + using (var server = await CreateServerAsync()) { + server.Analyzer.SetTypeStubPaths(new[] { TypeShedPath }); + server.Analyzer.Limits = new AnalysisLimits { UseTypeStubPackages = true, UseTypeStubPackagesExclusively = true }; + + var code = @"import sys + +l_1 = sys.argv + +s_1 = sys.argv[0] +s_2 = next(iter(sys.argv)) +s_3 = sys.stdout.encoding + +f_1 = sys.stdout.write +f_2 = sys.__stdin__.read + +i_1 = sys.flags.debug +i_2 = sys.flags.quiet +i_3 = sys.implementation.version.major +i_4 = sys.getsizeof(None) +i_5 = sys.getwindowsversion().platform_version[0] +"; + var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(code); + + analysis.Should().HaveVariable("l_1").OfTypes(BuiltinTypeId.List) + .And.HaveVariable("s_1").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("s_2").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("s_3").OfTypes(BuiltinTypeId.Str) + .And.HaveVariable("f_1").OfTypes(BuiltinTypeId.BuiltinMethodDescriptor) + .And.HaveVariable("f_2").OfTypes(BuiltinTypeId.BuiltinMethodDescriptor) + .And.HaveVariable("i_1").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("i_2").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("i_3").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("i_4").OfTypes(BuiltinTypeId.Int) + .And.HaveVariable("i_5").OfTypes(BuiltinTypeId.Int); + } + } + + [TestMethod, Priority(0)] + public void TypeStubConditionalDefine() { + var seen = new HashSet(); + + var code = @"import sys + +if sys.version_info < (2, 7): + LT_2_7 : bool = ... +if sys.version_info <= (2, 7): + LE_2_7 : bool = ... +if sys.version_info > (2, 7): + GT_2_7 : bool = ... +if sys.version_info >= (2, 7): + GE_2_7 : bool = ... + +"; + + var fullSet = new[] { "LT_2_7", "LE_2_7", "GT_2_7", "GE_2_7" }; + + foreach (var ver in PythonVersions.Versions) { + if (!seen.Add(ver.Version)) { + continue; + } + + Console.WriteLine("Testing with {0}", ver.InterpreterPath); + + var interpreter = InterpreterFactoryCreator.CreateAnalysisInterpreterFactory(ver.Version).CreateInterpreter(); + var entry = PythonModuleLoader.FromStream(interpreter, new MemoryStream(Encoding.ASCII.GetBytes(code)), "testmodule.pyi", ver.Version.ToLanguageVersion()); + + var expected = new List(); + var pythonVersion = ver.Version.ToLanguageVersion(); + if (pythonVersion.Is3x()) { + expected.Add("GT_2_7"); + expected.Add("GE_2_7"); + } else if (pythonVersion == PythonLanguageVersion.V27) { + expected.Add("GE_2_7"); + expected.Add("LE_2_7"); + } else { + expected.Add("LT_2_7"); + expected.Add("LE_2_7"); + } + + entry.GetMemberNames(null).Where(n => n.EndsWithOrdinal("2_7")) + .Should().Contain(expected) + .And.NotContain(fullSet.Except(expected)); + } + } + #endregion + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Microsoft.Python.LanguageServer.Implementation.Server::.ctor() at Line 87) of type Microsoft.Python.LanguageServer.Implementation.Server in method "Task`1 AstAnalysisTests.CreateServerAsync(InterpreterConfiguration,String)". + +### Severity: +ERROR + +### Procedure: +Task`1 AstAnalysisTests.CreateServerAsync(InterpreterConfiguration,String) + +### File: +src/Analysis/Engine/Test/AstAnalysisTests.cs + +### Key: +AstAnalysisTests.cs|CreateServerAsync|DOTNET_RESOURCE_LEAK + +### Hash: +ffe34e7356dc681013b232d91859e554 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0732/instruction.md b/inferredbugs-0732/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ad6128ec24243b0087cb11eed18c7b8f475b195d --- /dev/null +++ b/inferredbugs-0732/instruction.md @@ -0,0 +1,157 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Dynaframe3 +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Diagnostics; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Markup.Xaml; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using Avalonia.Rendering.SceneGraph; +using Avalonia.Skia; +using Avalonia.Threading; +using SkiaSharp; + + +namespace Dynaframe3.ImagePresenters +{ + public partial class BlurBoxImage : UserControl + { + Image backgroundImage; + Image foregroundImage; + + Bitmap bitmapData; + SKImageInfo blurInfo; + SKBitmap blurredbitmap; + SKPaint blurPaint; + + + public string ImageString { get; set; } + public BlurBoxImage() + { + ClipToBounds = true; + InitializeComponent(); + ImageString = ""; + backgroundImage = this.FindControl("backgroundImage"); + foregroundImage = this.FindControl("foregroundImage"); + + // Frontloading some allocations + blurInfo = new SKImageInfo(640, 480); + blurredbitmap = new SKBitmap(blurInfo); + blurPaint = new SKPaint(); + blurPaint.ImageFilter = SKImageFilter.CreateBlur(20, 20); + } + + /// + /// Set the 'stretch' of the foreground image + /// + /// + public void SetImageStretch(Stretch stretch) + { + foregroundImage.Stretch = stretch; + } + private void InitializeComponent() + { + AvaloniaXamlLoader.Load(this); + + + if (!String.IsNullOrEmpty(ImageString)) + { + ShowBitmapWithBlurbox(); + } + } + public void UpdateImage() + { + ShowBitmapWithBlurbox(); + } + + public void UpdateImage(string newImagePath) + { + ImageString = newImagePath; + ShowBitmapWithBlurbox(); + } + + + private void ShowBitmapWithBlurbox() + { + SKBitmap bitmap = SKBitmap.Decode(ImageString); + bitmap.ScalePixels(blurredbitmap, SKFilterQuality.Medium); + + SKCanvas canvas = new SKCanvas(blurredbitmap); + canvas.DrawBitmap(blurredbitmap, new SKPoint(0, 0), blurPaint); + + SKData data = SKImage.FromBitmap(blurredbitmap).Encode(SKEncodedImageFormat.Jpeg, 100); + + bitmapData = new Bitmap(data.AsStream()); + backgroundImage.Source = null; + foregroundImage.Source = null; + + backgroundImage.Source = bitmapData; + foregroundImage.Source = new Bitmap(ImageString); + + bitmap.Dispose(); + //blurredbitmap.Dispose(); + canvas.Dispose(); + //blurPaint.Dispose(); + data.Dispose(); + + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource this.Dynaframe3.ImagePresenters.BlurBoxImage.bitmapData of type Avalonia.Media.Imaging.Bitmap, Leaked resource (output of Avalonia.Media.Imaging.Bitmap::.ctor() at Line 89) of type Avalonia.Media.Imaging.Bitmap in method "Void BlurBoxImage.ShowBitmapWithBlurbox()". + +### Severity: +ERROR + +### Procedure: +Void BlurBoxImage.ShowBitmapWithBlurbox() + +### File: +ImagePresenters/BlurBoxImage.axaml.cs + +### Key: +BlurBoxImage.axaml.cs|ShowBitmapWithBlurbox|DOTNET_RESOURCE_LEAK + +### Hash: +5f80708eb98cd03709be47a3e2acc61c + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0735/instruction.md b/inferredbugs-0735/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99d8c50a90567bc87c884e00afd279ae3e1915a7 --- /dev/null +++ b/inferredbugs-0735/instruction.md @@ -0,0 +1,649 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Shielded +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Linq; +using System.Threading; +using System.Diagnostics; +using System.Threading.Tasks; +using Shielded; + +namespace ConsoleTests +{ + class MainClass + { + private static Stopwatch _timer; + + public static long mtTest(string name, int taskCount, Func task) + { + if (_timer == null) + _timer = Stopwatch.StartNew(); + + long time; + Console.Write("Test - {0}...", name); + time = _timer.ElapsedMilliseconds; + Task.WaitAll( + Enumerable.Range(0, taskCount) + .Select(task) + .ToArray()); + time = _timer.ElapsedMilliseconds - time; + return time; + } + + public static void TimeTests() + { + var randomizr = new Random(); + int transactionCounter; + int sleepTime = 1; + int taskCount = 1000; + + foreach (var i in Enumerable.Repeat(0, 5)) + { + var x = new int[100]; + transactionCounter = 0; + var time = mtTest("dirty write", taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + Interlocked.Increment(ref transactionCounter); + int v = x[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + x[rnd] = v + 1; + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = x.Sum() == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + + var lockCount = 10; + foreach (var i in Enumerable.Repeat(0, 5)) + { + var x = new int[100]; + transactionCounter = 0; + var l = Enumerable.Repeat(0, lockCount).Select(_ => new object()).ToArray(); + var time = mtTest(string.Format("{0} lock write", lockCount), taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + lock (l[rnd % lockCount]) + { + Interlocked.Increment(ref transactionCounter); + int v = x[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + x[rnd] = v + 1; + } + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = x.Sum() == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + + foreach (var i in Enumerable.Repeat(0, 5)) + { + var shx = Enumerable.Repeat(0, 100).Select(n => new Shielded(n)).ToArray(); + transactionCounter = 0; + var time = mtTest("shielded2 write", taskCount, _ => + { + var rnd = randomizr.Next(100); + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + int v = shx[rnd]; + if (sleepTime > 0) Thread.Sleep(sleepTime); + shx[rnd].Modify((ref int a) => a = v + 1); + }); + }, + sleepTime > 0 ? TaskCreationOptions.LongRunning : TaskCreationOptions.None + ); + }); + var correct = shx.Sum(s => s.Read) == taskCount; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + } + + static void OneTransaction() + { + Shielded sh = new Shielded(); + Shield.InTransaction(() => + { + int x = sh; + Console.WriteLine("Read: {0}", x); + sh.Modify((ref int a) => a = x + 1); + Console.WriteLine("Read after increment: {0}", sh.Read); + }); + } + + + struct Account + { + public int Id; + public decimal Balance; + // beware - copies of this struct share this reference! + public List Transfers; + } + + struct Transfer + { + public int OtherId; + public decimal AmountReceived; + } + + static void ControlledRace() + { + var acc1 = new Shielded(new Account() + { + Id = 1, + Balance = 1000M, + Transfers = new List() + }); + var acc2 = new Shielded(new Account() + { + Id = 2, + Balance = 1000M, + Transfers = new List() + }); + int transactionCount = 0; + + mtTest("controlled race", 20, n => + { + if (n % 2 == 0) + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + Shield.SideEffect(() => Console.WriteLine("Transferred 100.00 .. acc1 -> acc2"), + () => Console.WriteLine("Task 1 rollback!")); + acc1.Modify((ref Account a) => + { + a.Balance = a.Balance - 100M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc2.Read.Id, AmountReceived = -100M })); + }); + Thread.Sleep(100); + acc2.Modify((ref Account a) => + { + a.Balance = a.Balance + 100M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc1.Read.Id, AmountReceived = 100M })); + }); + }); + }, TaskCreationOptions.LongRunning); + else + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + Shield.SideEffect(() => Console.WriteLine("Transferred 200.00 .. acc1 <- acc2"), + () => Console.WriteLine("Task 2 rollback!")); + acc2.Modify((ref Account a) => + { + a.Balance = a.Balance - 200M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc1.Read.Id, AmountReceived = -200M })); + }); + Thread.Sleep(250); + acc1.Modify((ref Account a) => + { + a.Balance = a.Balance + 200M; + var list = a.Transfers; + Shield.SideEffect(() => list.Add( + new Transfer() { OtherId = acc2.Read.Id, AmountReceived = 200M })); + }); + }); + }, TaskCreationOptions.LongRunning); + }); + Console.WriteLine("\nCompleted 20 transactions in {0} total attempts.", transactionCount); + Console.WriteLine("Account 1 balance: {0}", acc1.Read.Balance); + foreach (var t in acc1.Read.Transfers) + { + Console.WriteLine(" {0:####,00}", t.AmountReceived); + } + Console.WriteLine("\nAccount 2 balance: {0}", acc2.Read.Balance); + foreach (var t in acc2.Read.Transfers) + { + Console.WriteLine(" {0:####,00}", t.AmountReceived); + } + } + + private static void DictionaryTest() + { + ShieldedDict> dict = new ShieldedDict>(); + var randomizr = new Random(); + foreach (var _ in Enumerable.Repeat(0, 10)) + { + var transactionCounter = 0; + var time = mtTest("dictionary", 1000, i => + { + var rnd = randomizr.Next(100); + if (i % 2 == 0) + // adder task - 500 of these + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + var v = dict[rnd]; + int? num = v != null ? (int?)v.Read : null; + Thread.Sleep(10); + if (v == null) + dict[rnd] = new Shielded(1); + else if (v.Read == -1) + dict[rnd] = null; + else + v.Modify((ref int a) => a = num.Value + 1); + } + ); + }, + TaskCreationOptions.LongRunning + ); + else + // subtractor task - 500 of these + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCounter); + var v = dict[rnd]; + int? num = v != null ? (int?)v.Read : null; + Thread.Sleep(10); + if (v == null) + dict[rnd] = new Shielded(-1); + else if (v.Read == 1) + dict[rnd] = null; + else + v.Modify((ref int a) => a = num.Value - 1); + } + ); + }, + TaskCreationOptions.LongRunning + ); + }); + var correct = Enumerable.Range(0, 100).Sum(n => dict[n] == null ? 0 : dict[n].Read) == 0; + Console.WriteLine(" {0} ms with {1} iterations and is {2}.", + time, transactionCounter, correct ? "correct" : "incorrect"); + } + } + + /// + /// Creates a BetShop, and tries to buy a large number of random tickets. Afterwards it + /// checks that the rule limiting same ticket winnings is not violated. + /// + public static void BetShopTest() + { + int numEvents = 100; + var betShop = new BetShop(numEvents); + var randomizr = new Random(); + int reportEvery = 1000; + //Shielded nextReport = new Shielded(reportEvery); + + //Shield.Conditional(() => betShop.TicketCount >= nextReport, () => + //{ + // nextReport.Modify((ref int n) => n += reportEvery); + // Shield.SideEffect(() => + // { + // Console.Write(" {0}..", betShop.TicketCount); + // }); + // return true; + //}); + Shielded lastReport = new Shielded(0); + Shielded lastTime = new Shielded(DateTime.UtcNow); + + Shield.Conditional(() => betShop.TicketCount >= lastReport + reportEvery, () => + { + DateTime newNow = DateTime.UtcNow; + int count = betShop.TicketCount; + int speed = (count - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; + lastTime.Assign(newNow); + lastReport.Modify((ref int n) => n += reportEvery); + Shield.SideEffect(() => + { + Console.Write("\n{0} at {1} item/s", count, speed); + }); + return true; + }); + + + var time = mtTest("bet shop w/ " + numEvents, 50000, i => + { + decimal payIn = (randomizr.Next(10) + 1m) * 1; + int event1Id = randomizr.Next(numEvents) + 1; + int event2Id = randomizr.Next(numEvents) + 1; + int event3Id = randomizr.Next(numEvents) + 1; + int offer1Ind = randomizr.Next(3); + int offer2Ind = randomizr.Next(3); + int offer3Ind = randomizr.Next(3); + return Task.Factory.StartNew(() => Shield.InTransaction(() => + { + var offer1 = betShop.Events[event1Id].Read.BetOffers[offer1Ind]; + var offer2 = betShop.Events[event2Id].Read.BetOffers[offer2Ind]; + var offer3 = betShop.Events[event3Id].Read.BetOffers[offer3Ind]; + betShop.BuyTicket(payIn, offer1, offer2, offer3); + })); + }); + int total; + var totalCorrect = betShop.VerifyTickets(out total); + Console.WriteLine(" {0} ms with {1} tickets paid in and is {2}.", + time, total, totalCorrect ? "correct" : "incorrect"); + } + + class TreeItem + { + public Guid Id = Guid.NewGuid(); + } + + public static void TreeTest() + { + int numTasks = 100000; + int reportEvery = 1000; + + ShieldedTree tree = new ShieldedTree(); + int transactionCount = 0; + Shielded lastReport = new Shielded(0); + Shielded countComplete = new Shielded(0); +// Shielded lastTime = new Shielded(DateTime.UtcNow); +// +// Shield.Conditional(() => countComplete >= lastReport + reportEvery, () => +// { +// DateTime newNow = DateTime.UtcNow; +// int speed = (countComplete - lastReport) * 1000 / (int)newNow.Subtract(lastTime).TotalMilliseconds; +// lastTime.Assign(newNow); +// lastReport.Modify((ref int n) => n += reportEvery); +// int count = countComplete; +// Shield.SideEffect(() => +// { +// Console.Write("\n{0} at {1} item/s", count, speed); +// } +// ); +// return true; +// } +// ); + + if (true) + { + var treeTime = mtTest("tree", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + tree.Add(item1.Id, item1); +// countComplete.Commute((ref int c) => c++); + } + ); + } + ); + } + ); + Guid? previous = null; + bool correct = true; + Shield.InTransaction(() => + { + int count = 0; + foreach (var item in tree) + { + count++; + if (previous != null && previous.Value.CompareTo(item.Key) > 0) + { + correct = false; + break; + } + previous = item.Key; + } + correct = correct && (count == numTasks); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.", + treeTime, transactionCount, correct ? "correct" : "incorrect"); + } + + if (true) + { + ShieldedDict dict = new ShieldedDict(); + transactionCount = 0; + Shield.InTransaction(() => + { + countComplete.Assign(0); + lastReport.Assign(0); + } + ); + + var time = mtTest("dictionary", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + dict[item1.Id] = item1; +// countComplete.Commute((ref int c) => c++); + } + ); + } + ); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.", + time, transactionCount); + } + + if (true) + { + ConcurrentDictionary dict = new ConcurrentDictionary(); + + var time = mtTest("ConcurrentDictionary", numTasks, i => + { + return Task.Factory.StartNew(() => + { + var item1 = new TreeItem(); + dict[item1.Id] = item1; + } + ); + } + ); + Console.WriteLine("\n -- {0} ms with {1} iterations. Not sorted.", + time, numTasks); + } + } + + public static void SkewTest() + { + var numTasks = 1000; + var numFields = 10; + var transactionCount = 0; + var randomizr = new Random(); + var shA = Enumerable.Repeat(0, numFields).Select(_ => new Shielded(100)).ToArray(); + var shB = Enumerable.Repeat(0, numFields).Select(_ => new Shielded(100)).ToArray(); + + var time = mtTest("skew write", numTasks, i => + { + int index = randomizr.Next(numFields << 1); + int amount = randomizr.Next(10) + 1; + return Task.Factory.StartNew(() => + { + Shield.InTransaction(() => + { + Interlocked.Increment(ref transactionCount); + // take one from one of the arrays, but only if it does not take sum under 100 + var sum = shA[index >> 1] + shB[index >> 1]; + if (sum - amount >= 100) + { + //Thread.Sleep(10); + if ((index & 1) == 0) + shA[index >> 1].Modify((ref int n) => n = n - amount); + else + shB[index >> 1].Modify((ref int n) => n = n - amount); + } + } + ); + }, + TaskCreationOptions.LongRunning + ); + } + ); + // it's correct if no sum is smaller than 100 + var correct = true; + for (int j = 0; j < numFields; j++) + if (shA[j] + shB[j] < 100) + { + correct = false; + break; + } + Console.WriteLine("\n -- {0} ms with {1} iterations and is {2}.", + time, transactionCount, correct ? "correct" : "incorrect"); + } + + private class Dummy + { + public int Value; + } + + public static void SimpleTreeTest() + { + ShieldedTree tree = new ShieldedTree(); + Shield.InTransaction(() => + { + foreach (int i in Enumerable.Range(1, 2000)) + { + tree.Add(1000 - i, new Dummy() { Value = 1000 - i }); + tree.Add(1000 - i, new Dummy() { Value = 1000 - i }); + } + }); + Shield.InTransaction(() => + { + foreach (int i in Enumerable.Range(1, 1000).Select(x => x << 1)) + { + tree.Remove(1000 - i); + } + }); + Shield.InTransaction(() => + { + foreach (var kvp in tree.Range(100, 110)) + Console.WriteLine("Item: {0}", kvp.Key); + }); + } + + public static void SimpleCommuteTest() + { + var a = new Shielded(); + + Shield.InTransaction(() => a.Commute((ref int n) => n++)); + Console.WriteLine(a); + + Shield.InTransaction(() => + { + Console.WriteLine(a); + a.Commute((ref int n) => n++); + Console.WriteLine(a); + }); + Console.WriteLine(a); + + Shield.InTransaction(() => + { + a.Commute((ref int n) => n++); + Console.WriteLine(a); + }); + Console.WriteLine(a); + } + + public static void Main(string[] args) + { + //TimeTests(); + + //OneTransaction(); + + //ControlledRace(); + + //DictionaryTest(); + + //BetShopTest(); + + //TreeTest(); + + //SkewTest(); + + //SimpleTreeTest(); + + //SimpleCommuteTest(); + + new Queue().Run(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of ConsoleTests.Queue::.ctor() at Line 587).ConsoleTests.Queue._barrier of type System.Threading.Barrier in method "Void MainClass.Main(String[])". + +### Severity: +ERROR + +### Procedure: +Void MainClass.Main(String[]) + +### File: +ConsoleTests/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +f4e4092cdea7cab66469ebe3ad31e814 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0750/instruction.md b/inferredbugs-0750/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dabfc3262ec4814849e9f171e39ae8d158e1fa2d --- /dev/null +++ b/inferredbugs-0750/instruction.md @@ -0,0 +1,241 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** parquet-dotnet +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using Parquet.File; +using System.Collections.Generic; +using System.Linq; +using System.Collections; +using Parquet.Data; + +namespace Parquet +{ + /// + /// Implements Apache Parquet format writer + /// + public class ParquetWriter : ParquetActor, IDisposable + { + private readonly Stream _output; + private readonly FileMetadataBuilder _meta; + private readonly ParquetOptions _formatOptions; + private readonly WriterOptions _writerOptions; + private Schema _existingSchema; + private bool _dataWritten; + + /// + /// Creates an instance of parquet writer on top of a stream + /// + /// Writeable, seekable stream + /// Additional options + /// The writer options. + /// Output is null. + /// Output stream is not writeable + public ParquetWriter(Stream output, ParquetOptions formatOptions = null, WriterOptions writerOptions = null) : base(output) + { + _output = output ?? throw new ArgumentNullException(nameof(output)); + if (!output.CanWrite) throw new ArgumentException("stream is not writeable", nameof(output)); + _formatOptions = formatOptions ?? new ParquetOptions(); + _writerOptions = writerOptions ?? new WriterOptions(); + _meta = new FileMetadataBuilder(); + } + + /// + /// Write out dataset to the output stream + /// + /// Dataset to write + /// Compression method + /// When true, appends to the file, otherwise creates a new file. + public void Write(DataSet dataSet, CompressionMethod compression = CompressionMethod.Gzip, bool append = false) + { + PrepareFile(dataSet, append); + + int offset = 0; + int count; + do + { + count = Math.Min(_writerOptions.RowGroupsSize, dataSet.Count - offset); + Thrift.RowGroup rg = _meta.AddRowGroup(); + long rgStartPos = _output.Position; + + rg.Columns = new List(); + foreach(SchemaElement se in dataSet.Schema.Flatten()) + { + var cw = new ColumnWriter(_output, ThriftStream, _meta, se, compression, _formatOptions, _writerOptions); + IList values = dataSet.GetColumn(se, offset, count); + Thrift.ColumnChunk chunk = cw.Write(offset, count, values); + rg.Columns.Add(chunk); + } + + //row group's size is a sum of _uncompressed_ sizes of all columns in it, including the headers + //luckily ColumnChunk already contains sizes of page+header in it's meta + rg.Total_byte_size = rg.Columns.Sum(c => c.Meta_data.Total_compressed_size); + rg.Num_rows = count; + + offset += _writerOptions.RowGroupsSize; + } + while (offset < dataSet.Count); + + _dataWritten = true; + } + + private void PrepareFile(DataSet ds, bool append) + { + if (append) + { + if (!_output.CanSeek) throw new IOException("destination stream must be seekable for append operations."); + + ValidateFile(); + + Thrift.FileMetaData fileMeta = ReadMetadata(); + _meta.SetMeta(fileMeta); + + Schema existingSchema = new FileMetadataParser(fileMeta).ParseSchema(_formatOptions); + + if (!ds.Schema.Equals(existingSchema)) + { + throw new ParquetException($"{nameof(DataSet)} schema does not match existing file schema"); + } + + GoBeforeFooter(); + } + else + { + if (_existingSchema == null) + { + _existingSchema = ds.Schema; + + //file starts with magic + WriteMagic(); + + _meta.AddSchema(ds); + } + else + { + if(!_existingSchema.Equals(ds.Schema)) + { + throw new ParquetException($"expeted schema {_existingSchema} but found {ds.Schema}."); + } + } + } + } + + /// + /// Writes to a target stream + /// + /// to write + /// Destination stream + /// Compression method + /// Parquet options, optional. + /// Writer options, optional. + /// When true, assumes that this stream contains existing file and appends data to it, otherwise writes a new Parquet file. + public static void Write(DataSet dataSet, Stream destination, CompressionMethod compression = CompressionMethod.Gzip, ParquetOptions formatOptions = null, WriterOptions writerOptions = null, bool append = false) + { + using (var writer = new ParquetWriter(destination, formatOptions, writerOptions)) + { + writer.Write(dataSet, compression, append); + } + } + + /// + /// Writes to a target file + /// + /// to write + /// Path to a file to write to. + /// Compression method + /// Parquet options, optional. + /// Writer options, optional. + /// When true, assumes that this stream contains existing file and appends data to it, otherwise writes a new Parquet file. + public static void WriteFile(DataSet dataSet, string fileName, CompressionMethod compression = CompressionMethod.Gzip, ParquetOptions formatOptions = null, WriterOptions writerOptions = null, bool append = false) + { + using (Stream fs = System.IO.File.Create(fileName)) + { + using (var writer = new ParquetWriter(fs, formatOptions, writerOptions)) + { + writer.Write(dataSet, compression); + } + } + } + + private void WriteMagic() + { + _output.Write(MagicBytes, 0, MagicBytes.Length); + } + + /// + /// Finalizes file, writes metadata and footer + /// + public void Dispose() + { + if (!_dataWritten) return; + + //finalize file + long size = ThriftStream.Write(_meta.ThriftMeta); + + //metadata size + Writer.Write((int)size); //4 bytes + + //end magic + WriteMagic(); //4 bytes + + Writer.Flush(); + _output.Flush(); + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.IO.BinaryWriter Parquet.ParquetActor::get_Writer() at Line 178) of type System.IO.BinaryWriter, Leaked resource (returned from System.IO.BinaryWriter Parquet.ParquetActor::get_Writer() at Line 173) of type System.IO.BinaryWriter, Leaked resource (returned from Parquet.File.ThriftStream Parquet.ParquetActor::get_ThriftStream() at Line 170).Parquet.File.ThriftStream._protocol of type Thrift.Protocol.TCompactProtocol in method "Void ParquetWriter.Dispose()". + +### Severity: +ERROR + +### Procedure: +Void ParquetWriter.Dispose() + +### File: +src/Parquet/ParquetWriter.cs + +### Key: +ParquetWriter.cs|Dispose|DOTNET_RESOURCE_LEAK + +### Hash: +ec9b4113a0b67e3e0285863db74b952a + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0751/instruction.md b/inferredbugs-0751/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fbd2c3abaf60337b648049643d405da33c2541ed --- /dev/null +++ b/inferredbugs-0751/instruction.md @@ -0,0 +1,203 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** parquet-dotnet +**Bug ID:** 3 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Parquet.Data; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace Parquet.File +{ + /// + /// Responsible for merging values from different parts of column chunk + /// + class ValueMerger + { + private readonly SchemaElement _schema; + private readonly ParquetOptions _formatOptions; + private IList _values; + + public ValueMerger(SchemaElement schema, ParquetOptions formatOptions, IList values) + { + _schema = schema; + _formatOptions = formatOptions; + _values = values; + } + + /// + /// Applies dictionary with indexes and definition levels directly over the column + /// + public IList Apply(IList dictionary, List definitions, List repetitions, List indexes, int maxValues) + { + if (dictionary == null && definitions == null && indexes == null && repetitions == null) return _values; //values are just values + + ApplyDictionary(dictionary, indexes, maxValues); + + ApplyDefinitions(definitions, maxValues); + + ApplyRepetitions(repetitions); + + return _values; + } + + private void ApplyDictionary(IList dictionary, List indexes, int maxValues) + { + //merge with dictionary if present + if (dictionary == null) return; + + //when dictionary has no indexes + if (indexes == null) return; + + TrimTail(indexes, maxValues); + + IList values = indexes + .Select(i => dictionary[i]) + .ToList(); + + TrimTail(values, maxValues); + + foreach (object el in values) _values.Add(el); + } + + private void ApplyDefinitions(List definitions, int maxValues) + { + if (definitions == null) return; + + TrimTail(definitions, maxValues); + + int valueIdx = 0; + IList values = TypeFactory.Create(_schema, _formatOptions, true); + + foreach (int isDefinedInt in definitions) + { + bool isDefined = isDefinedInt != 0; + + if (isDefined) + { + values.Add(_values[valueIdx++]); + } + else + { + values.Add(null); + } + } + + _values = values; + } + + private void ApplyRepetitions(List repetitions) + { + if (repetitions == null) return; + + var values = new List(); + IList chunk = null; + int rep = int.MaxValue; + + for(int i = 0; i < _values.Count; i++) + { + int cr = repetitions[i]; + + if (cr < rep) + { + if (chunk != null) values.Add(chunk); + chunk = TypeFactory.Create(_schema, _formatOptions, true); + } + + rep = cr; + chunk.Add(_values[i]); + } + + if (chunk.Count > 0) values.Add(chunk); + + _values = values; + } + + public static void TrimTail(IList list, int maxValues) + { + if (list == null) return; + + if (list.Count > maxValues) + { + int diffCount = list.Count - maxValues; + while (--diffCount >= 0) list.RemoveAt(list.Count - 1); //more effective than copying the list again + } + } + + public static void TrimHead(IList list, int maxValues) + { + if (list == null) return; + + while (list.Count > maxValues) + { + list.RemoveAt(0); + } + } + + public static void Trim(IList list, int offset, int count) + { + TrimHead(list, list.Count - offset); + TrimTail(list, count); + } + + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `chunk` last assigned on line 91 could be null and is dereferenced at line 105, column 13. + +### Severity: +ERROR + +### Procedure: +Void ValueMerger.ApplyRepetitions(List`1) + +### File: +src/Parquet/File/ValueMerger.cs + +### Key: +ValueMerger.cs|ApplyRepetitions|NULL_DEREFERENCE + +### Node Key: +237e920bd59c9281f7519159d3f6a5e3 + +### Hash: +483292eeea17ccd8e727783b932ba171 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0757/instruction.md b/inferredbugs-0757/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df11c7a6d38d340b7c05593aaeb6f082ee11954e --- /dev/null +++ b/inferredbugs-0757/instruction.md @@ -0,0 +1,126 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Disable-Windows-Defender +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Win32; +using System; +using System.Diagnostics; +using System.Security.Principal; +using System.Threading; + +// │ Author : NYAN CAT +// │ Name : Disable Windows Defender v0.2 +// │ Contact : https://github.com/NYAN-x-CAT + +// This program is distributed for educational purposes only. + +namespace Disable_Windows_Defender +{ + class Program + { + static void Main() + { + + if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) return; + + try + { + Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("DisableAntiSpyware", "00000001", RegistryValueKind.DWord); + } + catch { } + + try + { + Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("DisableBehaviorMonitoring", "00000001", RegistryValueKind.DWord); + + Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("DisableOnAccessProtection", "00000001", RegistryValueKind.DWord); + + Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", RegistryKeyPermissionCheck.ReadWriteSubTree).SetValue("DisableScanOnRealtimeEnable", "00000001", RegistryValueKind.DWord); + } + catch { } + + Thread.Sleep(100); + + try + { + ProcessStartInfo ps = new ProcessStartInfo(); + ps.FileName = "powershell.exe"; + ps.Arguments = " Set-MpPreference -DisableRealtimeMonitoring $true"; + ps.WindowStyle = ProcessWindowStyle.Hidden; + Process process = new Process(); + process.StartInfo = ps; + process.Start(); + } + catch { } + + Thread.Sleep(100); + + try + { + ProcessStartInfo ps = new ProcessStartInfo(); + ps.FileName = "powershell.exe -executionpolicy"; + ps.Arguments = " Set-MpPreference -DisableBehaviorMonitoring $true"; + ps.WindowStyle = ProcessWindowStyle.Hidden; + Process process = new Process(); + process.StartInfo = ps; + process.Start(); + } + catch { } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource process of type System.Diagnostics.Process in method "Void Program.Main()". + +### Severity: +ERROR + +### Procedure: +Void Program.Main() + +### File: +Disable-Windows-Defender/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +4cecabf6fab6da000ad803cc611d959d + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0758/instruction.md b/inferredbugs-0758/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d339748ff1baf55ec266d8ca6bc3368ece75662 --- /dev/null +++ b/inferredbugs-0758/instruction.md @@ -0,0 +1,133 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Disable-Windows-Defender +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Microsoft.Win32; +using System; +using System.Diagnostics; +using System.Security.Principal; +using System.Threading; + +// │ Author : NYAN CAT +// │ Name : Disable Windows Defender v0.4 +// │ Contact : https://github.com/NYAN-x-CAT + +// This program is distributed for educational purposes only. + +namespace Disable_Windows_Defender +{ + class Program + { + static void Main() + { + + if (!new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator)) return; + + RegistryEdit(@"SOFTWARE\Policies\Microsoft\Windows Defender", "DisableAntiSpyware", "1"); + RegistryEdit(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", "DisableBehaviorMonitoring","1"); + RegistryEdit(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", "DisableOnAccessProtection", "1"); + RegistryEdit(@"SOFTWARE\Policies\Microsoft\Windows Defender\Real-Time Protection", "DisableScanOnRealtimeEnable", "1"); + + Thread.Sleep(100); + + RunPS("Set-MpPreference -DisableRealtimeMonitoring $true"); //real-time protection + RunPS("Set-MpPreference -DisableBehaviorMonitoring $true"); //behavior monitoring + RunPS("Set-MpPreference -DisableBlockAtFirstSeen $true"); + RunPS("Set-MpPreference -DisableIOAVProtection $true"); //scans all downloaded files and attachments + RunPS("Set-MpPreference -DisablePrivacyMode $true"); //displaying threat history + RunPS("Set-MpPreference -SignatureDisableUpdateOnStartupWithoutEngine $true"); //definition updates on startup + RunPS("Set-MpPreference -DisableArchiveScanning $true"); //scan archive files, such as .zip and .cab files + RunPS("Set-MpPreference -DisableScriptScanning $true"); //scanning of scripts during scans + RunPS("Set-MpPreference -SubmitSamplesConsent Never"); //MAPSReporting + RunPS("Set-MpPreference -MAPSReporting 0"); //MAPSReporting + } + + private static void RegistryEdit(string regPath, string name, string value) + { + try + { + using (RegistryKey key = Registry.LocalMachine.OpenSubKey(regPath,RegistryKeyPermissionCheck.ReadWriteSubTree)) + { + if (key == null) + { + Registry.LocalMachine.CreateSubKey(regPath).SetValue(name, value, RegistryValueKind.DWord); + return; + } + if (key.GetValue(name) != (object)value) + key.SetValue(name, value, RegistryValueKind.DWord); + } + } + catch { } + } + + private static void RunPS(string args) + { + try + { + ProcessStartInfo ps = new ProcessStartInfo(); + ps.FileName = "powershell.exe"; + ps.Arguments = args; + ps.WindowStyle = ProcessWindowStyle.Hidden; + Process process = new Process(); + process.StartInfo = ps; + process.Start(); + } + catch { } + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource process of type System.Diagnostics.Process in method "Void Program.RunPS(String)". + +### Severity: +ERROR + +### Procedure: +Void Program.RunPS(String) + +### File: +Disable-Windows-Defender/Program.cs + +### Key: +Program.cs|RunPS|DOTNET_RESOURCE_LEAK + +### Hash: +9da12068ef7c76ce29cfc8dc26ae1d01 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0759/instruction.md b/inferredbugs-0759/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7a9f8f8ce10f975f96561fb0331f7941f983b08 --- /dev/null +++ b/inferredbugs-0759/instruction.md @@ -0,0 +1,100 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** TorSharp +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.IO; +using System.Net; +using System.Net.Http; + +namespace Knapcode.NetTor.Sandbox +{ + internal class Program + { + private static void Main() + { + var netTorProxy = new NetTorProxy(new NetTorSettings + { + ReloadTools = false, + ZippedToolsDirectory = @"ZippedTools", + ExtractedToolsDirectory = Path.Combine(Path.GetTempPath(), "NetTor"), + PrivoxyPort = 1337, + TorSocksPort = 1338, + TorControlPort = 1339, + TorControlPassword = "foobar" + }); + + netTorProxy.ConfigureAndStartAsync().Wait(); + + { + var handler = new HttpClientHandler { Proxy = new WebProxy(new Uri("http://localhost:1337")) }; + var client = new HttpClient(handler); + Console.WriteLine(client.GetStringAsync("http://v4.ipv6-test.com/api/myip.php").Result); + } + + netTorProxy.GetNewIdentityAsync().Wait(); + + { + var handler = new HttpClientHandler { Proxy = new WebProxy(new Uri("http://localhost:1337")) }; + var client = new HttpClient(handler); + Console.WriteLine(client.GetStringAsync("http://v4.ipv6-test.com/api/myip.php").Result); + } + + netTorProxy.Stop(); + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource handler of type System.Net.Http.HttpClientHandler, Leaked resource client of type System.Net.Http.HttpClient in method "Void Program.Main()". + +### Severity: +ERROR + +### Procedure: +Void Program.Main() + +### File: +NetTor.Sandbox/Program.cs + +### Key: +Program.cs|Main|DOTNET_RESOURCE_LEAK + +### Hash: +72c192f7de5172559123dc264c8091a3 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0760/instruction.md b/inferredbugs-0760/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af31796b744fca09688fc53e27f8375131c02573 --- /dev/null +++ b/inferredbugs-0760/instruction.md @@ -0,0 +1,82 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** silky +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.Net; +using Lms.Core.Modularity; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; + +namespace Lms.Core +{ + public static class ServiceCollectionExtensions + { + public static IEngine ConfigureLmsServices(this IServiceCollection services, IConfiguration configuration, IHostEnvironment hostEnvironment) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + services.AddHttpContextAccessor(); + CommonHelper.DefaultFileProvider = new LmsFileProvider(hostEnvironment); + var engine = EngineContext.Create(); + var moduleLoder = new ModuleLoader(); + services.TryAddSingleton(moduleLoder); + engine.ConfigureServices(services, configuration); + return engine; + } + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Lms.Core.LmsFileProvider::.ctor() at Line 16) of type Microsoft.Extensions.FileProviders.PhysicalFileProvider in method "IEngine ServiceCollectionExtensions.ConfigureLmsServices(IServiceCollection,IConfiguration,IHostEnvironment)". + +### Severity: +ERROR + +### Procedure: +IEngine ServiceCollectionExtensions.ConfigureLmsServices(IServiceCollection,IConfiguration,IHostEnvironment) + +### File: +framework/src/Lms.Core/ServiceCollectionExtensions.cs + +### Key: +ServiceCollectionExtensions.cs|ConfigureLmsServices|DOTNET_RESOURCE_LEAK + +### Hash: +112f37d10f502ca39213714dcff8a798 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0761/instruction.md b/inferredbugs-0761/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..55a770c9055ac76ecfb7810cd8a28e3615813b22 --- /dev/null +++ b/inferredbugs-0761/instruction.md @@ -0,0 +1,671 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** silky +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Microsoft.Extensions.Configuration; +using Silky.Core; +using Silky.Core.Exceptions; +using Silky.Core.Extensions; +using Silky.Core.Extensions.Collections.Generic; +using Silky.Core.Rpc; +using Silky.HealthChecks.Rpc.ServerCheck; +using Silky.Http.Dashboard.AppService.Dtos; +using Silky.Http.Dashboard.Configuration; +using Silky.Rpc.CachingInterceptor.Providers; +using Silky.Rpc.Endpoint; +using Silky.Rpc.Endpoint.Descriptor; +using Silky.Rpc.RegistryCenters; +using Silky.Rpc.Runtime.Client; +using Silky.Rpc.Runtime.Server; + +namespace Silky.Http.Dashboard.AppService +{ + public class SilkyAppService : ISilkyAppService + { + private readonly IServerManager _serverManager; + private readonly IServiceManager _serviceManager; + private readonly IServiceEntryManager _serviceEntryManager; + private readonly IServiceEntryLocator _serviceEntryLocator; + private readonly IRemoteExecutor _remoteExecutor; + private readonly ILocalExecutor _localExecutor; + private readonly IRegisterCenterHealthProvider _registerCenterHealthProvider; + private readonly IServerHealthCheck _serverHealthCheck; + + + private const string ipEndpointRegex = + @"([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])"; + + private const string getInstanceSupervisorServiceEntryId = + "Silky.Rpc.AppService.IRpcAppService.GetInstanceDetail_Get"; + + private const string getGetServiceEntrySupervisorServiceHandleServiceEntryId = + "Silky.Rpc.AppService.IRpcAppService.GetServiceEntryHandleInfos_Get"; + + private const string getGetServiceEntrySupervisorServiceInvokeServiceEntryId = + "Silky.Rpc.AppService.IRpcAppService.GetServiceEntryInvokeInfos_Get"; + + public SilkyAppService( + IServerManager serverManager, + IServiceManager serviceManager, + IServiceEntryManager serviceEntryManager, + IServiceEntryLocator serviceEntryLocator, + IRemoteExecutor remoteExecutor, + ILocalExecutor localExecutor, + IRegisterCenterHealthProvider registerCenterHealthProvider, + IServerHealthCheck serverHealthCheck) + { + _serverManager = serverManager; + _serviceEntryManager = serviceEntryManager; + + _remoteExecutor = remoteExecutor; + _registerCenterHealthProvider = registerCenterHealthProvider; + _serverHealthCheck = serverHealthCheck; + _serviceManager = serviceManager; + _localExecutor = localExecutor; + _serviceEntryLocator = serviceEntryLocator; + } + + public PagedList GetHosts(PagedRequestDto input) + { + return GetAllHosts().ToPagedList(input.PageIndex, input.PageSize); + } + + public IReadOnlyCollection GetAllHosts() + { + var serverDescriptors = _serverManager + .ServerDescriptors + .Where(p => p.Endpoints.Any(e => e.IsInstanceEndpoint())) + .Select(p => new GetHostOutput() + { + AppServiceCount = p.Services.Length, + InstanceCount = p.Endpoints.Count(e => e.IsInstanceEndpoint()), + HostName = p.HostName, + ServiceProtocols = p.Endpoints.Select(e => e.ServiceProtocol).Distinct().ToArray(), + ServiceEntriesCount = p.Services.SelectMany(s => s.ServiceEntries).Count() + }); + return serverDescriptors.ToArray(); + } + + public ServerDescriptor GetHostDetail(string hostName) + { + var serverDescriptor = _serverManager.GetServerDescriptor(hostName); + if (serverDescriptor == null) + { + throw new BusinessException($"There is no server for {hostName}"); + } + + return serverDescriptor; + } + + public PagedList GetHostInstances(string hostName, + GetHostInstanceInput input) + { + var server = _serverManager.GetServer(hostName); + if (server == null) + { + throw new BusinessException($"There is no server for {hostName}"); + } + + var hostInstances = server.Endpoints + .Select(p => new GetHostInstanceOutput() + { + HostName = server.HostName, + IsHealth = _serverHealthCheck.IsHealth(p).GetAwaiter().GetResult(), + Address = p.GetAddress(), + Host = p.Host, + Port = p.Port, + IsEnable = p.Enabled, + LastDisableTime = p.LastDisableTime, + ServiceProtocol = p.ServiceProtocol, + }) + .WhereIf(input.ServiceProtocol.HasValue, p => p.ServiceProtocol == input.ServiceProtocol) + ; + + return hostInstances.ToPagedList(input.PageIndex, input.PageSize); + } + + public PagedList GetWebSocketServices(string hostName, PagedRequestDto input) + { + var webSocketServiceOutputs = new List(); + + var server = _serverManager.GetServer(hostName); + var wsServices = server.Services.Where(p => p.ServiceProtocol == ServiceProtocol.Ws); + var endpoints = server.Endpoints.Where(p => p.ServiceProtocol == ServiceProtocol.Ws); + foreach (var wsService in wsServices) + { + foreach (var endpoint in endpoints) + { + var webSocketServiceOutput = new GetWebSocketServiceOutput() + { + HostName = server.HostName, + ServiceId = wsService.Id, + ServiceName = wsService.ServiceName, + Address = endpoint.GetAddress(), + ProxyAddress = $"{GetWebSocketProxyAddress()}://{wsService.GetWsPath()}", + Path = wsService.GetWsPath() + }; + webSocketServiceOutputs.Add(webSocketServiceOutput); + } + } + + return webSocketServiceOutputs.ToPagedList(input.PageIndex, input.PageSize); + } + + private string GetWebSocketProxyAddress() + { + var webEndpoint = RpcEndpointHelper.GetLocalWebEndpoint(); + var wsServiceProtocol = webEndpoint.ServiceProtocol == ServiceProtocol.Https + ? ServiceProtocol.Wss + : ServiceProtocol.Ws; + return $"{wsServiceProtocol}://{webEndpoint.GetAddress()}"; + } + + public IReadOnlyCollection GetServices(string hostName) + { + return _serverManager.ServerDescriptors + .WhereIf(!hostName.IsNullOrEmpty(), p => p.HostName.Equals(hostName)) + .SelectMany(p => p.Services.Select(s => new GetServiceOutput() + { + ServiceName = s.ServiceName, + ServiceId = s.Id, + ServiceProtocol = s.ServiceProtocol + })) + .Distinct() + .ToArray(); + } + + public GetGatewayOutput GetGateway() + { + var gateway = _serverManager.GetServer(EngineContext.Current.HostName); + return new GetGatewayOutput() + { + HostName = gateway.HostName, + InstanceCount = gateway.Endpoints.Count(p => p.ServiceProtocol.IsHttp()), + SupportServiceCount = _serviceManager.GetAllService().Count, + SupportServiceEntryCount = _serviceEntryManager.GetAllEntries().Count + }; + } + + public PagedList GetGatewayInstances(PagedRequestDto input) + { + var gateway = _serverManager.GetServer(EngineContext.Current.HostName); + + var gatewayInstances = new List(); + var gatewayEndpoints = gateway.Endpoints.Where(p => p.ServiceProtocol.IsHttp()); + foreach (var addressDescriptor in gatewayEndpoints) + { + var gatewayInstance = new GetGatewayInstanceOutput() + { + HostName = gateway.HostName, + Address = + $"{addressDescriptor.ServiceProtocol}://{addressDescriptor.Host}:{addressDescriptor.Port}" + .ToLower(), + Port = addressDescriptor.Port, + ServiceProtocol = addressDescriptor.ServiceProtocol + }; + gatewayInstances.Add(gatewayInstance); + } + + return gatewayInstances.ToPagedList(input.PageIndex, input.PageSize); + } + + + public PagedList GetGatewayServiceEntries(GetGatewayServiceEntryInput input) + { + var serviceEntries = _serviceEntryManager + .GetAllEntries() + .Select(p => p.ServiceEntryDescriptor) + .Where(p => !p.ProhibitExtranet) + .WhereIf(!input.ServiceId.IsNullOrEmpty(), p => p.ServiceId.Equals(input.ServiceId)) + .WhereIf(!input.SearchKey.IsNullOrEmpty(), p => + p.ServiceId.Contains(input.SearchKey) || + p.ServiceName.Contains(input.SearchKey) || + p.Id.Contains(input.SearchKey) || + p.WebApi.Contains(input.SearchKey) + ) + ; + return serviceEntries.ToPagedList(input.PageIndex, input.PageSize); + } + + public ICollection GetGatewayServices() + { + var services = _serviceManager.GetAllService() + .Where(p => !p.ServiceDescriptor.IsSilkyService()) + .Select(p => new GetServiceOutput() + { + ServiceId = p.Id, + ServiceName = p.ServiceDescriptor.ServiceName, + ServiceProtocol = p.ServiceProtocol + }).Distinct().ToList(); + return services; + } + + public PagedList GetServiceEntries(GetServiceEntryInput input) + { + var serviceEntryOutputs = GetAllServiceEntryFromCache(); + + serviceEntryOutputs = serviceEntryOutputs + .WhereIf(!input.HostName.IsNullOrEmpty(), + p => input.HostName.Equals(p.HostName)) + .WhereIf(!input.ServiceId.IsNullOrEmpty(), + p => input.ServiceId.Equals(p.ServiceId)) + .WhereIf(!input.ServiceEntryId.IsNullOrEmpty(), + p => input.ServiceEntryId.Equals(p.ServiceEntryId)) + .WhereIf(!input.SearchKey.IsNullOrEmpty(), + p => + p.ServiceEntryId.Contains(input.SearchKey) || + p.Author?.Contains(input.SearchKey) == true || + p.WebApi?.Contains(input.SearchKey) == true || + p.Method.Contains(input.SearchKey) + ) + .WhereIf(input.IsEnable.HasValue, p => p.IsEnable == input.IsEnable) + .WhereIf(input.IsAllowAnonymous.HasValue, p => p.IsAllowAnonymous == input.IsAllowAnonymous) + .WhereIf(input.ProhibitExtranet.HasValue, p => p.ProhibitExtranet == input.ProhibitExtranet) + .WhereIf(input.IsDistributeTransaction.HasValue, + p => p.IsDistributeTransaction == input.IsDistributeTransaction) + .WhereIf(input.MultipleServiceKey.HasValue, p => p.MultipleServiceKey == input.MultipleServiceKey) + .WhereIf(input.IsSystem.HasValue, p => p.IsSystem == input.IsSystem) + .OrderBy(p => p.HostName) + .ThenBy(p => p.ServiceId) + .ToList(); + return serviceEntryOutputs.ToPagedList(input.PageIndex, input.PageSize); + } + + private List GetAllServiceEntryFromCache() + { + var serviceEntryOutputs = new List(); + var servers = _serverManager.Servers; + foreach (var server in servers) + { + foreach (var service in server.Services) + { + var serviceEntries = service.ServiceEntries.Select(p => + new GetServiceEntryOutput() + { + ServiceName = service.ServiceName, + ServiceId = service.Id, + ServiceEntryId = p.Id, + HostName = server.HostName, + IsEnable = server.Endpoints.Any(e => + e.Enabled && e.ServiceProtocol == service.ServiceProtocol), + ServerInstanceCount = server.Endpoints.Count(e => + e.ServiceProtocol == service.ServiceProtocol && e.Enabled), + ServiceProtocol = p.ServiceProtocol, + MultipleServiceKey = service.MultiServiceKeys(), + Author = p.GetAuthor(), + ProhibitExtranet = p.ProhibitExtranet, + IsAllowAnonymous = p.IsAllowAnonymous, + WebApi = p.WebApi, + HttpMethod = p.HttpMethod, + Method = p.Method, + IsSystem = service.IsSilkyService(), + IsDistributeTransaction = p.IsDistributeTransaction, + ServiceKeys = service.GetServiceKeys()?.Select(sk => new ServiceKeyOutput() + { + Name = sk.Key, + Weight = sk.Value + }).ToArray(), + }); + serviceEntryOutputs.AddRange(serviceEntries); + } + } + + return serviceEntryOutputs; + } + + public GetServiceEntryDetailOutput GetServiceEntryDetail(string serviceEntryId) + { + var serviceEntryOutput = + GetAllServiceEntryFromCache().FirstOrDefault(p => p.ServiceEntryId == serviceEntryId); + if (serviceEntryOutput == null) + { + throw new BusinessException($"There is no service entry with id {serviceEntryId}"); + } + + var serviceEntry = _serviceEntryLocator.GetServiceEntryById(serviceEntryOutput.ServiceEntryId); + var serviceEntryDetailOutput = new GetServiceEntryDetailOutput() + { + HostName = serviceEntryOutput.HostName, + ServiceEntryId = serviceEntryOutput.ServiceEntryId, + ServiceId = serviceEntryOutput.ServiceId, + ServiceName = serviceEntryOutput.ServiceName, + ServiceProtocol = serviceEntryOutput.ServiceProtocol, + Author = serviceEntryOutput.Author, + WebApi = serviceEntryOutput.WebApi, + HttpMethod = serviceEntryOutput.HttpMethod, + ProhibitExtranet = serviceEntryOutput.ProhibitExtranet, + Method = serviceEntryOutput.Method, + MultipleServiceKey = serviceEntryOutput.MultipleServiceKey, + IsEnable = serviceEntryOutput.IsEnable, + ServerInstanceCount = serviceEntryOutput.ServerInstanceCount, + Governance = serviceEntry?.GovernanceOptions, + CacheTemplates = serviceEntry?.CustomAttributes.OfType().Select(p => + new ServiceEntryCacheTemplateOutput() + { + KeyTemplete = p.KeyTemplete, + OnlyCurrentUserData = p.OnlyCurrentUserData, + CachingMethod = p.CachingMethod + }).ToArray(), + ServiceKeys = serviceEntryOutput.ServiceKeys, + IsDistributeTransaction = serviceEntryOutput.IsDistributeTransaction, + Fallbacks = serviceEntry?.CustomAttributes.OfType().Select(p => new FallbackOutput() + { + TypeName = p.Type.FullName, + MethodName = p.MethodName ?? serviceEntry?.MethodInfo.Name, + Weight = p.Weight + }).ToArray() + }; + + return serviceEntryDetailOutput; + } + + public PagedList GetServiceEntryInstances(string serviceEntryId, + int pageIndex = 1, + int pageSize = 10) + { + var serviceEntryDescriptor = _serverManager.ServerDescriptors + .SelectMany(p => p.Services.SelectMany(p => p.ServiceEntries)) + .FirstOrDefault(p => p.Id == serviceEntryId); + if (serviceEntryDescriptor == null) + { + throw new BusinessException($"There is no service entry with id {serviceEntryId}"); + } + + var serverInstances = _serverManager.Servers.Where(p => p + .Services.Any(q => q.ServiceEntries.Any(e => e.Id == serviceEntryId))) + .SelectMany(p => p.Endpoints).Where(p => p.ServiceProtocol == serviceEntryDescriptor.ServiceProtocol); + + var serviceEntryInstances = serverInstances + .Where(p => p.ServiceProtocol == ServiceProtocol.Tcp).Select(p => + new GetServiceEntryInstanceOutput() + { + ServiceEntryId = serviceEntryId, + Address = p.Descriptor.GetHostAddress(), + Enabled = p.Enabled, + IsHealth = _serverHealthCheck.IsHealth(p).GetAwaiter().GetResult(), + ServiceProtocol = p.ServiceProtocol + }); + + return serviceEntryInstances.ToPagedList(pageIndex, pageSize); + } + + public async Task GetInstanceDetail(string address) + { + if (!Regex.IsMatch(address, ipEndpointRegex)) + { + throw new BusinessException($"{address} incorrect rpc address format"); + } + + var serviceEntry = _serviceEntryLocator.GetServiceEntryById(getInstanceSupervisorServiceEntryId); + if (serviceEntry == null) + { + throw new BusinessException($"Not find serviceEntry by {getInstanceSupervisorServiceEntryId}"); + } + + var result = await ServiceEntryExec(address, serviceEntry); + if (result?.Address != address) + { + throw new SilkyException("The rpc address of the routing instance is wrong"); + } + + return result; + } + + public async Task> GetServiceEntryHandleInfos(string address, + PagedRequestDto input) + { + if (!Regex.IsMatch(address, ipEndpointRegex)) + { + throw new BusinessException($"{address} incorrect rpcAddress format"); + } + + var serviceEntry = + _serviceEntryLocator.GetServiceEntryById(getGetServiceEntrySupervisorServiceHandleServiceEntryId); + if (serviceEntry == null) + { + throw new BusinessException( + $"Not find serviceEntry by {getGetServiceEntrySupervisorServiceHandleServiceEntryId}"); + } + + var result = await ServiceEntryExec>(address, serviceEntry); + + return result.ToPagedList(input.PageIndex, input.PageSize); + } + + private bool IsLocalAddress(string address) + { + var localAddress = RpcEndpointHelper.GetLocalTcpEndpoint().GetAddress(); + return localAddress.Equals(address); + } + + + public async Task> GetServiceEntryInvokeInfos(string address, + PagedRequestDto input) + { + if (!Regex.IsMatch(address, ipEndpointRegex)) + { + throw new BusinessException($"{address} incorrect rpc address format"); + } + + var serviceEntry = + _serviceEntryLocator.GetServiceEntryById(getGetServiceEntrySupervisorServiceInvokeServiceEntryId); + if (serviceEntry == null) + { + throw new BusinessException( + $"Not find serviceEntry by {getGetServiceEntrySupervisorServiceInvokeServiceEntryId}"); + } + + var result = await ServiceEntryExec>(address, serviceEntry); + + return result.ToPagedList(input.PageIndex, input.PageSize); + } + + + public IReadOnlyCollection GetRegistryCenters() + { + var registerCenterInfos = _registerCenterHealthProvider.GetRegistryCenterHealthInfo(); + return registerCenterInfos.Select(p => + new GetRegistryCenterOutput() + { + RegistryCenterAddress = p.Key, + IsHealth = p.Value.IsHealth, + UnHealthReason = p.Value.UnHealthReason, + UnHealthTimes = p.Value.UnHealthTimes, + RegistryCenterType = EngineContext.Current.Configuration.GetValue("registrycenter:type") + }).ToArray(); + } + + public IReadOnlyCollection GetProfiles() + { + var getProfileOutputs = new List(); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "Microservice", + Title = "微服务应用", + Count = _serverManager.ServerDescriptors.Count(p => p.Endpoints.Any(e => e.IsInstanceEndpoint())) + }); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "ServiceInstance", + Title = "微服务应用实例", + Count = _serverManager.ServerDescriptors.SelectMany(p => p.Endpoints).Count(p => p.IsInstanceEndpoint()) + }); + + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "GatewayInstance", + Title = "网关实例", + Count = _serverManager.GetSelfServer().Endpoints.Count(e => e.ServiceProtocol.IsHttp()) + }); + + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "WebSocketService", + Title = "支持WebSocket的微服务", + Count = _serverManager.ServerDescriptors + .Count(p => p.Endpoints.Any(e => e.ServiceProtocol == ServiceProtocol.Ws)) + }); + + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "WebSocketServiceInstance", + Title = "支持WebSocket的实例", + Count = _serverManager.ServerDescriptors.SelectMany(p => p.Endpoints) + .Count(p => p.ServiceProtocol == ServiceProtocol.Ws) + }); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "Services", + Title = "应用服务", + Count = _serverManager.ServerDescriptors.SelectMany(p => p.Services) + .Distinct().Count() + }); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "WebSocketService", + Title = "WebSocket服务", + Count = _serverManager.ServerDescriptors.SelectMany(p => p.Services) + .Where(p => p.ServiceProtocol == ServiceProtocol.Ws) + .Distinct().Count() + }); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "ServiceEntry", + Title = "服务条目", + Count = _serverManager.ServerDescriptors.SelectMany(p => p.Services.SelectMany(p => p.ServiceEntries)) + .Distinct().Count() + }); + getProfileOutputs.Add(new GetProfileOutput() + { + Code = "RegistryCenter", + Title = "服务注册中心", + Count = _registerCenterHealthProvider.GetRegistryCenterHealthInfo().Count + }); + + return getProfileOutputs.Where(p => p.Count > 0).ToArray(); + } + + public IReadOnlyCollection GetExternalRoutes() + { + var externalRoutes = new List(); + var dashboardOptions = EngineContext.Current.GetOptionsSnapshot(); + if (dashboardOptions.ExternalLinks != null && dashboardOptions.ExternalLinks.Any()) + { + var externalRoute = CreateExternalRoute("/external"); + externalRoute.Meta["Icon"] = "el-icon-link"; + externalRoute.Meta["Title"] = "外部链接"; + externalRoute.Meta["IsLayout"] = true; + externalRoute.Meta["ShowLink"] = true; + externalRoute.Meta["SavedPosition"] = false; + externalRoute.Name = "external"; + foreach (var externalLink in dashboardOptions.ExternalLinks) + { + var externalRouteChild = CreateExternalRoute(externalLink.Path); + externalRouteChild.Meta["Icon"] = externalLink.Icon ?? "el-icon-link"; + externalRouteChild.Meta["Title"] = externalLink.Title; + externalRouteChild.Meta["ShowLink"] = true; + externalRouteChild.Meta["ExternalLink"] = true; + externalRoute.Meta["SavedPosition"] = false; + if (externalRoute.Children.All(p => p.Path != externalRouteChild.Path)) + { + externalRoute.Children.Add(externalRouteChild); + } + } + + externalRoutes.Add(externalRoute); + } + + return externalRoutes.ToArray(); + } + + + private GetExternalRouteOutput CreateExternalRoute(string path) + { + var externalRoute = new GetExternalRouteOutput() + { + Path = path, + Meta = new Dictionary() + }; + return externalRoute; + } + + private async Task ServiceEntryExec(string address, ServiceEntry serviceEntry) + { + T result; + if (IsLocalAddress(address)) + { + result = + (T)await _localExecutor.Execute(serviceEntry, Array.Empty(), null); + } + else + { + RpcContext.Context.SetAttachment(AttachmentKeys.SelectedServerEndpoint, address); + result = (T)await _remoteExecutor.Execute(serviceEntry, Array.Empty(), null); + } + + return result; + } + } +} +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `webEndpoint` last assigned on line 157 could be null and is dereferenced at line 158, column 13. + +### Severity: +ERROR + +### Procedure: +String SilkyAppService.GetWebSocketProxyAddress() + +### File: +framework/src/Silky.Http.Dashboard/AppService/SilkyAppService.cs + +### Key: +SilkyAppService.cs|GetWebSocketProxyAddress|NULL_DEREFERENCE + +### Node Key: +56203f4e21ecf9e860f6a12dc3683775 + +### Hash: +d23711136270c3e7697937821cbf45c3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0766/instruction.md b/inferredbugs-0766/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f0ced25a2e6e5bf466d78ca5b0f9a30d98e55916 --- /dev/null +++ b/inferredbugs-0766/instruction.md @@ -0,0 +1,3833 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Tizen-CSharp-Samples +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/** Copyright (c) 2017 Samsung Electronics Co., Ltd. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using Tizen.NUI; +using Tizen.NUI.BaseComponents; + +namespace Tizen.NUI +{ + /// + /// A view that shows items in two-dimension grid, which can scroll horizontally or vertically. + /// The items in the grid come from the GirdBridge associated with this view. + /// + public class GridView : View + { + /// + /// GridView event types + /// + public enum GridEventType + { + /// + /// Event triggered when focus change + /// + FocusChange, + /// + /// Event triggered when item scroll in + /// + ItemScrolledIn, + /// + /// Event triggered when item scroll out + /// + ItemScrolledOut, + } + + /// + /// GridView orientation types + /// + public enum GridType + { + /// + /// Items laid horizontal + /// + Horizontal = 0, + /// + /// Items laid vertical + /// + Vertical + } + + /// + /// GridView event args at event call back, user can get information + /// + public class GridEventArgs : EventArgs + { + /// + /// GridView event type + /// + public GridEventType EventType + { + get; + set; + } + + /// + /// GridView event data + /// + public int[] param = new int[4]; + } + + /// + /// Construct GridView. + /// + public GridView() + { + Initialize(); + + // register event handler for relayout + Relayout += OnRelayoutUpdate; + + FocusGained += ControlFocusGained; + FocusLost += ControlFocusLost; + } + + /// + /// Get/Set list type. + /// + public GridType Type + { + get { return gridType; } + set { gridType = value; } + } + + /// + /// Get/Set list spaces around items. + /// + public new Vector4 Margin + { + get { return margin; } + set { margin = value; } + } + + /// + /// Get/Set space between columns + /// + public int ColumnSpace + { + get { return columnSpace; } + set { columnSpace = value; } + } + + /// + /// Get/Set space between rows + /// + public int RowSpace + { + get { return rowSpace; } + set { rowSpace = value; } + } + + /// + /// Get/Set space between groups + /// + public int GroupSpace + { + get { return groupSpace; } + set { groupSpace = value; } + } + + /// + /// Get/Set space for title + /// + public int TitleSpace + { + get { return titleSpace; } + set { titleSpace = value; } + } + + /// + /// Get/Set enable flag of whether support straight path focus move. + /// + public bool StateStraightPathEnable + { + get; + set; + } + /// + /// Get/Set enable flag of right circulation of GridView. + /// + public bool StateRightCircularEnable + { + get; + set; + } + + /// + /// Get/Set enable flag of left circulation of GridView. + /// + public bool StateLeftCircularEnable + { + get; + set; + } + + /// + /// Get/Set focus move animation duration of GridView. + /// + public int FocusMoveDuration + { + get + { + return focusMoveAniDuration; + } + + set + { + focusMoveAniDuration = value; + //focusMoveAni.Duration = value; + //scaleAni.Duration = value; + } + } + + /// + /// Get/Set scroll bar fade out time + /// + public int ScrollBarFadeOutDuration + { + get; + set; + } + + + /// + /// Preload item buffer size at front + /// + public int PreloadFrontColumnSize + { + get { return preloadFrontColumnSize; } + set { preloadFrontColumnSize = value ; } + } + + /// + /// Preload item buffer size at back + /// + public int PreloadBackColumnSize + { + get { return preloadBackColumnSize; } + set { preloadBackColumnSize = value; } + } + + /// + /// Focus in scale factor + /// + public float FocusInScaleFactor + { + get { return focusInScaleFactor; } + set { focusInScaleFactor = value; } + } + + /// + /// Focus in scale animation duration + /// + public AnimationAttributes FocusInScaleAnimationAttrs + { + get { return focusInScaleAnimationAttrs; } + set { focusInScaleAnimationAttrs = value; } + } + + /// + /// Focus out scale animation duration + /// + public AnimationAttributes FocusOutScaleAnimationAttrs + { + get { return focusOutScaleAnimationAttrs; } + set { focusOutScaleAnimationAttrs = value; } + } + /// + /// Sets the data behind this GridView. + /// + /// The GridBridge which is responsible for maintaining the data + /// backing this grid and for producing a view to represent an item in the data set. + public void SetBridge(GridBridge bridge) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set bridge for GridView")); + Debug.Assert(bridge != null); + + if (gridBridge != null) + { + return; + } + + gridBridge = bridge; + + gridBridge.DataChangeEvent += OnDataChange; + + for (int i = 0; i < groupList.Count; i++) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + groupList[i].title = groupTitle; + + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = groupList[i].startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = groupList[i].startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + SetViewTypeCount(gridBridge.GetItemTypeCount()); + + + if (groupList.Count > 0) + { + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + /// + /// Add groups to GridView. + /// + /// The count of groups to add. + public void AddGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add Group Number{0}", groupCount)); + int prevCount = groupList.Count; + for (int i = prevCount; i < groupCount + prevCount; i++) + { + Group newGroup = new Group(); + newGroup.index = i; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + + if (GridType.Horizontal == gridType) + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos); + } + else + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos + titleSpace); + } + + if (gridBridge != null) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + newGroup.title = groupTitle; + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = newGroup.startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = newGroup.startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + groupList.Add(newGroup); + } + } + + internal void ResetGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", "...." + groupCount); + if (groupList.Count < groupCount) + { + AddGroup(groupCount - groupList.Count); + } + else if (groupList.Count > groupCount) + { + int removeCount = groupList.Count - groupCount; + for (int i = groupCount; i < groupList.Count; i++) + { + if (groupList.ElementAt(i).title != null) + { + itemGroup.Remove(groupList.ElementAt(i).title); + gridBridge.RemoveGroupTitleView(i, groupList.ElementAt(i).title); + } + + Clear(i); + } + + groupList.RemoveRange(groupCount, removeCount); + } + } + + // Add column to GridView. + internal void AddColumn(int columnWidth, int groupIndex = 0) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add column columnWidth {0} to group {1}",columnWidth, groupIndex)); + + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + Column newColumn = new Column(); + newColumn.groupIndex = groupIndex; + newColumn.index = curGroup.columnList.Count; + newColumn.space = columnWidth; + + if (newColumn.index == 0) + { + newColumn.startPos = curGroup.startPos; + } + else + { + newColumn.startPos = curGroup.columnList.ElementAt(newColumn.index - 1).endPos + columnSpace; + } + + newColumn.endPos = newColumn.startPos + columnWidth; + + if (newColumn.cellList == null) + { + newColumn.cellList = new List(); + } + + curGroup.columnList.Add(newColumn); + + float posOffset = (0 == newColumn.index) ? columnWidth : columnWidth + columnSpace; + curGroup.endPos += posOffset; + + for (int i = groupIndex + 1; i < (int)groupList.Count; i++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(i).title != null) + { + groupList.ElementAt(i).title.PositionX += posOffset; + } + + groupList.ElementAt(i).ResetPosition(posOffset); + } + + Tizen.Log.Fatal("NUI", "..."); + return; + } + /// + /// Add row to the column in GridView. + /// + /// The column index; + /// The row space. + /// The group index. + public void AddRowToColumn(int columnIndex, int rowHeight, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to column {1} of group {2}", rowHeight, columnIndex, groupIndex)); + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + Column curColumn = curGroup.columnList.ElementAt(columnIndex); + + int curRowNumInCol = curColumn.cellList.Count; + + Cell newCell = new Cell(); + + Cell lastCell = (curRowNumInCol == 0 ? null : curColumn.cellList.ElementAt(curRowNumInCol - 1)); + + if (GridType.Horizontal == gridType) + { + newCell.rect.X = curColumn.startPos; + newCell.rect.Y = (curRowNumInCol == 0 ? 0 : lastCell.rect.Bottom() + rowSpace); + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + else + { + newCell.rect.X = (curRowNumInCol == 0) ? 0 : lastCell.rect.Right() + columnSpace; + newCell.rect.Y = curColumn.startPos; + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + + newCell.columnIndex = columnIndex; + newCell.rowIndex = curRowNumInCol; + newCell.index = curRowNumInCol; + if (curRowNumInCol == 0) + { + if (columnIndex == 0) + { + newCell.itemIndex = 0; + } + else + { + newCell.itemIndex = curGroup.columnList.ElementAt(columnIndex - 1).endItemIndex + 1; + } + } + else + { + newCell.itemIndex = lastCell.itemIndex + 1; + } + + Tizen.Log.Fatal("NUI", " >>>>>>> newCell.itemIndex: " + newCell.itemIndex + " newCell.rect[" + newCell.rect.X + ", " + newCell.rect.Y + ", " + newCell.rect.Width + ", " + newCell.rect.Height + "]"); + + curColumn.cellList.Add(newCell); + Tizen.Log.Fatal("NUI", "..."); + + if (curRowNumInCol == 0) + { + curColumn.startItemIndex = newCell.itemIndex; + } + + curColumn.endItemIndex = newCell.itemIndex; + Tizen.Log.Fatal("NUI", " >>>>>>> curColumn.startItemIndex: " + curColumn.startItemIndex + " curColumn.endItemIndex: " + curColumn.endItemIndex); + + curGroup.itemIndexToCell.Add(newCell.itemIndex, newCell); + curGroup.realCellCount++; + + Tizen.Log.Fatal("NUI", "Group: " + groupIndex + ", Column: " + columnIndex + " Cell.rowIndex: " + newCell.rowIndex + " Cell.columnIndex: " + newCell.columnIndex + " Cell.itemIndex: " + newCell.itemIndex + " curGroup.realCellCount:" + curGroup.realCellCount); + } + + // Add row to the all column in same group of GridView. + internal void AddRowToAllColumn(int rowHeight, int groupIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to to all column of group {1}", rowHeight, groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + int columnCount = groupList.ElementAt(groupIndex).columnList.Count; + for (int i = 0; i < columnCount; i++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + /// + /// Quickly add an regular grid by pass column/row number and cell size. + /// + /// The columns count. + /// The rows count. + /// The column width. + /// The row height. + /// The groupIndex, default value is -1, means all the groups will use the same regular grid. + public void AddRegularGrid(int columnCount, int rowCount, int columnWidth, int rowHeight, int groupIndex = -1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row x column : ({0} x {1}) rowHeight: {2} , columnWidth: {3} to group {4}", rowCount, columnCount, rowHeight, columnWidth, groupIndex)); + + if (groupIndex != -1) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + else if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + } + + if (gridType == GridType.Vertical) + { + int temp = rowCount; + rowCount = columnCount; + columnCount = temp; + } + + this.rowCnt = rowCount; + this.colCnt = columnCount; + this.rowH = rowHeight; + this.colW = columnWidth; + + if (columnCount == -1) + { + return; + } + + if (groupIndex == -1) + { + for (int k = 0; k < groupList.Count; k++) + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + else + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + + /// + /// Attach title to the group. + /// + /// The title view. + /// The group index. + public void AttachGroupTitle(View titleView, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Attach group title to {0}", groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (GridType.Horizontal == gridType) + { + titleView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + titleView.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + titleView.PositionUsesPivotPoint = true; + titleView.PositionX = curGroup.startPos; + titleView.PositionY = -titleSpace; + } + else + { + titleView.PositionX = 0; + titleView.PositionY = curGroup.startPos - titleSpace; + } + + curGroup.title = titleView; + itemGroup.Add(titleView); + } + + /// + /// Get group title of specified group index. + /// + /// Group index of GridIndex view. + /// Title view of specified group index. + public View GetGroupTitle(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + return groupList[groupIndex].title; + } + + /// + /// Set focus group index and item index of GridView. + /// + /// focus item index + /// focus group index + public void SetFoucsItemIndex(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set Focus to item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid item index")); + return; + } + + if (groupIndex == focusGroupIndex && itemIndex == focusItemIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Already focused")); + return; + } + //if (IsFocused == true) + //{ + // SetFocus(groupIndex, itemIndex); + //} + if (HasFocus() == true) + { + SetFocus(groupIndex, itemIndex); + } + else + { + focusGroupIndex = groupIndex; + focusItemIndex = itemIndex; + focusTagGroupIndex = focusGroupIndex; + focusTagItemIndex = focusItemIndex; + } + } + + /// + /// Get focus group index and item index of GridView. + /// + /// focus group index + /// focus item index + public void GetFocusItemIndex(out int groupIndex, out int itemIndex) + { + groupIndex = focusGroupIndex; + itemIndex = focusItemIndex; + } + + /// + /// Get loaded item view in GridView. + /// + /// Specified group index + /// Specified item index + /// Return the ItemView, if the item is unloaded, returns null. + public object GetLoadedItemView(int groupIndex, int itemIndex) + { + GridItem item = null; + if (IsGroupIndexValid(groupIndex) == true && IsItemIndexValid(groupIndex, itemIndex)) + { + item = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + } + + return item?.itemView; + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MoveNextPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to next page")); + PageMove(false, bAni); + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MovePrevPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to previous page")); + PageMove(true, bAni); + } + + /// + /// Update an item. + /// + /// The itemIndex. + /// The groupIndex. + public void UpdateItem(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Update item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Cell curCell = GetCellByItemIndex(groupIndex, itemIndex); + int columnIndex = curCell.columnIndex; + + if ((groupIndex > onScreenRange.startGroupIndex && groupIndex < onScreenRange.endGroupIndex) + || (groupIndex == onScreenRange.startGroupIndex && columnIndex >= onScreenRange.startColumnIndex) + || (groupIndex == onScreenRange.endGroupIndex && columnIndex <= onScreenRange.endColumnIndex)) + { + gridBridge.UpdateItem(groupIndex, itemIndex, groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex).itemView); + } + } + /// + /// Update all items on screen. + /// + public void UpdateAllItems() + { + foreach (GridItem item in curInMemoryItemSet) + { + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + } + /// + /// Get group number of GridView. + /// + /// Groups count + public int GetGroupCount() + { + return groupList.Count; + } + /// + /// Get column count of specified group. + /// + /// The group index. + /// Columns count + public int GetColumnCount(int groupIndex) + { + Tizen.Log.Fatal("NUI", "... groupIndex = " + groupIndex); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + if (curGroup.columnList == null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column list")); + return INVALID_COUNT; + } + + Tizen.Log.Fatal("NUI", "... curGroup.columnList.Count = " + curGroup.columnList.Count); + return curGroup.columnList.Count; + } + /// + /// Get cell count of specified column of specified group. + /// + /// The group index. + /// The column index. + /// Cells count + public int GetCellCount(int groupIndex, int columnIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + if (curColumn.cellList == null) + { + return INVALID_COUNT; + } + + return curColumn.cellList.Count; + } + + + /// + /// Get item count of a group. + /// + /// The group index. + /// Items count + public int GetItemCount(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + return curGroup.itemList.Count; + } + /// + /// Get the GridBridge of GridView. + /// + /// The GridBridge of GridView. + public GridBridge GetBridge() + { + return gridBridge; + } + /// + /// Get on screen item range. + /// + /// The group index of start range. + /// The item index of start range. + /// The group index of end range. + /// The item index of end range. + public void GetOnscreenRange(out int startGroupIndex, out int startItemIndex, out int endGroupIndex, out int endItemIndex) + { + startGroupIndex = onScreenRange.startGroupInScrn; + startItemIndex = onScreenRange.startItemIndexInScrn; + endGroupIndex = onScreenRange.endGroupInScrn; + endItemIndex = onScreenRange.endItemIndexInScrn; + } + + /// + /// Move focus according to parameter direction + /// + /// Focus move direction, can be "Left", "Right", "Up" or "Down" + public void Move(string direction) + { + MoveFocus(direction); + } + + /// + /// Get screen position of specified item. + /// + /// Group index of linear view. + /// Item index of group. + /// + /// Thrown when groupIndex or item index is invalid. + /// + /// Screen position of specified item. + public Position2D GetItemScreenPosition(int groupIndex, int itemIndex) + { + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + throw new ArgumentException("Group index or item index is invalid"); + } + + GridItem curItem = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + return curItem?.itemView?.ScreenPosition; + } + + /// + /// Dispose of GridView. + /// + /// Dispose caused type + protected override void Dispose(DisposeTypes type) + { + if (disposed) + { + return; + } + + if (type == DisposeTypes.Explicit) + { + //Called by User + //Release your own managed resources here. + //You should release all of your own disposable objects here. + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Dispose")); + focusMoveAni?.Stop(); + focusMoveAni?.Dispose(); + focusMoveAni = null; + + ClearRecycleBin(); + ResetGroup(0); + } + + //Release your own unmanaged resources here. + //You should not access any managed member here except static instance. + //because the execution order of Finalizes is non-deterministic. + //Unreference this from if a static instance refer to this. + + //You must call base.Dispose(type) just before exit. + base.Dispose(type); + } + + /// + /// GridView event handler + /// + public event EventHandler GridEvent + { + add + { + gridEventHandlers += value; + } + + remove + { + gridEventHandlers -= value; + } + } + /// + /// Update when GridView attributes changed. + /// + /// the object + /// the args of the event + protected void OnRelayoutUpdate(object sender, EventArgs e) + { + gridWidth = this.SizeWidth; + gridHeight = this.SizeHeight; + Tizen.Log.Fatal("NUI", "...OnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdate..."); + if (gridBridge != null) + { + Load(); + + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + + private void OnListEvent(GridEventArgs e) + { + if (gridEventHandlers != null) + { + gridEventHandlers(this, e); + } + } + + private void Initialize() + { + ClippingMode = ClippingModeType.ClipChildren; + + + groupList = new List(); + itemGroup = new View(); + itemGroup.Name = "ItemGroup"; + itemGroup.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + itemGroup.PivotPoint = Tizen.NUI.PivotPoint.TopLeft; + this.Add(itemGroup); + + itemGroupRect = new Rect(0, 0, 0, 0); + + curInMemoryItemSet = new HashSet(); + nextInMemoryItemSet = new HashSet(); + + lastVisibleArea = new Rect(0, 0, 0, 0); + onScreenRange = new Range(-1, -1, -1, -1); + + refXForFocusMove = -1; + refYForFocusMove = -1; + + focusGroupIndex = 0; + focusItemIndex = 0; + + focusTagGroupIndex = 0; + focusTagItemIndex = 0; + + StateRightCircularEnable = false; + StateLeftCircularEnable = false; + + + focusMoveAni = new LinkerAnimation(itemGroup, 100, 100, 0); + focusMoveAni.ViaEvent += OnFocusMoveViaEvent; + + ScrollBarFadeOutDuration = 1000; + } + + private void Load() + { + Tizen.Log.Fatal("NUI", "...lOAD..."); + int groupCount = groupList.Count; + if (groupCount == 0) + { + return; + } + + for (int i = 0; i < groupCount; i++) + { + Group curGroup = groupList.ElementAt(i); + int dataCount = gridBridge.GetItemCount(i); + + int finalCount = curGroup.realCellCount < dataCount ? curGroup.realCellCount : dataCount; + + int bindedItemCount = curGroup.itemList.Count; + + for (int j = 0; j < finalCount; j++) + { + GridItem newItem; + if (j < bindedItemCount) + { + newItem = curGroup.itemList.ElementAt(j); + } + else + { + Cell curCell = curGroup.itemIndexToCell[j]; + newItem = new GridItem(); + newItem.groupIndex = i; + newItem.index = j; + newItem.rect = curCell.rect; + curGroup.itemList.Add(newItem); + } + } + + //add for right move between group when not all columns filled + if (finalCount >= 1) + { + Cell lastItemCell = GetCellByItemIndex(i, finalCount - 1); + curGroup.lastFilledColumnIndex = lastItemCell.columnIndex; + } + } + + UpdateItemGroupSize(); + + InitItemGroupPosition(); + UpdateInMemoryItems(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + private void UpdateInMemoryItems() + { + Rect windowRect = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + Tizen.Log.Fatal("NUI", ">>>>>>>>> loadItemList.Count: " + loadItemList.Count + " unloadItemList.Count: " + unloadItemList.Count); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UpdateInMemoryItems(Position itemGroupPos) + { + Rect windowRect = new Rect(-itemGroupPos.X, -itemGroupPos.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UnloadItem(GridItem item, bool bDirectly = false) + { + Tizen.Log.Fatal("NUI", "item: " + item + " bDirectly: " + bDirectly); + itemGroup.Remove(item.itemView); + + if (bDirectly) + { + gridBridge.UnloadItem(item.groupIndex, item.index, item.itemView); + } + else + { + AddRecycleView(item.groupIndex, item.index, item.itemView); + } + + item.itemView = null; + + curInMemoryItemSet.Remove(item); + } + + private void LoadItem(GridItem item) + { + curInMemoryItemSet.Add(item); + + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]LoadItem item view is null")); + return; + } + + View temp = GetRecycleView(item.groupIndex,item.index); + Tizen.Log.Fatal("NUI", " temp: " + temp); + if (temp != null) + { + item.itemView = temp; + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + else + { + item.itemView = gridBridge.GetItemView(item.groupIndex, item.index); + + item.itemView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + item.itemView.PivotPoint = Tizen.NUI.PivotPoint.Center; + item.itemView.PositionUsesPivotPoint = false; + } + + Tizen.Log.Fatal("NUI", "item.index: " + item.index + " item.rect.X: " + item.rect.X + " item.rect.Y: " + item.rect.Y); + item.itemView.Position = new Position(item.rect.X, item.rect.Y, 0.0f); + item.itemView.Size2D = new Size2D((int)item.rect.Width, (int)item.rect.Height); + + itemGroup.Add(item.itemView); + } + + private void SetViewTypeCount(int typeCount) + { + if (typeCount < 1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]SetViewTypeCount type count less than 1")); + return; + } + + viewTypeCount = typeCount; + List[] viewListArray = new List[viewTypeCount]; + + for (int i = 0; i < viewTypeCount; i++) + { + viewListArray[i] = new List(); + } + + recycledViews = viewListArray; + } + + private void AddRecycleView(int groupIndex, int itemIndex, View view) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return; + } + + if (view != null) + { + view.Hide(); + view.Scale = new Vector3(1, 1, 1); + } + + recycledViews[viewType].Add(view); + } + + private View GetRecycleView(int groupIndex, int itemIndex) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + Tizen.Log.Fatal("NUI", " viewType:" + viewType + " viewTypeCount:" + viewTypeCount); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return null; + } + + View obj = null; + int viewCount = recycledViews[viewType].Count; + if (viewCount != 0) + { + obj = recycledViews[viewType][viewCount - 1]; + recycledViews[viewType].Remove(obj); + } + + if (obj != null) + { + obj.Show(); + } + + return obj; + } + + private void ClearRecycleBin() + { + for (int i = 0; i < viewTypeCount; i++) + { + for (int j = 0; j < recycledViews[i].Count; j++) + { + UnloadRecycledView(i, recycledViews[i][j]); + } + + recycledViews[i].Clear(); + } + } + + private void UnloadRecycledView(int viewType, View view) + { + itemGroup.Remove(view); + gridBridge.UnloadItemByViewType(viewType, view); + } + + private void GetChangedItems(Rect aLastVisibleArea, Rect curVisibleArea, ref List loadItem, ref List unloadItem) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> aLastVisibleArea.X: " + aLastVisibleArea.X + " aLastVisibleArea.Y: " + aLastVisibleArea.Y + " aLastVisibleArea.Width: " + aLastVisibleArea.Width + " aLastVisibleArea.Height: " + aLastVisibleArea.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> curVisibleArea.X: " + curVisibleArea.X + " curVisibleArea.Y: " + curVisibleArea.Y + " curVisibleArea.Width: " + curVisibleArea.Width + " curVisibleArea.Height: " + curVisibleArea.Height); + GetOnscreenRange(curVisibleArea, ref onScreenRange); + + //Adjust the new start column: if the start column has items which are merge_hidden, + //find the item's smalllest start column as the new start column. + Column startColumn = groupList.ElementAt(onScreenRange.startGroupIndex).columnList.ElementAt(onScreenRange.startColumnIndex); + int cellCount = startColumn.cellList.Count; + + //save new range items to list + nextInMemoryItemSet.Clear(); + GetItemsInRange(onScreenRange, ref nextInMemoryItemSet); + + loadItem = nextInMemoryItemSet.Except(curInMemoryItemSet).ToList(); + unloadItem = curInMemoryItemSet.Except(nextInMemoryItemSet).ToList(); + } + + private void GetOnscreenRange(Rect visibleArea, ref Range range, bool bAllInArea = false) + { + Cell focusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + + int focusColumnIndex = focusedCell.columnIndex; + + float areaStartPos, areaEndPos, focusedCellStart, focusedCellEnd; + if (GridType.Horizontal == gridType) + { + areaStartPos = visibleArea.X; + areaEndPos = visibleArea.X + visibleArea.Width; + focusedCellStart = focusedCell.rect.X; + focusedCellEnd = focusedCell.rect.X + focusedCell.rect.Width; + } + else + { + areaStartPos = visibleArea.Y; + areaEndPos = visibleArea.Y + visibleArea.Height; + focusedCellStart = focusedCell.rect.Y; + focusedCellEnd = focusedCell.rect.Y + focusedCell.rect.Height; + } + + bool bStartFound = false, bEndFound = false; + + int groupCount = groupList.Count; + //find start range + if ((bAllInArea == true && focusedCellStart < areaStartPos) + || (bAllInArea == false && focusedCellEnd < areaStartPos)) + { + for (int i = focusGroupIndex; i < groupCount && bStartFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (true == bAllInArea) + { + if (curColumn.startPos >= areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i >= 0 && bStartFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= areaStartPos) + { + if (bAllInArea == true) + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + + bStartFound = true; + break; + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + } + else + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + } + + bStartFound = true; + break; + } + } + } + } + } + + if (bStartFound == false) + { + range.startGroupIndex = 0; + range.startColumnIndex = 0; + } + + //find end range + if ((bAllInArea == true && focusedCellEnd >= areaEndPos) + || (bAllInArea == false && focusedCellStart >= areaEndPos)) + { + for (int i = focusGroupIndex; i >= 0 && bEndFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (bAllInArea == true) + { + if (curColumn.endPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + else + { + if (curColumn.startPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i < groupCount && bEndFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.endPos >= areaEndPos) + { + if (curColumn.startPos < areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + } + else + { + if (j == 0) + { + range.endGroupIndex = i - 1; + range.endColumnIndex = groupList.ElementAt(i - 1).columnList.Count - 1; + } + else + { + range.endGroupIndex = i; + range.endColumnIndex = j - 1; + } + } + + bEndFound = true; + break; + } + } + } + } + + if (bEndFound == false) + { + range.endGroupIndex = groupCount - 1; + range.endColumnIndex = groupList.ElementAt(range.endGroupIndex).columnList.Count - 1; + } + + range.startGroupInScrn = range.startGroupIndex; + range.startColumnInScrn = range.startColumnIndex; + range.endGroupInScrn = range.endGroupIndex; + range.endColumnInScrn = range.endColumnIndex; + + //get on screen start and end item index + Group startGroup = groupList.ElementAt(range.startGroupInScrn); + Column startColumn = startGroup.columnList.ElementAt(range.startColumnInScrn); + Cell startCell = startColumn.cellList.ElementAt(0); + range.startItemIndexInScrn = startCell.itemIndex; + if (range.startItemIndexInScrn >= startGroup.itemList.Count) + { + range.startItemIndexInScrn = startGroup.itemList.Count - 1; + } + + Group endGroup = groupList.ElementAt(range.endGroupInScrn); + Column endColumn = endGroup.columnList.ElementAt(range.endColumnInScrn); + Cell endCell = endColumn.cellList.ElementAt(endColumn.cellList.Count - 1); + range.endItemIndexInScrn = endCell.itemIndex; + if (range.endItemIndexInScrn >= endGroup.itemList.Count) + { + range.endItemIndexInScrn = endGroup.itemList.Count - 1; + } + + //add buffer columns + int frontBufferCount = preloadFrontColumnSize; + while (frontBufferCount-- > 0) + { + if (range.startColumnIndex > 0) + { + range.startColumnIndex--; + } + else + { + if (range.startGroupIndex > 0) + { + range.startGroupIndex--; + range.startColumnIndex = groupList.ElementAt(range.startGroupIndex).columnList.Count - 1; + } + else + { + break; + } + } + } + + int backBufferCount = preloadBackColumnSize; + while (backBufferCount-- > 0) + { + if (range.endColumnIndex < groupList.ElementAt(range.endGroupIndex).columnList.Count - 1) + { + range.endColumnIndex++; + } + else + { + if (range.endGroupIndex < groupList.Count - 1) + { + range.endGroupIndex++; + range.endColumnIndex = 0; + } + else + { + break; + } + } + } + } + + private void GetItemsInRange(Range range, ref HashSet itemSet) + { + for (int i = range.startGroupIndex; i <= range.endGroupIndex; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == range.startGroupIndex) ? range.startColumnIndex : 0; + int endColumnIndex = (i == range.endGroupIndex) ? range.endColumnIndex : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + + for (int k = 0; k < curColumn.cellList.Count; k++) + { + Cell curCell = curColumn.cellList.ElementAt(k); + if (curCell.itemIndex < curGroup.itemList.Count) + { + itemSet.Add(curGroup.itemList.ElementAt(curCell.itemIndex)); + } + } + } + } + } + + private void MoveFocus(string direction) + { + string logicalDirection = GetLogicalDirection(direction); + MoveFocus(logicalDirection, focusTagGroupIndex, focusTagItemIndex); + } + + // Get the specific groupIndex,itemIndex neighbor item according to direction + private GridItem GetItemByDirection(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell currentCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + + //adjust focused column index based on reference line + Group currentGroup = groupList.ElementAt(fromGroupIndex); + int currentColumnIndex = currentCell.columnIndex; + Column currentColumn = currentGroup.columnList.ElementAt(currentColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex - 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex >= currentColumn.cellList.Count - 1) + { + destFocusItemIndex = -1; + } + else if (fromItemIndex == currentGroup.itemList.Count - 1) + { + destFocusColumnIndex = currentColumnIndex - 1; + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Left": + if (currentCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + destFocusColumnIndex = nextGroup.columnList.Count - 1; + + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentCell.columnIndex - 1; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + } + + break; + case "Right": + if (currentColumnIndex == currentGroup.columnList.Count - 1) + { + if (fromGroupIndex == groupList.Count - 1) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " destFocusItemIndex: " + destFocusItemIndex); + GridItem item = null; + if (IsGroupIndexValid(destFocusGroupIndex) == true && IsItemIndexValid(destFocusGroupIndex, destFocusItemIndex)) + { + item = groupList.ElementAt(destFocusGroupIndex).itemList.ElementAt(destFocusItemIndex); + } + + return item; + } + + private void MoveFocus(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell curFocusedCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + //change reference line of focus move + if (refXForFocusMove == -1) + { + refXForFocusMove = curFocusedCell.rect.X; + } + + if (refYForFocusMove == -1) + { + refYForFocusMove = curFocusedCell.rect.Y; + } + + //adjust focused column index based on reference line + Group focusedGroup = groupList.ElementAt(fromGroupIndex); + int focusedColumnIndex = curFocusedCell.columnIndex; + + Column focusedColumn = focusedGroup.columnList.ElementAt(focusedColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (curFocusedCell.index == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = focusedColumn.cellList.ElementAt(curFocusedCell.index - 1); + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + int destCellIndex = curFocusedCell.index + 1; + if (destCellIndex >= focusedColumn.cellList.Count || fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusItemIndex = -1; + if (fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusColumnIndex = focusedColumnIndex - 1; + Cell cellBelow = FindCellBelow(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex); + if (cellBelow != null) + { + destFocusItemIndex = cellBelow.itemIndex; + refXForFocusMove = cellBelow.rect.X; + refYForFocusMove = cellBelow.rect.Y; + } + } + } + else + { + Cell nextCell = null; + for (; destCellIndex < focusedColumn.cellList.Count; destCellIndex++) + { + nextCell = focusedColumn.cellList.ElementAt(destCellIndex); + { + break; + } + } + + if (destCellIndex >= focusedColumn.cellList.Count) + { + destFocusItemIndex = -1; + } + else + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Left": + if (curFocusedCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + if (StateLeftCircularEnable && true/*check whether allow to loop*/) + { + destFocusGroupIndex = groupList.Count - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = curFocusedCell.columnIndex - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + break; + case "Right": + { + focusedColumnIndex = curFocusedCell.columnIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedColumnIndex: " + focusedColumnIndex); + if (focusedColumnIndex == focusedGroup.columnList.Count - 1 || focusedColumnIndex == focusedGroup.lastFilledColumnIndex) + { + if (fromGroupIndex == groupList.Count - 1) + { + if (StateRightCircularEnable && true/*check whether allow right circular*/) + { + destFocusGroupIndex = 0; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false && destFocusColumnIndex < focusedGroup.columnList.Count - 1) + { + destFocusColumnIndex++; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + + refXForFocusMove = refYForFocusMove = -1; + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = focusedColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + + if (StateRightCircularEnable) + { + if (destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + return; + } + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + if (destFocusGroupIndex >= 0 && destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + destFocusItemIndex = -1; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + if (destFocusItemIndex == -1) + { + //notify event focus move out + return; + } + + if (gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex) == false) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + } + else + { + PushFocus(destFocusGroupIndex, destFocusItemIndex); + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + + private void GetNearestItem(Cell focusedCell, int destGroupIndex, int destColumnIndex, ref int destItemIndex, bool bDirectMove = false) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + Cell nextCell = destColumn.cellList.ElementAt(0); + int cellCount = destColumn.cellList.Count; + + bool bNotAllItemDisabled = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= 0 && curCell.itemIndex < destGroup.itemList.Count) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex)) + { + bNotAllItemDisabled = true; + break; + } + } + } + + float yDis = gridHeight + 1; + bool bFound = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= destGroup.itemList.Count) + { + break; + } + + if (curCell.itemIndex >= 0 && bNotAllItemDisabled) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex) == false) + { + continue; + } + } + + if (curCell.itemIndex < 0) + { + Column realColumn = destGroup.columnList.ElementAt(curCell.columnIndex); + Cell realCell = realColumn.cellList.ElementAt(curCell.rowIndex); + if (realCell.itemIndex >= destGroup.itemList.Count || gridBridge.IsItemEnabled(destGroupIndex, realCell.itemIndex) == false) + { + continue; + } + } + + if (GridType.Vertical == gridType) + { + float tempXDis; + if (StateStraightPathEnable) + { + tempXDis = Math.Abs(curCell.rect.X - refXForFocusMove); + } + else + { + tempXDis = Math.Abs(curCell.rect.X - focusedCell.rect.X); + } + + if (tempXDis < yDis) + { + bFound = true; + yDis = tempXDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + else + { + float tempYDis; + if (StateStraightPathEnable) + { + tempYDis = Math.Abs(curCell.rect.Y - refYForFocusMove); + } + else + { + tempYDis = Math.Abs(curCell.rect.Y - focusedCell.rect.Y); + } + + if (tempYDis < yDis) + { + bFound = true; + yDis = tempYDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + + } + + { + destItemIndex = nextCell.itemIndex; + if (bFound) + { + refXForFocusMove = nextCell.rect.X; + if (bDirectMove == false) + { + refYForFocusMove = nextCell.rect.Y; + } + } + } + } + + private string GetLogicalDirection(string direction) + { + string logicalDirection = direction; + + if (GridType.Vertical == gridType) + { + if ("Left" == direction) + { + logicalDirection = "Up"; + } + else if ("Right" == direction) + { + logicalDirection = "Down"; + } + else if ("Down" == direction) + { + logicalDirection = "Right"; + } + else if ("Up" == direction) + { + logicalDirection = "Left"; + } + } + + return logicalDirection; + } + + private Cell FindCellBelow(Cell fromCell, int destGroupIndex, int destColumnIndex) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + + if (destColumnIndex < 0 || destColumnIndex >= destGroup.columnList.Count) + { + return null; + } + + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + for (int i = 0; i < destColumn.cellList.Count; i++) + { + Cell destCell = destColumn.cellList.ElementAt(i); + + if (destCell.rect.Y > fromCell.rect.Y && destCell.rect.Y + destCell.rect.Height > fromCell.rect.Y + fromCell.rect.Height) + { + { + return destCell; + } + } + } + + return null; + } + + private void SetFocus(int groupIndex, int itemIndex, bool bAnimation = false, Position newItemGroupPos = null) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex: " + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + bool bNeedScroll = false; + + if (newItemGroupPos == null) + { + Position itemGroupPos = new Position(0, 0, 0); + bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + } + else + { + if (GridType.Horizontal == gridType && itemGroupRect.X != newItemGroupPos.X + || GridType.Vertical == gridType && itemGroupRect.Y != newItemGroupPos.Y) + { + bNeedScroll = true; + } + + itemGroupRect.X = newItemGroupPos.X; + itemGroupRect.Y = newItemGroupPos.Y; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + ResetItemGroupRectPos(); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + if (bNeedScroll) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> bAnimation: " + bAnimation); + if (bAnimation == true) + { + FocusMoveViaObject obj = new FocusMoveViaObject(); + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + focusMoveAni.Play(); + } + else + { + UpdateInMemoryItems(); + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + else + { + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + + private void PushFocus(int groupIndex, int itemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex:" + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + Position itemGroupPos = new Position(0, 0, 0); + bool bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + + ResetItemGroupRectPos(); + + //focusTag keep move, but real focus will set when focusMoveVia trigger, + //so remember context of focus move, include from and to, and itemGroupPos information + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X:" + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + if (bNeedScroll) + { + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + FocusMoveViaObject obj = new FocusMoveViaObject(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusMoveViaQ.Count: " + focusMoveViaQ.Count); + Tizen.Log.Fatal("NUI", "::::: " + focusGroupIndex + ", " + focusItemIndex); + + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + focusMoveAni.Play(); + } + else + { + if (focusMoveAni.IsPlaying() == false) + { + Tizen.Log.Fatal("NUI", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ " + groupIndex + " " + itemIndex + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + //To keep focusBar on the top of + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + private bool GetItemGroupPosByFocusItem(int aFocusGroupIndex, int aFocusItemIndex, Position itemGroupPos) + { + bool bNeedScroll = false; + if (!IsItemIndexValid(aFocusGroupIndex, aFocusItemIndex)) + { + return false; + } + + Group focusedGroup = groupList.ElementAt(aFocusGroupIndex); + GridItem focusedItem = focusedGroup.itemList.ElementAt(aFocusItemIndex); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedItem.rect: " + focusedItem.rect.X + ", " + focusedItem.rect.Y + ", " + focusedItem.rect.Width + ", " + focusedItem.rect.Height); + + Rect focusBarRectBaseOnList = new Rect(focusedItem.rect.X, focusedItem.rect.Y, focusedItem.rect.Width, focusedItem.rect.Height); + focusBarRectBaseOnList.X += itemGroupRect.X; + focusBarRectBaseOnList.Y += itemGroupRect.Y; + + itemGroupPos.X = itemGroupRect.X; + itemGroupPos.Y = itemGroupRect.Y; + + float startFocusRange; + float endFocusRange; + + if (GridType.Horizontal == gridType) + { + if (0 == focusedItem.rect.X) + { + startFocusRange = margin[0]; + } + else + { + Tizen.Log.Fatal("NUI", "Left aFocusItemIndex:: " + aFocusGroupIndex + ", aFocusItemIndex:: " + aFocusItemIndex); + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "startFocusRange :: " + margin[0]); + startFocusRange = prevItem != null ? prevItem.rect.Width / 2 : margin[0]; + } + + if (itemGroupRect.Width == focusedItem.rect.Right()) + { + endFocusRange = gridWidth - margin[2]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "gridWidth::" + gridWidth + " gridWidth - margin[2] :: " + (gridWidth - margin[2])); + //Tizen.Log.Fatal("NUI", "gridWidth - nextItem.rect.Width / 2 :: " + (gridWidth - nextItem.rect.Width / 2)); + endFocusRange = nextItem != null ? gridWidth - nextItem.rect.Width / 2 : gridWidth - margin[2]; + Tizen.Log.Fatal("NUI", "endFocusRange :: " + endFocusRange); + } + + if (focusBarRectBaseOnList.X < startFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.X :: " + focusBarRectBaseOnList.X + " startFocusRange :: " + startFocusRange); + itemGroupPos.X += startFocusRange - focusBarRectBaseOnList.X; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Right() > endFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.Right() :: " + focusBarRectBaseOnList.Right() + " endFocusRange :: " + endFocusRange); + itemGroupPos.X += endFocusRange - focusBarRectBaseOnList.Right(); + bNeedScroll = true; + } + } + else + { + if (0 == focusedItem.rect.Y) + { + startFocusRange = margin[1]; + } + else + { + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + startFocusRange = prevItem != null ? prevItem.rect.Height / 2 : margin[1]; + } + + if (itemGroupRect.Height == focusedItem.rect.Bottom()) + { + endFocusRange = gridHeight - margin[3]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + endFocusRange = nextItem != null ? gridHeight - nextItem.rect.Height / 2 : gridHeight - margin[3]; + } + + if (focusBarRectBaseOnList.Y < startFocusRange) + { + itemGroupPos.Y += startFocusRange - focusBarRectBaseOnList.Y; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Bottom() > endFocusRange) + { + itemGroupPos.Y += endFocusRange - focusBarRectBaseOnList.Bottom(); + bNeedScroll = true; + } + } + + return bNeedScroll; + } + + private void NotifyFocusChange(int fromGroupIndex,int fromItemIndex,int toGroupIndex,int toItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex + " toGroupIndex: " + toGroupIndex + " toItemIndex: " + toItemIndex); + + if (IsItemIndexValid(fromGroupIndex, fromItemIndex) && (fromGroupIndex != toGroupIndex || fromItemIndex != toItemIndex)) + { + Group preGroup = groupList.ElementAt(fromGroupIndex); + GridItem preItem = preGroup.itemList.ElementAt(fromItemIndex); + + ScaleDownItem(preItem); + if (preItem.itemView != null) + { + gridBridge.FocusChange(fromGroupIndex, fromItemIndex, preItem.itemView, false); + } + } + + if (IsItemIndexValid(toGroupIndex, toItemIndex)) + { + Group curGroup = groupList.ElementAt(toGroupIndex); + GridItem item = curGroup.itemList.ElementAt(toItemIndex); + + ScaleUpItem(item); + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", "Call GridBridge.FocusChange to set focus"); + gridBridge.FocusChange(toGroupIndex, toItemIndex, item.itemView, true); + } + } + + //notify user focus change + GridEventArgs evtArgs = new GridEventArgs(); + evtArgs.EventType = GridEventType.FocusChange; + evtArgs.param[0] = fromGroupIndex; + evtArgs.param[1] = fromItemIndex; + evtArgs.param[2] = toGroupIndex; + evtArgs.param[3] = toItemIndex; + OnListEvent(evtArgs); + + if (toGroupIndex != -1 && toItemIndex != -1) + { + focusGroupIndex = toGroupIndex; + focusItemIndex = toItemIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusGroupIndex: " + focusGroupIndex + " focusItemIndex: " + focusItemIndex); + } + + private void ScaleUpItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.itemView.RaiseToTop(); + item.ScaleItem(new Vector3(focusInScaleFactor, focusInScaleFactor, 1.0f), focusInScaleAnimationAttrs); + } + + private void ScaleDownItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.ScaleItem(new Vector3(1.0f, 1.0f, 1.0f), focusOutScaleAnimationAttrs); + } + + private void UpdateItemGroupSize() + { + if (groupList.Count == 0) + { + return; + } + + Group lastGroup = groupList.ElementAt(groupList.Count - 1); + + int lastItemIndex = lastGroup.itemList.Count - 1; + if (lastItemIndex < 0) + { + return; + } + + Cell lastFilledCell = GetCellByItemIndex(groupList.Count - 1 ,lastItemIndex); + int lastFilledColumnIndex = lastFilledCell.columnIndex; + Column lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + int cellCount = lastFilledColumn.cellList.Count; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = lastFilledColumn.cellList.ElementAt(i); + if (curCell.columnIndex > lastFilledColumnIndex) + { + lastFilledColumnIndex = lastFilledColumn.cellList.ElementAt(i).columnIndex; + } + } + + lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + float width, height; + + if (GridType.Horizontal == gridType) + { + width = lastFilledColumn.endPos; + height = gridHeight - (margin[1] + margin[3]); + } + else + { + width = gridWidth - (margin[0] + margin[2]); + height = lastFilledColumn.endPos; + } + + itemGroupRect.Width = width; + itemGroupRect.Height = height; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + itemGroup.SizeWidth = itemGroupRect.Width; + itemGroup.SizeHeight = itemGroupRect.Height; + } + + private void InitItemGroupPosition() + { + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X > margin[0]) + { + itemGroupRect.X = margin[0]; + } + else if (itemGroupRect.Right() < gridWidth) + { + if (itemGroupRect.X >= gridWidth) + { + itemGroupRect.X = gridWidth - itemGroupRect.Width; + } + else + { + itemGroupRect.X = 0; + } + } + + itemGroupRect.Y = margin[1]; + } + else + { + itemGroupRect.X = margin[0]; + if (itemGroupRect.Y > margin[1]) + { + itemGroupRect.Y = margin[1]; + } + else if (itemGroupRect.Y + itemGroupRect.Height < gridHeight) + { + if (itemGroupRect.Y >= gridHeight) + { + itemGroupRect.Y = gridHeight - itemGroupRect.Height; + } + else + { + itemGroupRect.Y = 0; + } + } + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + ResetItemGroupRectPos(); + + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + } + + private void ResetItemGroupRectPos() + { + //adjust item Group pos, to add margin when item group scroll to Head or Tail + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X == 0) + { + itemGroupRect.X += margin[0]; + } + else if (itemGroupRect.Right() == gridWidth) + { + itemGroupRect.X -= margin[2]; + } + } + else + { + if (itemGroupRect.Y == 0) + { + itemGroupRect.Y += margin[1]; + } + else if (itemGroupRect.Bottom() == gridHeight) + { + itemGroupRect.Y -= margin[3]; + } + } + } + + private Cell GetCellByItemIndex(int groupIndex, int itemIndex) + { + Cell curCell = null; + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (curGroup.itemIndexToCell.ContainsKey(itemIndex)) + { + curCell = curGroup.itemIndexToCell[itemIndex]; + } + + return curCell; + } + + private bool IsGroupIndexValid(int groupIndex) + { + return (groupIndex >= 0 && groupList != null && groupIndex < groupList.Count); + } + + private bool IsItemIndexValid(int groupIndex, int itemIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (itemIndex >= 0 && curGroup.itemList != null && itemIndex < curGroup.itemList.Count); + } + + private bool IsColumnIndexValid(int groupIndex, int columnIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (columnIndex >= 0 && curGroup.columnList != null && columnIndex < curGroup.columnList.Count); + } + + private bool IsCellIndexValid(int groupIndex, int columnIndex, int cellIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return false; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + return (cellIndex >= 0 && curColumn.cellList != null && cellIndex < curColumn.cellList.Count); + } + + /// + /// Called when the control gain key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusGained(object sender, EventArgs e) + { + OnFocusGained(); + } + + public void OnFocusGained() + { + Tizen.Log.Fatal("NUI", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "); + SetFocus(focusGroupIndex, focusItemIndex); + } + + /// + /// Called when the control loses key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusLost(object sender, EventArgs e) + { + OnFocusLost(); + } + + public void OnFocusLost() + { + Tizen.Log.Fatal("NUI", "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, -1, -1); + } + + private void OnFocusMoveViaEvent(object o, EventArgs e) + { + Tizen.Log.Fatal("NUI", "--------------------- " + focusMoveViaQ.Count + " -------------------------------"); + if (focusMoveViaQ.Count > 0) + { + { + FocusMoveViaObject obj = focusMoveViaQ.Dequeue(); + { + UpdateInMemoryItems(itemGroup.Position); + } + + { + //common focus notify focus change at destination of every via + NotifyFocusChange(focusGroupIndex, focusItemIndex, obj.toGroupIndex, obj.toItemIndex); + } + } + + //viaMap1.Remove(args.ViaNode); + } + } + + private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + { + switch (e.ChangeType) + { + case GridBridge.DataChangeEventType.Add: + AddItem(e.param[0]); + break; + case GridBridge.DataChangeEventType.Remove: + DeleteItem(e.param[0], e.param[1], e.param[2]); + break; + case GridBridge.DataChangeEventType.Insert: + InsertItem(e.param[0], e.param[1]); + break; + case GridBridge.DataChangeEventType.Clear: + Clear(); + break; + case GridBridge.DataChangeEventType.Reset: + ResetByData(); + break; + case GridBridge.DataChangeEventType.Load: + Load(); + Group curGroup = groupList.ElementAt(e.param[0]); + for (int i = e.param[1]; i < gridBridge.GetItemCount(e.param[0]); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(e.param[0], i, curGroup.itemList.ElementAt(i).itemView); + } + } + + if (focusItemIndex >= e.param[1] && focusItemIndex <= e.param[1] + e.param[2] - 1) + { + if (e.param[1] > 0) + { + SetFoucsItemIndex(e.param[1] - 1, focusGroupIndex); + } + else if (e.param[1] + e.param[2] < curGroup.itemList.Count) + { + SetFoucsItemIndex(e.param[1] + e.param[2], focusGroupIndex); + } + } + else if (focusItemIndex >= e.param[1] + e.param[2]) + { + SetFoucsItemIndex(focusItemIndex - e.param[2], focusGroupIndex); + } + + break; + default: + + break; + } + + refXForFocusMove = refYForFocusMove = -1; + } + + private void AddItem(int groupIndex) + { + int dataCount = gridBridge.GetItemCount(groupIndex); + if (dataCount > groupList.ElementAt(groupIndex).realCellCount) + { + AddColumn(colW, groupIndex); + int columnIndex = groupList.ElementAt(groupIndex).columnList.Count - 1; + for (int i = 0; i < rowCnt; i++) + { + AddRowToColumn(columnIndex, rowH, groupIndex); + } + } + + Load(); + } + + private void AddAll(int groupIndex, int count) + { + Load(); + } + + + private void DeleteItem(int groupIndex, int fromItemIndex, int deleteItemNum) + { + Group curGroup = groupList.ElementAt(groupIndex); + + GridItem item = null; + + int toItemIndex = fromItemIndex + deleteItemNum - 1; + + int count = 0; + + for (int i = fromItemIndex; i < curGroup.itemList.Count; i++) + { + item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, true); + count++; + } + } + + for (int i = 0; i < count; i++) + { + curGroup.itemList.Remove(curGroup.itemList.ElementAt(curGroup.itemList.Count - 1)); + } + } + + private void InsertItem(int groupIndex, int itemIndex) + { + Load(); + + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = itemIndex; i < gridBridge.GetItemCount(groupIndex); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(groupIndex, i, curGroup.itemList.ElementAt(i).itemView); + } + } + } + + private void Clear() + { + for (int i = 0; i < groupList.Count; i++) + { + Clear(i); + } + + ClearRecycleBin(); + } + + private void Clear(int groupIndex) + { + Tizen.Log.Fatal("NUI", "--------------------- " + groupIndex + " -------------------------------"); + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = 0; i < curGroup.itemList.Count; i++) + { + GridItem item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, false); + } + } + + curGroup.itemList.Clear(); + } + + private void ResetByData() + { + Tizen.Log.Fatal("NUI", "...."); + int groupCount = gridBridge.GetGroupCount(); + ResetGroup(groupCount); + for (int i = 0; i < groupCount; i++) + { + Tizen.Log.Fatal("NUI", ".... group: " + i); + int dataCount = gridBridge.GetItemCount(i); + Tizen.Log.Fatal("NUI", ".... dataCount: " + dataCount + " rowCnt: " + rowCnt); + int columnCount = (dataCount + rowCnt - 1) / rowCnt; + Group group = groupList.ElementAt(i); + Tizen.Log.Fatal("NUI", ".... columnCount: " + columnCount + " group.columnList.Count: " + group.columnList.Count + " group.itemIndexToCell.Count: " + group.itemIndexToCell.Count); + if (columnCount > group.columnList.Count) + { + for (int c = group.columnList.Count; c < columnCount; c++) + { + AddColumn(colW, i); + for (int r = 0; r < rowCnt; r++) + { + AddRowToColumn(c, rowH, i); + } + } + } + else if (columnCount < group.columnList.Count) + { + float posOffset = -(group.columnList.Count - columnCount) * (colW + columnSpace) + ColumnSpace; + + for (int c = columnCount; c < group.columnList.Count; c++) + { + for (int r = 0; r < rowCnt; r++) + { + int itemIndex = c * rowCnt + r; + group.itemIndexToCell.Remove(itemIndex); + group.realCellCount--; + Tizen.Log.Fatal("NUI", ".... itemIndexToCell.Remove: " + itemIndex); + } + } + + group.columnList.RemoveRange(columnCount, group.columnList.Count - columnCount); + group.endPos = group.columnList.ElementAt(columnCount - 1).endPos; + for (int j = i + 1; j < groupList.Count; j++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(j).title != null) + { + groupList.ElementAt(j).title.PositionX += posOffset; + } + + groupList.ElementAt(j).ResetPosition(posOffset); + } + + } + + Tizen.Log.Fatal("NUI", ".... group.columnList.Count: " + group.columnList.Count); + } + + focusGroupIndex = 0; + focusItemIndex = 0; + Tizen.Log.Fatal("NUI", "...."); + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(0, 0); + } + } + + /*page length set to grid length*/ + private void PageMove(bool bPrev, bool bAni) + { + Rect visibleAreaOfItemGroup = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + if (GridType.Horizontal == gridType) + { + if (bPrev) + { + visibleAreaOfItemGroup.X -= gridWidth; + if (0 > visibleAreaOfItemGroup.X) + { + visibleAreaOfItemGroup.X = 0; + } + } + else + { + visibleAreaOfItemGroup.X += gridWidth; + if (-visibleAreaOfItemGroup.X + itemGroupRect.Width < gridWidth) + { + visibleAreaOfItemGroup.X = itemGroupRect.Width - gridWidth; + } + } + + if (-itemGroupRect.X == visibleAreaOfItemGroup.X) + { + return; + } + } + else + { + if (bPrev) + { + visibleAreaOfItemGroup.Y -= gridHeight; + if (0 > visibleAreaOfItemGroup.Y) + { + visibleAreaOfItemGroup.Y = 0; + } + } + else + { + visibleAreaOfItemGroup.Y += gridHeight; + if (-visibleAreaOfItemGroup.Y + itemGroupRect.Height < gridHeight) + { + visibleAreaOfItemGroup.Y = itemGroupRect.Height - gridHeight; + } + } + + if (-itemGroupRect.Y == visibleAreaOfItemGroup.Y) + { + return; + } + } + + Range newRange = new Range(0, 0, 0, 0); + GetOnscreenRange(visibleAreaOfItemGroup, ref newRange, true); + + Group curFocusedGroup = groupList.ElementAt(focusGroupIndex); + Cell curFocusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + Column curFocusedColumn = curFocusedGroup.columnList.ElementAt(curFocusedCell.columnIndex); + + float focusStartLine = curFocusedColumn.startPos; + float focusEndLine = curFocusedColumn.endPos; + float focusMiddleLine = 0; + + if (newRange.startGroupInScrn >= 0 && newRange.endGroupInScrn >= 0) + { + if (GridType.Horizontal == gridType) + { + focusStartLine = focusStartLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + focusEndLine = focusEndLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + } + else + { + focusStartLine = focusStartLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + focusEndLine = focusEndLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + } + + focusMiddleLine = focusStartLine + (focusEndLine - focusStartLine) / 2; + + int nextFocusGroup = -1; int nextFocusColumn = -1; + bool bFound = false; + for (int i = newRange.startGroupInScrn; i <= newRange.endGroupInScrn && bFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + + int startColumnIndex = (i == newRange.startGroupInScrn) ? newRange.startColumnInScrn : 0; + int endColumnIndex = (i == newRange.endGroupInScrn) ? newRange.endColumnInScrn : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= focusMiddleLine && curColumn.endPos >= focusMiddleLine) + { + nextFocusGroup = i; + nextFocusColumn = j; + bFound = true; + break; + } + } + + if (bFound == false && i == newRange.startGroupInScrn && focusMiddleLine < curGroup.columnList.ElementAt(startColumnIndex).startPos) + { + nextFocusGroup = i; + nextFocusColumn = startColumnIndex; + break; + } + + else if (bFound == false && i == newRange.endGroupInScrn && focusMiddleLine > curGroup.columnList.ElementAt(endColumnIndex).endPos) + { + nextFocusGroup = i; + nextFocusColumn = endColumnIndex; + break; + } + } + + if (nextFocusGroup >= 0 && nextFocusColumn >= 0) + { + int nextFocusItem = -1; + GetNearestItem(curFocusedCell, nextFocusGroup, nextFocusColumn, ref nextFocusItem); + + if (nextFocusItem >= 0) + { + while (gridBridge.IsItemEnabled(nextFocusGroup, nextFocusItem) == false) + { + nextFocusItem = GetNextColumnIndex(bPrev, nextFocusColumn, ref nextFocusGroup); + } + + if (nextFocusItem >= 0) + { + Position newItemGroupPos = new Position(-visibleAreaOfItemGroup.X, -visibleAreaOfItemGroup.Y, 0); + SetFocus(nextFocusGroup, nextFocusItem, bAni, newItemGroupPos); + } + } + } + } + } + + private int GetNextColumnIndex(bool bPrev, int curColumnIndex, ref int curGroupIndex) + { + if (bPrev == true) + { + if (curColumnIndex == 0) + { + if (curGroupIndex == 0) + { + return -1; + } + else + { + curGroupIndex--; + return groupList.ElementAt(curGroupIndex).columnList.Count - 1; + } + } + else + { + return curColumnIndex - 1; + } + } + else + { + Group curGroup = groupList.ElementAt(curGroupIndex); + if (curGroup.columnList.Count - 1 == curColumnIndex) + { + if (groupList.Count - 1 == curGroupIndex) + { + return -1; + } + else + { + curGroupIndex++; + return 0; + } + } + else + { + return curColumnIndex + 1; + } + } + } + + private class GridItem + { + public void ScaleItem(Vector3 scaleFactor, AnimationAttributes aniAttrs) + { + if (itemView == null || scaleFactor == null || aniAttrs == null) + { + return; + } + + if (scaleAni == null) + { + scaleAni = new Animation(); + } + + if (scaleAni.State == Animation.States.Playing) + { + scaleAni.Stop(Animation.EndActions.StopFinal); + } + + scaleAni.Clear(); + scaleAni.AnimateTo(itemView, "Scale", scaleFactor, 0, aniAttrs.Duration, new AlphaFunction(aniAttrs.BezierPoint1, aniAttrs.BezierPoint2)); + scaleAni.Play(); + } + + public int groupIndex; + public int index; + + public View itemView; + public Rect rect; + + private Animation scaleAni = null; + } + + private class Cell + { + public int columnIndex; + public int index; + public int itemIndex; + public int rowIndex; + + public Rect rect; + public Cell() + { + rect = new Rect(0, 0, 0, 0); + } + } + + private class Column + { + public int groupIndex; + public int index; + + public float space; + public float startPos; + public float endPos; + + public int startItemIndex; + public int endItemIndex; + + public List cellList; + } + + private class Group + { + public int index; + + public float startPos; + public float endPos; + + public int realCellCount; + public int lastFilledColumnIndex; + + public List columnList; + public List itemList; + public Dictionary itemIndexToCell; + + public void ResetPosition(float posOffset) + { + startPos += posOffset; + endPos += posOffset; + + int count = columnList.Count; + for (int i = 0; i < count; i++) + { + Column column = columnList.ElementAt(i); + column.startPos += posOffset; + column.endPos += posOffset; + + int cellCount = column.cellList.Count; + for (int j = 0; j < cellCount; j++) + { + column.cellList.ElementAt(j).rect.X += posOffset; + } + } + } + + public View title; + } + + private class Range + { + public int startGroupIndex; + public int startColumnIndex; + + public int endGroupIndex; + public int endColumnIndex; + + public int startGroupInScrn; + public int startColumnInScrn; + + public int endGroupInScrn; + public int endColumnInScrn; + + public int startItemIndexInScrn; + public int endItemIndexInScrn; + + public Range() + { + startGroupIndex = 0; + startColumnIndex = 0; + endGroupIndex = 0; + endColumnIndex = 0; + } + + public Range(int a, int b, int c, int d) + { + startGroupIndex = a; + startColumnIndex = b; + endGroupIndex = c; + endColumnIndex = d; + } + } + + private class FocusMoveViaObject + { + public int toGroupIndex; + public int toItemIndex; + } + + const int INVALID_COUNT = -1; + + private List groupList; + private GridBridge gridBridge; + + private View itemGroup; + private Rect itemGroupRect; + + private Vector4 margin = Vector4.Zero; + + private float gridWidth; + private float gridHeight; + + private int preloadFrontColumnSize = 1; + private int preloadBackColumnSize = 1; + + //layout attributes + private GridType gridType = GridType.Horizontal; + private int groupSpace = 0; + private int columnSpace = 0; + private int rowSpace = 0; + private int titleSpace = 0; + + private int rowCnt = 0; + private int colCnt = 0; + private int colW = 0; + private int rowH = 0; + + //focus + private int focusGroupIndex; + private int focusItemIndex; + + private float refXForFocusMove; + private float refYForFocusMove; + + private int focusTagGroupIndex; + private int focusTagItemIndex; + //animation + LinkerAnimation focusMoveAni; + + private float focusInScaleFactor; + + private AnimationAttributes focusInScaleAnimationAttrs; + + private AnimationAttributes focusOutScaleAnimationAttrs; + + private int focusMoveAniDuration; + + private Queue focusMoveViaQ = new Queue(); + + //for load + private HashSet curInMemoryItemSet; + private HashSet nextInMemoryItemSet; + + private Rect lastVisibleArea; + + private Range onScreenRange; + + //reuse + private List[] recycledViews; + private int viewTypeCount; + + private EventHandler gridEventHandlers; + } + + /// + /// The attributes of Animation. + /// + /// + /// AnimationAttributes attrs = new AnimationAttributes(); + /// attrs.BezierPoint1 = new Vector2(0.21f, 2); + /// attrs.BezierPoint2 = new Vector2(0.14f, 1); + /// attrs.Duration = 1000; + /// + public class AnimationAttributes + { + /// V1 on bezier curve + public Vector2 BezierPoint1; + /// V2 on bezier curve + public Vector2 BezierPoint2; + /// Animation duration + public int Duration; + + /// + /// Constructs a AnimationAttributes.. + /// + public AnimationAttributes() + { + } + + /// + /// Constructs a AnimationAttributes with curve style.. + /// + /// curve + public AnimationAttributes(string curve) + { + } + + /// + /// Constructs a AnimationAttributes that is a copy of attrs.. + /// + /// Construct Attributes + public AnimationAttributes(AnimationAttributes attrs = null) + { + if (attrs == null) + { + return; + } + + if (attrs.BezierPoint1 != null) + { + BezierPoint1 = new Vector2(attrs.BezierPoint1[0], attrs.BezierPoint1[1]); + } + + if (attrs.BezierPoint2 != null) + { + BezierPoint2 = new Vector2(attrs.BezierPoint2[0], attrs.BezierPoint2[1]); + } + + Duration = attrs.Duration; + } + + /// Clone a AnimationAttributes + /// The AnimationAttributes copy + public AnimationAttributes Clone() + { + return new AnimationAttributes(this); + } + } + + /// + /// A GridBridge object acts as a pipeline between an BridgeView and the + /// underlying data for that view. The Bridge provides access to the data items. + /// The Bridge is also responsible for making a View for each item in the data set. + /// + public abstract class GridBridge + { + /// + /// Event type of data change. + /// + public enum DataChangeEventType + { + Add, + Remove, + Insert, + Clear, + Load, + Reset + } + + /// + /// Data change event args at event call back, + /// user can get information about data change. + /// + /// + ///private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + ///{ + ///} + /// + public class DataChangeEventArgs : EventArgs + { + /// + /// Data changed event type. + /// + public DataChangeEventType ChangeType + { + get { return m_ChangeType; } + set { m_ChangeType = value; } + } + + /// + /// Changed data. + /// + public object data; + /// + /// Data change event parameters. + /// + public int[] param = new int[4]; + + private DataChangeEventType m_ChangeType; + } + + /// + /// Event handler of data change event. + /// + /// The object who sends the event. + /// The event arguments. + public delegate void EventHandler(object sender, DataChangeEventArgs e); + + /// + /// Data change event handler, user can add/remove. + /// + public event EventHandler DataChangeEvent + { + add + { + dataChangeEventHandlers += value; + } + + remove + { + dataChangeEventHandlers -= value; + } + } + + /// + /// Constructor to create a grid view bridge with multi-groups. + /// + /// Data list of differet groups. + public GridBridge(List> objects) + { + gridData = objects; + } + + /// + /// Simple constructor to create a grid view bridge with one group. + /// + /// Data list of grid view. + public GridBridge(List objects) + { + gridData = new List>(); + gridData.Add(objects); + } + + /// + /// Create item View. + /// + /// Group index of item in grid view. + /// Item index of specified group of grid view. + /// View of specified item. + public abstract View GetItemView(int groupIndex, int itemIndex); + + /// + /// Create group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual View GetGroupTitleView(int groupIndex) + { + return null; + } + + /// + /// Remove group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual void RemoveGroupTitleView(int groupIndex, View groupTitle) + { + + } + + /// + /// Update View that displays the data at the specified index in the data set when data change. + /// + /// The group index. + /// The item index. + /// A View that displays the data at the specified index in the data set. + public abstract void UpdateItem(int groupIndex, int itemIndex, View view); + + /// + /// Update View that displays the data at the specified index in the data set when focus change. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + /// Focus in or focus out + /// LinearView item selected or not. + public abstract void FocusChange(int groupIndex, int itemIndex, View view, bool FlagFocused, bool bSelected = false); + + /// + /// Unload view at the specified index when item scroll out or deleted. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + public abstract void UnloadItem(int groupIndex, int itemIndex, View view); + + /// + /// Unload view according to the specified viewType. + /// + /// Item type set by users. + /// A View that displays the data at the specified index in the data set. + public abstract void UnloadItemByViewType(int viewType, View view); + + /// + /// Get the type of View that will be created by GetView for the specified item. + /// + /// The group index. + /// The item index. + /// Integers must be in the range 0 to GetItemTypeCount() - 1. + /// Item type. + public virtual int GetItemType(int groupIndex, int itemIndex) + { + return 0; + } + + /// + /// Get the number of view types. + /// + /// The count of view type. + public virtual int GetItemTypeCount() + { + return 1; + } + + /// + /// Check whether item is enable or not. + /// + /// The group index. + /// The item index. + /// Item is enabled or disabled. + public virtual bool IsItemEnabled(int groupIndex, int itemIndex) + { + return true; + } + + /// + /// Get the data at the specified index. + /// + /// The item index. + /// The group index. + /// The data at the specified index. + public object GetData(int itemIndex, int groupIndex = 0) + { + object data = null; + if (gridData != null && gridData.ElementAt(groupIndex) != null && itemIndex >= 0 && itemIndex < gridData.ElementAt(groupIndex).Count) + { + data = gridData.ElementAt(groupIndex).ElementAt(itemIndex); + } + + return data; + } + + /// + /// Get data group count of the bridge. + /// + /// Group count of the data set. + public int GetGroupCount() + { + int count = 0; + if (gridData != null) + { + count = gridData.Count; + } + + return count; + } + + /// + /// How many items are in the data set of specified group. + /// + /// The data group index. + /// Count of items of specified group. + public int GetItemCount(int groupIndex = 0) + { + int count = 0; + if (gridData != null && gridData.ElementAtOrDefault(groupIndex) != null) + { + count = gridData.ElementAt(groupIndex).Count; + } + + return count; + } + + /// + /// How many items are in the data set of whole data list. + /// + /// Count of total items + public int GetTotalCount() + { + int count = 0; + if (gridData != null) + { + foreach (List group in gridData) + { + count += group.Count; + } + } + + return count; + } + + /// + /// Adds the specified data at the end of the List of specified group. + /// + /// The data to add at the end of the List. + /// The group index which need to add data. + /// Notify list to remove item or not. + public void Add(object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Add(data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Add; + e.param[0] = groupIndex; + e.data = data; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The remove number of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + + public void RemoveItems(int fromIndex, int removeNum, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + if (fromIndex + removeNum > gridData[groupIndex].Count) + { + return; + } + + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Remove; + e.param[0] = groupIndex; + e.param[1] = fromIndex; + e.param[2] = removeNum; + e.param[3] = withAni ? 1 : 0; + OnDataChangeEvent(this, e, sendEvent); + gridData[groupIndex].RemoveRange(fromIndex, removeNum); + e.ChangeType = DataChangeEventType.Load; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + public void Remove(int itemIndex, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + if (itemIndex < 0 || itemIndex >= GetItemCount(groupIndex)) + { + Tizen.Log.Fatal("NUI", "Error!! item index is invalid"); + return; + } + + RemoveItems(itemIndex, 1, groupIndex, withAni, sendEvent); + } + + /// + /// Inserts the specified data at the specified index in the List of specified group. + /// + /// The index at which the data must be inserted. + /// The data to insert into the list. + /// The group index which need to insert data. + /// Notify list to remove item or not. + public void Insert(int index, object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Insert(index, data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Insert; + e.data = data; + e.param[0] = groupIndex; + e.param[1] = index; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Remove all elements from the list. + /// + /// Notify list to remove item or not. + public void Clear(bool sendEvent = true) + { + if (gridData != null) + { + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Clear; + OnDataChangeEvent(this, e, sendEvent); + gridData.Clear(); + } + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of differet groups. + /// Notify list to remove item or not. + public void Reset(List> objects, bool sendEvent = true) + { + Clear(); + gridData = objects; + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of grid view. + /// Notify list to remove item or not. + public void Reset(List objects, bool sendEvent = true) + { + Clear(); + gridData = new List>(); + gridData.Add(objects); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Swap data of specified group. + /// + /// The group index which need to insert data. + /// First item index of the group. + /// Second item index of the group. + public void SwapGroupData(int groupIndex, int from, int to) + { + List groupDataList = gridData.ElementAt(groupIndex); + object fromData = groupDataList.ElementAt(from); + groupDataList[from] = groupDataList[to]; + groupDataList[to] = fromData; + } + + private void OnDataChangeEvent(object sender, DataChangeEventArgs e, bool sendEvent = true) + { + if (!sendEvent) + { + return; + } + + if (dataChangeEventHandlers != null) + { + dataChangeEventHandlers(sender, e); + } + } + + private List> gridData; + private EventHandler dataChangeEventHandlers; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `curFocusedCell` last assigned on line 1735 could be null and is dereferenced at line 1744, column 17. + +### Severity: +ERROR + +### Procedure: +Void GridView.MoveFocus(String,Int32,Int32) + +### File: +TV/MediaHubSample/MediaHubSample/src/View/GridView/Grid.cs + +### Key: +Grid.cs|MoveFocus|NULL_DEREFERENCE + +### Node Key: +cff514ccb90de40f899d1a804c0d1f8c + +### Hash: +cb75677025efdadd47289f6deab9aca5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0767/instruction.md b/inferredbugs-0767/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cc03e971c7c149db320528e1b3036d751caec20c --- /dev/null +++ b/inferredbugs-0767/instruction.md @@ -0,0 +1,3833 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Tizen-CSharp-Samples +**Bug ID:** 4 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/** Copyright (c) 2017 Samsung Electronics Co., Ltd. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using Tizen.NUI; +using Tizen.NUI.BaseComponents; + +namespace Tizen.NUI +{ + /// + /// A view that shows items in two-dimension grid, which can scroll horizontally or vertically. + /// The items in the grid come from the GirdBridge associated with this view. + /// + public class GridView : View + { + /// + /// GridView event types + /// + public enum GridEventType + { + /// + /// Event triggered when focus change + /// + FocusChange, + /// + /// Event triggered when item scroll in + /// + ItemScrolledIn, + /// + /// Event triggered when item scroll out + /// + ItemScrolledOut, + } + + /// + /// GridView orientation types + /// + public enum GridType + { + /// + /// Items laid horizontal + /// + Horizontal = 0, + /// + /// Items laid vertical + /// + Vertical + } + + /// + /// GridView event args at event call back, user can get information + /// + public class GridEventArgs : EventArgs + { + /// + /// GridView event type + /// + public GridEventType EventType + { + get; + set; + } + + /// + /// GridView event data + /// + public int[] param = new int[4]; + } + + /// + /// Construct GridView. + /// + public GridView() + { + Initialize(); + + // register event handler for relayout + Relayout += OnRelayoutUpdate; + + FocusGained += ControlFocusGained; + FocusLost += ControlFocusLost; + } + + /// + /// Get/Set list type. + /// + public GridType Type + { + get { return gridType; } + set { gridType = value; } + } + + /// + /// Get/Set list spaces around items. + /// + public new Vector4 Margin + { + get { return margin; } + set { margin = value; } + } + + /// + /// Get/Set space between columns + /// + public int ColumnSpace + { + get { return columnSpace; } + set { columnSpace = value; } + } + + /// + /// Get/Set space between rows + /// + public int RowSpace + { + get { return rowSpace; } + set { rowSpace = value; } + } + + /// + /// Get/Set space between groups + /// + public int GroupSpace + { + get { return groupSpace; } + set { groupSpace = value; } + } + + /// + /// Get/Set space for title + /// + public int TitleSpace + { + get { return titleSpace; } + set { titleSpace = value; } + } + + /// + /// Get/Set enable flag of whether support straight path focus move. + /// + public bool StateStraightPathEnable + { + get; + set; + } + /// + /// Get/Set enable flag of right circulation of GridView. + /// + public bool StateRightCircularEnable + { + get; + set; + } + + /// + /// Get/Set enable flag of left circulation of GridView. + /// + public bool StateLeftCircularEnable + { + get; + set; + } + + /// + /// Get/Set focus move animation duration of GridView. + /// + public int FocusMoveDuration + { + get + { + return focusMoveAniDuration; + } + + set + { + focusMoveAniDuration = value; + //focusMoveAni.Duration = value; + //scaleAni.Duration = value; + } + } + + /// + /// Get/Set scroll bar fade out time + /// + public int ScrollBarFadeOutDuration + { + get; + set; + } + + + /// + /// Preload item buffer size at front + /// + public int PreloadFrontColumnSize + { + get { return preloadFrontColumnSize; } + set { preloadFrontColumnSize = value ; } + } + + /// + /// Preload item buffer size at back + /// + public int PreloadBackColumnSize + { + get { return preloadBackColumnSize; } + set { preloadBackColumnSize = value; } + } + + /// + /// Focus in scale factor + /// + public float FocusInScaleFactor + { + get { return focusInScaleFactor; } + set { focusInScaleFactor = value; } + } + + /// + /// Focus in scale animation duration + /// + public AnimationAttributes FocusInScaleAnimationAttrs + { + get { return focusInScaleAnimationAttrs; } + set { focusInScaleAnimationAttrs = value; } + } + + /// + /// Focus out scale animation duration + /// + public AnimationAttributes FocusOutScaleAnimationAttrs + { + get { return focusOutScaleAnimationAttrs; } + set { focusOutScaleAnimationAttrs = value; } + } + /// + /// Sets the data behind this GridView. + /// + /// The GridBridge which is responsible for maintaining the data + /// backing this grid and for producing a view to represent an item in the data set. + public void SetBridge(GridBridge bridge) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set bridge for GridView")); + Debug.Assert(bridge != null); + + if (gridBridge != null) + { + return; + } + + gridBridge = bridge; + + gridBridge.DataChangeEvent += OnDataChange; + + for (int i = 0; i < groupList.Count; i++) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + groupList[i].title = groupTitle; + + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = groupList[i].startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = groupList[i].startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + SetViewTypeCount(gridBridge.GetItemTypeCount()); + + + if (groupList.Count > 0) + { + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + /// + /// Add groups to GridView. + /// + /// The count of groups to add. + public void AddGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add Group Number{0}", groupCount)); + int prevCount = groupList.Count; + for (int i = prevCount; i < groupCount + prevCount; i++) + { + Group newGroup = new Group(); + newGroup.index = i; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + + if (GridType.Horizontal == gridType) + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos); + } + else + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos + titleSpace); + } + + if (gridBridge != null) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + newGroup.title = groupTitle; + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = newGroup.startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = newGroup.startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + groupList.Add(newGroup); + } + } + + internal void ResetGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", "...." + groupCount); + if (groupList.Count < groupCount) + { + AddGroup(groupCount - groupList.Count); + } + else if (groupList.Count > groupCount) + { + int removeCount = groupList.Count - groupCount; + for (int i = groupCount; i < groupList.Count; i++) + { + if (groupList.ElementAt(i).title != null) + { + itemGroup.Remove(groupList.ElementAt(i).title); + gridBridge.RemoveGroupTitleView(i, groupList.ElementAt(i).title); + } + + Clear(i); + } + + groupList.RemoveRange(groupCount, removeCount); + } + } + + // Add column to GridView. + internal void AddColumn(int columnWidth, int groupIndex = 0) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add column columnWidth {0} to group {1}",columnWidth, groupIndex)); + + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + Column newColumn = new Column(); + newColumn.groupIndex = groupIndex; + newColumn.index = curGroup.columnList.Count; + newColumn.space = columnWidth; + + if (newColumn.index == 0) + { + newColumn.startPos = curGroup.startPos; + } + else + { + newColumn.startPos = curGroup.columnList.ElementAt(newColumn.index - 1).endPos + columnSpace; + } + + newColumn.endPos = newColumn.startPos + columnWidth; + + if (newColumn.cellList == null) + { + newColumn.cellList = new List(); + } + + curGroup.columnList.Add(newColumn); + + float posOffset = (0 == newColumn.index) ? columnWidth : columnWidth + columnSpace; + curGroup.endPos += posOffset; + + for (int i = groupIndex + 1; i < (int)groupList.Count; i++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(i).title != null) + { + groupList.ElementAt(i).title.PositionX += posOffset; + } + + groupList.ElementAt(i).ResetPosition(posOffset); + } + + Tizen.Log.Fatal("NUI", "..."); + return; + } + /// + /// Add row to the column in GridView. + /// + /// The column index; + /// The row space. + /// The group index. + public void AddRowToColumn(int columnIndex, int rowHeight, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to column {1} of group {2}", rowHeight, columnIndex, groupIndex)); + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + Column curColumn = curGroup.columnList.ElementAt(columnIndex); + + int curRowNumInCol = curColumn.cellList.Count; + + Cell newCell = new Cell(); + + Cell lastCell = (curRowNumInCol == 0 ? null : curColumn.cellList.ElementAt(curRowNumInCol - 1)); + + if (GridType.Horizontal == gridType) + { + newCell.rect.X = curColumn.startPos; + newCell.rect.Y = (curRowNumInCol == 0 ? 0 : lastCell.rect.Bottom() + rowSpace); + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + else + { + newCell.rect.X = (curRowNumInCol == 0) ? 0 : lastCell.rect.Right() + columnSpace; + newCell.rect.Y = curColumn.startPos; + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + + newCell.columnIndex = columnIndex; + newCell.rowIndex = curRowNumInCol; + newCell.index = curRowNumInCol; + if (curRowNumInCol == 0) + { + if (columnIndex == 0) + { + newCell.itemIndex = 0; + } + else + { + newCell.itemIndex = curGroup.columnList.ElementAt(columnIndex - 1).endItemIndex + 1; + } + } + else + { + newCell.itemIndex = lastCell.itemIndex + 1; + } + + Tizen.Log.Fatal("NUI", " >>>>>>> newCell.itemIndex: " + newCell.itemIndex + " newCell.rect[" + newCell.rect.X + ", " + newCell.rect.Y + ", " + newCell.rect.Width + ", " + newCell.rect.Height + "]"); + + curColumn.cellList.Add(newCell); + Tizen.Log.Fatal("NUI", "..."); + + if (curRowNumInCol == 0) + { + curColumn.startItemIndex = newCell.itemIndex; + } + + curColumn.endItemIndex = newCell.itemIndex; + Tizen.Log.Fatal("NUI", " >>>>>>> curColumn.startItemIndex: " + curColumn.startItemIndex + " curColumn.endItemIndex: " + curColumn.endItemIndex); + + curGroup.itemIndexToCell.Add(newCell.itemIndex, newCell); + curGroup.realCellCount++; + + Tizen.Log.Fatal("NUI", "Group: " + groupIndex + ", Column: " + columnIndex + " Cell.rowIndex: " + newCell.rowIndex + " Cell.columnIndex: " + newCell.columnIndex + " Cell.itemIndex: " + newCell.itemIndex + " curGroup.realCellCount:" + curGroup.realCellCount); + } + + // Add row to the all column in same group of GridView. + internal void AddRowToAllColumn(int rowHeight, int groupIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to to all column of group {1}", rowHeight, groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + int columnCount = groupList.ElementAt(groupIndex).columnList.Count; + for (int i = 0; i < columnCount; i++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + /// + /// Quickly add an regular grid by pass column/row number and cell size. + /// + /// The columns count. + /// The rows count. + /// The column width. + /// The row height. + /// The groupIndex, default value is -1, means all the groups will use the same regular grid. + public void AddRegularGrid(int columnCount, int rowCount, int columnWidth, int rowHeight, int groupIndex = -1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row x column : ({0} x {1}) rowHeight: {2} , columnWidth: {3} to group {4}", rowCount, columnCount, rowHeight, columnWidth, groupIndex)); + + if (groupIndex != -1) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + else if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + } + + if (gridType == GridType.Vertical) + { + int temp = rowCount; + rowCount = columnCount; + columnCount = temp; + } + + this.rowCnt = rowCount; + this.colCnt = columnCount; + this.rowH = rowHeight; + this.colW = columnWidth; + + if (columnCount == -1) + { + return; + } + + if (groupIndex == -1) + { + for (int k = 0; k < groupList.Count; k++) + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + else + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + + /// + /// Attach title to the group. + /// + /// The title view. + /// The group index. + public void AttachGroupTitle(View titleView, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Attach group title to {0}", groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (GridType.Horizontal == gridType) + { + titleView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + titleView.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + titleView.PositionUsesPivotPoint = true; + titleView.PositionX = curGroup.startPos; + titleView.PositionY = -titleSpace; + } + else + { + titleView.PositionX = 0; + titleView.PositionY = curGroup.startPos - titleSpace; + } + + curGroup.title = titleView; + itemGroup.Add(titleView); + } + + /// + /// Get group title of specified group index. + /// + /// Group index of GridIndex view. + /// Title view of specified group index. + public View GetGroupTitle(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + return groupList[groupIndex].title; + } + + /// + /// Set focus group index and item index of GridView. + /// + /// focus item index + /// focus group index + public void SetFoucsItemIndex(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set Focus to item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid item index")); + return; + } + + if (groupIndex == focusGroupIndex && itemIndex == focusItemIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Already focused")); + return; + } + //if (IsFocused == true) + //{ + // SetFocus(groupIndex, itemIndex); + //} + if (HasFocus() == true) + { + SetFocus(groupIndex, itemIndex); + } + else + { + focusGroupIndex = groupIndex; + focusItemIndex = itemIndex; + focusTagGroupIndex = focusGroupIndex; + focusTagItemIndex = focusItemIndex; + } + } + + /// + /// Get focus group index and item index of GridView. + /// + /// focus group index + /// focus item index + public void GetFocusItemIndex(out int groupIndex, out int itemIndex) + { + groupIndex = focusGroupIndex; + itemIndex = focusItemIndex; + } + + /// + /// Get loaded item view in GridView. + /// + /// Specified group index + /// Specified item index + /// Return the ItemView, if the item is unloaded, returns null. + public object GetLoadedItemView(int groupIndex, int itemIndex) + { + GridItem item = null; + if (IsGroupIndexValid(groupIndex) == true && IsItemIndexValid(groupIndex, itemIndex)) + { + item = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + } + + return item?.itemView; + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MoveNextPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to next page")); + PageMove(false, bAni); + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MovePrevPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to previous page")); + PageMove(true, bAni); + } + + /// + /// Update an item. + /// + /// The itemIndex. + /// The groupIndex. + public void UpdateItem(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Update item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Cell curCell = GetCellByItemIndex(groupIndex, itemIndex); + int columnIndex = curCell.columnIndex; + + if ((groupIndex > onScreenRange.startGroupIndex && groupIndex < onScreenRange.endGroupIndex) + || (groupIndex == onScreenRange.startGroupIndex && columnIndex >= onScreenRange.startColumnIndex) + || (groupIndex == onScreenRange.endGroupIndex && columnIndex <= onScreenRange.endColumnIndex)) + { + gridBridge.UpdateItem(groupIndex, itemIndex, groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex).itemView); + } + } + /// + /// Update all items on screen. + /// + public void UpdateAllItems() + { + foreach (GridItem item in curInMemoryItemSet) + { + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + } + /// + /// Get group number of GridView. + /// + /// Groups count + public int GetGroupCount() + { + return groupList.Count; + } + /// + /// Get column count of specified group. + /// + /// The group index. + /// Columns count + public int GetColumnCount(int groupIndex) + { + Tizen.Log.Fatal("NUI", "... groupIndex = " + groupIndex); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + if (curGroup.columnList == null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column list")); + return INVALID_COUNT; + } + + Tizen.Log.Fatal("NUI", "... curGroup.columnList.Count = " + curGroup.columnList.Count); + return curGroup.columnList.Count; + } + /// + /// Get cell count of specified column of specified group. + /// + /// The group index. + /// The column index. + /// Cells count + public int GetCellCount(int groupIndex, int columnIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + if (curColumn.cellList == null) + { + return INVALID_COUNT; + } + + return curColumn.cellList.Count; + } + + + /// + /// Get item count of a group. + /// + /// The group index. + /// Items count + public int GetItemCount(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + return curGroup.itemList.Count; + } + /// + /// Get the GridBridge of GridView. + /// + /// The GridBridge of GridView. + public GridBridge GetBridge() + { + return gridBridge; + } + /// + /// Get on screen item range. + /// + /// The group index of start range. + /// The item index of start range. + /// The group index of end range. + /// The item index of end range. + public void GetOnscreenRange(out int startGroupIndex, out int startItemIndex, out int endGroupIndex, out int endItemIndex) + { + startGroupIndex = onScreenRange.startGroupInScrn; + startItemIndex = onScreenRange.startItemIndexInScrn; + endGroupIndex = onScreenRange.endGroupInScrn; + endItemIndex = onScreenRange.endItemIndexInScrn; + } + + /// + /// Move focus according to parameter direction + /// + /// Focus move direction, can be "Left", "Right", "Up" or "Down" + public void Move(string direction) + { + MoveFocus(direction); + } + + /// + /// Get screen position of specified item. + /// + /// Group index of linear view. + /// Item index of group. + /// + /// Thrown when groupIndex or item index is invalid. + /// + /// Screen position of specified item. + public Position2D GetItemScreenPosition(int groupIndex, int itemIndex) + { + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + throw new ArgumentException("Group index or item index is invalid"); + } + + GridItem curItem = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + return curItem?.itemView?.ScreenPosition; + } + + /// + /// Dispose of GridView. + /// + /// Dispose caused type + protected override void Dispose(DisposeTypes type) + { + if (disposed) + { + return; + } + + if (type == DisposeTypes.Explicit) + { + //Called by User + //Release your own managed resources here. + //You should release all of your own disposable objects here. + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Dispose")); + focusMoveAni?.Stop(); + focusMoveAni?.Dispose(); + focusMoveAni = null; + + ClearRecycleBin(); + ResetGroup(0); + } + + //Release your own unmanaged resources here. + //You should not access any managed member here except static instance. + //because the execution order of Finalizes is non-deterministic. + //Unreference this from if a static instance refer to this. + + //You must call base.Dispose(type) just before exit. + base.Dispose(type); + } + + /// + /// GridView event handler + /// + public event EventHandler GridEvent + { + add + { + gridEventHandlers += value; + } + + remove + { + gridEventHandlers -= value; + } + } + /// + /// Update when GridView attributes changed. + /// + /// the object + /// the args of the event + protected void OnRelayoutUpdate(object sender, EventArgs e) + { + gridWidth = this.SizeWidth; + gridHeight = this.SizeHeight; + Tizen.Log.Fatal("NUI", "...OnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdate..."); + if (gridBridge != null) + { + Load(); + + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + + private void OnListEvent(GridEventArgs e) + { + if (gridEventHandlers != null) + { + gridEventHandlers(this, e); + } + } + + private void Initialize() + { + ClippingMode = ClippingModeType.ClipChildren; + + + groupList = new List(); + itemGroup = new View(); + itemGroup.Name = "ItemGroup"; + itemGroup.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + itemGroup.PivotPoint = Tizen.NUI.PivotPoint.TopLeft; + this.Add(itemGroup); + + itemGroupRect = new Rect(0, 0, 0, 0); + + curInMemoryItemSet = new HashSet(); + nextInMemoryItemSet = new HashSet(); + + lastVisibleArea = new Rect(0, 0, 0, 0); + onScreenRange = new Range(-1, -1, -1, -1); + + refXForFocusMove = -1; + refYForFocusMove = -1; + + focusGroupIndex = 0; + focusItemIndex = 0; + + focusTagGroupIndex = 0; + focusTagItemIndex = 0; + + StateRightCircularEnable = false; + StateLeftCircularEnable = false; + + + focusMoveAni = new LinkerAnimation(itemGroup, 100, 100, 0); + focusMoveAni.ViaEvent += OnFocusMoveViaEvent; + + ScrollBarFadeOutDuration = 1000; + } + + private void Load() + { + Tizen.Log.Fatal("NUI", "...lOAD..."); + int groupCount = groupList.Count; + if (groupCount == 0) + { + return; + } + + for (int i = 0; i < groupCount; i++) + { + Group curGroup = groupList.ElementAt(i); + int dataCount = gridBridge.GetItemCount(i); + + int finalCount = curGroup.realCellCount < dataCount ? curGroup.realCellCount : dataCount; + + int bindedItemCount = curGroup.itemList.Count; + + for (int j = 0; j < finalCount; j++) + { + GridItem newItem; + if (j < bindedItemCount) + { + newItem = curGroup.itemList.ElementAt(j); + } + else + { + Cell curCell = curGroup.itemIndexToCell[j]; + newItem = new GridItem(); + newItem.groupIndex = i; + newItem.index = j; + newItem.rect = curCell.rect; + curGroup.itemList.Add(newItem); + } + } + + //add for right move between group when not all columns filled + if (finalCount >= 1) + { + Cell lastItemCell = GetCellByItemIndex(i, finalCount - 1); + curGroup.lastFilledColumnIndex = lastItemCell.columnIndex; + } + } + + UpdateItemGroupSize(); + + InitItemGroupPosition(); + UpdateInMemoryItems(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + private void UpdateInMemoryItems() + { + Rect windowRect = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + Tizen.Log.Fatal("NUI", ">>>>>>>>> loadItemList.Count: " + loadItemList.Count + " unloadItemList.Count: " + unloadItemList.Count); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UpdateInMemoryItems(Position itemGroupPos) + { + Rect windowRect = new Rect(-itemGroupPos.X, -itemGroupPos.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UnloadItem(GridItem item, bool bDirectly = false) + { + Tizen.Log.Fatal("NUI", "item: " + item + " bDirectly: " + bDirectly); + itemGroup.Remove(item.itemView); + + if (bDirectly) + { + gridBridge.UnloadItem(item.groupIndex, item.index, item.itemView); + } + else + { + AddRecycleView(item.groupIndex, item.index, item.itemView); + } + + item.itemView = null; + + curInMemoryItemSet.Remove(item); + } + + private void LoadItem(GridItem item) + { + curInMemoryItemSet.Add(item); + + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]LoadItem item view is null")); + return; + } + + View temp = GetRecycleView(item.groupIndex,item.index); + Tizen.Log.Fatal("NUI", " temp: " + temp); + if (temp != null) + { + item.itemView = temp; + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + else + { + item.itemView = gridBridge.GetItemView(item.groupIndex, item.index); + + item.itemView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + item.itemView.PivotPoint = Tizen.NUI.PivotPoint.Center; + item.itemView.PositionUsesPivotPoint = false; + } + + Tizen.Log.Fatal("NUI", "item.index: " + item.index + " item.rect.X: " + item.rect.X + " item.rect.Y: " + item.rect.Y); + item.itemView.Position = new Position(item.rect.X, item.rect.Y, 0.0f); + item.itemView.Size2D = new Size2D((int)item.rect.Width, (int)item.rect.Height); + + itemGroup.Add(item.itemView); + } + + private void SetViewTypeCount(int typeCount) + { + if (typeCount < 1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]SetViewTypeCount type count less than 1")); + return; + } + + viewTypeCount = typeCount; + List[] viewListArray = new List[viewTypeCount]; + + for (int i = 0; i < viewTypeCount; i++) + { + viewListArray[i] = new List(); + } + + recycledViews = viewListArray; + } + + private void AddRecycleView(int groupIndex, int itemIndex, View view) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return; + } + + if (view != null) + { + view.Hide(); + view.Scale = new Vector3(1, 1, 1); + } + + recycledViews[viewType].Add(view); + } + + private View GetRecycleView(int groupIndex, int itemIndex) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + Tizen.Log.Fatal("NUI", " viewType:" + viewType + " viewTypeCount:" + viewTypeCount); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return null; + } + + View obj = null; + int viewCount = recycledViews[viewType].Count; + if (viewCount != 0) + { + obj = recycledViews[viewType][viewCount - 1]; + recycledViews[viewType].Remove(obj); + } + + if (obj != null) + { + obj.Show(); + } + + return obj; + } + + private void ClearRecycleBin() + { + for (int i = 0; i < viewTypeCount; i++) + { + for (int j = 0; j < recycledViews[i].Count; j++) + { + UnloadRecycledView(i, recycledViews[i][j]); + } + + recycledViews[i].Clear(); + } + } + + private void UnloadRecycledView(int viewType, View view) + { + itemGroup.Remove(view); + gridBridge.UnloadItemByViewType(viewType, view); + } + + private void GetChangedItems(Rect aLastVisibleArea, Rect curVisibleArea, ref List loadItem, ref List unloadItem) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> aLastVisibleArea.X: " + aLastVisibleArea.X + " aLastVisibleArea.Y: " + aLastVisibleArea.Y + " aLastVisibleArea.Width: " + aLastVisibleArea.Width + " aLastVisibleArea.Height: " + aLastVisibleArea.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> curVisibleArea.X: " + curVisibleArea.X + " curVisibleArea.Y: " + curVisibleArea.Y + " curVisibleArea.Width: " + curVisibleArea.Width + " curVisibleArea.Height: " + curVisibleArea.Height); + GetOnscreenRange(curVisibleArea, ref onScreenRange); + + //Adjust the new start column: if the start column has items which are merge_hidden, + //find the item's smalllest start column as the new start column. + Column startColumn = groupList.ElementAt(onScreenRange.startGroupIndex).columnList.ElementAt(onScreenRange.startColumnIndex); + int cellCount = startColumn.cellList.Count; + + //save new range items to list + nextInMemoryItemSet.Clear(); + GetItemsInRange(onScreenRange, ref nextInMemoryItemSet); + + loadItem = nextInMemoryItemSet.Except(curInMemoryItemSet).ToList(); + unloadItem = curInMemoryItemSet.Except(nextInMemoryItemSet).ToList(); + } + + private void GetOnscreenRange(Rect visibleArea, ref Range range, bool bAllInArea = false) + { + Cell focusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + + int focusColumnIndex = focusedCell.columnIndex; + + float areaStartPos, areaEndPos, focusedCellStart, focusedCellEnd; + if (GridType.Horizontal == gridType) + { + areaStartPos = visibleArea.X; + areaEndPos = visibleArea.X + visibleArea.Width; + focusedCellStart = focusedCell.rect.X; + focusedCellEnd = focusedCell.rect.X + focusedCell.rect.Width; + } + else + { + areaStartPos = visibleArea.Y; + areaEndPos = visibleArea.Y + visibleArea.Height; + focusedCellStart = focusedCell.rect.Y; + focusedCellEnd = focusedCell.rect.Y + focusedCell.rect.Height; + } + + bool bStartFound = false, bEndFound = false; + + int groupCount = groupList.Count; + //find start range + if ((bAllInArea == true && focusedCellStart < areaStartPos) + || (bAllInArea == false && focusedCellEnd < areaStartPos)) + { + for (int i = focusGroupIndex; i < groupCount && bStartFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (true == bAllInArea) + { + if (curColumn.startPos >= areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i >= 0 && bStartFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= areaStartPos) + { + if (bAllInArea == true) + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + + bStartFound = true; + break; + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + } + else + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + } + + bStartFound = true; + break; + } + } + } + } + } + + if (bStartFound == false) + { + range.startGroupIndex = 0; + range.startColumnIndex = 0; + } + + //find end range + if ((bAllInArea == true && focusedCellEnd >= areaEndPos) + || (bAllInArea == false && focusedCellStart >= areaEndPos)) + { + for (int i = focusGroupIndex; i >= 0 && bEndFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (bAllInArea == true) + { + if (curColumn.endPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + else + { + if (curColumn.startPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i < groupCount && bEndFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.endPos >= areaEndPos) + { + if (curColumn.startPos < areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + } + else + { + if (j == 0) + { + range.endGroupIndex = i - 1; + range.endColumnIndex = groupList.ElementAt(i - 1).columnList.Count - 1; + } + else + { + range.endGroupIndex = i; + range.endColumnIndex = j - 1; + } + } + + bEndFound = true; + break; + } + } + } + } + + if (bEndFound == false) + { + range.endGroupIndex = groupCount - 1; + range.endColumnIndex = groupList.ElementAt(range.endGroupIndex).columnList.Count - 1; + } + + range.startGroupInScrn = range.startGroupIndex; + range.startColumnInScrn = range.startColumnIndex; + range.endGroupInScrn = range.endGroupIndex; + range.endColumnInScrn = range.endColumnIndex; + + //get on screen start and end item index + Group startGroup = groupList.ElementAt(range.startGroupInScrn); + Column startColumn = startGroup.columnList.ElementAt(range.startColumnInScrn); + Cell startCell = startColumn.cellList.ElementAt(0); + range.startItemIndexInScrn = startCell.itemIndex; + if (range.startItemIndexInScrn >= startGroup.itemList.Count) + { + range.startItemIndexInScrn = startGroup.itemList.Count - 1; + } + + Group endGroup = groupList.ElementAt(range.endGroupInScrn); + Column endColumn = endGroup.columnList.ElementAt(range.endColumnInScrn); + Cell endCell = endColumn.cellList.ElementAt(endColumn.cellList.Count - 1); + range.endItemIndexInScrn = endCell.itemIndex; + if (range.endItemIndexInScrn >= endGroup.itemList.Count) + { + range.endItemIndexInScrn = endGroup.itemList.Count - 1; + } + + //add buffer columns + int frontBufferCount = preloadFrontColumnSize; + while (frontBufferCount-- > 0) + { + if (range.startColumnIndex > 0) + { + range.startColumnIndex--; + } + else + { + if (range.startGroupIndex > 0) + { + range.startGroupIndex--; + range.startColumnIndex = groupList.ElementAt(range.startGroupIndex).columnList.Count - 1; + } + else + { + break; + } + } + } + + int backBufferCount = preloadBackColumnSize; + while (backBufferCount-- > 0) + { + if (range.endColumnIndex < groupList.ElementAt(range.endGroupIndex).columnList.Count - 1) + { + range.endColumnIndex++; + } + else + { + if (range.endGroupIndex < groupList.Count - 1) + { + range.endGroupIndex++; + range.endColumnIndex = 0; + } + else + { + break; + } + } + } + } + + private void GetItemsInRange(Range range, ref HashSet itemSet) + { + for (int i = range.startGroupIndex; i <= range.endGroupIndex; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == range.startGroupIndex) ? range.startColumnIndex : 0; + int endColumnIndex = (i == range.endGroupIndex) ? range.endColumnIndex : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + + for (int k = 0; k < curColumn.cellList.Count; k++) + { + Cell curCell = curColumn.cellList.ElementAt(k); + if (curCell.itemIndex < curGroup.itemList.Count) + { + itemSet.Add(curGroup.itemList.ElementAt(curCell.itemIndex)); + } + } + } + } + } + + private void MoveFocus(string direction) + { + string logicalDirection = GetLogicalDirection(direction); + MoveFocus(logicalDirection, focusTagGroupIndex, focusTagItemIndex); + } + + // Get the specific groupIndex,itemIndex neighbor item according to direction + private GridItem GetItemByDirection(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell currentCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + + //adjust focused column index based on reference line + Group currentGroup = groupList.ElementAt(fromGroupIndex); + int currentColumnIndex = currentCell.columnIndex; + Column currentColumn = currentGroup.columnList.ElementAt(currentColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex - 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex >= currentColumn.cellList.Count - 1) + { + destFocusItemIndex = -1; + } + else if (fromItemIndex == currentGroup.itemList.Count - 1) + { + destFocusColumnIndex = currentColumnIndex - 1; + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Left": + if (currentCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + destFocusColumnIndex = nextGroup.columnList.Count - 1; + + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentCell.columnIndex - 1; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + } + + break; + case "Right": + if (currentColumnIndex == currentGroup.columnList.Count - 1) + { + if (fromGroupIndex == groupList.Count - 1) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " destFocusItemIndex: " + destFocusItemIndex); + GridItem item = null; + if (IsGroupIndexValid(destFocusGroupIndex) == true && IsItemIndexValid(destFocusGroupIndex, destFocusItemIndex)) + { + item = groupList.ElementAt(destFocusGroupIndex).itemList.ElementAt(destFocusItemIndex); + } + + return item; + } + + private void MoveFocus(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell curFocusedCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + //change reference line of focus move + if (refXForFocusMove == -1) + { + refXForFocusMove = curFocusedCell.rect.X; + } + + if (refYForFocusMove == -1) + { + refYForFocusMove = curFocusedCell.rect.Y; + } + + //adjust focused column index based on reference line + Group focusedGroup = groupList.ElementAt(fromGroupIndex); + int focusedColumnIndex = curFocusedCell.columnIndex; + + Column focusedColumn = focusedGroup.columnList.ElementAt(focusedColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (curFocusedCell.index == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = focusedColumn.cellList.ElementAt(curFocusedCell.index - 1); + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + int destCellIndex = curFocusedCell.index + 1; + if (destCellIndex >= focusedColumn.cellList.Count || fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusItemIndex = -1; + if (fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusColumnIndex = focusedColumnIndex - 1; + Cell cellBelow = FindCellBelow(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex); + if (cellBelow != null) + { + destFocusItemIndex = cellBelow.itemIndex; + refXForFocusMove = cellBelow.rect.X; + refYForFocusMove = cellBelow.rect.Y; + } + } + } + else + { + Cell nextCell = null; + for (; destCellIndex < focusedColumn.cellList.Count; destCellIndex++) + { + nextCell = focusedColumn.cellList.ElementAt(destCellIndex); + { + break; + } + } + + if (destCellIndex >= focusedColumn.cellList.Count) + { + destFocusItemIndex = -1; + } + else + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Left": + if (curFocusedCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + if (StateLeftCircularEnable && true/*check whether allow to loop*/) + { + destFocusGroupIndex = groupList.Count - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = curFocusedCell.columnIndex - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + break; + case "Right": + { + focusedColumnIndex = curFocusedCell.columnIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedColumnIndex: " + focusedColumnIndex); + if (focusedColumnIndex == focusedGroup.columnList.Count - 1 || focusedColumnIndex == focusedGroup.lastFilledColumnIndex) + { + if (fromGroupIndex == groupList.Count - 1) + { + if (StateRightCircularEnable && true/*check whether allow right circular*/) + { + destFocusGroupIndex = 0; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false && destFocusColumnIndex < focusedGroup.columnList.Count - 1) + { + destFocusColumnIndex++; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + + refXForFocusMove = refYForFocusMove = -1; + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = focusedColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + + if (StateRightCircularEnable) + { + if (destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + return; + } + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + if (destFocusGroupIndex >= 0 && destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + destFocusItemIndex = -1; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + if (destFocusItemIndex == -1) + { + //notify event focus move out + return; + } + + if (gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex) == false) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + } + else + { + PushFocus(destFocusGroupIndex, destFocusItemIndex); + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + + private void GetNearestItem(Cell focusedCell, int destGroupIndex, int destColumnIndex, ref int destItemIndex, bool bDirectMove = false) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + Cell nextCell = destColumn.cellList.ElementAt(0); + int cellCount = destColumn.cellList.Count; + + bool bNotAllItemDisabled = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= 0 && curCell.itemIndex < destGroup.itemList.Count) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex)) + { + bNotAllItemDisabled = true; + break; + } + } + } + + float yDis = gridHeight + 1; + bool bFound = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= destGroup.itemList.Count) + { + break; + } + + if (curCell.itemIndex >= 0 && bNotAllItemDisabled) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex) == false) + { + continue; + } + } + + if (curCell.itemIndex < 0) + { + Column realColumn = destGroup.columnList.ElementAt(curCell.columnIndex); + Cell realCell = realColumn.cellList.ElementAt(curCell.rowIndex); + if (realCell.itemIndex >= destGroup.itemList.Count || gridBridge.IsItemEnabled(destGroupIndex, realCell.itemIndex) == false) + { + continue; + } + } + + if (GridType.Vertical == gridType) + { + float tempXDis; + if (StateStraightPathEnable) + { + tempXDis = Math.Abs(curCell.rect.X - refXForFocusMove); + } + else + { + tempXDis = Math.Abs(curCell.rect.X - focusedCell.rect.X); + } + + if (tempXDis < yDis) + { + bFound = true; + yDis = tempXDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + else + { + float tempYDis; + if (StateStraightPathEnable) + { + tempYDis = Math.Abs(curCell.rect.Y - refYForFocusMove); + } + else + { + tempYDis = Math.Abs(curCell.rect.Y - focusedCell.rect.Y); + } + + if (tempYDis < yDis) + { + bFound = true; + yDis = tempYDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + + } + + { + destItemIndex = nextCell.itemIndex; + if (bFound) + { + refXForFocusMove = nextCell.rect.X; + if (bDirectMove == false) + { + refYForFocusMove = nextCell.rect.Y; + } + } + } + } + + private string GetLogicalDirection(string direction) + { + string logicalDirection = direction; + + if (GridType.Vertical == gridType) + { + if ("Left" == direction) + { + logicalDirection = "Up"; + } + else if ("Right" == direction) + { + logicalDirection = "Down"; + } + else if ("Down" == direction) + { + logicalDirection = "Right"; + } + else if ("Up" == direction) + { + logicalDirection = "Left"; + } + } + + return logicalDirection; + } + + private Cell FindCellBelow(Cell fromCell, int destGroupIndex, int destColumnIndex) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + + if (destColumnIndex < 0 || destColumnIndex >= destGroup.columnList.Count) + { + return null; + } + + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + for (int i = 0; i < destColumn.cellList.Count; i++) + { + Cell destCell = destColumn.cellList.ElementAt(i); + + if (destCell.rect.Y > fromCell.rect.Y && destCell.rect.Y + destCell.rect.Height > fromCell.rect.Y + fromCell.rect.Height) + { + { + return destCell; + } + } + } + + return null; + } + + private void SetFocus(int groupIndex, int itemIndex, bool bAnimation = false, Position newItemGroupPos = null) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex: " + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + bool bNeedScroll = false; + + if (newItemGroupPos == null) + { + Position itemGroupPos = new Position(0, 0, 0); + bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + } + else + { + if (GridType.Horizontal == gridType && itemGroupRect.X != newItemGroupPos.X + || GridType.Vertical == gridType && itemGroupRect.Y != newItemGroupPos.Y) + { + bNeedScroll = true; + } + + itemGroupRect.X = newItemGroupPos.X; + itemGroupRect.Y = newItemGroupPos.Y; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + ResetItemGroupRectPos(); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + if (bNeedScroll) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> bAnimation: " + bAnimation); + if (bAnimation == true) + { + FocusMoveViaObject obj = new FocusMoveViaObject(); + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + focusMoveAni.Play(); + } + else + { + UpdateInMemoryItems(); + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + else + { + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + + private void PushFocus(int groupIndex, int itemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex:" + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + Position itemGroupPos = new Position(0, 0, 0); + bool bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + + ResetItemGroupRectPos(); + + //focusTag keep move, but real focus will set when focusMoveVia trigger, + //so remember context of focus move, include from and to, and itemGroupPos information + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X:" + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + if (bNeedScroll) + { + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + FocusMoveViaObject obj = new FocusMoveViaObject(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusMoveViaQ.Count: " + focusMoveViaQ.Count); + Tizen.Log.Fatal("NUI", "::::: " + focusGroupIndex + ", " + focusItemIndex); + + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + focusMoveAni.Play(); + } + else + { + if (focusMoveAni.IsPlaying() == false) + { + Tizen.Log.Fatal("NUI", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ " + groupIndex + " " + itemIndex + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + //To keep focusBar on the top of + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + private bool GetItemGroupPosByFocusItem(int aFocusGroupIndex, int aFocusItemIndex, Position itemGroupPos) + { + bool bNeedScroll = false; + if (!IsItemIndexValid(aFocusGroupIndex, aFocusItemIndex)) + { + return false; + } + + Group focusedGroup = groupList.ElementAt(aFocusGroupIndex); + GridItem focusedItem = focusedGroup.itemList.ElementAt(aFocusItemIndex); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedItem.rect: " + focusedItem.rect.X + ", " + focusedItem.rect.Y + ", " + focusedItem.rect.Width + ", " + focusedItem.rect.Height); + + Rect focusBarRectBaseOnList = new Rect(focusedItem.rect.X, focusedItem.rect.Y, focusedItem.rect.Width, focusedItem.rect.Height); + focusBarRectBaseOnList.X += itemGroupRect.X; + focusBarRectBaseOnList.Y += itemGroupRect.Y; + + itemGroupPos.X = itemGroupRect.X; + itemGroupPos.Y = itemGroupRect.Y; + + float startFocusRange; + float endFocusRange; + + if (GridType.Horizontal == gridType) + { + if (0 == focusedItem.rect.X) + { + startFocusRange = margin[0]; + } + else + { + Tizen.Log.Fatal("NUI", "Left aFocusItemIndex:: " + aFocusGroupIndex + ", aFocusItemIndex:: " + aFocusItemIndex); + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "startFocusRange :: " + margin[0]); + startFocusRange = prevItem != null ? prevItem.rect.Width / 2 : margin[0]; + } + + if (itemGroupRect.Width == focusedItem.rect.Right()) + { + endFocusRange = gridWidth - margin[2]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "gridWidth::" + gridWidth + " gridWidth - margin[2] :: " + (gridWidth - margin[2])); + //Tizen.Log.Fatal("NUI", "gridWidth - nextItem.rect.Width / 2 :: " + (gridWidth - nextItem.rect.Width / 2)); + endFocusRange = nextItem != null ? gridWidth - nextItem.rect.Width / 2 : gridWidth - margin[2]; + Tizen.Log.Fatal("NUI", "endFocusRange :: " + endFocusRange); + } + + if (focusBarRectBaseOnList.X < startFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.X :: " + focusBarRectBaseOnList.X + " startFocusRange :: " + startFocusRange); + itemGroupPos.X += startFocusRange - focusBarRectBaseOnList.X; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Right() > endFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.Right() :: " + focusBarRectBaseOnList.Right() + " endFocusRange :: " + endFocusRange); + itemGroupPos.X += endFocusRange - focusBarRectBaseOnList.Right(); + bNeedScroll = true; + } + } + else + { + if (0 == focusedItem.rect.Y) + { + startFocusRange = margin[1]; + } + else + { + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + startFocusRange = prevItem != null ? prevItem.rect.Height / 2 : margin[1]; + } + + if (itemGroupRect.Height == focusedItem.rect.Bottom()) + { + endFocusRange = gridHeight - margin[3]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + endFocusRange = nextItem != null ? gridHeight - nextItem.rect.Height / 2 : gridHeight - margin[3]; + } + + if (focusBarRectBaseOnList.Y < startFocusRange) + { + itemGroupPos.Y += startFocusRange - focusBarRectBaseOnList.Y; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Bottom() > endFocusRange) + { + itemGroupPos.Y += endFocusRange - focusBarRectBaseOnList.Bottom(); + bNeedScroll = true; + } + } + + return bNeedScroll; + } + + private void NotifyFocusChange(int fromGroupIndex,int fromItemIndex,int toGroupIndex,int toItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex + " toGroupIndex: " + toGroupIndex + " toItemIndex: " + toItemIndex); + + if (IsItemIndexValid(fromGroupIndex, fromItemIndex) && (fromGroupIndex != toGroupIndex || fromItemIndex != toItemIndex)) + { + Group preGroup = groupList.ElementAt(fromGroupIndex); + GridItem preItem = preGroup.itemList.ElementAt(fromItemIndex); + + ScaleDownItem(preItem); + if (preItem.itemView != null) + { + gridBridge.FocusChange(fromGroupIndex, fromItemIndex, preItem.itemView, false); + } + } + + if (IsItemIndexValid(toGroupIndex, toItemIndex)) + { + Group curGroup = groupList.ElementAt(toGroupIndex); + GridItem item = curGroup.itemList.ElementAt(toItemIndex); + + ScaleUpItem(item); + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", "Call GridBridge.FocusChange to set focus"); + gridBridge.FocusChange(toGroupIndex, toItemIndex, item.itemView, true); + } + } + + //notify user focus change + GridEventArgs evtArgs = new GridEventArgs(); + evtArgs.EventType = GridEventType.FocusChange; + evtArgs.param[0] = fromGroupIndex; + evtArgs.param[1] = fromItemIndex; + evtArgs.param[2] = toGroupIndex; + evtArgs.param[3] = toItemIndex; + OnListEvent(evtArgs); + + if (toGroupIndex != -1 && toItemIndex != -1) + { + focusGroupIndex = toGroupIndex; + focusItemIndex = toItemIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusGroupIndex: " + focusGroupIndex + " focusItemIndex: " + focusItemIndex); + } + + private void ScaleUpItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.itemView.RaiseToTop(); + item.ScaleItem(new Vector3(focusInScaleFactor, focusInScaleFactor, 1.0f), focusInScaleAnimationAttrs); + } + + private void ScaleDownItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.ScaleItem(new Vector3(1.0f, 1.0f, 1.0f), focusOutScaleAnimationAttrs); + } + + private void UpdateItemGroupSize() + { + if (groupList.Count == 0) + { + return; + } + + Group lastGroup = groupList.ElementAt(groupList.Count - 1); + + int lastItemIndex = lastGroup.itemList.Count - 1; + if (lastItemIndex < 0) + { + return; + } + + Cell lastFilledCell = GetCellByItemIndex(groupList.Count - 1 ,lastItemIndex); + int lastFilledColumnIndex = lastFilledCell.columnIndex; + Column lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + int cellCount = lastFilledColumn.cellList.Count; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = lastFilledColumn.cellList.ElementAt(i); + if (curCell.columnIndex > lastFilledColumnIndex) + { + lastFilledColumnIndex = lastFilledColumn.cellList.ElementAt(i).columnIndex; + } + } + + lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + float width, height; + + if (GridType.Horizontal == gridType) + { + width = lastFilledColumn.endPos; + height = gridHeight - (margin[1] + margin[3]); + } + else + { + width = gridWidth - (margin[0] + margin[2]); + height = lastFilledColumn.endPos; + } + + itemGroupRect.Width = width; + itemGroupRect.Height = height; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + itemGroup.SizeWidth = itemGroupRect.Width; + itemGroup.SizeHeight = itemGroupRect.Height; + } + + private void InitItemGroupPosition() + { + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X > margin[0]) + { + itemGroupRect.X = margin[0]; + } + else if (itemGroupRect.Right() < gridWidth) + { + if (itemGroupRect.X >= gridWidth) + { + itemGroupRect.X = gridWidth - itemGroupRect.Width; + } + else + { + itemGroupRect.X = 0; + } + } + + itemGroupRect.Y = margin[1]; + } + else + { + itemGroupRect.X = margin[0]; + if (itemGroupRect.Y > margin[1]) + { + itemGroupRect.Y = margin[1]; + } + else if (itemGroupRect.Y + itemGroupRect.Height < gridHeight) + { + if (itemGroupRect.Y >= gridHeight) + { + itemGroupRect.Y = gridHeight - itemGroupRect.Height; + } + else + { + itemGroupRect.Y = 0; + } + } + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + ResetItemGroupRectPos(); + + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + } + + private void ResetItemGroupRectPos() + { + //adjust item Group pos, to add margin when item group scroll to Head or Tail + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X == 0) + { + itemGroupRect.X += margin[0]; + } + else if (itemGroupRect.Right() == gridWidth) + { + itemGroupRect.X -= margin[2]; + } + } + else + { + if (itemGroupRect.Y == 0) + { + itemGroupRect.Y += margin[1]; + } + else if (itemGroupRect.Bottom() == gridHeight) + { + itemGroupRect.Y -= margin[3]; + } + } + } + + private Cell GetCellByItemIndex(int groupIndex, int itemIndex) + { + Cell curCell = null; + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (curGroup.itemIndexToCell.ContainsKey(itemIndex)) + { + curCell = curGroup.itemIndexToCell[itemIndex]; + } + + return curCell; + } + + private bool IsGroupIndexValid(int groupIndex) + { + return (groupIndex >= 0 && groupList != null && groupIndex < groupList.Count); + } + + private bool IsItemIndexValid(int groupIndex, int itemIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (itemIndex >= 0 && curGroup.itemList != null && itemIndex < curGroup.itemList.Count); + } + + private bool IsColumnIndexValid(int groupIndex, int columnIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (columnIndex >= 0 && curGroup.columnList != null && columnIndex < curGroup.columnList.Count); + } + + private bool IsCellIndexValid(int groupIndex, int columnIndex, int cellIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return false; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + return (cellIndex >= 0 && curColumn.cellList != null && cellIndex < curColumn.cellList.Count); + } + + /// + /// Called when the control gain key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusGained(object sender, EventArgs e) + { + OnFocusGained(); + } + + public void OnFocusGained() + { + Tizen.Log.Fatal("NUI", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "); + SetFocus(focusGroupIndex, focusItemIndex); + } + + /// + /// Called when the control loses key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusLost(object sender, EventArgs e) + { + OnFocusLost(); + } + + public void OnFocusLost() + { + Tizen.Log.Fatal("NUI", "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, -1, -1); + } + + private void OnFocusMoveViaEvent(object o, EventArgs e) + { + Tizen.Log.Fatal("NUI", "--------------------- " + focusMoveViaQ.Count + " -------------------------------"); + if (focusMoveViaQ.Count > 0) + { + { + FocusMoveViaObject obj = focusMoveViaQ.Dequeue(); + { + UpdateInMemoryItems(itemGroup.Position); + } + + { + //common focus notify focus change at destination of every via + NotifyFocusChange(focusGroupIndex, focusItemIndex, obj.toGroupIndex, obj.toItemIndex); + } + } + + //viaMap1.Remove(args.ViaNode); + } + } + + private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + { + switch (e.ChangeType) + { + case GridBridge.DataChangeEventType.Add: + AddItem(e.param[0]); + break; + case GridBridge.DataChangeEventType.Remove: + DeleteItem(e.param[0], e.param[1], e.param[2]); + break; + case GridBridge.DataChangeEventType.Insert: + InsertItem(e.param[0], e.param[1]); + break; + case GridBridge.DataChangeEventType.Clear: + Clear(); + break; + case GridBridge.DataChangeEventType.Reset: + ResetByData(); + break; + case GridBridge.DataChangeEventType.Load: + Load(); + Group curGroup = groupList.ElementAt(e.param[0]); + for (int i = e.param[1]; i < gridBridge.GetItemCount(e.param[0]); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(e.param[0], i, curGroup.itemList.ElementAt(i).itemView); + } + } + + if (focusItemIndex >= e.param[1] && focusItemIndex <= e.param[1] + e.param[2] - 1) + { + if (e.param[1] > 0) + { + SetFoucsItemIndex(e.param[1] - 1, focusGroupIndex); + } + else if (e.param[1] + e.param[2] < curGroup.itemList.Count) + { + SetFoucsItemIndex(e.param[1] + e.param[2], focusGroupIndex); + } + } + else if (focusItemIndex >= e.param[1] + e.param[2]) + { + SetFoucsItemIndex(focusItemIndex - e.param[2], focusGroupIndex); + } + + break; + default: + + break; + } + + refXForFocusMove = refYForFocusMove = -1; + } + + private void AddItem(int groupIndex) + { + int dataCount = gridBridge.GetItemCount(groupIndex); + if (dataCount > groupList.ElementAt(groupIndex).realCellCount) + { + AddColumn(colW, groupIndex); + int columnIndex = groupList.ElementAt(groupIndex).columnList.Count - 1; + for (int i = 0; i < rowCnt; i++) + { + AddRowToColumn(columnIndex, rowH, groupIndex); + } + } + + Load(); + } + + private void AddAll(int groupIndex, int count) + { + Load(); + } + + + private void DeleteItem(int groupIndex, int fromItemIndex, int deleteItemNum) + { + Group curGroup = groupList.ElementAt(groupIndex); + + GridItem item = null; + + int toItemIndex = fromItemIndex + deleteItemNum - 1; + + int count = 0; + + for (int i = fromItemIndex; i < curGroup.itemList.Count; i++) + { + item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, true); + count++; + } + } + + for (int i = 0; i < count; i++) + { + curGroup.itemList.Remove(curGroup.itemList.ElementAt(curGroup.itemList.Count - 1)); + } + } + + private void InsertItem(int groupIndex, int itemIndex) + { + Load(); + + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = itemIndex; i < gridBridge.GetItemCount(groupIndex); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(groupIndex, i, curGroup.itemList.ElementAt(i).itemView); + } + } + } + + private void Clear() + { + for (int i = 0; i < groupList.Count; i++) + { + Clear(i); + } + + ClearRecycleBin(); + } + + private void Clear(int groupIndex) + { + Tizen.Log.Fatal("NUI", "--------------------- " + groupIndex + " -------------------------------"); + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = 0; i < curGroup.itemList.Count; i++) + { + GridItem item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, false); + } + } + + curGroup.itemList.Clear(); + } + + private void ResetByData() + { + Tizen.Log.Fatal("NUI", "...."); + int groupCount = gridBridge.GetGroupCount(); + ResetGroup(groupCount); + for (int i = 0; i < groupCount; i++) + { + Tizen.Log.Fatal("NUI", ".... group: " + i); + int dataCount = gridBridge.GetItemCount(i); + Tizen.Log.Fatal("NUI", ".... dataCount: " + dataCount + " rowCnt: " + rowCnt); + int columnCount = (dataCount + rowCnt - 1) / rowCnt; + Group group = groupList.ElementAt(i); + Tizen.Log.Fatal("NUI", ".... columnCount: " + columnCount + " group.columnList.Count: " + group.columnList.Count + " group.itemIndexToCell.Count: " + group.itemIndexToCell.Count); + if (columnCount > group.columnList.Count) + { + for (int c = group.columnList.Count; c < columnCount; c++) + { + AddColumn(colW, i); + for (int r = 0; r < rowCnt; r++) + { + AddRowToColumn(c, rowH, i); + } + } + } + else if (columnCount < group.columnList.Count) + { + float posOffset = -(group.columnList.Count - columnCount) * (colW + columnSpace) + ColumnSpace; + + for (int c = columnCount; c < group.columnList.Count; c++) + { + for (int r = 0; r < rowCnt; r++) + { + int itemIndex = c * rowCnt + r; + group.itemIndexToCell.Remove(itemIndex); + group.realCellCount--; + Tizen.Log.Fatal("NUI", ".... itemIndexToCell.Remove: " + itemIndex); + } + } + + group.columnList.RemoveRange(columnCount, group.columnList.Count - columnCount); + group.endPos = group.columnList.ElementAt(columnCount - 1).endPos; + for (int j = i + 1; j < groupList.Count; j++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(j).title != null) + { + groupList.ElementAt(j).title.PositionX += posOffset; + } + + groupList.ElementAt(j).ResetPosition(posOffset); + } + + } + + Tizen.Log.Fatal("NUI", ".... group.columnList.Count: " + group.columnList.Count); + } + + focusGroupIndex = 0; + focusItemIndex = 0; + Tizen.Log.Fatal("NUI", "...."); + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(0, 0); + } + } + + /*page length set to grid length*/ + private void PageMove(bool bPrev, bool bAni) + { + Rect visibleAreaOfItemGroup = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + if (GridType.Horizontal == gridType) + { + if (bPrev) + { + visibleAreaOfItemGroup.X -= gridWidth; + if (0 > visibleAreaOfItemGroup.X) + { + visibleAreaOfItemGroup.X = 0; + } + } + else + { + visibleAreaOfItemGroup.X += gridWidth; + if (-visibleAreaOfItemGroup.X + itemGroupRect.Width < gridWidth) + { + visibleAreaOfItemGroup.X = itemGroupRect.Width - gridWidth; + } + } + + if (-itemGroupRect.X == visibleAreaOfItemGroup.X) + { + return; + } + } + else + { + if (bPrev) + { + visibleAreaOfItemGroup.Y -= gridHeight; + if (0 > visibleAreaOfItemGroup.Y) + { + visibleAreaOfItemGroup.Y = 0; + } + } + else + { + visibleAreaOfItemGroup.Y += gridHeight; + if (-visibleAreaOfItemGroup.Y + itemGroupRect.Height < gridHeight) + { + visibleAreaOfItemGroup.Y = itemGroupRect.Height - gridHeight; + } + } + + if (-itemGroupRect.Y == visibleAreaOfItemGroup.Y) + { + return; + } + } + + Range newRange = new Range(0, 0, 0, 0); + GetOnscreenRange(visibleAreaOfItemGroup, ref newRange, true); + + Group curFocusedGroup = groupList.ElementAt(focusGroupIndex); + Cell curFocusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + Column curFocusedColumn = curFocusedGroup.columnList.ElementAt(curFocusedCell.columnIndex); + + float focusStartLine = curFocusedColumn.startPos; + float focusEndLine = curFocusedColumn.endPos; + float focusMiddleLine = 0; + + if (newRange.startGroupInScrn >= 0 && newRange.endGroupInScrn >= 0) + { + if (GridType.Horizontal == gridType) + { + focusStartLine = focusStartLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + focusEndLine = focusEndLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + } + else + { + focusStartLine = focusStartLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + focusEndLine = focusEndLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + } + + focusMiddleLine = focusStartLine + (focusEndLine - focusStartLine) / 2; + + int nextFocusGroup = -1; int nextFocusColumn = -1; + bool bFound = false; + for (int i = newRange.startGroupInScrn; i <= newRange.endGroupInScrn && bFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + + int startColumnIndex = (i == newRange.startGroupInScrn) ? newRange.startColumnInScrn : 0; + int endColumnIndex = (i == newRange.endGroupInScrn) ? newRange.endColumnInScrn : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= focusMiddleLine && curColumn.endPos >= focusMiddleLine) + { + nextFocusGroup = i; + nextFocusColumn = j; + bFound = true; + break; + } + } + + if (bFound == false && i == newRange.startGroupInScrn && focusMiddleLine < curGroup.columnList.ElementAt(startColumnIndex).startPos) + { + nextFocusGroup = i; + nextFocusColumn = startColumnIndex; + break; + } + + else if (bFound == false && i == newRange.endGroupInScrn && focusMiddleLine > curGroup.columnList.ElementAt(endColumnIndex).endPos) + { + nextFocusGroup = i; + nextFocusColumn = endColumnIndex; + break; + } + } + + if (nextFocusGroup >= 0 && nextFocusColumn >= 0) + { + int nextFocusItem = -1; + GetNearestItem(curFocusedCell, nextFocusGroup, nextFocusColumn, ref nextFocusItem); + + if (nextFocusItem >= 0) + { + while (gridBridge.IsItemEnabled(nextFocusGroup, nextFocusItem) == false) + { + nextFocusItem = GetNextColumnIndex(bPrev, nextFocusColumn, ref nextFocusGroup); + } + + if (nextFocusItem >= 0) + { + Position newItemGroupPos = new Position(-visibleAreaOfItemGroup.X, -visibleAreaOfItemGroup.Y, 0); + SetFocus(nextFocusGroup, nextFocusItem, bAni, newItemGroupPos); + } + } + } + } + } + + private int GetNextColumnIndex(bool bPrev, int curColumnIndex, ref int curGroupIndex) + { + if (bPrev == true) + { + if (curColumnIndex == 0) + { + if (curGroupIndex == 0) + { + return -1; + } + else + { + curGroupIndex--; + return groupList.ElementAt(curGroupIndex).columnList.Count - 1; + } + } + else + { + return curColumnIndex - 1; + } + } + else + { + Group curGroup = groupList.ElementAt(curGroupIndex); + if (curGroup.columnList.Count - 1 == curColumnIndex) + { + if (groupList.Count - 1 == curGroupIndex) + { + return -1; + } + else + { + curGroupIndex++; + return 0; + } + } + else + { + return curColumnIndex + 1; + } + } + } + + private class GridItem + { + public void ScaleItem(Vector3 scaleFactor, AnimationAttributes aniAttrs) + { + if (itemView == null || scaleFactor == null || aniAttrs == null) + { + return; + } + + if (scaleAni == null) + { + scaleAni = new Animation(); + } + + if (scaleAni.State == Animation.States.Playing) + { + scaleAni.Stop(Animation.EndActions.StopFinal); + } + + scaleAni.Clear(); + scaleAni.AnimateTo(itemView, "Scale", scaleFactor, 0, aniAttrs.Duration, new AlphaFunction(aniAttrs.BezierPoint1, aniAttrs.BezierPoint2)); + scaleAni.Play(); + } + + public int groupIndex; + public int index; + + public View itemView; + public Rect rect; + + private Animation scaleAni = null; + } + + private class Cell + { + public int columnIndex; + public int index; + public int itemIndex; + public int rowIndex; + + public Rect rect; + public Cell() + { + rect = new Rect(0, 0, 0, 0); + } + } + + private class Column + { + public int groupIndex; + public int index; + + public float space; + public float startPos; + public float endPos; + + public int startItemIndex; + public int endItemIndex; + + public List cellList; + } + + private class Group + { + public int index; + + public float startPos; + public float endPos; + + public int realCellCount; + public int lastFilledColumnIndex; + + public List columnList; + public List itemList; + public Dictionary itemIndexToCell; + + public void ResetPosition(float posOffset) + { + startPos += posOffset; + endPos += posOffset; + + int count = columnList.Count; + for (int i = 0; i < count; i++) + { + Column column = columnList.ElementAt(i); + column.startPos += posOffset; + column.endPos += posOffset; + + int cellCount = column.cellList.Count; + for (int j = 0; j < cellCount; j++) + { + column.cellList.ElementAt(j).rect.X += posOffset; + } + } + } + + public View title; + } + + private class Range + { + public int startGroupIndex; + public int startColumnIndex; + + public int endGroupIndex; + public int endColumnIndex; + + public int startGroupInScrn; + public int startColumnInScrn; + + public int endGroupInScrn; + public int endColumnInScrn; + + public int startItemIndexInScrn; + public int endItemIndexInScrn; + + public Range() + { + startGroupIndex = 0; + startColumnIndex = 0; + endGroupIndex = 0; + endColumnIndex = 0; + } + + public Range(int a, int b, int c, int d) + { + startGroupIndex = a; + startColumnIndex = b; + endGroupIndex = c; + endColumnIndex = d; + } + } + + private class FocusMoveViaObject + { + public int toGroupIndex; + public int toItemIndex; + } + + const int INVALID_COUNT = -1; + + private List groupList; + private GridBridge gridBridge; + + private View itemGroup; + private Rect itemGroupRect; + + private Vector4 margin = Vector4.Zero; + + private float gridWidth; + private float gridHeight; + + private int preloadFrontColumnSize = 1; + private int preloadBackColumnSize = 1; + + //layout attributes + private GridType gridType = GridType.Horizontal; + private int groupSpace = 0; + private int columnSpace = 0; + private int rowSpace = 0; + private int titleSpace = 0; + + private int rowCnt = 0; + private int colCnt = 0; + private int colW = 0; + private int rowH = 0; + + //focus + private int focusGroupIndex; + private int focusItemIndex; + + private float refXForFocusMove; + private float refYForFocusMove; + + private int focusTagGroupIndex; + private int focusTagItemIndex; + //animation + LinkerAnimation focusMoveAni; + + private float focusInScaleFactor; + + private AnimationAttributes focusInScaleAnimationAttrs; + + private AnimationAttributes focusOutScaleAnimationAttrs; + + private int focusMoveAniDuration; + + private Queue focusMoveViaQ = new Queue(); + + //for load + private HashSet curInMemoryItemSet; + private HashSet nextInMemoryItemSet; + + private Rect lastVisibleArea; + + private Range onScreenRange; + + //reuse + private List[] recycledViews; + private int viewTypeCount; + + private EventHandler gridEventHandlers; + } + + /// + /// The attributes of Animation. + /// + /// + /// AnimationAttributes attrs = new AnimationAttributes(); + /// attrs.BezierPoint1 = new Vector2(0.21f, 2); + /// attrs.BezierPoint2 = new Vector2(0.14f, 1); + /// attrs.Duration = 1000; + /// + public class AnimationAttributes + { + /// V1 on bezier curve + public Vector2 BezierPoint1; + /// V2 on bezier curve + public Vector2 BezierPoint2; + /// Animation duration + public int Duration; + + /// + /// Constructs a AnimationAttributes.. + /// + public AnimationAttributes() + { + } + + /// + /// Constructs a AnimationAttributes with curve style.. + /// + /// curve + public AnimationAttributes(string curve) + { + } + + /// + /// Constructs a AnimationAttributes that is a copy of attrs.. + /// + /// Construct Attributes + public AnimationAttributes(AnimationAttributes attrs = null) + { + if (attrs == null) + { + return; + } + + if (attrs.BezierPoint1 != null) + { + BezierPoint1 = new Vector2(attrs.BezierPoint1[0], attrs.BezierPoint1[1]); + } + + if (attrs.BezierPoint2 != null) + { + BezierPoint2 = new Vector2(attrs.BezierPoint2[0], attrs.BezierPoint2[1]); + } + + Duration = attrs.Duration; + } + + /// Clone a AnimationAttributes + /// The AnimationAttributes copy + public AnimationAttributes Clone() + { + return new AnimationAttributes(this); + } + } + + /// + /// A GridBridge object acts as a pipeline between an BridgeView and the + /// underlying data for that view. The Bridge provides access to the data items. + /// The Bridge is also responsible for making a View for each item in the data set. + /// + public abstract class GridBridge + { + /// + /// Event type of data change. + /// + public enum DataChangeEventType + { + Add, + Remove, + Insert, + Clear, + Load, + Reset + } + + /// + /// Data change event args at event call back, + /// user can get information about data change. + /// + /// + ///private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + ///{ + ///} + /// + public class DataChangeEventArgs : EventArgs + { + /// + /// Data changed event type. + /// + public DataChangeEventType ChangeType + { + get { return m_ChangeType; } + set { m_ChangeType = value; } + } + + /// + /// Changed data. + /// + public object data; + /// + /// Data change event parameters. + /// + public int[] param = new int[4]; + + private DataChangeEventType m_ChangeType; + } + + /// + /// Event handler of data change event. + /// + /// The object who sends the event. + /// The event arguments. + public delegate void EventHandler(object sender, DataChangeEventArgs e); + + /// + /// Data change event handler, user can add/remove. + /// + public event EventHandler DataChangeEvent + { + add + { + dataChangeEventHandlers += value; + } + + remove + { + dataChangeEventHandlers -= value; + } + } + + /// + /// Constructor to create a grid view bridge with multi-groups. + /// + /// Data list of differet groups. + public GridBridge(List> objects) + { + gridData = objects; + } + + /// + /// Simple constructor to create a grid view bridge with one group. + /// + /// Data list of grid view. + public GridBridge(List objects) + { + gridData = new List>(); + gridData.Add(objects); + } + + /// + /// Create item View. + /// + /// Group index of item in grid view. + /// Item index of specified group of grid view. + /// View of specified item. + public abstract View GetItemView(int groupIndex, int itemIndex); + + /// + /// Create group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual View GetGroupTitleView(int groupIndex) + { + return null; + } + + /// + /// Remove group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual void RemoveGroupTitleView(int groupIndex, View groupTitle) + { + + } + + /// + /// Update View that displays the data at the specified index in the data set when data change. + /// + /// The group index. + /// The item index. + /// A View that displays the data at the specified index in the data set. + public abstract void UpdateItem(int groupIndex, int itemIndex, View view); + + /// + /// Update View that displays the data at the specified index in the data set when focus change. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + /// Focus in or focus out + /// LinearView item selected or not. + public abstract void FocusChange(int groupIndex, int itemIndex, View view, bool FlagFocused, bool bSelected = false); + + /// + /// Unload view at the specified index when item scroll out or deleted. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + public abstract void UnloadItem(int groupIndex, int itemIndex, View view); + + /// + /// Unload view according to the specified viewType. + /// + /// Item type set by users. + /// A View that displays the data at the specified index in the data set. + public abstract void UnloadItemByViewType(int viewType, View view); + + /// + /// Get the type of View that will be created by GetView for the specified item. + /// + /// The group index. + /// The item index. + /// Integers must be in the range 0 to GetItemTypeCount() - 1. + /// Item type. + public virtual int GetItemType(int groupIndex, int itemIndex) + { + return 0; + } + + /// + /// Get the number of view types. + /// + /// The count of view type. + public virtual int GetItemTypeCount() + { + return 1; + } + + /// + /// Check whether item is enable or not. + /// + /// The group index. + /// The item index. + /// Item is enabled or disabled. + public virtual bool IsItemEnabled(int groupIndex, int itemIndex) + { + return true; + } + + /// + /// Get the data at the specified index. + /// + /// The item index. + /// The group index. + /// The data at the specified index. + public object GetData(int itemIndex, int groupIndex = 0) + { + object data = null; + if (gridData != null && gridData.ElementAt(groupIndex) != null && itemIndex >= 0 && itemIndex < gridData.ElementAt(groupIndex).Count) + { + data = gridData.ElementAt(groupIndex).ElementAt(itemIndex); + } + + return data; + } + + /// + /// Get data group count of the bridge. + /// + /// Group count of the data set. + public int GetGroupCount() + { + int count = 0; + if (gridData != null) + { + count = gridData.Count; + } + + return count; + } + + /// + /// How many items are in the data set of specified group. + /// + /// The data group index. + /// Count of items of specified group. + public int GetItemCount(int groupIndex = 0) + { + int count = 0; + if (gridData != null && gridData.ElementAtOrDefault(groupIndex) != null) + { + count = gridData.ElementAt(groupIndex).Count; + } + + return count; + } + + /// + /// How many items are in the data set of whole data list. + /// + /// Count of total items + public int GetTotalCount() + { + int count = 0; + if (gridData != null) + { + foreach (List group in gridData) + { + count += group.Count; + } + } + + return count; + } + + /// + /// Adds the specified data at the end of the List of specified group. + /// + /// The data to add at the end of the List. + /// The group index which need to add data. + /// Notify list to remove item or not. + public void Add(object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Add(data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Add; + e.param[0] = groupIndex; + e.data = data; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The remove number of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + + public void RemoveItems(int fromIndex, int removeNum, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + if (fromIndex + removeNum > gridData[groupIndex].Count) + { + return; + } + + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Remove; + e.param[0] = groupIndex; + e.param[1] = fromIndex; + e.param[2] = removeNum; + e.param[3] = withAni ? 1 : 0; + OnDataChangeEvent(this, e, sendEvent); + gridData[groupIndex].RemoveRange(fromIndex, removeNum); + e.ChangeType = DataChangeEventType.Load; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + public void Remove(int itemIndex, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + if (itemIndex < 0 || itemIndex >= GetItemCount(groupIndex)) + { + Tizen.Log.Fatal("NUI", "Error!! item index is invalid"); + return; + } + + RemoveItems(itemIndex, 1, groupIndex, withAni, sendEvent); + } + + /// + /// Inserts the specified data at the specified index in the List of specified group. + /// + /// The index at which the data must be inserted. + /// The data to insert into the list. + /// The group index which need to insert data. + /// Notify list to remove item or not. + public void Insert(int index, object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Insert(index, data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Insert; + e.data = data; + e.param[0] = groupIndex; + e.param[1] = index; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Remove all elements from the list. + /// + /// Notify list to remove item or not. + public void Clear(bool sendEvent = true) + { + if (gridData != null) + { + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Clear; + OnDataChangeEvent(this, e, sendEvent); + gridData.Clear(); + } + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of differet groups. + /// Notify list to remove item or not. + public void Reset(List> objects, bool sendEvent = true) + { + Clear(); + gridData = objects; + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of grid view. + /// Notify list to remove item or not. + public void Reset(List objects, bool sendEvent = true) + { + Clear(); + gridData = new List>(); + gridData.Add(objects); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Swap data of specified group. + /// + /// The group index which need to insert data. + /// First item index of the group. + /// Second item index of the group. + public void SwapGroupData(int groupIndex, int from, int to) + { + List groupDataList = gridData.ElementAt(groupIndex); + object fromData = groupDataList.ElementAt(from); + groupDataList[from] = groupDataList[to]; + groupDataList[to] = fromData; + } + + private void OnDataChangeEvent(object sender, DataChangeEventArgs e, bool sendEvent = true) + { + if (!sendEvent) + { + return; + } + + if (dataChangeEventHandlers != null) + { + dataChangeEventHandlers(sender, e); + } + } + + private List> gridData; + private EventHandler dataChangeEventHandlers; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `curFocusedCell` last assigned on line 1735 could be null and is dereferenced at line 1749, column 13. + +### Severity: +ERROR + +### Procedure: +Void GridView.MoveFocus(String,Int32,Int32) + +### File: +TV/MediaHubSample/MediaHubSample/src/View/GridView/Grid.cs + +### Key: +Grid.cs|MoveFocus|NULL_DEREFERENCE + +### Node Key: +31b38c1bf5e12b39f64b6563a58bebed + +### Hash: +cb75677025efdadd47289f6deab9aca5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0769/instruction.md b/inferredbugs-0769/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..935c4beac958195d8362e0bd38c7caa6d11c56b1 --- /dev/null +++ b/inferredbugs-0769/instruction.md @@ -0,0 +1,3833 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Tizen-CSharp-Samples +**Bug ID:** 2 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +/** Copyright (c) 2017 Samsung Electronics Co., Ltd. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Diagnostics; +using Tizen.NUI; +using Tizen.NUI.BaseComponents; + +namespace Tizen.NUI +{ + /// + /// A view that shows items in two-dimension grid, which can scroll horizontally or vertically. + /// The items in the grid come from the GirdBridge associated with this view. + /// + public class GridView : View + { + /// + /// GridView event types + /// + public enum GridEventType + { + /// + /// Event triggered when focus change + /// + FocusChange, + /// + /// Event triggered when item scroll in + /// + ItemScrolledIn, + /// + /// Event triggered when item scroll out + /// + ItemScrolledOut, + } + + /// + /// GridView orientation types + /// + public enum GridType + { + /// + /// Items laid horizontal + /// + Horizontal = 0, + /// + /// Items laid vertical + /// + Vertical + } + + /// + /// GridView event args at event call back, user can get information + /// + public class GridEventArgs : EventArgs + { + /// + /// GridView event type + /// + public GridEventType EventType + { + get; + set; + } + + /// + /// GridView event data + /// + public int[] param = new int[4]; + } + + /// + /// Construct GridView. + /// + public GridView() + { + Initialize(); + + // register event handler for relayout + Relayout += OnRelayoutUpdate; + + FocusGained += ControlFocusGained; + FocusLost += ControlFocusLost; + } + + /// + /// Get/Set list type. + /// + public GridType Type + { + get { return gridType; } + set { gridType = value; } + } + + /// + /// Get/Set list spaces around items. + /// + public new Vector4 Margin + { + get { return margin; } + set { margin = value; } + } + + /// + /// Get/Set space between columns + /// + public int ColumnSpace + { + get { return columnSpace; } + set { columnSpace = value; } + } + + /// + /// Get/Set space between rows + /// + public int RowSpace + { + get { return rowSpace; } + set { rowSpace = value; } + } + + /// + /// Get/Set space between groups + /// + public int GroupSpace + { + get { return groupSpace; } + set { groupSpace = value; } + } + + /// + /// Get/Set space for title + /// + public int TitleSpace + { + get { return titleSpace; } + set { titleSpace = value; } + } + + /// + /// Get/Set enable flag of whether support straight path focus move. + /// + public bool StateStraightPathEnable + { + get; + set; + } + /// + /// Get/Set enable flag of right circulation of GridView. + /// + public bool StateRightCircularEnable + { + get; + set; + } + + /// + /// Get/Set enable flag of left circulation of GridView. + /// + public bool StateLeftCircularEnable + { + get; + set; + } + + /// + /// Get/Set focus move animation duration of GridView. + /// + public int FocusMoveDuration + { + get + { + return focusMoveAniDuration; + } + + set + { + focusMoveAniDuration = value; + //focusMoveAni.Duration = value; + //scaleAni.Duration = value; + } + } + + /// + /// Get/Set scroll bar fade out time + /// + public int ScrollBarFadeOutDuration + { + get; + set; + } + + + /// + /// Preload item buffer size at front + /// + public int PreloadFrontColumnSize + { + get { return preloadFrontColumnSize; } + set { preloadFrontColumnSize = value ; } + } + + /// + /// Preload item buffer size at back + /// + public int PreloadBackColumnSize + { + get { return preloadBackColumnSize; } + set { preloadBackColumnSize = value; } + } + + /// + /// Focus in scale factor + /// + public float FocusInScaleFactor + { + get { return focusInScaleFactor; } + set { focusInScaleFactor = value; } + } + + /// + /// Focus in scale animation duration + /// + public AnimationAttributes FocusInScaleAnimationAttrs + { + get { return focusInScaleAnimationAttrs; } + set { focusInScaleAnimationAttrs = value; } + } + + /// + /// Focus out scale animation duration + /// + public AnimationAttributes FocusOutScaleAnimationAttrs + { + get { return focusOutScaleAnimationAttrs; } + set { focusOutScaleAnimationAttrs = value; } + } + /// + /// Sets the data behind this GridView. + /// + /// The GridBridge which is responsible for maintaining the data + /// backing this grid and for producing a view to represent an item in the data set. + public void SetBridge(GridBridge bridge) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set bridge for GridView")); + Debug.Assert(bridge != null); + + if (gridBridge != null) + { + return; + } + + gridBridge = bridge; + + gridBridge.DataChangeEvent += OnDataChange; + + for (int i = 0; i < groupList.Count; i++) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + groupList[i].title = groupTitle; + + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = groupList[i].startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = groupList[i].startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + SetViewTypeCount(gridBridge.GetItemTypeCount()); + + + if (groupList.Count > 0) + { + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + /// + /// Add groups to GridView. + /// + /// The count of groups to add. + public void AddGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add Group Number{0}", groupCount)); + int prevCount = groupList.Count; + for (int i = prevCount; i < groupCount + prevCount; i++) + { + Group newGroup = new Group(); + newGroup.index = i; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + + if (GridType.Horizontal == gridType) + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos); + } + else + { + newGroup.startPos = newGroup.endPos = (i == 0 ? 0 : groupSpace + groupList.ElementAt(i - 1).endPos + titleSpace); + } + + if (gridBridge != null) + { + View groupTitle = gridBridge.GetGroupTitleView(i); + if (groupTitle != null) + { + newGroup.title = groupTitle; + if (GridType.Horizontal == gridType) + { + groupTitle.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + groupTitle.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + groupTitle.PositionUsesPivotPoint = true; + groupTitle.PositionX = newGroup.startPos; + groupTitle.PositionY = -titleSpace; + Tizen.Log.Fatal("NUI", "titleView.PositionX: " + groupTitle.PositionX + ", titleView.PositionY: " + groupTitle.PositionY); + } + else + { + groupTitle.PositionX = 0; + groupTitle.PositionY = newGroup.startPos - titleSpace; + } + + itemGroup.Add(groupTitle); + } + } + + groupList.Add(newGroup); + } + } + + internal void ResetGroup(int groupCount) + { + Tizen.Log.Fatal("NUI", "...." + groupCount); + if (groupList.Count < groupCount) + { + AddGroup(groupCount - groupList.Count); + } + else if (groupList.Count > groupCount) + { + int removeCount = groupList.Count - groupCount; + for (int i = groupCount; i < groupList.Count; i++) + { + if (groupList.ElementAt(i).title != null) + { + itemGroup.Remove(groupList.ElementAt(i).title); + gridBridge.RemoveGroupTitleView(i, groupList.ElementAt(i).title); + } + + Clear(i); + } + + groupList.RemoveRange(groupCount, removeCount); + } + } + + // Add column to GridView. + internal void AddColumn(int columnWidth, int groupIndex = 0) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add column columnWidth {0} to group {1}",columnWidth, groupIndex)); + + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + Column newColumn = new Column(); + newColumn.groupIndex = groupIndex; + newColumn.index = curGroup.columnList.Count; + newColumn.space = columnWidth; + + if (newColumn.index == 0) + { + newColumn.startPos = curGroup.startPos; + } + else + { + newColumn.startPos = curGroup.columnList.ElementAt(newColumn.index - 1).endPos + columnSpace; + } + + newColumn.endPos = newColumn.startPos + columnWidth; + + if (newColumn.cellList == null) + { + newColumn.cellList = new List(); + } + + curGroup.columnList.Add(newColumn); + + float posOffset = (0 == newColumn.index) ? columnWidth : columnWidth + columnSpace; + curGroup.endPos += posOffset; + + for (int i = groupIndex + 1; i < (int)groupList.Count; i++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(i).title != null) + { + groupList.ElementAt(i).title.PositionX += posOffset; + } + + groupList.ElementAt(i).ResetPosition(posOffset); + } + + Tizen.Log.Fatal("NUI", "..."); + return; + } + /// + /// Add row to the column in GridView. + /// + /// The column index; + /// The row space. + /// The group index. + public void AddRowToColumn(int columnIndex, int rowHeight, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to column {1} of group {2}", rowHeight, columnIndex, groupIndex)); + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + Column curColumn = curGroup.columnList.ElementAt(columnIndex); + + int curRowNumInCol = curColumn.cellList.Count; + + Cell newCell = new Cell(); + + Cell lastCell = (curRowNumInCol == 0 ? null : curColumn.cellList.ElementAt(curRowNumInCol - 1)); + + if (GridType.Horizontal == gridType) + { + newCell.rect.X = curColumn.startPos; + newCell.rect.Y = (curRowNumInCol == 0 ? 0 : lastCell.rect.Bottom() + rowSpace); + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + else + { + newCell.rect.X = (curRowNumInCol == 0) ? 0 : lastCell.rect.Right() + columnSpace; + newCell.rect.Y = curColumn.startPos; + newCell.rect.Height = rowHeight; + newCell.rect.Width = curColumn.space; + } + + newCell.columnIndex = columnIndex; + newCell.rowIndex = curRowNumInCol; + newCell.index = curRowNumInCol; + if (curRowNumInCol == 0) + { + if (columnIndex == 0) + { + newCell.itemIndex = 0; + } + else + { + newCell.itemIndex = curGroup.columnList.ElementAt(columnIndex - 1).endItemIndex + 1; + } + } + else + { + newCell.itemIndex = lastCell.itemIndex + 1; + } + + Tizen.Log.Fatal("NUI", " >>>>>>> newCell.itemIndex: " + newCell.itemIndex + " newCell.rect[" + newCell.rect.X + ", " + newCell.rect.Y + ", " + newCell.rect.Width + ", " + newCell.rect.Height + "]"); + + curColumn.cellList.Add(newCell); + Tizen.Log.Fatal("NUI", "..."); + + if (curRowNumInCol == 0) + { + curColumn.startItemIndex = newCell.itemIndex; + } + + curColumn.endItemIndex = newCell.itemIndex; + Tizen.Log.Fatal("NUI", " >>>>>>> curColumn.startItemIndex: " + curColumn.startItemIndex + " curColumn.endItemIndex: " + curColumn.endItemIndex); + + curGroup.itemIndexToCell.Add(newCell.itemIndex, newCell); + curGroup.realCellCount++; + + Tizen.Log.Fatal("NUI", "Group: " + groupIndex + ", Column: " + columnIndex + " Cell.rowIndex: " + newCell.rowIndex + " Cell.columnIndex: " + newCell.columnIndex + " Cell.itemIndex: " + newCell.itemIndex + " curGroup.realCellCount:" + curGroup.realCellCount); + } + + // Add row to the all column in same group of GridView. + internal void AddRowToAllColumn(int rowHeight, int groupIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row rowHeight {0} to to all column of group {1}", rowHeight, groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + int columnCount = groupList.ElementAt(groupIndex).columnList.Count; + for (int i = 0; i < columnCount; i++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + /// + /// Quickly add an regular grid by pass column/row number and cell size. + /// + /// The columns count. + /// The rows count. + /// The column width. + /// The row height. + /// The groupIndex, default value is -1, means all the groups will use the same regular grid. + public void AddRegularGrid(int columnCount, int rowCount, int columnWidth, int rowHeight, int groupIndex = -1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Add row x column : ({0} x {1}) rowHeight: {2} , columnWidth: {3} to group {4}", rowCount, columnCount, rowHeight, columnWidth, groupIndex)); + + if (groupIndex != -1) + { + if (groupList.Count == 0) + { + Group newGroup = new Group(); + newGroup.index = 0; + newGroup.columnList = new List(); + newGroup.itemList = new List(); + newGroup.itemIndexToCell = new Dictionary(); + newGroup.startPos = newGroup.endPos = 0; + groupList.Add(newGroup); + } + else if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + } + + if (gridType == GridType.Vertical) + { + int temp = rowCount; + rowCount = columnCount; + columnCount = temp; + } + + this.rowCnt = rowCount; + this.colCnt = columnCount; + this.rowH = rowHeight; + this.colW = columnWidth; + + if (columnCount == -1) + { + return; + } + + if (groupIndex == -1) + { + for (int k = 0; k < groupList.Count; k++) + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + else + { + for (int i = 0; i < columnCount; i++) + { + AddColumn(columnWidth, groupIndex); + + for (int j = 0; j < rowCount; j++) + { + AddRowToColumn(i, rowHeight, groupIndex); + } + } + } + } + + /// + /// Attach title to the group. + /// + /// The title view. + /// The group index. + public void AttachGroupTitle(View titleView, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Attach group title to {0}", groupIndex)); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (GridType.Horizontal == gridType) + { + titleView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + titleView.PivotPoint = Tizen.NUI.PivotPoint.BottomLeft; + titleView.PositionUsesPivotPoint = true; + titleView.PositionX = curGroup.startPos; + titleView.PositionY = -titleSpace; + } + else + { + titleView.PositionX = 0; + titleView.PositionY = curGroup.startPos - titleSpace; + } + + curGroup.title = titleView; + itemGroup.Add(titleView); + } + + /// + /// Get group title of specified group index. + /// + /// Group index of GridIndex view. + /// Title view of specified group index. + public View GetGroupTitle(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + return groupList[groupIndex].title; + } + + /// + /// Set focus group index and item index of GridView. + /// + /// focus item index + /// focus group index + public void SetFoucsItemIndex(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Set Focus to item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid item index")); + return; + } + + if (groupIndex == focusGroupIndex && itemIndex == focusItemIndex) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Already focused")); + return; + } + //if (IsFocused == true) + //{ + // SetFocus(groupIndex, itemIndex); + //} + if (HasFocus() == true) + { + SetFocus(groupIndex, itemIndex); + } + else + { + focusGroupIndex = groupIndex; + focusItemIndex = itemIndex; + focusTagGroupIndex = focusGroupIndex; + focusTagItemIndex = focusItemIndex; + } + } + + /// + /// Get focus group index and item index of GridView. + /// + /// focus group index + /// focus item index + public void GetFocusItemIndex(out int groupIndex, out int itemIndex) + { + groupIndex = focusGroupIndex; + itemIndex = focusItemIndex; + } + + /// + /// Get loaded item view in GridView. + /// + /// Specified group index + /// Specified item index + /// Return the ItemView, if the item is unloaded, returns null. + public object GetLoadedItemView(int groupIndex, int itemIndex) + { + GridItem item = null; + if (IsGroupIndexValid(groupIndex) == true && IsItemIndexValid(groupIndex, itemIndex)) + { + item = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + } + + return item?.itemView; + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MoveNextPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to next page")); + PageMove(false, bAni); + } + + /// + /// User to do the page move. + /// + /// Used to control whether support animation. + public void MovePrevPage(bool bAni = true) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Move to previous page")); + PageMove(true, bAni); + } + + /// + /// Update an item. + /// + /// The itemIndex. + /// The groupIndex. + public void UpdateItem(int itemIndex, int groupIndex = 0) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Update item {0} of group {1}", itemIndex, groupIndex)); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return; + } + + Cell curCell = GetCellByItemIndex(groupIndex, itemIndex); + int columnIndex = curCell.columnIndex; + + if ((groupIndex > onScreenRange.startGroupIndex && groupIndex < onScreenRange.endGroupIndex) + || (groupIndex == onScreenRange.startGroupIndex && columnIndex >= onScreenRange.startColumnIndex) + || (groupIndex == onScreenRange.endGroupIndex && columnIndex <= onScreenRange.endColumnIndex)) + { + gridBridge.UpdateItem(groupIndex, itemIndex, groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex).itemView); + } + } + /// + /// Update all items on screen. + /// + public void UpdateAllItems() + { + foreach (GridItem item in curInMemoryItemSet) + { + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + } + /// + /// Get group number of GridView. + /// + /// Groups count + public int GetGroupCount() + { + return groupList.Count; + } + /// + /// Get column count of specified group. + /// + /// The group index. + /// Columns count + public int GetColumnCount(int groupIndex) + { + Tizen.Log.Fatal("NUI", "... groupIndex = " + groupIndex); + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + if (curGroup.columnList == null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column list")); + return INVALID_COUNT; + } + + Tizen.Log.Fatal("NUI", "... curGroup.columnList.Count = " + curGroup.columnList.Count); + return curGroup.columnList.Count; + } + /// + /// Get cell count of specified column of specified group. + /// + /// The group index. + /// The column index. + /// Cells count + public int GetCellCount(int groupIndex, int columnIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + if (curColumn.cellList == null) + { + return INVALID_COUNT; + } + + return curColumn.cellList.Count; + } + + + /// + /// Get item count of a group. + /// + /// The group index. + /// Items count + public int GetItemCount(int groupIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return INVALID_COUNT; + } + + Group curGroup = groupList.ElementAt(groupIndex); + return curGroup.itemList.Count; + } + /// + /// Get the GridBridge of GridView. + /// + /// The GridBridge of GridView. + public GridBridge GetBridge() + { + return gridBridge; + } + /// + /// Get on screen item range. + /// + /// The group index of start range. + /// The item index of start range. + /// The group index of end range. + /// The item index of end range. + public void GetOnscreenRange(out int startGroupIndex, out int startItemIndex, out int endGroupIndex, out int endItemIndex) + { + startGroupIndex = onScreenRange.startGroupInScrn; + startItemIndex = onScreenRange.startItemIndexInScrn; + endGroupIndex = onScreenRange.endGroupInScrn; + endItemIndex = onScreenRange.endItemIndexInScrn; + } + + /// + /// Move focus according to parameter direction + /// + /// Focus move direction, can be "Left", "Right", "Up" or "Down" + public void Move(string direction) + { + MoveFocus(direction); + } + + /// + /// Get screen position of specified item. + /// + /// Group index of linear view. + /// Item index of group. + /// + /// Thrown when groupIndex or item index is invalid. + /// + /// Screen position of specified item. + public Position2D GetItemScreenPosition(int groupIndex, int itemIndex) + { + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + throw new ArgumentException("Group index or item index is invalid"); + } + + GridItem curItem = groupList.ElementAt(groupIndex).itemList.ElementAt(itemIndex); + return curItem?.itemView?.ScreenPosition; + } + + /// + /// Dispose of GridView. + /// + /// Dispose caused type + protected override void Dispose(DisposeTypes type) + { + if (disposed) + { + return; + } + + if (type == DisposeTypes.Explicit) + { + //Called by User + //Release your own managed resources here. + //You should release all of your own disposable objects here. + + Tizen.Log.Fatal("NUI", string.Format("[GridView]Dispose")); + focusMoveAni?.Stop(); + focusMoveAni?.Dispose(); + focusMoveAni = null; + + ClearRecycleBin(); + ResetGroup(0); + } + + //Release your own unmanaged resources here. + //You should not access any managed member here except static instance. + //because the execution order of Finalizes is non-deterministic. + //Unreference this from if a static instance refer to this. + + //You must call base.Dispose(type) just before exit. + base.Dispose(type); + } + + /// + /// GridView event handler + /// + public event EventHandler GridEvent + { + add + { + gridEventHandlers += value; + } + + remove + { + gridEventHandlers -= value; + } + } + /// + /// Update when GridView attributes changed. + /// + /// the object + /// the args of the event + protected void OnRelayoutUpdate(object sender, EventArgs e) + { + gridWidth = this.SizeWidth; + gridHeight = this.SizeHeight; + Tizen.Log.Fatal("NUI", "...OnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdateOnRelayoutUpdate..."); + if (gridBridge != null) + { + Load(); + + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(focusGroupIndex, focusItemIndex); + } + } + } + + private void OnListEvent(GridEventArgs e) + { + if (gridEventHandlers != null) + { + gridEventHandlers(this, e); + } + } + + private void Initialize() + { + ClippingMode = ClippingModeType.ClipChildren; + + + groupList = new List(); + itemGroup = new View(); + itemGroup.Name = "ItemGroup"; + itemGroup.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + itemGroup.PivotPoint = Tizen.NUI.PivotPoint.TopLeft; + this.Add(itemGroup); + + itemGroupRect = new Rect(0, 0, 0, 0); + + curInMemoryItemSet = new HashSet(); + nextInMemoryItemSet = new HashSet(); + + lastVisibleArea = new Rect(0, 0, 0, 0); + onScreenRange = new Range(-1, -1, -1, -1); + + refXForFocusMove = -1; + refYForFocusMove = -1; + + focusGroupIndex = 0; + focusItemIndex = 0; + + focusTagGroupIndex = 0; + focusTagItemIndex = 0; + + StateRightCircularEnable = false; + StateLeftCircularEnable = false; + + + focusMoveAni = new LinkerAnimation(itemGroup, 100, 100, 0); + focusMoveAni.ViaEvent += OnFocusMoveViaEvent; + + ScrollBarFadeOutDuration = 1000; + } + + private void Load() + { + Tizen.Log.Fatal("NUI", "...lOAD..."); + int groupCount = groupList.Count; + if (groupCount == 0) + { + return; + } + + for (int i = 0; i < groupCount; i++) + { + Group curGroup = groupList.ElementAt(i); + int dataCount = gridBridge.GetItemCount(i); + + int finalCount = curGroup.realCellCount < dataCount ? curGroup.realCellCount : dataCount; + + int bindedItemCount = curGroup.itemList.Count; + + for (int j = 0; j < finalCount; j++) + { + GridItem newItem; + if (j < bindedItemCount) + { + newItem = curGroup.itemList.ElementAt(j); + } + else + { + Cell curCell = curGroup.itemIndexToCell[j]; + newItem = new GridItem(); + newItem.groupIndex = i; + newItem.index = j; + newItem.rect = curCell.rect; + curGroup.itemList.Add(newItem); + } + } + + //add for right move between group when not all columns filled + if (finalCount >= 1) + { + Cell lastItemCell = GetCellByItemIndex(i, finalCount - 1); + curGroup.lastFilledColumnIndex = lastItemCell.columnIndex; + } + } + + UpdateItemGroupSize(); + + InitItemGroupPosition(); + UpdateInMemoryItems(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + private void UpdateInMemoryItems() + { + Rect windowRect = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + Tizen.Log.Fatal("NUI", ">>>>>>>>> loadItemList.Count: " + loadItemList.Count + " unloadItemList.Count: " + unloadItemList.Count); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UpdateInMemoryItems(Position itemGroupPos) + { + Rect windowRect = new Rect(-itemGroupPos.X, -itemGroupPos.Y, gridWidth, gridHeight); + + List loadItemList = new List(); + List unloadItemList = new List(); + + GetChangedItems(lastVisibleArea, windowRect, ref loadItemList, ref unloadItemList); + lastVisibleArea.X = windowRect.X; + lastVisibleArea.Y = windowRect.Y; + lastVisibleArea.Width = windowRect.Width; + lastVisibleArea.Height = windowRect.Height; + + foreach (GridItem item in unloadItemList) + { + UnloadItem(item); + } + + foreach (GridItem item in loadItemList) + { + LoadItem(item); + } + + } + + private void UnloadItem(GridItem item, bool bDirectly = false) + { + Tizen.Log.Fatal("NUI", "item: " + item + " bDirectly: " + bDirectly); + itemGroup.Remove(item.itemView); + + if (bDirectly) + { + gridBridge.UnloadItem(item.groupIndex, item.index, item.itemView); + } + else + { + AddRecycleView(item.groupIndex, item.index, item.itemView); + } + + item.itemView = null; + + curInMemoryItemSet.Remove(item); + } + + private void LoadItem(GridItem item) + { + curInMemoryItemSet.Add(item); + + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]LoadItem item view is null")); + return; + } + + View temp = GetRecycleView(item.groupIndex,item.index); + Tizen.Log.Fatal("NUI", " temp: " + temp); + if (temp != null) + { + item.itemView = temp; + gridBridge.UpdateItem(item.groupIndex, item.index, item.itemView); + } + else + { + item.itemView = gridBridge.GetItemView(item.groupIndex, item.index); + + item.itemView.ParentOrigin = Tizen.NUI.ParentOrigin.TopLeft; + item.itemView.PivotPoint = Tizen.NUI.PivotPoint.Center; + item.itemView.PositionUsesPivotPoint = false; + } + + Tizen.Log.Fatal("NUI", "item.index: " + item.index + " item.rect.X: " + item.rect.X + " item.rect.Y: " + item.rect.Y); + item.itemView.Position = new Position(item.rect.X, item.rect.Y, 0.0f); + item.itemView.Size2D = new Size2D((int)item.rect.Width, (int)item.rect.Height); + + itemGroup.Add(item.itemView); + } + + private void SetViewTypeCount(int typeCount) + { + if (typeCount < 1) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]SetViewTypeCount type count less than 1")); + return; + } + + viewTypeCount = typeCount; + List[] viewListArray = new List[viewTypeCount]; + + for (int i = 0; i < viewTypeCount; i++) + { + viewListArray[i] = new List(); + } + + recycledViews = viewListArray; + } + + private void AddRecycleView(int groupIndex, int itemIndex, View view) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return; + } + + if (view != null) + { + view.Hide(); + view.Scale = new Vector3(1, 1, 1); + } + + recycledViews[viewType].Add(view); + } + + private View GetRecycleView(int groupIndex, int itemIndex) + { + int viewType = gridBridge.GetItemType(groupIndex, itemIndex); + Tizen.Log.Fatal("NUI", " viewType:" + viewType + " viewTypeCount:" + viewTypeCount); + + if (viewType >= viewTypeCount) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]AddRecycleView viewType larger than viewTypeCount")); + return null; + } + + View obj = null; + int viewCount = recycledViews[viewType].Count; + if (viewCount != 0) + { + obj = recycledViews[viewType][viewCount - 1]; + recycledViews[viewType].Remove(obj); + } + + if (obj != null) + { + obj.Show(); + } + + return obj; + } + + private void ClearRecycleBin() + { + for (int i = 0; i < viewTypeCount; i++) + { + for (int j = 0; j < recycledViews[i].Count; j++) + { + UnloadRecycledView(i, recycledViews[i][j]); + } + + recycledViews[i].Clear(); + } + } + + private void UnloadRecycledView(int viewType, View view) + { + itemGroup.Remove(view); + gridBridge.UnloadItemByViewType(viewType, view); + } + + private void GetChangedItems(Rect aLastVisibleArea, Rect curVisibleArea, ref List loadItem, ref List unloadItem) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> aLastVisibleArea.X: " + aLastVisibleArea.X + " aLastVisibleArea.Y: " + aLastVisibleArea.Y + " aLastVisibleArea.Width: " + aLastVisibleArea.Width + " aLastVisibleArea.Height: " + aLastVisibleArea.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> curVisibleArea.X: " + curVisibleArea.X + " curVisibleArea.Y: " + curVisibleArea.Y + " curVisibleArea.Width: " + curVisibleArea.Width + " curVisibleArea.Height: " + curVisibleArea.Height); + GetOnscreenRange(curVisibleArea, ref onScreenRange); + + //Adjust the new start column: if the start column has items which are merge_hidden, + //find the item's smalllest start column as the new start column. + Column startColumn = groupList.ElementAt(onScreenRange.startGroupIndex).columnList.ElementAt(onScreenRange.startColumnIndex); + int cellCount = startColumn.cellList.Count; + + //save new range items to list + nextInMemoryItemSet.Clear(); + GetItemsInRange(onScreenRange, ref nextInMemoryItemSet); + + loadItem = nextInMemoryItemSet.Except(curInMemoryItemSet).ToList(); + unloadItem = curInMemoryItemSet.Except(nextInMemoryItemSet).ToList(); + } + + private void GetOnscreenRange(Rect visibleArea, ref Range range, bool bAllInArea = false) + { + Cell focusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + + int focusColumnIndex = focusedCell.columnIndex; + + float areaStartPos, areaEndPos, focusedCellStart, focusedCellEnd; + if (GridType.Horizontal == gridType) + { + areaStartPos = visibleArea.X; + areaEndPos = visibleArea.X + visibleArea.Width; + focusedCellStart = focusedCell.rect.X; + focusedCellEnd = focusedCell.rect.X + focusedCell.rect.Width; + } + else + { + areaStartPos = visibleArea.Y; + areaEndPos = visibleArea.Y + visibleArea.Height; + focusedCellStart = focusedCell.rect.Y; + focusedCellEnd = focusedCell.rect.Y + focusedCell.rect.Height; + } + + bool bStartFound = false, bEndFound = false; + + int groupCount = groupList.Count; + //find start range + if ((bAllInArea == true && focusedCellStart < areaStartPos) + || (bAllInArea == false && focusedCellEnd < areaStartPos)) + { + for (int i = focusGroupIndex; i < groupCount && bStartFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (true == bAllInArea) + { + if (curColumn.startPos >= areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + bStartFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i >= 0 && bStartFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= areaStartPos) + { + if (bAllInArea == true) + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + + bStartFound = true; + break; + } + else + { + if (curColumn.endPos > areaStartPos) + { + range.startGroupIndex = i; + range.startColumnIndex = j; + } + else + { + if (j == columnCount - 1) + { + range.startGroupIndex = i + 1; + range.startColumnIndex = 0; + } + else + { + range.startGroupIndex = i; + range.startColumnIndex = j + 1; + } + } + + bStartFound = true; + break; + } + } + } + } + } + + if (bStartFound == false) + { + range.startGroupIndex = 0; + range.startColumnIndex = 0; + } + + //find end range + if ((bAllInArea == true && focusedCellEnd >= areaEndPos) + || (bAllInArea == false && focusedCellStart >= areaEndPos)) + { + for (int i = focusGroupIndex; i >= 0 && bEndFound == false; i--) + { + Group curGroup = groupList.ElementAt(i); + int columnCount = curGroup.columnList.Count; + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : columnCount - 1; + for (int j = startColumnIndex; j >= 0; j--) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (bAllInArea == true) + { + if (curColumn.endPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + else + { + if (curColumn.startPos <= areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + bEndFound = true; + break; + } + } + } + } + } + else + { + for (int i = focusGroupIndex; i < groupCount && bEndFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == focusItemIndex) ? focusColumnIndex : 0; + int columnCount = curGroup.columnList.Count; + for (int j = startColumnIndex; j < columnCount; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.endPos >= areaEndPos) + { + if (curColumn.startPos < areaEndPos) + { + range.endGroupIndex = i; + range.endColumnIndex = j; + } + else + { + if (j == 0) + { + range.endGroupIndex = i - 1; + range.endColumnIndex = groupList.ElementAt(i - 1).columnList.Count - 1; + } + else + { + range.endGroupIndex = i; + range.endColumnIndex = j - 1; + } + } + + bEndFound = true; + break; + } + } + } + } + + if (bEndFound == false) + { + range.endGroupIndex = groupCount - 1; + range.endColumnIndex = groupList.ElementAt(range.endGroupIndex).columnList.Count - 1; + } + + range.startGroupInScrn = range.startGroupIndex; + range.startColumnInScrn = range.startColumnIndex; + range.endGroupInScrn = range.endGroupIndex; + range.endColumnInScrn = range.endColumnIndex; + + //get on screen start and end item index + Group startGroup = groupList.ElementAt(range.startGroupInScrn); + Column startColumn = startGroup.columnList.ElementAt(range.startColumnInScrn); + Cell startCell = startColumn.cellList.ElementAt(0); + range.startItemIndexInScrn = startCell.itemIndex; + if (range.startItemIndexInScrn >= startGroup.itemList.Count) + { + range.startItemIndexInScrn = startGroup.itemList.Count - 1; + } + + Group endGroup = groupList.ElementAt(range.endGroupInScrn); + Column endColumn = endGroup.columnList.ElementAt(range.endColumnInScrn); + Cell endCell = endColumn.cellList.ElementAt(endColumn.cellList.Count - 1); + range.endItemIndexInScrn = endCell.itemIndex; + if (range.endItemIndexInScrn >= endGroup.itemList.Count) + { + range.endItemIndexInScrn = endGroup.itemList.Count - 1; + } + + //add buffer columns + int frontBufferCount = preloadFrontColumnSize; + while (frontBufferCount-- > 0) + { + if (range.startColumnIndex > 0) + { + range.startColumnIndex--; + } + else + { + if (range.startGroupIndex > 0) + { + range.startGroupIndex--; + range.startColumnIndex = groupList.ElementAt(range.startGroupIndex).columnList.Count - 1; + } + else + { + break; + } + } + } + + int backBufferCount = preloadBackColumnSize; + while (backBufferCount-- > 0) + { + if (range.endColumnIndex < groupList.ElementAt(range.endGroupIndex).columnList.Count - 1) + { + range.endColumnIndex++; + } + else + { + if (range.endGroupIndex < groupList.Count - 1) + { + range.endGroupIndex++; + range.endColumnIndex = 0; + } + else + { + break; + } + } + } + } + + private void GetItemsInRange(Range range, ref HashSet itemSet) + { + for (int i = range.startGroupIndex; i <= range.endGroupIndex; i++) + { + Group curGroup = groupList.ElementAt(i); + int startColumnIndex = (i == range.startGroupIndex) ? range.startColumnIndex : 0; + int endColumnIndex = (i == range.endGroupIndex) ? range.endColumnIndex : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + + for (int k = 0; k < curColumn.cellList.Count; k++) + { + Cell curCell = curColumn.cellList.ElementAt(k); + if (curCell.itemIndex < curGroup.itemList.Count) + { + itemSet.Add(curGroup.itemList.ElementAt(curCell.itemIndex)); + } + } + } + } + } + + private void MoveFocus(string direction) + { + string logicalDirection = GetLogicalDirection(direction); + MoveFocus(logicalDirection, focusTagGroupIndex, focusTagItemIndex); + } + + // Get the specific groupIndex,itemIndex neighbor item according to direction + private GridItem GetItemByDirection(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell currentCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + + //adjust focused column index based on reference line + Group currentGroup = groupList.ElementAt(fromGroupIndex); + int currentColumnIndex = currentCell.columnIndex; + Column currentColumn = currentGroup.columnList.ElementAt(currentColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex - 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + if (currentCell.rowIndex >= currentColumn.cellList.Count - 1) + { + destFocusItemIndex = -1; + } + else if (fromItemIndex == currentGroup.itemList.Count - 1) + { + destFocusColumnIndex = currentColumnIndex - 1; + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = currentColumn.cellList.ElementAt(currentCell.rowIndex + 1); + destFocusItemIndex = nextCell.itemIndex; + } + + break; + case "Left": + if (currentCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + destFocusColumnIndex = nextGroup.columnList.Count - 1; + + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentCell.columnIndex - 1; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + } + + break; + case "Right": + if (currentColumnIndex == currentGroup.columnList.Count - 1) + { + if (fromGroupIndex == groupList.Count - 1) + { + destFocusItemIndex = -1; + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + Group nextGroup = groupList.ElementAt(destFocusGroupIndex); + Column nextColumn = nextGroup.columnList.ElementAt(destFocusColumnIndex); + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = currentColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " currentCell.rowIndex: " + currentCell.rowIndex); + Column nextColumn = currentGroup.columnList.ElementAt(destFocusColumnIndex); + if (currentCell.rowIndex >= nextColumn.cellList.Count) + { + + Cell nextCell = nextColumn.cellList.ElementAt(nextColumn.cellList.Count - 1); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + else + { + Cell nextCell = nextColumn.cellList.ElementAt(currentCell.rowIndex); + destFocusItemIndex = nextCell.itemIndex; + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex + " currentCell.rowIndex: " + currentCell.rowIndex + " nextColumn.cellList.Count: " + nextColumn.cellList.Count); + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex + " destFocusItemIndex: " + destFocusItemIndex); + GridItem item = null; + if (IsGroupIndexValid(destFocusGroupIndex) == true && IsItemIndexValid(destFocusGroupIndex, destFocusItemIndex)) + { + item = groupList.ElementAt(destFocusGroupIndex).itemList.ElementAt(destFocusItemIndex); + } + + return item; + } + + private void MoveFocus(string direction, int fromGroupIndex, int fromItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> direction: " + direction + " fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex); + Cell curFocusedCell = GetCellByItemIndex(fromGroupIndex, fromItemIndex); + //change reference line of focus move + if (refXForFocusMove == -1) + { + refXForFocusMove = curFocusedCell.rect.X; + } + + if (refYForFocusMove == -1) + { + refYForFocusMove = curFocusedCell.rect.Y; + } + + //adjust focused column index based on reference line + Group focusedGroup = groupList.ElementAt(fromGroupIndex); + int focusedColumnIndex = curFocusedCell.columnIndex; + + Column focusedColumn = focusedGroup.columnList.ElementAt(focusedColumnIndex); + + int destFocusGroupIndex = -2, destFocusItemIndex = -2; + int destFocusColumnIndex = -1; + switch (direction) + { + case "Up": + destFocusGroupIndex = fromGroupIndex; + if (curFocusedCell.index == 0) + { + destFocusItemIndex = -1; + } + else + { + Cell nextCell = focusedColumn.cellList.ElementAt(curFocusedCell.index - 1); + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Down": + destFocusGroupIndex = fromGroupIndex; + int destCellIndex = curFocusedCell.index + 1; + if (destCellIndex >= focusedColumn.cellList.Count || fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusItemIndex = -1; + if (fromItemIndex == focusedGroup.itemList.Count - 1) + { + destFocusColumnIndex = focusedColumnIndex - 1; + Cell cellBelow = FindCellBelow(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex); + if (cellBelow != null) + { + destFocusItemIndex = cellBelow.itemIndex; + refXForFocusMove = cellBelow.rect.X; + refYForFocusMove = cellBelow.rect.Y; + } + } + } + else + { + Cell nextCell = null; + for (; destCellIndex < focusedColumn.cellList.Count; destCellIndex++) + { + nextCell = focusedColumn.cellList.ElementAt(destCellIndex); + { + break; + } + } + + if (destCellIndex >= focusedColumn.cellList.Count) + { + destFocusItemIndex = -1; + } + else + { + destFocusItemIndex = nextCell.itemIndex; + if (destFocusItemIndex >= 0 && destFocusItemIndex < groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + if (GridType.Horizontal == gridType) + { + refYForFocusMove = nextCell.rect.Y; + } + else + { + refXForFocusMove = nextCell.rect.X; + } + } + } + } + + break; + case "Left": + if (curFocusedCell.columnIndex == 0) + { + if (fromGroupIndex == 0) + { + if (StateLeftCircularEnable && true/*check whether allow to loop*/) + { + destFocusGroupIndex = groupList.Count - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + + } + else + { + destFocusGroupIndex = fromGroupIndex - 1; + destFocusColumnIndex = groupList.ElementAt(destFocusGroupIndex).columnList.Count - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + int itemCount = groupList.ElementAt(destFocusGroupIndex).itemList.Count; + while (destFocusItemIndex >= itemCount) + { + destFocusColumnIndex--; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = curFocusedCell.columnIndex - 1; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + + break; + case "Right": + { + focusedColumnIndex = curFocusedCell.columnIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedColumnIndex: " + focusedColumnIndex); + if (focusedColumnIndex == focusedGroup.columnList.Count - 1 || focusedColumnIndex == focusedGroup.lastFilledColumnIndex) + { + if (fromGroupIndex == groupList.Count - 1) + { + if (StateRightCircularEnable && true/*check whether allow right circular*/) + { + destFocusGroupIndex = 0; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + + bool bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + while (bEnabled == false && destFocusColumnIndex < focusedGroup.columnList.Count - 1) + { + destFocusColumnIndex++; + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + bEnabled = gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex); + + refXForFocusMove = refYForFocusMove = -1; + } + + /*ToDo Left Circular*/ + SetFocus(destFocusGroupIndex, destFocusItemIndex); + return; + } + else + { + destFocusItemIndex = -1; + } + } + else + { + destFocusGroupIndex = fromGroupIndex + 1; + destFocusColumnIndex = 0; + + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + } + } + else + { + destFocusGroupIndex = fromGroupIndex; + destFocusColumnIndex = focusedColumnIndex + 1; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + GetNearestItem(curFocusedCell, destFocusGroupIndex, destFocusColumnIndex, ref destFocusItemIndex, true); + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + + if (StateRightCircularEnable) + { + if (destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + return; + } + } + } + + break; + default: + break; + } + + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusGroupIndex: " + destFocusGroupIndex + " destFocusColumnIndex:" + destFocusColumnIndex); + if (destFocusGroupIndex >= 0 && destFocusItemIndex >= groupList.ElementAt(destFocusGroupIndex).itemList.Count) + { + destFocusItemIndex = -1; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> destFocusItemIndex: " + destFocusItemIndex); + if (destFocusItemIndex == -1) + { + //notify event focus move out + return; + } + + if (gridBridge.IsItemEnabled(destFocusGroupIndex, destFocusItemIndex) == false) + { + MoveFocus(direction, destFocusGroupIndex, destFocusItemIndex); + } + else + { + PushFocus(destFocusGroupIndex, destFocusItemIndex); + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + + private void GetNearestItem(Cell focusedCell, int destGroupIndex, int destColumnIndex, ref int destItemIndex, bool bDirectMove = false) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + Cell nextCell = destColumn.cellList.ElementAt(0); + int cellCount = destColumn.cellList.Count; + + bool bNotAllItemDisabled = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= 0 && curCell.itemIndex < destGroup.itemList.Count) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex)) + { + bNotAllItemDisabled = true; + break; + } + } + } + + float yDis = gridHeight + 1; + bool bFound = false; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = destColumn.cellList.ElementAt(i); + if (curCell.itemIndex >= destGroup.itemList.Count) + { + break; + } + + if (curCell.itemIndex >= 0 && bNotAllItemDisabled) + { + if (gridBridge.IsItemEnabled(destGroupIndex, curCell.itemIndex) == false) + { + continue; + } + } + + if (curCell.itemIndex < 0) + { + Column realColumn = destGroup.columnList.ElementAt(curCell.columnIndex); + Cell realCell = realColumn.cellList.ElementAt(curCell.rowIndex); + if (realCell.itemIndex >= destGroup.itemList.Count || gridBridge.IsItemEnabled(destGroupIndex, realCell.itemIndex) == false) + { + continue; + } + } + + if (GridType.Vertical == gridType) + { + float tempXDis; + if (StateStraightPathEnable) + { + tempXDis = Math.Abs(curCell.rect.X - refXForFocusMove); + } + else + { + tempXDis = Math.Abs(curCell.rect.X - focusedCell.rect.X); + } + + if (tempXDis < yDis) + { + bFound = true; + yDis = tempXDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + else + { + float tempYDis; + if (StateStraightPathEnable) + { + tempYDis = Math.Abs(curCell.rect.Y - refYForFocusMove); + } + else + { + tempYDis = Math.Abs(curCell.rect.Y - focusedCell.rect.Y); + } + + if (tempYDis < yDis) + { + bFound = true; + yDis = tempYDis; + nextCell = curCell; + if (yDis == 0) + { + break; + } + } + } + + } + + { + destItemIndex = nextCell.itemIndex; + if (bFound) + { + refXForFocusMove = nextCell.rect.X; + if (bDirectMove == false) + { + refYForFocusMove = nextCell.rect.Y; + } + } + } + } + + private string GetLogicalDirection(string direction) + { + string logicalDirection = direction; + + if (GridType.Vertical == gridType) + { + if ("Left" == direction) + { + logicalDirection = "Up"; + } + else if ("Right" == direction) + { + logicalDirection = "Down"; + } + else if ("Down" == direction) + { + logicalDirection = "Right"; + } + else if ("Up" == direction) + { + logicalDirection = "Left"; + } + } + + return logicalDirection; + } + + private Cell FindCellBelow(Cell fromCell, int destGroupIndex, int destColumnIndex) + { + Group destGroup = groupList.ElementAt(destGroupIndex); + + if (destColumnIndex < 0 || destColumnIndex >= destGroup.columnList.Count) + { + return null; + } + + Column destColumn = destGroup.columnList.ElementAt(destColumnIndex); + + for (int i = 0; i < destColumn.cellList.Count; i++) + { + Cell destCell = destColumn.cellList.ElementAt(i); + + if (destCell.rect.Y > fromCell.rect.Y && destCell.rect.Y + destCell.rect.Height > fromCell.rect.Y + fromCell.rect.Height) + { + { + return destCell; + } + } + } + + return null; + } + + private void SetFocus(int groupIndex, int itemIndex, bool bAnimation = false, Position newItemGroupPos = null) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex: " + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + bool bNeedScroll = false; + + if (newItemGroupPos == null) + { + Position itemGroupPos = new Position(0, 0, 0); + bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + } + else + { + if (GridType.Horizontal == gridType && itemGroupRect.X != newItemGroupPos.X + || GridType.Vertical == gridType && itemGroupRect.Y != newItemGroupPos.Y) + { + bNeedScroll = true; + } + + itemGroupRect.X = newItemGroupPos.X; + itemGroupRect.Y = newItemGroupPos.Y; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + ResetItemGroupRectPos(); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y: " + itemGroupRect.Y); + if (bNeedScroll) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> bAnimation: " + bAnimation); + if (bAnimation == true) + { + FocusMoveViaObject obj = new FocusMoveViaObject(); + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + focusMoveAni.Play(); + } + else + { + UpdateInMemoryItems(); + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + else + { + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + } + + + private void PushFocus(int groupIndex, int itemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> groupIndex: " + groupIndex + " itemIndex:" + itemIndex); + if (!IsItemIndexValid(groupIndex, itemIndex)) + { + return; + } + + Position itemGroupPos = new Position(0, 0, 0); + bool bNeedScroll = GetItemGroupPosByFocusItem(groupIndex, itemIndex, itemGroupPos); + + itemGroupRect.X = itemGroupPos.X; + itemGroupRect.Y = itemGroupPos.Y; + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect.X: " + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + + ResetItemGroupRectPos(); + + //focusTag keep move, but real focus will set when focusMoveVia trigger, + //so remember context of focus move, include from and to, and itemGroupPos information + focusTagGroupIndex = groupIndex; + focusTagItemIndex = itemIndex; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> bNeedScroll: " + bNeedScroll + " itemGroupRect.X:" + itemGroupRect.X + " itemGroupRect.Y:" + itemGroupRect.Y); + if (bNeedScroll) + { + if (gridType == GridType.Horizontal) + { + focusMoveAni.SetDestination("PositionX", itemGroupRect.X); + } + else + { + focusMoveAni.SetDestination("PositionY", itemGroupRect.Y); + } + + FocusMoveViaObject obj = new FocusMoveViaObject(); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusMoveViaQ.Count: " + focusMoveViaQ.Count); + Tizen.Log.Fatal("NUI", "::::: " + focusGroupIndex + ", " + focusItemIndex); + + obj.toGroupIndex = groupIndex; + obj.toItemIndex = itemIndex; + focusMoveViaQ.Enqueue(obj); + focusMoveAni.Play(); + } + else + { + if (focusMoveAni.IsPlaying() == false) + { + Tizen.Log.Fatal("NUI", "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ " + groupIndex + " " + itemIndex + " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, groupIndex, itemIndex); + } + } + //To keep focusBar on the top of + + Tizen.Log.Fatal("NUI", ">>>>>>>>> "); + } + + private bool GetItemGroupPosByFocusItem(int aFocusGroupIndex, int aFocusItemIndex, Position itemGroupPos) + { + bool bNeedScroll = false; + if (!IsItemIndexValid(aFocusGroupIndex, aFocusItemIndex)) + { + return false; + } + + Group focusedGroup = groupList.ElementAt(aFocusGroupIndex); + GridItem focusedItem = focusedGroup.itemList.ElementAt(aFocusItemIndex); + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusedItem.rect: " + focusedItem.rect.X + ", " + focusedItem.rect.Y + ", " + focusedItem.rect.Width + ", " + focusedItem.rect.Height); + + Rect focusBarRectBaseOnList = new Rect(focusedItem.rect.X, focusedItem.rect.Y, focusedItem.rect.Width, focusedItem.rect.Height); + focusBarRectBaseOnList.X += itemGroupRect.X; + focusBarRectBaseOnList.Y += itemGroupRect.Y; + + itemGroupPos.X = itemGroupRect.X; + itemGroupPos.Y = itemGroupRect.Y; + + float startFocusRange; + float endFocusRange; + + if (GridType.Horizontal == gridType) + { + if (0 == focusedItem.rect.X) + { + startFocusRange = margin[0]; + } + else + { + Tizen.Log.Fatal("NUI", "Left aFocusItemIndex:: " + aFocusGroupIndex + ", aFocusItemIndex:: " + aFocusItemIndex); + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "startFocusRange :: " + margin[0]); + startFocusRange = prevItem != null ? prevItem.rect.Width / 2 : margin[0]; + } + + if (itemGroupRect.Width == focusedItem.rect.Right()) + { + endFocusRange = gridWidth - margin[2]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + //Tizen.Log.Fatal("NUI", "gridWidth::" + gridWidth + " gridWidth - margin[2] :: " + (gridWidth - margin[2])); + //Tizen.Log.Fatal("NUI", "gridWidth - nextItem.rect.Width / 2 :: " + (gridWidth - nextItem.rect.Width / 2)); + endFocusRange = nextItem != null ? gridWidth - nextItem.rect.Width / 2 : gridWidth - margin[2]; + Tizen.Log.Fatal("NUI", "endFocusRange :: " + endFocusRange); + } + + if (focusBarRectBaseOnList.X < startFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.X :: " + focusBarRectBaseOnList.X + " startFocusRange :: " + startFocusRange); + itemGroupPos.X += startFocusRange - focusBarRectBaseOnList.X; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Right() > endFocusRange) + { + Tizen.Log.Fatal("NUI", "focusBarRectBaseOnList.Right() :: " + focusBarRectBaseOnList.Right() + " endFocusRange :: " + endFocusRange); + itemGroupPos.X += endFocusRange - focusBarRectBaseOnList.Right(); + bNeedScroll = true; + } + } + else + { + if (0 == focusedItem.rect.Y) + { + startFocusRange = margin[1]; + } + else + { + GridItem prevItem = GetItemByDirection("Left", aFocusGroupIndex, aFocusItemIndex); + startFocusRange = prevItem != null ? prevItem.rect.Height / 2 : margin[1]; + } + + if (itemGroupRect.Height == focusedItem.rect.Bottom()) + { + endFocusRange = gridHeight - margin[3]; + } + else + { + GridItem nextItem = GetItemByDirection("Right", aFocusGroupIndex, aFocusItemIndex); + endFocusRange = nextItem != null ? gridHeight - nextItem.rect.Height / 2 : gridHeight - margin[3]; + } + + if (focusBarRectBaseOnList.Y < startFocusRange) + { + itemGroupPos.Y += startFocusRange - focusBarRectBaseOnList.Y; + bNeedScroll = true; + } + else if (focusBarRectBaseOnList.Bottom() > endFocusRange) + { + itemGroupPos.Y += endFocusRange - focusBarRectBaseOnList.Bottom(); + bNeedScroll = true; + } + } + + return bNeedScroll; + } + + private void NotifyFocusChange(int fromGroupIndex,int fromItemIndex,int toGroupIndex,int toItemIndex) + { + Tizen.Log.Fatal("NUI", ">>>>>>>>> fromGroupIndex: " + fromGroupIndex + " fromItemIndex: " + fromItemIndex + " toGroupIndex: " + toGroupIndex + " toItemIndex: " + toItemIndex); + + if (IsItemIndexValid(fromGroupIndex, fromItemIndex) && (fromGroupIndex != toGroupIndex || fromItemIndex != toItemIndex)) + { + Group preGroup = groupList.ElementAt(fromGroupIndex); + GridItem preItem = preGroup.itemList.ElementAt(fromItemIndex); + + ScaleDownItem(preItem); + if (preItem.itemView != null) + { + gridBridge.FocusChange(fromGroupIndex, fromItemIndex, preItem.itemView, false); + } + } + + if (IsItemIndexValid(toGroupIndex, toItemIndex)) + { + Group curGroup = groupList.ElementAt(toGroupIndex); + GridItem item = curGroup.itemList.ElementAt(toItemIndex); + + ScaleUpItem(item); + if (item.itemView != null) + { + Tizen.Log.Fatal("NUI", "Call GridBridge.FocusChange to set focus"); + gridBridge.FocusChange(toGroupIndex, toItemIndex, item.itemView, true); + } + } + + //notify user focus change + GridEventArgs evtArgs = new GridEventArgs(); + evtArgs.EventType = GridEventType.FocusChange; + evtArgs.param[0] = fromGroupIndex; + evtArgs.param[1] = fromItemIndex; + evtArgs.param[2] = toGroupIndex; + evtArgs.param[3] = toItemIndex; + OnListEvent(evtArgs); + + if (toGroupIndex != -1 && toItemIndex != -1) + { + focusGroupIndex = toGroupIndex; + focusItemIndex = toItemIndex; + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> focusGroupIndex: " + focusGroupIndex + " focusItemIndex: " + focusItemIndex); + } + + private void ScaleUpItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.itemView.RaiseToTop(); + item.ScaleItem(new Vector3(focusInScaleFactor, focusInScaleFactor, 1.0f), focusInScaleAnimationAttrs); + } + + private void ScaleDownItem(GridItem item) + { + if (item.itemView == null) + { + return; + } + + item.ScaleItem(new Vector3(1.0f, 1.0f, 1.0f), focusOutScaleAnimationAttrs); + } + + private void UpdateItemGroupSize() + { + if (groupList.Count == 0) + { + return; + } + + Group lastGroup = groupList.ElementAt(groupList.Count - 1); + + int lastItemIndex = lastGroup.itemList.Count - 1; + if (lastItemIndex < 0) + { + return; + } + + Cell lastFilledCell = GetCellByItemIndex(groupList.Count - 1 ,lastItemIndex); + int lastFilledColumnIndex = lastFilledCell.columnIndex; + Column lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + int cellCount = lastFilledColumn.cellList.Count; + for (int i = 0; i < cellCount; i++) + { + Cell curCell = lastFilledColumn.cellList.ElementAt(i); + if (curCell.columnIndex > lastFilledColumnIndex) + { + lastFilledColumnIndex = lastFilledColumn.cellList.ElementAt(i).columnIndex; + } + } + + lastFilledColumn = lastGroup.columnList.ElementAt(lastFilledColumnIndex); + + float width, height; + + if (GridType.Horizontal == gridType) + { + width = lastFilledColumn.endPos; + height = gridHeight - (margin[1] + margin[3]); + } + else + { + width = gridWidth - (margin[0] + margin[2]); + height = lastFilledColumn.endPos; + } + + itemGroupRect.Width = width; + itemGroupRect.Height = height; + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroup: " + itemGroup.PositionX + ", " + itemGroup.PositionY + ", " + itemGroup.SizeWidth + ", " + itemGroup.SizeHeight); + itemGroup.SizeWidth = itemGroupRect.Width; + itemGroup.SizeHeight = itemGroupRect.Height; + } + + private void InitItemGroupPosition() + { + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X > margin[0]) + { + itemGroupRect.X = margin[0]; + } + else if (itemGroupRect.Right() < gridWidth) + { + if (itemGroupRect.X >= gridWidth) + { + itemGroupRect.X = gridWidth - itemGroupRect.Width; + } + else + { + itemGroupRect.X = 0; + } + } + + itemGroupRect.Y = margin[1]; + } + else + { + itemGroupRect.X = margin[0]; + if (itemGroupRect.Y > margin[1]) + { + itemGroupRect.Y = margin[1]; + } + else if (itemGroupRect.Y + itemGroupRect.Height < gridHeight) + { + if (itemGroupRect.Y >= gridHeight) + { + itemGroupRect.Y = gridHeight - itemGroupRect.Height; + } + else + { + itemGroupRect.Y = 0; + } + } + } + + Tizen.Log.Fatal("NUI", ">>>>>>>>> itemGroupRect: " + itemGroupRect.X + ", " + itemGroupRect.Y + ", " + itemGroupRect.Width + ", " + itemGroupRect.Height); + ResetItemGroupRectPos(); + + itemGroup.PositionX = itemGroupRect.X; + itemGroup.PositionY = itemGroupRect.Y; + } + + private void ResetItemGroupRectPos() + { + //adjust item Group pos, to add margin when item group scroll to Head or Tail + if (GridType.Horizontal == gridType) + { + if (itemGroupRect.X == 0) + { + itemGroupRect.X += margin[0]; + } + else if (itemGroupRect.Right() == gridWidth) + { + itemGroupRect.X -= margin[2]; + } + } + else + { + if (itemGroupRect.Y == 0) + { + itemGroupRect.Y += margin[1]; + } + else if (itemGroupRect.Bottom() == gridHeight) + { + itemGroupRect.Y -= margin[3]; + } + } + } + + private Cell GetCellByItemIndex(int groupIndex, int itemIndex) + { + Cell curCell = null; + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return null; + } + + Group curGroup = groupList.ElementAt(groupIndex); + if (curGroup.itemIndexToCell.ContainsKey(itemIndex)) + { + curCell = curGroup.itemIndexToCell[itemIndex]; + } + + return curCell; + } + + private bool IsGroupIndexValid(int groupIndex) + { + return (groupIndex >= 0 && groupList != null && groupIndex < groupList.Count); + } + + private bool IsItemIndexValid(int groupIndex, int itemIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (itemIndex >= 0 && curGroup.itemList != null && itemIndex < curGroup.itemList.Count); + } + + private bool IsColumnIndexValid(int groupIndex, int columnIndex) + { + if (!IsGroupIndexValid(groupIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid group index")); + return false; + } + + Group curGroup = groupList.ElementAt(groupIndex); + + return (columnIndex >= 0 && curGroup.columnList != null && columnIndex < curGroup.columnList.Count); + } + + private bool IsCellIndexValid(int groupIndex, int columnIndex, int cellIndex) + { + if (!IsColumnIndexValid(groupIndex, columnIndex)) + { + Tizen.Log.Fatal("NUI", string.Format("[GridView]Invalid column index")); + return false; + } + + Column curColumn = groupList.ElementAt(groupIndex).columnList.ElementAt(columnIndex); + + return (cellIndex >= 0 && curColumn.cellList != null && cellIndex < curColumn.cellList.Count); + } + + /// + /// Called when the control gain key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusGained(object sender, EventArgs e) + { + OnFocusGained(); + } + + public void OnFocusGained() + { + Tizen.Log.Fatal("NUI", ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "); + SetFocus(focusGroupIndex, focusItemIndex); + } + + /// + /// Called when the control loses key input focus. + /// + /// the object + /// the args of the event + public void ControlFocusLost(object sender, EventArgs e) + { + OnFocusLost(); + } + + public void OnFocusLost() + { + Tizen.Log.Fatal("NUI", "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); + NotifyFocusChange(focusGroupIndex, focusItemIndex, -1, -1); + } + + private void OnFocusMoveViaEvent(object o, EventArgs e) + { + Tizen.Log.Fatal("NUI", "--------------------- " + focusMoveViaQ.Count + " -------------------------------"); + if (focusMoveViaQ.Count > 0) + { + { + FocusMoveViaObject obj = focusMoveViaQ.Dequeue(); + { + UpdateInMemoryItems(itemGroup.Position); + } + + { + //common focus notify focus change at destination of every via + NotifyFocusChange(focusGroupIndex, focusItemIndex, obj.toGroupIndex, obj.toItemIndex); + } + } + + //viaMap1.Remove(args.ViaNode); + } + } + + private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + { + switch (e.ChangeType) + { + case GridBridge.DataChangeEventType.Add: + AddItem(e.param[0]); + break; + case GridBridge.DataChangeEventType.Remove: + DeleteItem(e.param[0], e.param[1], e.param[2]); + break; + case GridBridge.DataChangeEventType.Insert: + InsertItem(e.param[0], e.param[1]); + break; + case GridBridge.DataChangeEventType.Clear: + Clear(); + break; + case GridBridge.DataChangeEventType.Reset: + ResetByData(); + break; + case GridBridge.DataChangeEventType.Load: + Load(); + Group curGroup = groupList.ElementAt(e.param[0]); + for (int i = e.param[1]; i < gridBridge.GetItemCount(e.param[0]); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(e.param[0], i, curGroup.itemList.ElementAt(i).itemView); + } + } + + if (focusItemIndex >= e.param[1] && focusItemIndex <= e.param[1] + e.param[2] - 1) + { + if (e.param[1] > 0) + { + SetFoucsItemIndex(e.param[1] - 1, focusGroupIndex); + } + else if (e.param[1] + e.param[2] < curGroup.itemList.Count) + { + SetFoucsItemIndex(e.param[1] + e.param[2], focusGroupIndex); + } + } + else if (focusItemIndex >= e.param[1] + e.param[2]) + { + SetFoucsItemIndex(focusItemIndex - e.param[2], focusGroupIndex); + } + + break; + default: + + break; + } + + refXForFocusMove = refYForFocusMove = -1; + } + + private void AddItem(int groupIndex) + { + int dataCount = gridBridge.GetItemCount(groupIndex); + if (dataCount > groupList.ElementAt(groupIndex).realCellCount) + { + AddColumn(colW, groupIndex); + int columnIndex = groupList.ElementAt(groupIndex).columnList.Count - 1; + for (int i = 0; i < rowCnt; i++) + { + AddRowToColumn(columnIndex, rowH, groupIndex); + } + } + + Load(); + } + + private void AddAll(int groupIndex, int count) + { + Load(); + } + + + private void DeleteItem(int groupIndex, int fromItemIndex, int deleteItemNum) + { + Group curGroup = groupList.ElementAt(groupIndex); + + GridItem item = null; + + int toItemIndex = fromItemIndex + deleteItemNum - 1; + + int count = 0; + + for (int i = fromItemIndex; i < curGroup.itemList.Count; i++) + { + item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, true); + count++; + } + } + + for (int i = 0; i < count; i++) + { + curGroup.itemList.Remove(curGroup.itemList.ElementAt(curGroup.itemList.Count - 1)); + } + } + + private void InsertItem(int groupIndex, int itemIndex) + { + Load(); + + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = itemIndex; i < gridBridge.GetItemCount(groupIndex); i++) + { + if (i < curGroup.itemList.Count) + { + gridBridge.UpdateItem(groupIndex, i, curGroup.itemList.ElementAt(i).itemView); + } + } + } + + private void Clear() + { + for (int i = 0; i < groupList.Count; i++) + { + Clear(i); + } + + ClearRecycleBin(); + } + + private void Clear(int groupIndex) + { + Tizen.Log.Fatal("NUI", "--------------------- " + groupIndex + " -------------------------------"); + Group curGroup = groupList.ElementAt(groupIndex); + for (int i = 0; i < curGroup.itemList.Count; i++) + { + GridItem item = curGroup.itemList.ElementAt(i); + if (curInMemoryItemSet.Contains(item)) + { + UnloadItem(item, false); + } + } + + curGroup.itemList.Clear(); + } + + private void ResetByData() + { + Tizen.Log.Fatal("NUI", "...."); + int groupCount = gridBridge.GetGroupCount(); + ResetGroup(groupCount); + for (int i = 0; i < groupCount; i++) + { + Tizen.Log.Fatal("NUI", ".... group: " + i); + int dataCount = gridBridge.GetItemCount(i); + Tizen.Log.Fatal("NUI", ".... dataCount: " + dataCount + " rowCnt: " + rowCnt); + int columnCount = (dataCount + rowCnt - 1) / rowCnt; + Group group = groupList.ElementAt(i); + Tizen.Log.Fatal("NUI", ".... columnCount: " + columnCount + " group.columnList.Count: " + group.columnList.Count + " group.itemIndexToCell.Count: " + group.itemIndexToCell.Count); + if (columnCount > group.columnList.Count) + { + for (int c = group.columnList.Count; c < columnCount; c++) + { + AddColumn(colW, i); + for (int r = 0; r < rowCnt; r++) + { + AddRowToColumn(c, rowH, i); + } + } + } + else if (columnCount < group.columnList.Count) + { + float posOffset = -(group.columnList.Count - columnCount) * (colW + columnSpace) + ColumnSpace; + + for (int c = columnCount; c < group.columnList.Count; c++) + { + for (int r = 0; r < rowCnt; r++) + { + int itemIndex = c * rowCnt + r; + group.itemIndexToCell.Remove(itemIndex); + group.realCellCount--; + Tizen.Log.Fatal("NUI", ".... itemIndexToCell.Remove: " + itemIndex); + } + } + + group.columnList.RemoveRange(columnCount, group.columnList.Count - columnCount); + group.endPos = group.columnList.ElementAt(columnCount - 1).endPos; + for (int j = i + 1; j < groupList.Count; j++) + { + if (GridType.Horizontal == gridType && groupList.ElementAt(j).title != null) + { + groupList.ElementAt(j).title.PositionX += posOffset; + } + + groupList.ElementAt(j).ResetPosition(posOffset); + } + + } + + Tizen.Log.Fatal("NUI", ".... group.columnList.Count: " + group.columnList.Count); + } + + focusGroupIndex = 0; + focusItemIndex = 0; + Tizen.Log.Fatal("NUI", "...."); + Load(); + if (HasFocus() == true && curInMemoryItemSet.Count != 0) + { + SetFocus(0, 0); + } + } + + /*page length set to grid length*/ + private void PageMove(bool bPrev, bool bAni) + { + Rect visibleAreaOfItemGroup = new Rect(-itemGroupRect.X, -itemGroupRect.Y, gridWidth, gridHeight); + + if (GridType.Horizontal == gridType) + { + if (bPrev) + { + visibleAreaOfItemGroup.X -= gridWidth; + if (0 > visibleAreaOfItemGroup.X) + { + visibleAreaOfItemGroup.X = 0; + } + } + else + { + visibleAreaOfItemGroup.X += gridWidth; + if (-visibleAreaOfItemGroup.X + itemGroupRect.Width < gridWidth) + { + visibleAreaOfItemGroup.X = itemGroupRect.Width - gridWidth; + } + } + + if (-itemGroupRect.X == visibleAreaOfItemGroup.X) + { + return; + } + } + else + { + if (bPrev) + { + visibleAreaOfItemGroup.Y -= gridHeight; + if (0 > visibleAreaOfItemGroup.Y) + { + visibleAreaOfItemGroup.Y = 0; + } + } + else + { + visibleAreaOfItemGroup.Y += gridHeight; + if (-visibleAreaOfItemGroup.Y + itemGroupRect.Height < gridHeight) + { + visibleAreaOfItemGroup.Y = itemGroupRect.Height - gridHeight; + } + } + + if (-itemGroupRect.Y == visibleAreaOfItemGroup.Y) + { + return; + } + } + + Range newRange = new Range(0, 0, 0, 0); + GetOnscreenRange(visibleAreaOfItemGroup, ref newRange, true); + + Group curFocusedGroup = groupList.ElementAt(focusGroupIndex); + Cell curFocusedCell = GetCellByItemIndex(focusGroupIndex, focusItemIndex); + Column curFocusedColumn = curFocusedGroup.columnList.ElementAt(curFocusedCell.columnIndex); + + float focusStartLine = curFocusedColumn.startPos; + float focusEndLine = curFocusedColumn.endPos; + float focusMiddleLine = 0; + + if (newRange.startGroupInScrn >= 0 && newRange.endGroupInScrn >= 0) + { + if (GridType.Horizontal == gridType) + { + focusStartLine = focusStartLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + focusEndLine = focusEndLine + itemGroupRect.X + visibleAreaOfItemGroup.X; + } + else + { + focusStartLine = focusStartLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + focusEndLine = focusEndLine + itemGroupRect.Y + visibleAreaOfItemGroup.Y; + } + + focusMiddleLine = focusStartLine + (focusEndLine - focusStartLine) / 2; + + int nextFocusGroup = -1; int nextFocusColumn = -1; + bool bFound = false; + for (int i = newRange.startGroupInScrn; i <= newRange.endGroupInScrn && bFound == false; i++) + { + Group curGroup = groupList.ElementAt(i); + + int startColumnIndex = (i == newRange.startGroupInScrn) ? newRange.startColumnInScrn : 0; + int endColumnIndex = (i == newRange.endGroupInScrn) ? newRange.endColumnInScrn : curGroup.columnList.Count - 1; + + for (int j = startColumnIndex; j <= endColumnIndex; j++) + { + Column curColumn = curGroup.columnList.ElementAt(j); + if (curColumn.startPos <= focusMiddleLine && curColumn.endPos >= focusMiddleLine) + { + nextFocusGroup = i; + nextFocusColumn = j; + bFound = true; + break; + } + } + + if (bFound == false && i == newRange.startGroupInScrn && focusMiddleLine < curGroup.columnList.ElementAt(startColumnIndex).startPos) + { + nextFocusGroup = i; + nextFocusColumn = startColumnIndex; + break; + } + + else if (bFound == false && i == newRange.endGroupInScrn && focusMiddleLine > curGroup.columnList.ElementAt(endColumnIndex).endPos) + { + nextFocusGroup = i; + nextFocusColumn = endColumnIndex; + break; + } + } + + if (nextFocusGroup >= 0 && nextFocusColumn >= 0) + { + int nextFocusItem = -1; + GetNearestItem(curFocusedCell, nextFocusGroup, nextFocusColumn, ref nextFocusItem); + + if (nextFocusItem >= 0) + { + while (gridBridge.IsItemEnabled(nextFocusGroup, nextFocusItem) == false) + { + nextFocusItem = GetNextColumnIndex(bPrev, nextFocusColumn, ref nextFocusGroup); + } + + if (nextFocusItem >= 0) + { + Position newItemGroupPos = new Position(-visibleAreaOfItemGroup.X, -visibleAreaOfItemGroup.Y, 0); + SetFocus(nextFocusGroup, nextFocusItem, bAni, newItemGroupPos); + } + } + } + } + } + + private int GetNextColumnIndex(bool bPrev, int curColumnIndex, ref int curGroupIndex) + { + if (bPrev == true) + { + if (curColumnIndex == 0) + { + if (curGroupIndex == 0) + { + return -1; + } + else + { + curGroupIndex--; + return groupList.ElementAt(curGroupIndex).columnList.Count - 1; + } + } + else + { + return curColumnIndex - 1; + } + } + else + { + Group curGroup = groupList.ElementAt(curGroupIndex); + if (curGroup.columnList.Count - 1 == curColumnIndex) + { + if (groupList.Count - 1 == curGroupIndex) + { + return -1; + } + else + { + curGroupIndex++; + return 0; + } + } + else + { + return curColumnIndex + 1; + } + } + } + + private class GridItem + { + public void ScaleItem(Vector3 scaleFactor, AnimationAttributes aniAttrs) + { + if (itemView == null || scaleFactor == null || aniAttrs == null) + { + return; + } + + if (scaleAni == null) + { + scaleAni = new Animation(); + } + + if (scaleAni.State == Animation.States.Playing) + { + scaleAni.Stop(Animation.EndActions.StopFinal); + } + + scaleAni.Clear(); + scaleAni.AnimateTo(itemView, "Scale", scaleFactor, 0, aniAttrs.Duration, new AlphaFunction(aniAttrs.BezierPoint1, aniAttrs.BezierPoint2)); + scaleAni.Play(); + } + + public int groupIndex; + public int index; + + public View itemView; + public Rect rect; + + private Animation scaleAni = null; + } + + private class Cell + { + public int columnIndex; + public int index; + public int itemIndex; + public int rowIndex; + + public Rect rect; + public Cell() + { + rect = new Rect(0, 0, 0, 0); + } + } + + private class Column + { + public int groupIndex; + public int index; + + public float space; + public float startPos; + public float endPos; + + public int startItemIndex; + public int endItemIndex; + + public List cellList; + } + + private class Group + { + public int index; + + public float startPos; + public float endPos; + + public int realCellCount; + public int lastFilledColumnIndex; + + public List columnList; + public List itemList; + public Dictionary itemIndexToCell; + + public void ResetPosition(float posOffset) + { + startPos += posOffset; + endPos += posOffset; + + int count = columnList.Count; + for (int i = 0; i < count; i++) + { + Column column = columnList.ElementAt(i); + column.startPos += posOffset; + column.endPos += posOffset; + + int cellCount = column.cellList.Count; + for (int j = 0; j < cellCount; j++) + { + column.cellList.ElementAt(j).rect.X += posOffset; + } + } + } + + public View title; + } + + private class Range + { + public int startGroupIndex; + public int startColumnIndex; + + public int endGroupIndex; + public int endColumnIndex; + + public int startGroupInScrn; + public int startColumnInScrn; + + public int endGroupInScrn; + public int endColumnInScrn; + + public int startItemIndexInScrn; + public int endItemIndexInScrn; + + public Range() + { + startGroupIndex = 0; + startColumnIndex = 0; + endGroupIndex = 0; + endColumnIndex = 0; + } + + public Range(int a, int b, int c, int d) + { + startGroupIndex = a; + startColumnIndex = b; + endGroupIndex = c; + endColumnIndex = d; + } + } + + private class FocusMoveViaObject + { + public int toGroupIndex; + public int toItemIndex; + } + + const int INVALID_COUNT = -1; + + private List groupList; + private GridBridge gridBridge; + + private View itemGroup; + private Rect itemGroupRect; + + private Vector4 margin = Vector4.Zero; + + private float gridWidth; + private float gridHeight; + + private int preloadFrontColumnSize = 1; + private int preloadBackColumnSize = 1; + + //layout attributes + private GridType gridType = GridType.Horizontal; + private int groupSpace = 0; + private int columnSpace = 0; + private int rowSpace = 0; + private int titleSpace = 0; + + private int rowCnt = 0; + private int colCnt = 0; + private int colW = 0; + private int rowH = 0; + + //focus + private int focusGroupIndex; + private int focusItemIndex; + + private float refXForFocusMove; + private float refYForFocusMove; + + private int focusTagGroupIndex; + private int focusTagItemIndex; + //animation + LinkerAnimation focusMoveAni; + + private float focusInScaleFactor; + + private AnimationAttributes focusInScaleAnimationAttrs; + + private AnimationAttributes focusOutScaleAnimationAttrs; + + private int focusMoveAniDuration; + + private Queue focusMoveViaQ = new Queue(); + + //for load + private HashSet curInMemoryItemSet; + private HashSet nextInMemoryItemSet; + + private Rect lastVisibleArea; + + private Range onScreenRange; + + //reuse + private List[] recycledViews; + private int viewTypeCount; + + private EventHandler gridEventHandlers; + } + + /// + /// The attributes of Animation. + /// + /// + /// AnimationAttributes attrs = new AnimationAttributes(); + /// attrs.BezierPoint1 = new Vector2(0.21f, 2); + /// attrs.BezierPoint2 = new Vector2(0.14f, 1); + /// attrs.Duration = 1000; + /// + public class AnimationAttributes + { + /// V1 on bezier curve + public Vector2 BezierPoint1; + /// V2 on bezier curve + public Vector2 BezierPoint2; + /// Animation duration + public int Duration; + + /// + /// Constructs a AnimationAttributes.. + /// + public AnimationAttributes() + { + } + + /// + /// Constructs a AnimationAttributes with curve style.. + /// + /// curve + public AnimationAttributes(string curve) + { + } + + /// + /// Constructs a AnimationAttributes that is a copy of attrs.. + /// + /// Construct Attributes + public AnimationAttributes(AnimationAttributes attrs = null) + { + if (attrs == null) + { + return; + } + + if (attrs.BezierPoint1 != null) + { + BezierPoint1 = new Vector2(attrs.BezierPoint1[0], attrs.BezierPoint1[1]); + } + + if (attrs.BezierPoint2 != null) + { + BezierPoint2 = new Vector2(attrs.BezierPoint2[0], attrs.BezierPoint2[1]); + } + + Duration = attrs.Duration; + } + + /// Clone a AnimationAttributes + /// The AnimationAttributes copy + public AnimationAttributes Clone() + { + return new AnimationAttributes(this); + } + } + + /// + /// A GridBridge object acts as a pipeline between an BridgeView and the + /// underlying data for that view. The Bridge provides access to the data items. + /// The Bridge is also responsible for making a View for each item in the data set. + /// + public abstract class GridBridge + { + /// + /// Event type of data change. + /// + public enum DataChangeEventType + { + Add, + Remove, + Insert, + Clear, + Load, + Reset + } + + /// + /// Data change event args at event call back, + /// user can get information about data change. + /// + /// + ///private void OnDataChange(object o, GridBridge.DataChangeEventArgs e) + ///{ + ///} + /// + public class DataChangeEventArgs : EventArgs + { + /// + /// Data changed event type. + /// + public DataChangeEventType ChangeType + { + get { return m_ChangeType; } + set { m_ChangeType = value; } + } + + /// + /// Changed data. + /// + public object data; + /// + /// Data change event parameters. + /// + public int[] param = new int[4]; + + private DataChangeEventType m_ChangeType; + } + + /// + /// Event handler of data change event. + /// + /// The object who sends the event. + /// The event arguments. + public delegate void EventHandler(object sender, DataChangeEventArgs e); + + /// + /// Data change event handler, user can add/remove. + /// + public event EventHandler DataChangeEvent + { + add + { + dataChangeEventHandlers += value; + } + + remove + { + dataChangeEventHandlers -= value; + } + } + + /// + /// Constructor to create a grid view bridge with multi-groups. + /// + /// Data list of differet groups. + public GridBridge(List> objects) + { + gridData = objects; + } + + /// + /// Simple constructor to create a grid view bridge with one group. + /// + /// Data list of grid view. + public GridBridge(List objects) + { + gridData = new List>(); + gridData.Add(objects); + } + + /// + /// Create item View. + /// + /// Group index of item in grid view. + /// Item index of specified group of grid view. + /// View of specified item. + public abstract View GetItemView(int groupIndex, int itemIndex); + + /// + /// Create group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual View GetGroupTitleView(int groupIndex) + { + return null; + } + + /// + /// Remove group title of specified group, need to be overrided. + /// + /// Group index of grid view. + /// Group title view. + public virtual void RemoveGroupTitleView(int groupIndex, View groupTitle) + { + + } + + /// + /// Update View that displays the data at the specified index in the data set when data change. + /// + /// The group index. + /// The item index. + /// A View that displays the data at the specified index in the data set. + public abstract void UpdateItem(int groupIndex, int itemIndex, View view); + + /// + /// Update View that displays the data at the specified index in the data set when focus change. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + /// Focus in or focus out + /// LinearView item selected or not. + public abstract void FocusChange(int groupIndex, int itemIndex, View view, bool FlagFocused, bool bSelected = false); + + /// + /// Unload view at the specified index when item scroll out or deleted. + /// + /// The group index. + /// The item index. + /// Item view of specified item. + public abstract void UnloadItem(int groupIndex, int itemIndex, View view); + + /// + /// Unload view according to the specified viewType. + /// + /// Item type set by users. + /// A View that displays the data at the specified index in the data set. + public abstract void UnloadItemByViewType(int viewType, View view); + + /// + /// Get the type of View that will be created by GetView for the specified item. + /// + /// The group index. + /// The item index. + /// Integers must be in the range 0 to GetItemTypeCount() - 1. + /// Item type. + public virtual int GetItemType(int groupIndex, int itemIndex) + { + return 0; + } + + /// + /// Get the number of view types. + /// + /// The count of view type. + public virtual int GetItemTypeCount() + { + return 1; + } + + /// + /// Check whether item is enable or not. + /// + /// The group index. + /// The item index. + /// Item is enabled or disabled. + public virtual bool IsItemEnabled(int groupIndex, int itemIndex) + { + return true; + } + + /// + /// Get the data at the specified index. + /// + /// The item index. + /// The group index. + /// The data at the specified index. + public object GetData(int itemIndex, int groupIndex = 0) + { + object data = null; + if (gridData != null && gridData.ElementAt(groupIndex) != null && itemIndex >= 0 && itemIndex < gridData.ElementAt(groupIndex).Count) + { + data = gridData.ElementAt(groupIndex).ElementAt(itemIndex); + } + + return data; + } + + /// + /// Get data group count of the bridge. + /// + /// Group count of the data set. + public int GetGroupCount() + { + int count = 0; + if (gridData != null) + { + count = gridData.Count; + } + + return count; + } + + /// + /// How many items are in the data set of specified group. + /// + /// The data group index. + /// Count of items of specified group. + public int GetItemCount(int groupIndex = 0) + { + int count = 0; + if (gridData != null && gridData.ElementAtOrDefault(groupIndex) != null) + { + count = gridData.ElementAt(groupIndex).Count; + } + + return count; + } + + /// + /// How many items are in the data set of whole data list. + /// + /// Count of total items + public int GetTotalCount() + { + int count = 0; + if (gridData != null) + { + foreach (List group in gridData) + { + count += group.Count; + } + } + + return count; + } + + /// + /// Adds the specified data at the end of the List of specified group. + /// + /// The data to add at the end of the List. + /// The group index which need to add data. + /// Notify list to remove item or not. + public void Add(object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Add(data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Add; + e.param[0] = groupIndex; + e.data = data; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The remove number of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + + public void RemoveItems(int fromIndex, int removeNum, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + if (fromIndex + removeNum > gridData[groupIndex].Count) + { + return; + } + + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Remove; + e.param[0] = groupIndex; + e.param[1] = fromIndex; + e.param[2] = removeNum; + e.param[3] = withAni ? 1 : 0; + OnDataChangeEvent(this, e, sendEvent); + gridData[groupIndex].RemoveRange(fromIndex, removeNum); + e.ChangeType = DataChangeEventType.Load; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Removes the specified data from the List of specified group. + /// + /// The from index of data to remove from the list. + /// The group index which need to add data. + /// Remove with animation or not. + /// Notify list to remove item or not. + public void Remove(int itemIndex, int groupIndex = 0, bool withAni = false, bool sendEvent = true) + { + if (itemIndex < 0 || itemIndex >= GetItemCount(groupIndex)) + { + Tizen.Log.Fatal("NUI", "Error!! item index is invalid"); + return; + } + + RemoveItems(itemIndex, 1, groupIndex, withAni, sendEvent); + } + + /// + /// Inserts the specified data at the specified index in the List of specified group. + /// + /// The index at which the data must be inserted. + /// The data to insert into the list. + /// The group index which need to insert data. + /// Notify list to remove item or not. + public void Insert(int index, object data, int groupIndex = 0, bool sendEvent = true) + { + Debug.Assert(groupIndex < gridData.Count); + + gridData[groupIndex].Insert(index, data); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Insert; + e.data = data; + e.param[0] = groupIndex; + e.param[1] = index; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Remove all elements from the list. + /// + /// Notify list to remove item or not. + public void Clear(bool sendEvent = true) + { + if (gridData != null) + { + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Clear; + OnDataChangeEvent(this, e, sendEvent); + gridData.Clear(); + } + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of differet groups. + /// Notify list to remove item or not. + public void Reset(List> objects, bool sendEvent = true) + { + Clear(); + gridData = objects; + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Reset bridge, and Update LinearView with new bridge data. + /// + /// Data list of grid view. + /// Notify list to remove item or not. + public void Reset(List objects, bool sendEvent = true) + { + Clear(); + gridData = new List>(); + gridData.Add(objects); + DataChangeEventArgs e = new DataChangeEventArgs(); + e.ChangeType = DataChangeEventType.Reset; + OnDataChangeEvent(this, e, sendEvent); + } + + /// + /// Swap data of specified group. + /// + /// The group index which need to insert data. + /// First item index of the group. + /// Second item index of the group. + public void SwapGroupData(int groupIndex, int from, int to) + { + List groupDataList = gridData.ElementAt(groupIndex); + object fromData = groupDataList.ElementAt(from); + groupDataList[from] = groupDataList[to]; + groupDataList[to] = fromData; + } + + private void OnDataChangeEvent(object sender, DataChangeEventArgs e, bool sendEvent = true) + { + if (!sendEvent) + { + return; + } + + if (dataChangeEventHandlers != null) + { + dataChangeEventHandlers(sender, e); + } + } + + private List> gridData; + private EventHandler dataChangeEventHandlers; + } +} + +``` + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +pointer `curCell` last assigned on line 769 could be null and is dereferenced at line 770, column 13. + +### Severity: +ERROR + +### Procedure: +Void GridView.UpdateItem(Int32,Int32) + +### File: +TV/MediaHubSample/MediaHubSample/src/View/GridView/Grid.cs + +### Key: +Grid.cs|UpdateItem|NULL_DEREFERENCE + +### Node Key: +44f51522748942dcf2a0bd14d230aaeb + +### Hash: +a775d8c51f20159e39f5d15aed07095b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-0793/instruction.md b/inferredbugs-0793/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3848f1b6814c24ed0bcedaae8ed59db3d072ad37 --- /dev/null +++ b/inferredbugs-0793/instruction.md @@ -0,0 +1,179 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** Chia-Plot-Status +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Input.Platform; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Markup.Xaml; +using Avalonia.Markup.Xaml.Styling; +using Avalonia.Platform; +using ChiaPlotStatus.GUI.Models; +using ChiaPlotStatus.Logic.Models; +using Octokit; +using ReactiveUI; +using System; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Reactive; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using YamlDotNet.Serialization; + +namespace ChiaPlotStatus.Views +{ + public class UpdateDialog : Window + { + public GUI.Models.Language Language { get; set; } + public Release Latest { get; set; } + public string Current { get; set; } + public string current { get; set; } + + public UpdateDialog() { } + + public UpdateDialog(GUI.Models.Language language) + { + this.DataContext = this; + this.Language = language; + this.Current = LoadCurrentRelease(); + this.Latest = LoadLatestRelease(); + InitializeComponent(); +#if DEBUG + this.AttachDevTools(); +#endif + this.Find("UpToDate").IsVisible = string.Equals(this.Latest.TagName, this.Current); + this.Find","\n\t\t$1") + .replaceAll("(?i)","") + .replaceAll("(\t|\n|\\s){2,}","\n") + .replaceAll("No Same as","No Same as\nNo Same as Sponsor"); + + if(status.contains("Bill Status Information Not Found")) + return false; + + String strings[] = status.split("\n"); + + bill.setSponsor(new Person(strings[2])); + + String sameAsBillNo = strings[3].replaceAll("(Same as| |\\-)",""); + bill.setSameAs(sameAsBillNo); + + bill.setLawSection(strings[5]); + + String title = strings[6].replace("TITLE....",""); + bill.setTitle(title); + + SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy"); + for(int i = 7; i < strings.length;) { + if(strings[i].matches("\\d{2}/\\d{2}/\\d{2}")) { + BillEvent be = new BillEvent(); + try { + + be.setEventDate(sdf.parse(strings[i])); + i++; + be.setEventText(strings[i]); + + bill.addBillEvent(be); + } catch (ParseException e) { + logger.error(e); + } + i++; + } + else { + if(strings[i].charAt(0) == sameAsBillNo.charAt(0)) { + i += 2; + while(strings[i].matches("\\d{2}/\\d{2}/\\d{2}")) { + i += 2; + } + i += 2; + } + else { + break; + } + } + } + return true; + } + + public boolean parseSummary(String summary, Bill bill) { + if(summary == null) + return false; + + summary = summary.replaceAll("(?i)
","\n") + .replaceAll("(?i)","") + .replaceAll("(\t|\n|\\s){2,}","\n"); + + if(summary.contains("Bill Summary Information Not Available")) + return false; + + String[] strings = summary.split("\n"); + + bill.setSummary(strings[3]); + + return true; + } + + public boolean parseText(String text, Bill bill) { + if(text == null) + return false; + + text = text.replaceAll("(?i)
","\n") + .replaceAll("(?i)",""); + + String[] strings = text.split("\n"); + + bill.setFulltext(strings[1]); + + return true; + } + + public boolean parseMemo(String memo, Bill bill) { + if(memo == null) + return false; + + memo = memo.replaceAll(" ", "").replaceAll("(?i)
","\n") + .replaceAll(" ","") + .replaceAll("(?i)",""); + + if(memo.contains("Memo Text Not Found")) + return false; + + String[] strings = memo.split("\n"); + + bill.setMemo(strings[5]); + + return true; + } + + private static String getInstanceKey() { + String key = null; + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(new URL(KEY_URL).openStream())); + + Pattern tokenPattern = Pattern.compile(""); + Matcher tokenMatcher = null; + + String in = null; + + while((in = br.readLine()) != null) { + + tokenMatcher = tokenPattern.matcher(in); + + if(tokenMatcher.find()) { + key = tokenMatcher.group(1); + } + } + br.close(); + } + catch (IOException ioe) { + logger.error(ioe); + } + + return key; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `l` last assigned on line 22 could be null and is dereferenced at line 24. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LRSConnect.main(java.lang.String[]) + +### Procedure Id: +gov.nysenate.openleg.qa.LRSConnect.main(java.lang.String[]):void.b9122a778ed48d3f3b3997d1f4687190 + +### File: +src/main/java/gov/nysenate/openleg/qa/LRSConnect.java + +### Key: +LRSConnect.java|main|NULL_DEREFERENCE + +### Node Key: +518e186ffce84ce33052e851bc5427a0 + +### Hash: +1087a545a5cd6baf93f5bbdfe1c1bfa4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6379/instruction.md b/inferredbugs-6379/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d24161d1ac737ec82c09fb6aa49a9f7f386b163 --- /dev/null +++ b/inferredbugs-6379/instruction.md @@ -0,0 +1,293 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** blynk-server +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package cc.blynk.server.workers; + +import cc.blynk.server.core.dao.ReportingDao; +import cc.blynk.server.core.model.enums.GraphType; +import cc.blynk.server.core.model.enums.PinType; +import cc.blynk.server.core.reporting.average.AggregationKey; +import cc.blynk.server.core.reporting.average.AggregationValue; +import cc.blynk.server.core.reporting.average.AverageAggregator; +import cc.blynk.server.db.DBManager; +import cc.blynk.utils.ReportingUtil; +import cc.blynk.utils.ServerProperties; +import org.apache.commons.io.FileUtils; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.runners.MockitoJUnitRunner; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.concurrent.ConcurrentHashMap; + +import static cc.blynk.server.core.dao.ReportingDao.*; +import static cc.blynk.utils.ReportingUtil.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +/** + * The Blynk Project. + * Created by Dmitriy Dumanskiy. + * Created on 11.08.15. + */ +@RunWith(MockitoJUnitRunner.class) +public class StorageWorkerTest { + + private final String reportingFolder = getReportingFolder(System.getProperty("java.io.tmpdir")); + + @Mock + public AverageAggregator averageAggregator; + + @Mock + public ServerProperties properties; + + @Before + public void cleanup() throws IOException { + Path dataFolder1 = Paths.get(reportingFolder, "test"); + FileUtils.deleteDirectory(dataFolder1.toFile()); + ReportingUtil.createReportingFolder(reportingFolder, "test"); + + Path dataFolder2 = Paths.get(reportingFolder, "test2"); + FileUtils.deleteDirectory(dataFolder2.toFile()); + ReportingUtil.createReportingFolder(reportingFolder, "test2"); + } + + @Test + public void testStore() throws IOException { + StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); + + ConcurrentHashMap map = new ConcurrentHashMap<>(); + + long ts = getTS() / AverageAggregator.HOUR; + + AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); + AggregationValue aggregationValue = new AggregationValue(); + aggregationValue.update(100); + AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); + AggregationValue aggregationValue2 = new AggregationValue(); + aggregationValue2.update(150.54); + AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); + AggregationValue aggregationValue3 = new AggregationValue(); + aggregationValue3.update(200); + + map.put(aggregationKey, aggregationValue); + map.put(aggregationKey2, aggregationValue2); + map.put(aggregationKey3, aggregationValue3); + + when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); + when(averageAggregator.getHourly()).thenReturn(map); + when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); + + storageWorker.run(); + + assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); + assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); + + byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 2, GraphType.HOURLY); + ByteBuffer byteBuffer = ByteBuffer.wrap(data); + assertNotNull(data); + assertEquals(32, data.length); + + assertEquals(150.54, byteBuffer.getDouble(), 0.001); + assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); + + assertEquals(100.0, byteBuffer.getDouble(), 0.001); + assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); + + data = ReportingDao.getAllFromDisk(reportingFolder, "test2", 2, PinType.ANALOG, (byte) 2, 1, GraphType.HOURLY); + byteBuffer = ByteBuffer.wrap(data); + assertNotNull(data); + assertEquals(16, data.length); + assertEquals(200.0, byteBuffer.getDouble(), 0.001); + assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); + } + + @Test + public void testStore2() throws IOException { + StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); + + ConcurrentHashMap map = new ConcurrentHashMap<>(); + + long ts = getTS() / AverageAggregator.HOUR; + + AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); + AggregationValue aggregationValue = new AggregationValue(); + aggregationValue.update(100); + AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); + AggregationValue aggregationValue2 = new AggregationValue(); + aggregationValue2.update(150.54); + AggregationKey aggregationKey3 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 2); + AggregationValue aggregationValue3 = new AggregationValue(); + aggregationValue3.update(200); + + map.put(aggregationKey, aggregationValue); + map.put(aggregationKey2, aggregationValue2); + map.put(aggregationKey3, aggregationValue3); + + when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); + when(averageAggregator.getHourly()).thenReturn(map); + when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); + + storageWorker.run(); + + assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); + + //take less + byte[] data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 1, GraphType.HOURLY); + ByteBuffer byteBuffer = ByteBuffer.wrap(data); + assertNotNull(data); + assertEquals(16, data.length); + + assertEquals(100.0, byteBuffer.getDouble(), 0.001); + assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); + + + //take more + data = ReportingDao.getAllFromDisk(reportingFolder, "test", 1, PinType.ANALOG, (byte) 1, 24, GraphType.HOURLY); + byteBuffer = ByteBuffer.wrap(data); + assertNotNull(data); + assertEquals(48, data.length); + + assertEquals(200.0, byteBuffer.getDouble(), 0.001); + assertEquals((ts - 2) * AverageAggregator.HOUR, byteBuffer.getLong()); + + assertEquals(150.54, byteBuffer.getDouble(), 0.001); + assertEquals((ts - 1) * AverageAggregator.HOUR, byteBuffer.getLong()); + + assertEquals(100.0, byteBuffer.getDouble(), 0.001); + assertEquals(ts * AverageAggregator.HOUR, byteBuffer.getLong()); + } + + + @Test + public void testDeleteCommand() throws IOException { + StorageWorker storageWorker = new StorageWorker(averageAggregator, reportingFolder, new DBManager(null)); + + ConcurrentHashMap map = new ConcurrentHashMap<>(); + + long ts = getTS() / AverageAggregator.HOUR; + + AggregationKey aggregationKey = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts); + AggregationValue aggregationValue = new AggregationValue(); + aggregationValue.update(100); + AggregationKey aggregationKey2 = new AggregationKey("test", 1, PinType.ANALOG, (byte) 1, ts - 1); + AggregationValue aggregationValue2 = new AggregationValue(); + aggregationValue2.update(150.54); + AggregationKey aggregationKey3 = new AggregationKey("test2", 2, PinType.ANALOG, (byte) 2, ts); + AggregationValue aggregationValue3 = new AggregationValue(); + aggregationValue3.update(200); + + map.put(aggregationKey, aggregationValue); + map.put(aggregationKey2, aggregationValue2); + map.put(aggregationKey3, aggregationValue3); + + when(averageAggregator.getMinute()).thenReturn(new ConcurrentHashMap<>()); + when(averageAggregator.getHourly()).thenReturn(map); + when(averageAggregator.getDaily()).thenReturn(new ConcurrentHashMap<>()); + when(properties.getProperty("data.folder")).thenReturn(System.getProperty("java.io.tmpdir")); + + storageWorker.run(); + + assertTrue(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); + assertTrue(Files.exists(Paths.get(reportingFolder, "test2", generateFilename(2, PinType.ANALOG, (byte) 2, GraphType.HOURLY)))); + + new ReportingDao(reportingFolder, null, properties).delete("test", 1, PinType.ANALOG, (byte) 1); + assertFalse(Files.exists(Paths.get(reportingFolder, "test", generateFilename(1, PinType.ANALOG, (byte) 1, GraphType.HOURLY)))); + } + + private long getTS() { + SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss"); + String dateInString = "Aug 10, 2015 12:10:56"; + + try { + + Date date = formatter.parse(dateInString); + return date.getTime(); + } catch (ParseException e) { + e.printStackTrace(); + } + + return 0; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.zaxxer.hikari.HikariDataSource` acquired by call to `DBManager(...)` at line 170 is not released after line 195. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void StorageWorkerTest.testDeleteCommand() + +### Procedure Id: +cc.blynk.server.workers.StorageWorkerTest.testDeleteCommand():void.997d17f6c57378ae7b1be51820da4ae0 + +### File: +server/launcher/src/test/java/cc/blynk/server/workers/StorageWorkerTest.java + +### Key: +StorageWorkerTest.java|testDeleteCommand|RESOURCE_LEAK + +### Node Key: +f748d9ffd849bf00ecfc267a3683e52c + +### Hash: +9237c8a8fa6d16a81afd5c7914261b96 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6384/instruction.md b/inferredbugs-6384/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f76b59c33c853be3096b50039faa7212ec746df5 --- /dev/null +++ b/inferredbugs-6384/instruction.md @@ -0,0 +1,214 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** blynk-server +**Bug ID:** 36 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package cc.blynk.server.workers; + +import cc.blynk.server.core.dao.ReportingDao; +import cc.blynk.server.core.dao.UserDao; +import cc.blynk.server.core.model.DashBoard; +import cc.blynk.server.core.model.DataStream; +import cc.blynk.server.core.model.auth.User; +import cc.blynk.server.core.model.widgets.Target; +import cc.blynk.server.core.model.widgets.Widget; +import cc.blynk.server.core.model.widgets.outputs.HistoryGraph; +import cc.blynk.server.core.model.widgets.outputs.graph.EnhancedHistoryGraph; +import cc.blynk.server.core.model.widgets.outputs.graph.GraphDataStream; +import cc.blynk.server.core.model.widgets.outputs.graph.GraphGranularityType; +import cc.blynk.server.core.model.widgets.ui.tiles.DeviceTiles; +import cc.blynk.server.core.model.widgets.ui.tiles.TileTemplate; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.util.HashSet; +import java.util.Set; + +/** + * Daily job used to clean reporting data that is not used by the history graphs + * but stored anyway on the disk. + * + * The Blynk Project. + * Created by Dmitriy Dumanskiy. + * Created on 04.01.18. + */ +public class HistoryGraphUnusedPinDataCleanerWorker implements Runnable { + + private static final Logger log = LogManager.getLogger(HistoryGraphUnusedPinDataCleanerWorker.class); + + private final UserDao userDao; + private final ReportingDao reportingDao; + + private long lastStart; + + public HistoryGraphUnusedPinDataCleanerWorker(UserDao userDao, ReportingDao reportingDao) { + this.userDao = userDao; + this.reportingDao = reportingDao; + this.lastStart = System.currentTimeMillis(); + + } + + @Override + public void run() { + try { + log.info("Start removing unused reporting data..."); + + long now = System.currentTimeMillis(); + //todo + //actually, it is better to do not save data for such pins + //but fow now this approach is simpler and quicker + int result = removeUnsedInHistoryGraphData(); + + lastStart = now; + + log.info("Removed {} files. Time : {} ms.", result, System.currentTimeMillis() - now); + } catch (Throwable t) { + log.error("Error removing unused reporting data.", t); + } + } + + private int removeUnsedInHistoryGraphData() { + int removedFilesCounter = 0; + Set doNotRemovePaths = new HashSet<>(); + + for (User user : userDao.getUsers().values()) { + //we don't want to do a lot of work here, + //so we check only active profiles that actually write data + if (user.isUpdated(lastStart)) { + doNotRemovePaths.clear(); + try { + for (DashBoard dashBoard : user.profile.dashBoards) { + for (Widget widget : dashBoard.widgets) { + if (widget instanceof DeviceTiles) { + DeviceTiles deviceTiles = (DeviceTiles) widget; + for (TileTemplate tileTemplate : deviceTiles.templates) { + for (Widget tilesWidget : tileTemplate.widgets) { + add(doNotRemovePaths, dashBoard, tilesWidget); + } + } + } else { + add(doNotRemovePaths, dashBoard, widget); + } + } + } + + removedFilesCounter += reportingDao.delete(user, + reportingFile -> !doNotRemovePaths.contains(reportingFile.getFileName().toString())); + } catch (Exception e) { + log.error("Error cleaning reporting record for user {}. {}", user.email, e.getMessage()); + } + } + } + return removedFilesCounter; + } + + private static void add(Set doNotRemovePaths, DashBoard dash, Widget widget) { + if (widget instanceof HistoryGraph) { + HistoryGraph historyGraph = (HistoryGraph) widget; + add(doNotRemovePaths, dash.id, historyGraph); + } else if (widget instanceof EnhancedHistoryGraph) { + EnhancedHistoryGraph enhancedHistoryGraph = (EnhancedHistoryGraph) widget; + add(doNotRemovePaths, dash, enhancedHistoryGraph); + } + } + + private static void add(Set doNotRemovePaths, DashBoard dash, EnhancedHistoryGraph graph) { + for (GraphDataStream graphDataStream : graph.dataStreams) { + if (graphDataStream != null && graphDataStream.dataStream != null && graphDataStream.dataStream.isValid()) { + DataStream dataStream = graphDataStream.dataStream; + Target target = dash.getTarget(graphDataStream.targetId); + for (int deviceId : target.getAssignedDeviceIds()) { + for (GraphGranularityType type : GraphGranularityType.values()) { + String filename = ReportingDao.generateFilename(dash.id, + deviceId, + dataStream.pinType.pintTypeChar, dataStream.pin, type.label); + doNotRemovePaths.add(filename); + } + } + } + } + } + + //todo history graph is only for back compatibility and should be removed in future + private static void add(Set doNotRemovePaths, int dashId, HistoryGraph graph) { + for (DataStream dataStream : graph.dataStreams) { + if (dataStream.isValid()) { + for (GraphGranularityType type : GraphGranularityType.values()) { + String filename = ReportingDao.generateFilename(dashId, graph.deviceId, + dataStream.pinType.pintTypeChar, dataStream.pin, type.label); + doNotRemovePaths.add(filename); + } + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `target` last assigned on line 114 could be null and is dereferenced at line 115. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HistoryGraphUnusedPinDataCleanerWorker.add(Set,DashBoard,EnhancedHistoryGraph) + +### Procedure Id: +cc.blynk.server.workers.HistoryGraphUnusedPinDataCleanerWorker.add(java.util.Set,cc.blynk.server.cor.a9a5e452892d3a140dd9b06590d186f6 + +### File: +server/launcher/src/main/java/cc/blynk/server/workers/HistoryGraphUnusedPinDataCleanerWorker.java + +### Key: +HistoryGraphUnusedPinDataCleanerWorker.java|add|NULL_DEREFERENCE + +### Node Key: +50cb5ef8465ad6b6a77b806e5d8dd53e + +### Hash: +7c26ad592d99660923cddc10f81034df + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6400/instruction.md b/inferredbugs-6400/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0b3391146207a45a5ee374d8e5eecdc958f8d90 --- /dev/null +++ b/inferredbugs-6400/instruction.md @@ -0,0 +1,400 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 61 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class CSVPrinterTest { + + public static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + + public void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, format); + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + Utils.compare("Printer output :" + printable(result), lines, parseResult); + } + + public void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + public String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = '"'; + break; + case 7: + ch = '\''; + break; + case 8: + ch = '\\'; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printComment("This is a comment"); + + assertEquals("", sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), + Arrays.asList(new String[] { "r2c1", "r2c2" }) })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + try { + final Statement stmt = connection.createStatement(); + stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); + stmt.execute("insert into TEST values(1, 'r1')"); + stmt.execute("insert into TEST values(2, 'r2')"); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); + assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); + } finally { + connection.close(); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.ALL).build()); + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.NON_NUMERIC).build()); + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + } + + @Test + public void testRandom() throws Exception { + final int iter = 10000; + doRandom(CSVFormat.DEFAULT, iter); + doRandom(CSVFormat.EXCEL, iter); + doRandom(CSVFormat.MYSQL, iter); + } + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment"); + + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.CSVPrinter` acquired to `printer` by call to `new()` at line 248 is not released after line 249. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVPrinterTest.testPrinter3() + +### Procedure Id: +org.apache.commons.csv.CSVPrinterTest.testPrinter3():void.e5f36d470e5082cf8397c5e1162bff86 + +### File: +src/test/java/org/apache/commons/csv/CSVPrinterTest.java + +### Key: +CSVPrinterTest.java|testPrinter3|RESOURCE_LEAK + +### Node Key: +0fb8a1c0ca4d50e67c93620b0e0bccf7 + +### Hash: +a9375bf00ff3edbc35b64380f07dcecc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6407/instruction.md b/inferredbugs-6407/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c10e5f16ed60965baf627fd4dcc069195c33a38f --- /dev/null +++ b/inferredbugs-6407/instruction.md @@ -0,0 +1,400 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 50 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class CSVPrinterTest { + + public static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + + public void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, format); + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + Utils.compare("Printer output :" + printable(result), lines, parseResult); + } + + public void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + public String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = '"'; + break; + case 7: + ch = '\''; + break; + case 8: + ch = '\\'; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printComment("This is a comment"); + + assertEquals("", sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), + Arrays.asList(new String[] { "r2c1", "r2c2" }) })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + try { + final Statement stmt = connection.createStatement(); + stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); + stmt.execute("insert into TEST values(1, 'r1')"); + stmt.execute("insert into TEST values(2, 'r2')"); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); + assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); + } finally { + connection.close(); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.ALL).build()); + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.NON_NUMERIC).build()); + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + } + + @Test + public void testRandom() throws Exception { + final int iter = 10000; + doRandom(CSVFormat.DEFAULT, iter); + doRandom(CSVFormat.EXCEL, iter); + doRandom(CSVFormat.MYSQL, iter); + } + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment"); + + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.CSVPrinter` acquired to `printer` by call to `new()` at line 147 is not released after line 148. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVPrinterTest.testDisabledComment() + +### Procedure Id: +org.apache.commons.csv.CSVPrinterTest.testDisabledComment():void.929d9c723601f34e28c0580ed36fb76b + +### File: +src/test/java/org/apache/commons/csv/CSVPrinterTest.java + +### Key: +CSVPrinterTest.java|testDisabledComment|RESOURCE_LEAK + +### Node Key: +3821ccc1fe016266c26ff3d1e7f13420 + +### Hash: +650ed91245e9619a1a81f13f416594fc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6409/instruction.md b/inferredbugs-6409/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..445a6444d387945794f450aa931f1e2e1987153a --- /dev/null +++ b/inferredbugs-6409/instruction.md @@ -0,0 +1,812 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 103 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parseString(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parseString(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = CSVParser.parseString(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = CSVParser.parseString(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parseString(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true) + .parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true) + .parse(in).iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parseString("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordWithMultiiLineValues() throws Exception { + final CSVParser parser = CSVParser.parseString("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser((Reader) null, invalidFormat).close(); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parseString("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parseString("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `parseString(...)` at line 383 is not released after line 384. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testDefaultFormat() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testDefaultFormat():void.90b030b6ec0a6fbfae29a1f268d7e11a + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testDefaultFormat|RESOURCE_LEAK + +### Node Key: +93644ec69cbfe39e33422caaa4675eaa + +### Hash: +412c34112c63a464fe1d96f59e254a59 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6431/instruction.md b/inferredbugs-6431/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb2db4e3d938d568aab898cfcab6c61667d87be9 --- /dev/null +++ b/inferredbugs-6431/instruction.md @@ -0,0 +1,280 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 145 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.StringReader; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + final ExtendedBufferedReader br = getBufferedReader(""); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + + @Test + public void testReadLookahead1() throws Exception { + final ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + final ExtendedBufferedReader br = getBufferedReader("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + + @Test + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertNull(br.readLine()); + + br = getBufferedReader("\n"); + assertEquals("",br.readLine()); + assertNull(br.readLine()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello",br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello",br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + + br = getBufferedReader("foo\rbaar\r\nfoo"); + assertEquals("foo",br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar",br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo",br.readLine()); + assertNull(br.readLine()); + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF="\n"; final String CR="\r"; final String CRLF=CR+LF; final String LFCR=LF+CR;// easier to read the string below + final String test="a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f "+ CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + ExtendedBufferedReader br; + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + + private ExtendedBufferedReader getBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `br` by call to `getBufferedReader(...)` at line 159 is not released after line 165. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testReadLine() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testReadLine():void.e38b90399370c04e7bcace6e540a3af8 + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testReadLine|RESOURCE_LEAK + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +d9e228eabc73257ac0060a4b3c304987 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6436/instruction.md b/inferredbugs-6436/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84806f07575a80a1b979dea56e4d241fb8704b1f --- /dev/null +++ b/inferredbugs-6436/instruction.md @@ -0,0 +1,685 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import junit.framework.TestCase; + +import static org.apache.commons.csv.CSVParser.Token.Type.*; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + */ +public class CSVParserTest extends TestCase { + + /** + * TestCSVParser. + */ + class TestCSVParser extends CSVParser { + /** + * Test parser to investigate the type of the internal Token. + * + * @param in a Reader + */ + TestCSVParser(Reader in) { + super(in); + } + + TestCSVParser(Reader in, CSVFormat format) { + super(in, format); + } + + /** + * Calls super.nextToken() and prints out a String representation of token + * type and content. + * + * @return String representation of token type and content + * @throws IOException like {@link CSVParser#nextToken()} + */ + public String testNextToken() throws IOException { + Token t = super.nextToken(); + return t.type.name() + ";" + t.content + ";"; + } + } + + // ====================================================== + // lexer tests + // ====================================================== + + // Single line (without comment) + public void testNextToken1() throws IOException { + String code = "abc,def, hijk, lmnop, qrst,uv ,wxy ,z , ,"; + TestCSVParser parser = new TestCSVParser(new StringReader(code)); + assertEquals(TOKEN + ";abc;", parser.testNextToken()); + assertEquals(TOKEN + ";def;", parser.testNextToken()); + assertEquals(TOKEN + ";hijk;", parser.testNextToken()); + assertEquals(TOKEN + ";lmnop;", parser.testNextToken()); + assertEquals(TOKEN + ";qrst;", parser.testNextToken()); + assertEquals(TOKEN + ";uv;", parser.testNextToken()); + assertEquals(TOKEN + ";wxy;", parser.testNextToken()); + assertEquals(TOKEN + ";z;", parser.testNextToken()); + assertEquals(TOKEN + ";;", parser.testNextToken()); + assertEquals(EOF + ";;", parser.testNextToken()); + } + + // multiline including comments (and empty lines) + public void testNextToken2() throws IOException { + /* file: 1,2,3, + * a,b x,c + * + * # this is a comment + * d,e, + * + */ + String code = "1,2,3,\na,b x,c\n#foo\n\nd,e,\n\n"; + CSVFormat format = CSVFormat.DEFAULT.withCommentStart('#'); + + TestCSVParser parser = new TestCSVParser(new StringReader(code), format); + + + assertEquals(TOKEN + ";1;", parser.testNextToken()); + assertEquals(TOKEN + ";2;", parser.testNextToken()); + assertEquals(TOKEN + ";3;", parser.testNextToken()); + assertEquals(EORECORD + ";;", parser.testNextToken()); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + ";b x;", parser.testNextToken()); + assertEquals(EORECORD + ";c;", parser.testNextToken()); + assertEquals(EORECORD + ";;", parser.testNextToken()); + assertEquals(TOKEN + ";d;", parser.testNextToken()); + assertEquals(TOKEN + ";e;", parser.testNextToken()); + assertEquals(EORECORD + ";;", parser.testNextToken()); + assertEquals(EOF + ";;", parser.testNextToken()); + assertEquals(EOF + ";;", parser.testNextToken()); + + } + + // simple token with escaping + public void testNextToken3() throws IOException { + /* file: a,\,,b + * \,, + */ + String code = "a,\\,,b\n\\,,"; + CSVFormat format = CSVFormat.DEFAULT.withCommentStart('#'); + TestCSVParser parser = new TestCSVParser(new StringReader(code), format); + + assertEquals(TOKEN + ";a;", parser.testNextToken()); + // an unquoted single backslash is not an escape char + assertEquals(TOKEN + ";\\;", parser.testNextToken()); + assertEquals(TOKEN + ";;", parser.testNextToken()); + assertEquals(EORECORD + ";b;", parser.testNextToken()); + // an unquoted single backslash is not an escape char + assertEquals(TOKEN + ";\\;", parser.testNextToken()); + assertEquals(TOKEN + ";;", parser.testNextToken()); + assertEquals(EOF + ";;", parser.testNextToken()); + } + + // encapsulator tokenizer (sinle line) + public void testNextToken4() throws IOException { + /* file: a,"foo",b + * a, " foo",b + * a,"foo " ,b // whitespace after closing encapsulator + * a, " foo " ,b + */ + String code = + "a,\"foo\",b\na, \" foo\",b\na,\"foo \" ,b\na, \" foo \" ,b"; + TestCSVParser parser = new TestCSVParser(new StringReader(code)); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + ";foo;", parser.testNextToken()); + assertEquals(EORECORD + ";b;", parser.testNextToken()); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + "; foo;", parser.testNextToken()); + assertEquals(EORECORD + ";b;", parser.testNextToken()); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + ";foo ;", parser.testNextToken()); + assertEquals(EORECORD + ";b;", parser.testNextToken()); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + "; foo ;", parser.testNextToken()); +// assertEquals(EORECORD + ";b;", parser.testNextToken()); + assertEquals(EOF + ";b;", parser.testNextToken()); + } + + // encapsulator tokenizer (multi line, delimiter in string) + public void testNextToken5() throws IOException { + String code = + "a,\"foo\n\",b\n\"foo\n baar ,,,\"\n\"\n\t \n\""; + TestCSVParser parser = new TestCSVParser(new StringReader(code)); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals(TOKEN + ";foo\n;", parser.testNextToken()); + assertEquals(EORECORD + ";b;", parser.testNextToken()); + assertEquals(EORECORD + ";foo\n baar ,,,;", + parser.testNextToken()); + assertEquals(EOF + ";\n\t \n;", parser.testNextToken()); + + } + + // change delimiters, comment, encapsulater + public void testNextToken6() throws IOException { + /* file: a;'b and \' more + * ' + * !comment;;;; + * ;; + */ + String code = "a;'b and '' more\n'\n!comment;;;;\n;;"; + TestCSVParser parser = new TestCSVParser(new StringReader(code), new CSVFormat(';', '\'', '!')); + assertEquals(TOKEN + ";a;", parser.testNextToken()); + assertEquals( + EORECORD + ";b and ' more\n;", + parser.testNextToken()); + } + + + // ====================================================== + // parser tests + // ====================================================== + + String code = + "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + String[][] res = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + public void testGetLine() throws IOException { + CSVParser parser = new CSVParser(new StringReader(code)); + for (String[] re : res) { + assertTrue(Arrays.equals(re, parser.getLine())); + } + + assertTrue(parser.getLine() == null); + } + + public void testGetRecords() throws IOException { + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + public void testExcelFormat1() throws IOException { + String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + public void testExcelFormat2() throws Exception { + String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + public void testEndOfFileBehaviourExcel() throws Exception { + String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (String code : codes) { + CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + public void testEndOfFileBehaviorCSV() throws Exception { + String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + String code; + for (int codeIndex = 0; codeIndex < codes.length; codeIndex++) { + code = codes[codeIndex]; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + public void testEmptyLineBehaviourExcel() throws Exception { + String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + String code; + for (int codeIndex = 0; codeIndex < codes.length; codeIndex++) { + code = codes[codeIndex]; + CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + public void testEmptyLineBehaviourCSV() throws Exception { + String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + String code; + for (int codeIndex = 0; codeIndex < codes.length; codeIndex++) { + code = codes[codeIndex]; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + public void OLDtestBackslashEscaping() throws IOException { + String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" \" / string\" "}, + {"9", " \n "}, + }; + + + CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, true); + + CSVParser parser = new CSVParser(new StringReader(code), format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, //3 + }; + + + CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, true); + + CSVParser parser = new CSVParser(new StringReader(code), format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + + if (!CSVPrinterTest.equals(res, tmp)) { + assertTrue(false); + } + + } + + + public void testDefaultFormat() throws IOException { + + String code = "" + + "a,b\n" // 1) + + "\"\n\",\" \"\n" // 2) + + "\"\",#\n" // 2) + ; + String[][] res = { + {"a", "b"}, + {"\n", " "}, + {"", "#"}, + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertEquals(CSVFormat.DISABLED, format.getCommentStart()); + + CSVParser parser = new CSVParser(new StringReader(code), format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + + if (!CSVPrinterTest.equals(res, tmp)) { + assertTrue(false); + } + + String[][] res_comments = { + {"a", "b"}, + {"\n", " "}, + {""}, + }; + + format = new CSVFormat(',', '"', '#'); + parser = new CSVParser(new StringReader(code), format); + tmp = parser.getRecords(); + + if (!CSVPrinterTest.equals(res_comments, tmp)) { + assertTrue(false); + } + } + + + public void testUnicodeEscape() throws IOException { + String code = "abc,\\u0070\\u0075\\u0062\\u006C\\u0069\\u0063"; + CSVParser parser = new CSVParser(new StringReader(code), CSVFormat.DEFAULT.withUnicodeEscapesInterpreted(true)); + String[] data = parser.iterator().next(); + assertEquals(2, data.length); + assertEquals("abc", data[0]); + assertEquals("public", data[1]); + } + + public void testCarriageReturnLineFeedEndings() throws IOException { + String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + public void testCarriageReturnEndings() throws IOException { + String code = "foo\rbaar,\rhello,world\r,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + public void testLineFeedEndings() throws IOException { + String code = "foo\nbaar,\nhello,world\n,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + public void testIgnoreEmptyLines() throws IOException { + String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(3, data.length); + } + + // From SANDBOX-153 + public void testDelimiterIsWhitespace() throws IOException { + String code = "one\ttwo\t\tfour \t five\t six"; + TestCSVParser parser = new TestCSVParser(new StringReader(code), CSVFormat.TDF); + assertEquals(TOKEN + ";one;", parser.testNextToken()); + assertEquals(TOKEN + ";two;", parser.testNextToken()); + assertEquals(TOKEN + ";;", parser.testNextToken()); + assertEquals(TOKEN + ";four;", parser.testNextToken()); + assertEquals(TOKEN + ";five;", parser.testNextToken()); + assertEquals(EOF + ";six;", parser.testNextToken()); + } + + public void testForEach() { + List records = new ArrayList(); + + String code = "a,b,c\n1,2,3\nx,y,z"; + Reader in = new StringReader(code); + + for (String[] record : new CSVParser(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertTrue(Arrays.equals(new String[] {"a", "b", "c"}, records.get(0))); + assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, records.get(1))); + assertTrue(Arrays.equals(new String[] {"x", "y", "z"}, records.get(2))); + } + + public void testIterator() { + String code = "a,b,c\n1,2,3\nx,y,z"; + Iterator iterator = new CSVParser(new StringReader(code)).iterator(); + + assertTrue(iterator.hasNext()); + iterator.remove(); + assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next())); + assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next())); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next())); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (NoSuchElementException e) { + // expected + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `CSVParser(...)` at line 591 is not released after line 609. +**Note**: potential exception at line 596 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testIterator() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testIterator():void.99c7e0d51220c61183c31c9cc4e20cce + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testIterator|RESOURCE_LEAK + +### Node Key: +95ced91ca0473a6646194f1eb482b307 + +### Hash: +f8be408977d57975325996ad470429d6 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6438/instruction.md b/inferredbugs-6438/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..251f1e23cbd75da2e06948bb641b2b97881de021 --- /dev/null +++ b/inferredbugs-6438/instruction.md @@ -0,0 +1,264 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import java.io.StringReader; +import java.util.Arrays; + +import org.junit.Test; + +import static org.junit.Assert.*; + +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + + @Test + public void testReadLookahead1() throws Exception { + ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n"); + assertEquals('1', br.lookAhead()); + assertEquals(ExtendedBufferedReader.UNDEFINED, br.readAgain()); + assertEquals('1', br.read()); + assertEquals('1', br.readAgain()); + + assertEquals(0, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(0, br.getLineNumber()); + assertEquals('1', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + assertEquals('2', br.read()); + assertEquals('2', br.readAgain()); + + assertEquals('\r', br.lookAhead()); + assertEquals('2', br.readAgain()); + assertEquals('\r', br.read()); + assertEquals('\r', br.readAgain()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.readAgain()); + assertEquals('3', br.read()); + assertEquals('3', br.readAgain()); + + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getLineNumber()); // will need fixing for CSV-75 + assertEquals('3', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(2, br.getLineNumber()); // will need fixing for CSV-75 + assertEquals('\n', br.readAgain()); + assertEquals(2, br.getLineNumber()); // will need fixing for CSV-75 + + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + + } + + @Test + public void testReadLookahead2() throws Exception { + char[] ref = new char[5]; + char[] res = new char[5]; + + ExtendedBufferedReader br = getBufferedReader("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('c', br.readAgain()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('d', br.readAgain()); + } + + @Test + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertTrue(br.readLine() == null); + + br = getBufferedReader("\n"); + assertEquals("",br.readLine()); + assertTrue(br.readLine() == null); + + br = getBufferedReader("foo\n\nhello"); + assertEquals(0, br.getLineNumber()); + assertEquals("foo",br.readLine()); + assertEquals(1, br.getLineNumber()); + assertEquals("",br.readLine()); + assertEquals(2, br.getLineNumber()); + assertEquals("hello",br.readLine()); + assertEquals(3, br.getLineNumber()); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo",br.readLine()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("",br.readLine()); + assertEquals(2, br.getLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello",br.readLine()); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + + br = getBufferedReader("foo\rbaar\r\nfoo"); + assertEquals("foo",br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar",br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo",br.readLine()); + assertTrue(br.readLine() == null); + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + * TODO fix checks when code is fixed + */ + @Test + public void testReadChar() throws Exception { + String LF="\n"; String CR="\r"; String CRLF=CR+LF; String LFCR=LF+CR;// easier to read the string below + String test="a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f "+ CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + // EOL = current EOL behaviour with read() methods + // eol = additional behaviour with readLine() + final int EOLct=5; + final int EOLeolct=9; + ExtendedBufferedReader br; + + br = getBufferedReader(test); + assertEquals(0, br.getLineNumber()); + while(br.readLine()!=null) {} + assertEquals(EOLeolct, br.getLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getLineNumber()); + while(br.read()!=-1) {} + assertEquals(EOLct, br.getLineNumber()); // will need fixing for CSV-75 + + br = getBufferedReader(test); + assertEquals(0, br.getLineNumber()); + char[] buff = new char[10]; + while(br.read(buff ,0, 3)!=-1) {} + assertEquals(EOLct, br.getLineNumber()); // will need fixing for CSV-75 + } + + private ExtendedBufferedReader getBufferedReader(String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `br` by call to `getBufferedReader(...)` at line 115 is not released after line 117. +**Note**: potential exception at line 117 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testReadLine() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testReadLine():void.e38b90399370c04e7bcace6e540a3af8 + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testReadLine|RESOURCE_LEAK + +### Node Key: +b0332e11c33066b7b27fa03971d6db83 + +### Hash: +3046510e1a385a4187e6cceda30032e9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6452/instruction.md b/inferredbugs-6452/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f5ad29874f98a50472662f2daf594077971993f --- /dev/null +++ b/inferredbugs-6452/instruction.md @@ -0,0 +1,280 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 143 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.StringReader; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + final ExtendedBufferedReader br = getBufferedReader(""); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + + @Test + public void testReadLookahead1() throws Exception { + final ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + final ExtendedBufferedReader br = getBufferedReader("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + + @Test + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertNull(br.readLine()); + + br = getBufferedReader("\n"); + assertEquals("",br.readLine()); + assertNull(br.readLine()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello",br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello",br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + + br = getBufferedReader("foo\rbaar\r\nfoo"); + assertEquals("foo",br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar",br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo",br.readLine()); + assertNull(br.readLine()); + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF="\n"; final String CR="\r"; final String CRLF=CR+LF; final String LFCR=LF+CR;// easier to read the string below + final String test="a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f "+ CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + ExtendedBufferedReader br; + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + + private ExtendedBufferedReader getBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `br` by call to `getBufferedReader(...)` at line 134 is not released after line 143. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testReadLine() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testReadLine():void.e38b90399370c04e7bcace6e540a3af8 + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testReadLine|RESOURCE_LEAK + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +d9e228eabc73257ac0060a4b3c304987 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6453/instruction.md b/inferredbugs-6453/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aaecc6c877c6b519c33ea59a9ff57dc2b80d76d1 --- /dev/null +++ b/inferredbugs-6453/instruction.md @@ -0,0 +1,225 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import java.io.StringReader; +import java.util.Arrays; + +import junit.framework.TestCase; + +/** + * ExtendedBufferedReaderTest + */ +public class ExtendedBufferedReaderTest extends TestCase { + + public void testReadLookahead1() throws Exception { + + assertEquals(ExtendedBufferedReader.END_OF_STREAM, getEBR("").read()); + ExtendedBufferedReader br = getEBR("1\n2\r3\n"); + assertEquals('1', br.lookAhead()); + assertEquals(ExtendedBufferedReader.UNDEFINED, br.readAgain()); + assertEquals('1', br.read()); + assertEquals('1', br.readAgain()); + + assertEquals(0, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(0, br.getLineNumber()); + assertEquals('1', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + assertEquals('2', br.read()); + assertEquals('2', br.readAgain()); + + assertEquals('\r', br.lookAhead()); + assertEquals('2', br.readAgain()); + assertEquals('\r', br.read()); + assertEquals('\r', br.readAgain()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.readAgain()); + assertEquals('3', br.read()); + assertEquals('3', br.readAgain()); + + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getLineNumber()); + assertEquals('3', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(2, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(2, br.getLineNumber()); + + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + + } + + + public void testReadLookahead2() throws Exception { + char[] ref = new char[5]; + char[] res = new char[5]; + + ExtendedBufferedReader br = getEBR(""); + assertEquals(0, br.read(res, 0, 0)); + assertTrue(Arrays.equals(res, ref)); + + br = getEBR("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('c', br.readAgain()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('d', br.readAgain()); + + } + + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getEBR(""); + assertTrue(br.readLine() == null); + + br = getEBR("\n"); + assertTrue(br.readLine().equals("")); + assertTrue(br.readLine() == null); + + br = getEBR("foo\n\nhello"); + assertEquals(0, br.getLineNumber()); + assertTrue(br.readLine().equals("foo")); + assertEquals(1, br.getLineNumber()); + assertTrue(br.readLine().equals("")); + assertEquals(2, br.getLineNumber()); + assertTrue(br.readLine().equals("hello")); + assertEquals(3, br.getLineNumber()); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + br = getEBR("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertTrue(br.readLine().equals("oo")); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertTrue(br.readLine().equals("")); + assertEquals(2, br.getLineNumber()); + assertEquals('h', br.lookAhead()); + assertTrue(br.readLine().equals("hello")); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + + br = getEBR("foo\rbaar\r\nfoo"); + assertTrue(br.readLine().equals("foo")); + assertEquals('b', br.lookAhead()); + assertTrue(br.readLine().equals("baar")); + assertEquals('f', br.lookAhead()); + assertTrue(br.readLine().equals("foo")); + assertTrue(br.readLine() == null); + } + + private ExtendedBufferedReader getEBR(String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `getEBR(...)` at line 31 is not released after line 31. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testReadLookahead1() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testReadLookahead1():void.7a5ea71d745cd8578baac8b5bcd592ee + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testReadLookahead1|RESOURCE_LEAK + +### Node Key: +15891b12c6ce50257e480adc810587ae + +### Hash: +31cb925b4d39bb3feb6f4ac53d4ce369 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6454/instruction.md b/inferredbugs-6454/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b38fce0ff9e13315c3e7daa748c69b88f83ed54c --- /dev/null +++ b/inferredbugs-6454/instruction.md @@ -0,0 +1,280 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 144 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.StringReader; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + final ExtendedBufferedReader br = getBufferedReader(""); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + + @Test + public void testReadLookahead1() throws Exception { + final ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + final ExtendedBufferedReader br = getBufferedReader("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + + @Test + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertNull(br.readLine()); + + br = getBufferedReader("\n"); + assertEquals("",br.readLine()); + assertNull(br.readLine()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello",br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello",br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + + br = getBufferedReader("foo\rbaar\r\nfoo"); + assertEquals("foo",br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar",br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo",br.readLine()); + assertNull(br.readLine()); + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF="\n"; final String CR="\r"; final String CRLF=CR+LF; final String LFCR=LF+CR;// easier to read the string below + final String test="a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f "+ CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + ExtendedBufferedReader br; + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + + private ExtendedBufferedReader getBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `br` by call to `getBufferedReader(...)` at line 145 is not released after line 156. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testReadLine() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testReadLine():void.e38b90399370c04e7bcace6e540a3af8 + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testReadLine|RESOURCE_LEAK + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +d9e228eabc73257ac0060a4b3c304987 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6455/instruction.md b/inferredbugs-6455/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4081a5fcfa3872b9770f5e3d9a039997e8a1c947 --- /dev/null +++ b/inferredbugs-6455/instruction.md @@ -0,0 +1,310 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.csv; + +import java.io.StringReader; +import java.util.Arrays; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * ExtendedBufferedReaderTest + * + */ +public class ExtendedBufferedReaderTest extends TestCase { + + private ExtendedBufferedReader br = null; + + /** + * Constructor for ExtendedBufferedReaderTest. + * @param arg0 + */ + public ExtendedBufferedReaderTest(String arg0) { + super(arg0); + } + + public static Test suite() { + return new TestSuite(ExtendedBufferedReaderTest.class); + } + + // ====================================================== + // the test cases + // ====================================================== + + public void testConstructors() { + br = new ExtendedBufferedReader(new StringReader("")); + br = new ExtendedBufferedReader(new StringReader(""), 10); + } + + public void testReadLookahead1() throws Exception { + + assertEquals(ExtendedBufferedReader.END_OF_STREAM, getEBR("").read()); + br = getEBR("1\n2\r3\n"); + assertEquals('1', br.lookAhead()); + assertEquals(ExtendedBufferedReader.UNDEFINED, br.readAgain()); + assertEquals('1', br.read()); + assertEquals('1', br.readAgain()); + + assertEquals(0, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(0, br.getLineNumber()); + assertEquals('1', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(1, br.getLineNumber()); + assertEquals('2', br.read()); + assertEquals('2', br.readAgain()); + + assertEquals('\r', br.lookAhead()); + assertEquals('2', br.readAgain()); + assertEquals('\r', br.read()); + assertEquals('\r', br.readAgain()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.readAgain()); + assertEquals('3', br.read()); + assertEquals('3', br.readAgain()); + + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getLineNumber()); + assertEquals('3', br.readAgain()); + assertEquals('\n', br.read()); + assertEquals(2, br.getLineNumber()); + assertEquals('\n', br.readAgain()); + assertEquals(2, br.getLineNumber()); + + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read()); + assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead()); + + } + + + public void testReadLookahead2() throws Exception { + char[] ref = new char[5]; + char[] res = new char[5]; + + br = getEBR(""); + assertEquals(0, br.read(res, 0, 0)); + assertTrue(Arrays.equals(res, ref)); + + br = getEBR("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('c', br.readAgain()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertTrue(Arrays.equals(res, ref)); + assertEquals('d', br.readAgain()); + + } + + public void testMarkSupported() { + assertFalse(getEBR("foo").markSupported()); + } + + public void testReadLine() throws Exception { + br = getEBR(""); + assertTrue(br.readLine() == null); + + br = getEBR("\n"); + assertTrue(br.readLine().equals("")); + assertTrue(br.readLine() == null); + + br = getEBR("foo\n\nhello"); + assertEquals(0, br.getLineNumber()); + assertTrue(br.readLine().equals("foo")); + assertEquals(1, br.getLineNumber()); + assertTrue(br.readLine().equals("")); + assertEquals(2, br.getLineNumber()); + assertTrue(br.readLine().equals("hello")); + assertEquals(3, br.getLineNumber()); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + br = getEBR("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertTrue(br.readLine().equals("oo")); + assertEquals(1, br.getLineNumber()); + assertEquals('\n', br.lookAhead()); + assertTrue(br.readLine().equals("")); + assertEquals(2, br.getLineNumber()); + assertEquals('h', br.lookAhead()); + assertTrue(br.readLine().equals("hello")); + assertTrue(br.readLine() == null); + assertEquals(3, br.getLineNumber()); + + + br = getEBR("foo\rbaar\r\nfoo"); + assertTrue(br.readLine().equals("foo")); + assertEquals('b', br.lookAhead()); + assertTrue(br.readLine().equals("baar")); + assertEquals('f', br.lookAhead()); + assertTrue(br.readLine().equals("foo")); + assertTrue(br.readLine() == null); + } + + public void testSkip0() throws Exception { + + br = getEBR(""); + assertEquals(0, br.skip(0)); + assertEquals(0, br.skip(1)); + + br = getEBR(""); + assertEquals(0, br.skip(1)); + + br = getEBR("abcdefg"); + assertEquals(0, br.skip(0)); + assertEquals('a', br.lookAhead()); + assertEquals(0, br.skip(0)); + assertEquals('a', br.lookAhead()); + assertEquals(1, br.skip(1)); + assertEquals('b', br.lookAhead()); + assertEquals('b', br.read()); + assertEquals(3, br.skip(3)); + assertEquals('f', br.lookAhead()); + assertEquals(2, br.skip(5)); + assertTrue(br.readLine() == null); + + br = getEBR("12345"); + assertEquals(5, br.skip(5)); + assertTrue (br.lookAhead() == ExtendedBufferedReader.END_OF_STREAM); + } + + public void testSkipUntil() throws Exception { + br = getEBR(""); + assertEquals(0, br.skipUntil(';')); + br = getEBR("ABCDEF,GHL,,MN"); + assertEquals(6, br.skipUntil(',')); + assertEquals(0, br.skipUntil(',')); + br.skip(1); + assertEquals(3, br.skipUntil(',')); + br.skip(1); + assertEquals(0, br.skipUntil(',')); + br.skip(1); + assertEquals(2, br.skipUntil(',')); + } + + public void testReadUntil() throws Exception { + br = getEBR(""); + assertTrue(br.readUntil(';').equals("")); + br = getEBR("ABCDEF;GHL;;MN"); + assertTrue(br.readUntil(';').equals("ABCDEF")); + assertTrue(br.readUntil(';').length() == 0); + br.skip(1); + assertTrue(br.readUntil(';').equals("GHL")); + br.skip(1); + assertTrue(br.readUntil(';').equals("")); + br.skip(1); + assertTrue(br.readUntil(',').equals("MN")); + } + + private ExtendedBufferedReader getEBR(String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `ExtendedBufferedReaderTest.br` by call to `new()` at line 51 is not released after line 52. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testConstructors() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testConstructors():void.ad46b5105e12bc1f01d8ce73be0b4ac9 + +### File: +src/test/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testConstructors|RESOURCE_LEAK + +### Node Key: +b00d3f56cf93871ab48a48bae780d0ab + +### Hash: +be08ddbdc8f874d641f3e00ea193636e + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6462/instruction.md b/inferredbugs-6462/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0070e5997b77593434db58e26aee4f7e5cdf947 --- /dev/null +++ b/inferredbugs-6462/instruction.md @@ -0,0 +1,784 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 81 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = new CSVParser(new StringReader(CSVINPUT), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = new CSVParser(new StringReader(CSVINPUT), CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = new CSVParser("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = new CSVParser("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = new CSVParser(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = new CSVParser(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = new CSVParser(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = new CSVParser(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + assertNull(records.next()); + assertFalse(records.hasNext()); + assertNull(records.next()); + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = new CSVParser(new StringReader(code)); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVFormat.DEFAULT.parse(new StringReader(input))) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + // header record + assertTrue(records.hasNext()); + CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("a", record.get("A")); + assertEquals("b", record.get("B")); + assertEquals("c", record.get("C")); + assertTrue(record.isConsistent()); + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = new CSVParser("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordWithMultiiLineValues() throws Exception { + final CSVParser parser = new CSVParser("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser((Reader) null, invalidFormat); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = new CSVParser("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = new CSVParser("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `CSVParser(...)` at line 371 is not released after line 372. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testDefaultFormat() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testDefaultFormat():void.90b030b6ec0a6fbfae29a1f268d7e11a + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testDefaultFormat|RESOURCE_LEAK + +### Node Key: +abf778a0fb58a097b72f1ea16dfb9fcd + +### Hash: +7aaa91bfffc2351c75dbb95a448a7a69 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6463/instruction.md b/inferredbugs-6463/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..067ceb754b2a2dc9d7d2027b9b43495d23ba977f --- /dev/null +++ b/inferredbugs-6463/instruction.md @@ -0,0 +1,920 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 121 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.io.input.BOMInputStream; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + @Ignore("CSV-107") + public void testBOM() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + final CSVParser parser = CSVParser.parse(url, null, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testBOMInputStream() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8"); + final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = CSVParser.parse(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = CSVParser.parse(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testGetRecordWithMultiLineValues() throws Exception { + final CSVParser parser = CSVParser.parse("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser(null, invalidFormat).close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true) + .parse(in).iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? + public void testMultipleIterators() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); + + final Iterator itr1 = parser.iterator(); + final Iterator itr2 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr2.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserNullReaderFormat() throws Exception { + new CSVParser(null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserReaderNullFormat() throws Exception { + new CSVParser(new StringReader(""), null); + } + + @Test + public void testNoHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT); + Assert.assertNull(parser.getHeaderMap()); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseFileNullFormat() throws Exception { + CSVParser.parse(new File(""), null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullFileFormat() throws Exception { + CSVParser.parse((File) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullStringFormat() throws Exception { + CSVParser.parse((String) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullUrlCharsetFormat() throws Exception { + CSVParser.parse(null, Charset.defaultCharset(), CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParserUrlNullCharsetFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT); + parser.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseStringNullFormat() throws Exception { + CSVParser.parse("csv data", null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseUrlCharsetNullFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null); + parser.close(); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true) + .parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `parse(...)` at line 286 is not released after line 287. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testEmptyFile() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testEmptyFile():void.33788f170b9aaf2c1a2650786d3c2e19 + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testEmptyFile|RESOURCE_LEAK + +### Node Key: +15891b12c6ce50257e480adc810587ae + +### Hash: +d19da39953078266d6ecd9c33b82d3e0 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6464/instruction.md b/inferredbugs-6464/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..794b7fa8cd2e70e0964ccc5df88958024152000b --- /dev/null +++ b/inferredbugs-6464/instruction.md @@ -0,0 +1,920 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 119 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.io.input.BOMInputStream; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + @Ignore("CSV-107") + public void testBOM() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + final CSVParser parser = CSVParser.parse(url, null, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testBOMInputStream() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8"); + final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = CSVParser.parse(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = CSVParser.parse(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testGetRecordWithMultiLineValues() throws Exception { + final CSVParser parser = CSVParser.parse("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser(null, invalidFormat).close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true) + .parse(in).iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? + public void testMultipleIterators() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); + + final Iterator itr1 = parser.iterator(); + final Iterator itr2 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr2.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserNullReaderFormat() throws Exception { + new CSVParser(null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserReaderNullFormat() throws Exception { + new CSVParser(new StringReader(""), null); + } + + @Test + public void testNoHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT); + Assert.assertNull(parser.getHeaderMap()); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseFileNullFormat() throws Exception { + CSVParser.parse(new File(""), null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullFileFormat() throws Exception { + CSVParser.parse((File) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullStringFormat() throws Exception { + CSVParser.parse((String) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullUrlCharsetFormat() throws Exception { + CSVParser.parse(null, Charset.defaultCharset(), CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParserUrlNullCharsetFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT); + parser.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseStringNullFormat() throws Exception { + CSVParser.parse("csv data", null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseUrlCharsetNullFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null); + parser.close(); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true) + .parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `parse(...)` at line 266 is not released after line 267. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testDefaultFormat() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testDefaultFormat():void.90b030b6ec0a6fbfae29a1f268d7e11a + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testDefaultFormat|RESOURCE_LEAK + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +7d3bcfeecbe1dfb3f8c086699c16478b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6491/instruction.md b/inferredbugs-6491/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..54c965c8efbf41d629754fa2db251fd605247796 --- /dev/null +++ b/inferredbugs-6491/instruction.md @@ -0,0 +1,541 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 37 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; + +import org.junit.Ignore; +import org.junit.Test; + +import static org.junit.Assert.*; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + */ +public class CSVParserTest { + + String code = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + String[][] res = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testGetLine() throws IOException { + CSVParser parser = new CSVParser(new StringReader(code)); + for (String[] re : res) { + assertTrue(Arrays.equals(re, parser.getRecord())); + } + + assertTrue(parser.getRecord() == null); + } + + @Test + public void testGetRecords() throws IOException { + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + @Test + public void testExcelFormat1() throws IOException { + String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + @Test + public void testExcelFormat2() throws Exception { + String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (String code : codes) { + CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (String code : codes) { + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (String code : codes) { + CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (String code : codes) { + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] tmp = parser.getRecords(); + assertEquals(res.length, tmp.length); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" \" / string\" "}, + {"9", " \n "}, + }; + + + CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, true, "\r\n"); + + CSVParser parser = new CSVParser(code, format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + for (int i = 0; i < res.length; i++) { + assertTrue(Arrays.equals(res[i], tmp[i])); + } + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, true, "\r\n"); + + CSVParser parser = new CSVParser(code, format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + + if (!CSVPrinterTest.equals(res, tmp)) { + assertTrue(false); + } + } + + @Test + public void testDefaultFormat() throws IOException { + + String code = "" + + "a,b\n" // 1) + + "\"\n\",\" \"\n" // 2) + + "\"\",#\n" // 2) + ; + String[][] res = { + {"a", "b"}, + {"\n", " "}, + {"", "#"}, + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertEquals(CSVFormat.DISABLED, format.getCommentStart()); + + CSVParser parser = new CSVParser(code, format); + String[][] tmp = parser.getRecords(); + assertTrue(tmp.length > 0); + + if (!CSVPrinterTest.equals(res, tmp)) { + assertTrue(false); + } + + String[][] res_comments = { + {"a", "b"}, + {"\n", " "}, + {""}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = new CSVParser(code, format); + tmp = parser.getRecords(); + + if (!CSVPrinterTest.equals(res_comments, tmp)) { + assertTrue(false); + } + } + + @Test + public void testUnicodeEscape() throws Exception { + String code = "abc,\\u0070\\u0075\\u0062\\u006C\\u0069\\u0063"; + CSVParser parser = new CSVParser(code, CSVFormat.DEFAULT.withUnicodeEscapesInterpreted(true)); + final Iterator iterator = parser.iterator(); + String[] data = iterator.next(); + assertEquals(2, data.length); + assertEquals("abc", data[0]); + assertEquals("public", data[1]); + assertFalse("Should not have any more records", iterator.hasNext()); + } + + @Test + public void testUnicodeEscapeMySQL() throws Exception { + String code = "abc\t\\u0070\\u0075\\u0062\\u006C\\u0069\\u0063"; + CSVParser parser = new CSVParser(code, CSVFormat.MYSQL.withUnicodeEscapesInterpreted(true)); + final Iterator iterator = parser.iterator(); + String[] data = iterator.next(); + assertEquals(2, data.length); + assertEquals("abc", data[0]); + assertEquals("public", data[1]); + assertFalse("Should not have any more records", iterator.hasNext()); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + @Test + public void testCarriageReturnEndings() throws IOException { + String code = "foo\rbaar,\rhello,world\r,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + @Test + public void testLineFeedEndings() throws IOException { + String code = "foo\nbaar,\nhello,world\n,kanu"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(4, data.length); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + CSVParser parser = new CSVParser(new StringReader(code)); + String[][] data = parser.getRecords(); + assertEquals(3, data.length); + } + + @Test + public void testForEach() { + List records = new ArrayList(); + + Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (String[] record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, records.get(0))); + assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, records.get(1))); + assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, records.get(2))); + } + + @Test + public void testIterator() { + Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (UnsupportedOperationException expected) { + } + assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next())); + assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next())); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next())); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (NoSuchElementException e) { + // expected + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `data` last assigned on line 410 could be null and is dereferenced at line 411. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testLineFeedEndings() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testLineFeedEndings():void.b68def46c30f2d9ae623b6fb9e8f7231 + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testLineFeedEndings|NULL_DEREFERENCE + +### Node Key: +8bd297b3d28e30f1b4b70c0be2cf3e0d + +### Hash: +bbb689b085313af3a2f57550e1c4c8dc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6496/instruction.md b/inferredbugs-6496/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..64f302669b7d22449af66552dfd6597fcd6f2372 --- /dev/null +++ b/inferredbugs-6496/instruction.md @@ -0,0 +1,280 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 139 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.END_OF_STREAM; +import static org.apache.commons.csv.Constants.UNDEFINED; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.StringReader; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class ExtendedBufferedReaderTest { + + @Test + public void testEmptyInput() throws Exception { + final ExtendedBufferedReader br = getBufferedReader(""); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertNull(br.readLine()); + assertEquals(0, br.read(new char[10], 0, 0)); + } + + @Test + public void testReadLookahead1() throws Exception { + final ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.lookAhead()); + assertEquals(UNDEFINED, br.getLastChar()); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals('1', br.read()); // Start line 1 + assertEquals('1', br.getLastChar()); + + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('1', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + + assertEquals('2', br.lookAhead()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('2', br.read()); // Start line 2 + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + + assertEquals('\r', br.lookAhead()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('2', br.getLastChar()); + assertEquals('\r', br.read()); + assertEquals('\r', br.getLastChar()); + assertEquals(2, br.getCurrentLineNumber()); + + assertEquals('3', br.lookAhead()); + assertEquals('\r', br.getLastChar()); + assertEquals('3', br.read()); // Start line 3 + assertEquals('3', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals('\n', br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('3', br.getLastChar()); + assertEquals('\n', br.read()); + assertEquals(3, br.getCurrentLineNumber()); + assertEquals('\n', br.getLastChar()); + assertEquals(3, br.getCurrentLineNumber()); + + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals('\n', br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.getLastChar()); + assertEquals(END_OF_STREAM, br.read()); + assertEquals(END_OF_STREAM, br.lookAhead()); + assertEquals(3, br.getCurrentLineNumber()); + + } + + @Test + public void testReadLookahead2() throws Exception { + final char[] ref = new char[5]; + final char[] res = new char[5]; + + final ExtendedBufferedReader br = getBufferedReader("abcdefg"); + ref[0] = 'a'; + ref[1] = 'b'; + ref[2] = 'c'; + assertEquals(3, br.read(res, 0, 3)); + assertArrayEquals(ref, res); + assertEquals('c', br.getLastChar()); + + assertEquals('d', br.lookAhead()); + ref[4] = 'd'; + assertEquals(1, br.read(res, 4, 1)); + assertArrayEquals(ref, res); + assertEquals('d', br.getLastChar()); + } + + @Test + public void testReadLine() throws Exception { + ExtendedBufferedReader br = getBufferedReader(""); + assertNull(br.readLine()); + + br = getBufferedReader("\n"); + assertEquals("",br.readLine()); + assertNull(br.readLine()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals(0, br.getCurrentLineNumber()); + assertEquals("foo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals("hello",br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + br = getBufferedReader("foo\n\nhello"); + assertEquals('f', br.read()); + assertEquals('o', br.lookAhead()); + assertEquals("oo",br.readLine()); + assertEquals(1, br.getCurrentLineNumber()); + assertEquals('\n', br.lookAhead()); + assertEquals("",br.readLine()); + assertEquals(2, br.getCurrentLineNumber()); + assertEquals('h', br.lookAhead()); + assertEquals("hello",br.readLine()); + assertNull(br.readLine()); + assertEquals(3, br.getCurrentLineNumber()); + + + br = getBufferedReader("foo\rbaar\r\nfoo"); + assertEquals("foo",br.readLine()); + assertEquals('b', br.lookAhead()); + assertEquals("baar",br.readLine()); + assertEquals('f', br.lookAhead()); + assertEquals("foo",br.readLine()); + assertNull(br.readLine()); + } + + /* + * Test to illustrate https://issues.apache.org/jira/browse/CSV-75 + * + */ + @Test + public void testReadChar() throws Exception { + final String LF="\n"; final String CR="\r"; final String CRLF=CR+LF; final String LFCR=LF+CR;// easier to read the string below + final String test="a" + LF + "b" + CR + "c" + LF + LF + "d" + CR + CR + "e" + LFCR + "f "+ CRLF; + // EOL eol EOL EOL eol eol EOL+CR EOL + final int EOLeolct = 9; + ExtendedBufferedReader br; + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.readLine() != null) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + while (br.read() != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + + br = getBufferedReader(test); + assertEquals(0, br.getCurrentLineNumber()); + final char[] buff = new char[10]; + while (br.read(buff, 0, 3) != -1) { + // consume all + } + assertEquals(EOLeolct, br.getCurrentLineNumber()); + } + + private ExtendedBufferedReader getBufferedReader(final String s) { + return new ExtendedBufferedReader(new StringReader(s)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired to `br` by call to `getBufferedReader(...)` at line 39 is not released after line 44. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExtendedBufferedReaderTest.testEmptyInput() + +### Procedure Id: +org.apache.commons.csv.ExtendedBufferedReaderTest.testEmptyInput():void.a2359c053c20466efd12ba1122f4c322 + +### File: +src/test/java/org/apache/commons/csv/ExtendedBufferedReaderTest.java + +### Key: +ExtendedBufferedReaderTest.java|testEmptyInput|RESOURCE_LEAK + +### Node Key: +f133a6dfaa072505a5ed16416e655ea0 + +### Hash: +910ef03374e5eceab54c24ce981d417d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6497/instruction.md b/inferredbugs-6497/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f6da77ff09a873671a5812e47c09e8d9e4b1f08 --- /dev/null +++ b/inferredbugs-6497/instruction.md @@ -0,0 +1,812 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 101 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parseString(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parseString(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = CSVParser.parseString(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = CSVParser.parseString(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parseString(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true) + .parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true) + .parse(in).iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parseString("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordWithMultiiLineValues() throws Exception { + final CSVParser parser = CSVParser.parseString("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser((Reader) null, invalidFormat).close(); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parseString("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parseString("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `parseString(...)` at line 346 is not released after line 347. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testBackslashEscaping2() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testBackslashEscaping2():void.d5cd32cf6dbf5de216d833176fc2b395 + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testBackslashEscaping2|RESOURCE_LEAK + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +e09bf3a51ff3f196ec365bcaeeca3140 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6498/instruction.md b/inferredbugs-6498/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..655f734773460024d32881d47faf430b8dc63166 --- /dev/null +++ b/inferredbugs-6498/instruction.md @@ -0,0 +1,400 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 55 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.List; +import java.util.Random; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class CSVPrinterTest { + + public static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + + public void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, format); + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + Utils.compare("Printer output :" + printable(result), lines, parseResult); + } + + public void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + public String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = '"'; + break; + case 7: + ch = '\''; + break; + case 8: + ch = '\\'; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printComment("This is a comment"); + + assertEquals("", sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), + Arrays.asList(new String[] { "r2c1", "r2c2" }) })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + try { + final Statement stmt = connection.createStatement(); + stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); + stmt.execute("insert into TEST values(1, 'r1')"); + stmt.execute("insert into TEST values(2, 'r2')"); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); + assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); + } finally { + connection.close(); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.ALL).build()); + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.NON_NUMERIC).build()); + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + } + + @Test + public void testRandom() throws Exception { + final int iter = 10000; + doRandom(CSVFormat.DEFAULT, iter); + doRandom(CSVFormat.EXCEL, iter); + doRandom(CSVFormat.MYSQL, iter); + } + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withCommentStart('#').build()); + printer.printComment("This is a comment"); + + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.CSVPrinter` acquired to `printer` by call to `new()` at line 189 is not released after line 190. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVPrinterTest.testExcelPrinter1() + +### Procedure Id: +org.apache.commons.csv.CSVPrinterTest.testExcelPrinter1():void.99f61c68cd8cb1745b3fa4a6f4891838 + +### File: +src/test/java/org/apache/commons/csv/CSVPrinterTest.java + +### Key: +CSVPrinterTest.java|testExcelPrinter1|RESOURCE_LEAK + +### Node Key: +0fb8a1c0ca4d50e67c93620b0e0bccf7 + +### Hash: +73fb78f9de94a1fb0048bcce5030ed48 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6499/instruction.md b/inferredbugs-6499/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aee77e9f3487527243f3d3dfc8c914e7633bafab --- /dev/null +++ b/inferredbugs-6499/instruction.md @@ -0,0 +1,576 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 137 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; + +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Random; + +import org.junit.Test; + +/** + * + * + * @version $Id$ + */ +public class CSVPrinterTest { + + private final String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); + + private static String printable(final String s) { + final StringBuilder sb = new StringBuilder(); + for (int i = 0; i < s.length(); i++) { + final char ch = s.charAt(i); + if (ch <= ' ' || ch >= 128) { + sb.append("(").append((int) ch).append(")"); + } else { + sb.append(ch); + } + } + return sb.toString(); + } + + private void doOneRandom(final CSVFormat format) throws Exception { + final Random r = new Random(); + + final int nLines = r.nextInt(4) + 1; + final int nCol = r.nextInt(3) + 1; + // nLines=1;nCol=2; + final String[][] lines = new String[nLines][]; + for (int i = 0; i < nLines; i++) { + final String[] line = new String[nCol]; + lines[i] = line; + for (int j = 0; j < nCol; j++) { + line[j] = randStr(); + } + } + + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, format); + + for (int i = 0; i < nLines; i++) { + // for (int j=0; j parseResult = parser.getRecords(); + + Utils.compare("Printer output :" + printable(result), lines, parseResult); + } + + private void doRandom(final CSVFormat format, final int iter) throws Exception { + for (int i = 0; i < iter; i++) { + doOneRandom(format); + } + } + + private String randStr() { + final Random r = new Random(); + + final int sz = r.nextInt(20); + // sz = r.nextInt(3); + final char[] buf = new char[sz]; + for (int i = 0; i < sz; i++) { + // stick in special chars with greater frequency + char ch; + final int what = r.nextInt(20); + switch (what) { + case 0: + ch = '\r'; + break; + case 1: + ch = '\n'; + break; + case 2: + ch = '\t'; + break; + case 3: + ch = '\f'; + break; + case 4: + ch = ' '; + break; + case 5: + ch = ','; + break; + case 6: + ch = '"'; + break; + case 7: + ch = '\''; + break; + case 8: + ch = '\\'; + break; + default: + ch = (char) r.nextInt(300); + break; + // default: ch = 'a'; break; + } + buf[i] = ch; + } + return new String(buf); + } + + @Test + public void testDisabledComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printComment("This is a comment"); + + assertEquals("", sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrintAllArrayOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrintAllArrayOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(new List[] { Arrays.asList("r1c1", "r1c2"), Arrays.asList("r2c1", "r2c2") }); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrintAllIterableOfArrays() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrintAllIterableOfLists() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecords(Arrays.asList(new List[] { Arrays.asList("r1c1", "r1c2"), + Arrays.asList("r2c1", "r2c2") })); + assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testExcelPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testJdbcPrinter() throws IOException, ClassNotFoundException, SQLException { + final StringWriter sw = new StringWriter(); + Class.forName("org.h2.Driver"); + final Connection connection = DriverManager.getConnection("jdbc:h2:mem:my_test;", "sa", ""); + try { + final Statement stmt = connection.createStatement(); + stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))"); + stmt.execute("insert into TEST values(1, 'r1')"); + stmt.execute("insert into TEST values(2, 'r2')"); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecords(stmt.executeQuery("select ID, NAME from TEST")); + assertEquals("1,r1" + recordSeparator + "2,r2" + recordSeparator, sw.toString()); + printer.close(); + } finally { + connection.close(); + } + } + + @Test + public void testMultiLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#')); + printer.printComment("This is a comment\non multiple lines"); + + assertEquals("# This is a comment" + recordSeparator + "# on multiple lines" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter1() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b"); + assertEquals("a,b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter2() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a,b", "b"); + assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter3() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a, b", "b "); + assertEquals("\"a, b\",\"b \"" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter4() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\"c"); + assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter5() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\nc"); + assertEquals("a,\"b\nc\"" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter6() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\r\nc"); + assertEquals("a,\"b\r\nc\"" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrinter7() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", "b\\c"); + assertEquals("a,b\\c" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrintNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); + printer.printRecord("a", null, "b"); + assertEquals("a,,b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testPrintCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withNullString("NULL")); + printer.printRecord("a", null, "b"); + assertEquals("a,NULL,b" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testParseCustomNullValues() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); + final CSVPrinter printer = new CSVPrinter(sw, format); + printer.printRecord("a", null, "b"); + printer.close(); + final String csvString = sw.toString(); + assertEquals("a,NULL,b" + recordSeparator, csvString); + final Iterable iterable = format.parse(new StringReader(csvString)); + final Iterator iterator = iterable.iterator(); + final CSVRecord record = iterator.next(); + assertEquals("a", record.get(0)); + assertEquals(null, record.get(1)); + assertEquals("b", record.get(2)); + assertFalse(iterator.hasNext()); + } + + @Test + public void testQuoteAll() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.ALL)); + printer.printRecord("a", "b\nc", "d"); + assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testQuoteNonNumeric() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuotePolicy(Quote.NON_NUMERIC)); + printer.printRecord("a", "b\nc", Integer.valueOf(1)); + assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testRandom() throws Exception { + final int iter = 10000; + doRandom(CSVFormat.DEFAULT, iter); + doRandom(CSVFormat.EXCEL, iter); + doRandom(CSVFormat.MYSQL, iter); + } + + @Test + public void testPlainQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\'')); + printer.print("abc"); + assertEquals("abc", sw.toString()); + printer.close(); + } + + @Test + public void testSingleLineComment() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withCommentStart('#')); + printer.printComment("This is a comment"); + + assertEquals("# This is a comment" + recordSeparator, sw.toString()); + printer.close(); + } + + @Test + public void testSingleQuoteQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\'')); + printer.print("a'b'c"); + printer.print("xyz"); + assertEquals("'a''b''c',xyz", sw.toString()); + printer.close(); + } + + @Test + public void testDelimeterQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\'')); + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("'a,b,c',xyz", sw.toString()); + printer.close(); + } + + @Test + public void testDelimeterQuoteNONE() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVFormat format = CSVFormat.DEFAULT.withEscape('!').withQuotePolicy(Quote.NONE); + final CSVPrinter printer = new CSVPrinter(sw, format); + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + printer.close(); + } + + @Test + public void testEOLQuoted() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar('\'')); + printer.print("a\rb\nc"); + printer.print("x\by\fz"); + assertEquals("'a\rb\nc',x\by\fz", sw.toString()); + printer.close(); + } + + @Test + public void testPlainEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!')); + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + printer.close(); + } + + @Test + public void testDelimiterEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withEscape('!').withQuoteChar(null)); + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a!,b!,c,xyz", sw.toString()); + printer.close(); + } + + @Test + public void testEOLEscaped() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null).withEscape('!')); + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a!rb!nc,x\fy\bz", sw.toString()); + printer.close(); + } + + @Test + public void testPlainPlain() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null)); + printer.print("abc"); + printer.print("xyz"); + assertEquals("abc,xyz", sw.toString()); + printer.close(); + } + + @Test + public void testDelimiterPlain() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null)); + printer.print("a,b,c"); + printer.print("xyz"); + assertEquals("a,b,c,xyz", sw.toString()); + printer.close(); + } + + @Test + public void testEOLPlain() throws IOException { + final StringWriter sw = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT.withQuoteChar(null)); + printer.print("a\rb\nc"); + printer.print("x\fy\bz"); + assertEquals("a\rb\nc,x\fy\bz", sw.toString()); + printer.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVPrinter(new StringWriter(), invalidFormat).close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVPrinterNullAppendableFormat() throws Exception { + new CSVPrinter(null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCsvPrinterAppendableNullFormat() throws Exception { + new CSVPrinter(new StringWriter(), null); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.CSVParser` acquired by call to `parse(...)` at line 332 is not released after line 338. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVPrinterTest.testParseCustomNullValues() + +### Procedure Id: +org.apache.commons.csv.CSVPrinterTest.testParseCustomNullValues():void.7f49e3a843e16d57bd422b45dafd518a + +### File: +src/test/java/org/apache/commons/csv/CSVPrinterTest.java + +### Key: +CSVPrinterTest.java|testParseCustomNullValues|RESOURCE_LEAK + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +bc4e262aab37cc65086955c9f88a6444 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6510/instruction.md b/inferredbugs-6510/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3140dc4c700054a1f8bed3c0a6ea333eac77e490 --- /dev/null +++ b/inferredbugs-6510/instruction.md @@ -0,0 +1,920 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-csv +**Bug ID:** 115 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.commons.csv; + +import static org.apache.commons.csv.Constants.CR; +import static org.apache.commons.csv.Constants.CRLF; +import static org.apache.commons.csv.Constants.LF; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; + +import org.apache.commons.io.input.BOMInputStream; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * CSVParserTest + * + * The test are organized in three different sections: + * The 'setter/getter' section, the lexer section and finally the parser + * section. In case a test fails, you should follow a top-down approach for + * fixing a potential bug (its likely that the parser itself fails if the lexer + * has problems...). + * + * @version $Id$ + */ +public class CSVParserTest { + + private static final String CSVINPUT = "a,b,c,d\n" + + " a , b , 1 2 \n" + + "\"foo baar\", b,\n" + // + " \"foo\n,,\n\"\",,\n\\\"\",d,e\n"; + + " \"foo\n,,\n\"\",,\n\"\"\",d,e\n"; // changed to use standard CSV escaping + + private static final String[][] RESULT = { + {"a", "b", "c", "d"}, + {"a", "b", "1 2"}, + {"foo baar", "b", ""}, + {"foo\n,,\n\",,\n\"", "d", "e"} + }; + + @Test + public void testBackslashEscaping() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = + "one,two,three\n" // 0 + + "'',''\n" // 1) empty encapsulators + + "/',/'\n" // 2) single encapsulators + + "'/'','/''\n" // 3) single encapsulators encapsulated via escape + + "'''',''''\n" // 4) single encapsulators encapsulated via doubling + + "/,,/,\n" // 5) separator escaped + + "//,//\n" // 6) escape escaped + + "'//','//'\n" // 7) escape escaped in encapsulation + + " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces + + "9, /\n \n" // escaped newline + + ""; + final String[][] res = { + {"one", "two", "three"}, // 0 + {"", ""}, // 1 + {"'", "'"}, // 2 + {"'", "'"}, // 3 + {"'", "'"}, // 4 + {",", ","}, // 5 + {"/", "/"}, // 6 + {"/", "/"}, // 7 + {" 8 ", " \"quoted \"\" /\" / string\" "}, + {"9", " \n "}, + }; + + + final CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('\'') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Records do not match expected result", res, records); + } + + @Test + public void testBackslashEscaping2() throws IOException { + + // To avoid confusion over the need for escaping chars in java code, + // We will test with a forward slash as the escape char, and a single + // quote as the encapsulator. + + final String code = "" + + " , , \n" // 1) + + " \t , , \n" // 2) + + " // , /, , /,\n" // 3) + + ""; + final String[][] res = { + {" ", " ", " "}, // 1 + {" \t ", " ", " "}, // 2 + {" / ", " , ", " ,"}, // 3 + }; + + + final CSVFormat format = CSVFormat.newFormat(',') + .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); + + final CSVParser parser = CSVParser.parse(code, format); + final List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("", res, records); + } + + @Test + @Ignore + public void testBackslashEscapingOld() throws IOException { + final String code = + "one,two,three\n" + + "on\\\"e,two\n" + + "on\"e,two\n" + + "one,\"tw\\\"o\"\n" + + "one,\"t\\,wo\"\n" + + "one,two,\"th,ree\"\n" + + "\"a\\\\\"\n" + + "a\\,b\n" + + "\"a\\\\,b\""; + final String[][] res = { + {"one", "two", "three"}, + {"on\\\"e", "two"}, + {"on\"e", "two"}, + {"one", "tw\"o"}, + {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") + {"one", "two", "th,ree"}, + {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") + {"a\\", "b"}, // a backslash must be returnd + {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + @Ignore("CSV-107") + public void testBOM() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + final CSVParser parser = CSVParser.parse(url, null, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testBOMInputStream() throws IOException { + URL url = ClassLoader.getSystemClassLoader().getResource("CSVFileParser/bom.csv"); + Reader reader = new InputStreamReader(new BOMInputStream(url.openStream()), "UTF-8"); + final CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader()); + try { + for (CSVRecord record : parser) { + final String string = record.get("Date"); + Assert.assertNotNull(string); + //System.out.println("date: " + record.get("Date")); + } + } finally { + parser.close(); + } + } + + @Test + public void testCarriageReturnEndings() throws IOException { + final String code = "foo\rbaar,\rhello,world\r,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testCarriageReturnLineFeedEndings() throws IOException { + final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test(expected = NoSuchElementException.class) + public void testClose() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + final CSVParser parser = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in); + final Iterator records = parser.iterator(); + assertTrue(records.hasNext()); + parser.close(); + assertFalse(records.hasNext()); + records.next(); + } + + @Test + public void testCSV57() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + final List list = parser.getRecords(); + assertNotNull(list); + assertEquals(0, list.size()); + } + + @Test + public void testDefaultFormat() throws IOException { + final String code = "" + + "a,b#\n" // 1) + + "\"\n\",\" \",#\n" // 2) + + "#,\"\"\n" // 3) + + "# Final comment\n"// 4) + ; + final String[][] res = { + {"a", "b#"}, + {"\n", " ", "#"}, + {"#", ""}, + {"# Final comment"} + }; + + CSVFormat format = CSVFormat.DEFAULT; + assertFalse(format.isCommentingEnabled()); + + CSVParser parser = CSVParser.parse(code, format); + List records = parser.getRecords(); + assertTrue(records.size() > 0); + + Utils.compare("Failed to parse without comments", res, records); + + final String[][] res_comments = { + {"a", "b#"}, + {"\n", " ", "#"}, + }; + + format = CSVFormat.DEFAULT.withCommentStart('#'); + parser = CSVParser.parse(code, format); + records = parser.getRecords(); + + Utils.compare("Failed to parse with comments", res_comments, records); + } + + @Test + public void testEmptyFile() throws Exception { + final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); + assertNull(parser.nextRecord()); + } + + @Test + public void testEmptyLineBehaviourCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""} // CSV format ignores empty lines + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEmptyLineBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\n\r\n", + "hello,\n\n\n", + "hello,\"\"\r\n\r\n\r\n", + "hello,\"\"\n\n\n" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviorCSV() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, // CSV format ignores empty lines + {"world", ""} + }; + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testEndOfFileBehaviourExcel() throws Exception { + final String[] codes = { + "hello,\r\n\r\nworld,\r\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\r\n", + "hello,\r\n\r\nworld,\"\"", + "hello,\r\n\r\nworld,\n", + "hello,\r\n\r\nworld,", + "hello,\r\n\r\nworld,\"\"\n", + "hello,\r\n\r\nworld,\"\"" + }; + final String[][] res = { + {"hello", ""}, + {""}, // Excel format does not ignore empty lines + {"world", ""} + }; + + for (final String code : codes) { + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + } + + @Test + public void testExcelFormat1() throws IOException { + final String code = + "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; + final String[][] res = { + {"value1", "value2", "value3", "value4"}, + {"a", "b", "c", "d"}, + {" x", "", "", ""}, + {""}, + {"\"hello\"", " \"world\"", "abc\ndef", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testExcelFormat2() throws Exception { + final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; + final String[][] res = { + {"foo", "baar"}, + {""}, + {"hello", ""}, + {""}, + {"world", ""} + }; + final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); + final List records = parser.getRecords(); + assertEquals(res.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < res.length; i++) { + assertArrayEquals(res[i], records.get(i).values()); + } + } + + @Test + public void testForEach() throws Exception { + final List records = new ArrayList(); + + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + for (final CSVRecord record : CSVFormat.DEFAULT.parse(in)) { + records.add(record); + } + + assertEquals(3, records.size()); + assertArrayEquals(new String[]{"a", "b", "c"}, records.get(0).values()); + assertArrayEquals(new String[]{"1", "2", "3"}, records.get(1).values()); + assertArrayEquals(new String[]{"x", "y", "z"}, records.get(2).values()); + } + + @Test + public void testGetHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT.withHeader("A", "B", "C")); + final Map headerMap = parser.getHeaderMap(); + final Iterator columnNames = headerMap.keySet().iterator(); + // Headers are iterated in column order. + Assert.assertEquals("A", columnNames.next()); + Assert.assertEquals("B", columnNames.next()); + Assert.assertEquals("C", columnNames.next()); + final Iterator records = parser.iterator(); + + // Parse to make sure getHeaderMap did not have a side-effect. + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testGetLine() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + for (final String[] re : RESULT) { + assertArrayEquals(re, parser.nextRecord().values()); + } + + assertNull(parser.nextRecord()); + } + + @Test + public void testGetLineNumberWithCR() throws Exception { + this.validateLineNumbers(String.valueOf(CR)); + } + + @Test + public void testGetLineNumberWithCRLF() throws Exception { + this.validateLineNumbers(CRLF); + } + + @Test + public void testGetLineNumberWithLF() throws Exception { + this.validateLineNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecordNumberWithCR() throws Exception { + this.validateRecordNumbers(String.valueOf(CR)); + } + + @Test + public void testGetRecordNumberWithCRLF() throws Exception { + this.validateRecordNumbers(CRLF); + } + + @Test + public void testGetRecordNumberWithLF() throws Exception { + this.validateRecordNumbers(String.valueOf(LF)); + } + + @Test + public void testGetRecords() throws IOException { + final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); + final List records = parser.getRecords(); + assertEquals(RESULT.length, records.size()); + assertTrue(records.size() > 0); + for (int i = 0; i < RESULT.length; i++) { + assertArrayEquals(RESULT[i], records.get(i).values()); + } + } + + @Test + public void testGetRecordWithMultiLineValues() throws Exception { + final CSVParser parser = CSVParser.parse("\"a\r\n1\",\"a\r\n2\"" + CRLF + "\"b\r\n1\",\"b\r\n2\"" + CRLF + "\"c\r\n1\",\"c\r\n2\"", + CSVFormat.DEFAULT.withRecordSeparator(CRLF)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, parser.getCurrentLineNumber()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(6, parser.getCurrentLineNumber()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(8, parser.getCurrentLineNumber()); + assertEquals(3, parser.getRecordNumber()); + } + + @Test + public void testHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testHeaderComment() throws Exception { + final Reader in = new StringReader("# comment\na,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withCommentStart('#').withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testIgnoreEmptyLines() throws IOException { + final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; + //String code = "world\r\n\n"; + //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(3, records.size()); + } + + @Test(expected = IllegalArgumentException.class) + public void testInvalidFormat() throws Exception { + final CSVFormat invalidFormat = CSVFormat.DEFAULT.withDelimiter(CR); + new CSVParser(null, invalidFormat).close(); + } + + @Test + public void testIterator() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator iterator = CSVFormat.DEFAULT.parse(in).iterator(); + + assertTrue(iterator.hasNext()); + try { + iterator.remove(); + fail("expected UnsupportedOperationException"); + } catch (final UnsupportedOperationException expected) { + // expected + } + assertArrayEquals(new String[]{"a", "b", "c"}, iterator.next().values()); + assertArrayEquals(new String[]{"1", "2", "3"}, iterator.next().values()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertTrue(iterator.hasNext()); + assertArrayEquals(new String[]{"x", "y", "z"}, iterator.next().values()); + assertFalse(iterator.hasNext()); + + try { + iterator.next(); + fail("NoSuchElementException expected"); + } catch (final NoSuchElementException e) { + // expected + } + } + + @Test + public void testLineFeedEndings() throws IOException { + final String code = "foo\nbaar,\nhello,world\n,kanu"; + final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); + final List records = parser.getRecords(); + assertEquals(4, records.size()); + } + + @Test + public void testMappedButNotSetAsOutlook2007ContactExport() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").withSkipHeaderRecord(true) + .parse(in).iterator(); + CSVRecord record; + + // 1st record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertFalse(record.isSet("C")); + assertEquals("1", record.get("A")); + assertEquals("2", record.get("B")); + assertFalse(record.isConsistent()); + + // 2nd record + record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertTrue(record.isSet("A")); + assertTrue(record.isSet("B")); + assertTrue(record.isSet("C")); + assertEquals("x", record.get("A")); + assertEquals("y", record.get("B")); + assertEquals("z", record.get("C")); + assertTrue(record.isConsistent()); + + assertFalse(records.hasNext()); + } + + @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? + public void testMultipleIterators() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); + + final Iterator itr1 = parser.iterator(); + final Iterator itr2 = parser.iterator(); + + final CSVRecord first = itr1.next(); + assertEquals("a", first.get(0)); + assertEquals("b", first.get(1)); + assertEquals("c", first.get(2)); + + final CSVRecord second = itr2.next(); + assertEquals("d", second.get(0)); + assertEquals("e", second.get(1)); + assertEquals("f", second.get(2)); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserNullReaderFormat() throws Exception { + new CSVParser(null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testNewCSVParserReaderNullFormat() throws Exception { + new CSVParser(new StringReader(""), null); + } + + @Test + public void testNoHeaderMap() throws Exception { + final CSVParser parser = CSVParser.parse("a,b,c\n1,2,3\nx,y,z", CSVFormat.DEFAULT); + Assert.assertNull(parser.getHeaderMap()); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseFileNullFormat() throws Exception { + CSVParser.parse(new File(""), null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullFileFormat() throws Exception { + CSVParser.parse((File) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullStringFormat() throws Exception { + CSVParser.parse((String) null, CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseNullUrlCharsetFormat() throws Exception { + CSVParser.parse(null, Charset.defaultCharset(), CSVFormat.DEFAULT); + } + + @Test(expected = IllegalArgumentException.class) + public void testParserUrlNullCharsetFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), null, CSVFormat.DEFAULT); + parser.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseStringNullFormat() throws Exception { + CSVParser.parse("csv data", null); + } + + @Test(expected = IllegalArgumentException.class) + public void testParseUrlCharsetNullFormat() throws Exception { + final CSVParser parser = CSVParser.parse(new URL("http://commons.apache.org"), Charset.defaultCharset(), null); + parser.close(); + } + + @Test + public void testProvidedHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader("A", "B", "C").parse(in).iterator(); + + for (int i = 0; i < 3; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("A")); + assertTrue(record.isMapped("B")); + assertTrue(record.isMapped("C")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("A")); + assertEquals(record.get(1), record.get("B")); + assertEquals(record.get(2), record.get("C")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testProvidedHeaderAuto() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + + for (int i = 0; i < 2; i++) { + assertTrue(records.hasNext()); + final CSVRecord record = records.next(); + assertTrue(record.isMapped("a")); + assertTrue(record.isMapped("b")); + assertTrue(record.isMapped("c")); + assertFalse(record.isMapped("NOT MAPPED")); + assertEquals(record.get(0), record.get("a")); + assertEquals(record.get(1), record.get("b")); + assertEquals(record.get(2), record.get("c")); + } + + assertFalse(records.hasNext()); + } + + @Test + public void testRoundtrip() throws Exception { + final StringWriter out = new StringWriter(); + final CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT); + final String input = "a,b,c\r\n1,2,3\r\nx,y,z\r\n"; + for (final CSVRecord record : CSVParser.parse(input, CSVFormat.DEFAULT)) { + printer.printRecord(record); + } + assertEquals(input, out.toString()); + printer.close(); + } + + @Test + public void testSkipAutoHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader().parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + @Test + public void testSkipSetHeader() throws Exception { + final Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); + final Iterator records = CSVFormat.DEFAULT.withHeader("a", "b", "c").withSkipHeaderRecord(true) + .parse(in).iterator(); + final CSVRecord record = records.next(); + assertEquals("1", record.get("a")); + assertEquals("2", record.get("b")); + assertEquals("3", record.get("c")); + } + + private void validateLineNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + assertEquals(0, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(1, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + assertEquals(2, parser.getCurrentLineNumber()); + assertNotNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + assertNull(parser.nextRecord()); + // Still 2 because the last line is does not have EOL chars + assertEquals(2, parser.getCurrentLineNumber()); + } + + private void validateRecordNumbers(final String lineSeparator) throws IOException { + final CSVParser parser = CSVParser.parse("a" + lineSeparator + "b" + lineSeparator + "c", CSVFormat.DEFAULT.withRecordSeparator(lineSeparator)); + CSVRecord record; + assertEquals(0, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(1, record.getRecordNumber()); + assertEquals(1, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(2, record.getRecordNumber()); + assertEquals(2, parser.getRecordNumber()); + assertNotNull(record = parser.nextRecord()); + assertEquals(3, record.getRecordNumber()); + assertEquals(3, parser.getRecordNumber()); + assertNull(record = parser.nextRecord()); + assertEquals(3, parser.getRecordNumber()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.ExtendedBufferedReader` acquired by call to `parse(...)` at line 172 is not released after line 173. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CSVParserTest.testBackslashEscapingOld() + +### Procedure Id: +org.apache.commons.csv.CSVParserTest.testBackslashEscapingOld():void.ddfb5a14fc3bd94ed8d9e181a8c66b04 + +### File: +src/test/java/org/apache/commons/csv/CSVParserTest.java + +### Key: +CSVParserTest.java|testBackslashEscapingOld|RESOURCE_LEAK + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +e9df51a2824e86f608ac78955dbdd729 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6603/instruction.md b/inferredbugs-6603/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2304ec19ebf948200f20802689e9d0d76bc24650 --- /dev/null +++ b/inferredbugs-6603/instruction.md @@ -0,0 +1,211 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** vertx-zero +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.vertx.tp.plugin.excel.tpl; + +import io.vertx.up.fn.Fn; +import io.vertx.up.util.Ut; +import org.apache.poi.ss.usermodel.*; + +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.util.Date; +import java.util.TimeZone; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * @author lang + */ +class BlueDye { + private static final ConcurrentMap PICKER_POOL = + new ConcurrentHashMap<>(); + /* + * Fix Issue: + * The maximum number of Cell Styles was exceeded. You can define up to 64000 style in a .xlsx Workbook + */ + private final ConcurrentMap stylePool = + new ConcurrentHashMap<>(); + + private final transient Workbook workbook; + + private BlueDye(final Workbook workbook) { + this.workbook = workbook; + } + /* + * Style applying to fix issue: + */ + + static BlueDye get(final Workbook workbook) { + return Fn.pool(PICKER_POOL, workbook.hashCode(), () -> new BlueDye(workbook)); + } + + /* + * {TABLE} cell + */ + void onTable(final Cell cell) { + final DyeCell dyeCell = Fn.pool(this.stylePool, "TABLE", + () -> DyeCell.create(this.workbook) + .color("FFFFFF", "3EB7FF") + .align(HorizontalAlignment.CENTER) + .border(BorderStyle.THIN) + .font(13, false)); + cell.setCellStyle(dyeCell.build()); + } + + void onModel(final Cell cell) { + final DyeCell dyeCell = Fn.pool(this.stylePool, "MODEL", + () -> DyeCell.create(this.workbook) + .color("FFFFFF", "696969") + .align(HorizontalAlignment.CENTER) + .border(BorderStyle.THIN) + .font(13, false)); + cell.setCellStyle(dyeCell.build()); + } + + void onEmpty(final Cell cell) { + final DyeCell dyeCell = Fn.pool(this.stylePool, "EMPTY", + () -> DyeCell.create(this.workbook) + .align(HorizontalAlignment.CENTER) + .border(BorderStyle.THIN)); + cell.setCellStyle(dyeCell.build()); + } + + void onCnHeader(final Cell cell) { + this.onTable(cell); + } + + void onEnHeader(final Cell cell) { + final DyeCell dyeCell = Fn.pool(this.stylePool, "HEADER", + () -> DyeCell.create(this.workbook) + .color("000000", "FFEC8B") + .align(HorizontalAlignment.CENTER) + .border(BorderStyle.THIN) + .font(13, false)); + cell.setCellStyle(dyeCell.build()); + } + + /* + * Here are simple rule for excel exporting + * 1) When the cell is NUMERIC, we should determine whether the value is Number or Date + * -- NUMBER, the style pool is DATA-VALUE, the same as other date type + * -- Date, when time equal the min ( 00:00 ), use format of `yyyy-MM-dd`, otherwise: `yyyy-MM-dd HH:mm` + * The pool name is DATA-DATE & DATA-DATETIME + * 2) Other date type should be pool of DATA-VALUE also. + */ + void onData(final Cell cell) { + final DyeCell dye; + if (CellType.NUMERIC == cell.getCellType()) { + /* + * Buf for date exporting here + */ + final double cellValue = cell.getNumericCellValue(); + if (DateUtil.isValidExcelDate(cellValue)) { + final Date value = DateUtil.getJavaDate(cellValue, TimeZone.getDefault()); + final LocalDateTime datetime = Ut.toDateTime(value); + final LocalTime time = datetime.toLocalTime(); + if (LocalTime.MIN == time) { + /* + * LocalDate + */ + dye = this.onDataValue("DATA-DATE").dateFormat(false); + } else { + /* + * LocalDateTime + */ + dye = this.onDataValue("DATA-DATETIME").dateFormat(true); + } + } else { + /* + * Number + */ + dye = this.onDataValue("DATA-VALUE"); + } + } else { + /* + * Other + */ + dye = this.onDataValue("DATA-VALUE"); + } + cell.setCellStyle(dye.build()); + } + + private DyeCell onDataValue(final String key) { + return Fn.pool(this.stylePool, key, + () -> DyeCell.create(this.workbook) + .border(BorderStyle.THIN) + .align(null, VerticalAlignment.TOP) + .font(13, false)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `onDataValue(this,"DATA-DATE")` could be null and is dereferenced at line 108. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlueDye.onData(Cell) + +### Procedure Id: +io.vertx.tp.plugin.excel.tpl.BlueDye.onData(org.apache.poi.ss.usermodel.Cell):void.baa22f670ec8a3d9ee1cd733740c9c43 + +### File: +vertx-ifx/zero-ifx-excel/src/main/java/io/vertx/tp/plugin/excel/tpl/BlueDye.java + +### Key: +BlueDye.java|onData|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +fd1d41ee63f7568cd168d8f1816d84b8 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6604/instruction.md b/inferredbugs-6604/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2a302c61fd8dc48d5dfdb15dc938e7eac2e1f65 --- /dev/null +++ b/inferredbugs-6604/instruction.md @@ -0,0 +1,111 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** vertx-zero +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package cn.vertxup.ambient.service; + +import cn.vertxup.ambient.domain.tables.daos.XModuleDao; +import io.vertx.core.Future; +import io.vertx.core.json.JsonArray; +import io.vertx.core.json.JsonObject; +import io.vertx.tp.ke.cv.KeField; +import io.vertx.tp.ke.refine.Ke; +import io.vertx.tp.optic.business.ExModel; +import io.vertx.up.unity.Ux; + +public class ModelService implements ModelStub { + @Override + public Future fetchModule(final String appId, final String entry) { + final JsonObject filters = new JsonObject() + .put("", Boolean.TRUE) + .put("entry", entry) + .put("appId", appId); + return Ux.Jooq.on(XModuleDao.class) + .fetchOneAsync(filters) + .compose(Ux::fnJObject) + /* Metadata field usage */ + .compose(Ke.mount(KeField.METADATA)); + } + + @Override + public Future fetchModels(final String sigma) { + return Ke.channel(ExModel.class, JsonArray::new, + model -> model.fetchAsync(sigma)); + } + + @Override + public Future fetchAttrs(final String identifier, final String sigma) { + return Ke.channel(ExModel.class, JsonArray::new, + model -> model.fetchAttrs(identifier, sigma)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `on(cn.vertxup.ambient.domain.tables.daos.XModuleDao)` could be null and is dereferenced at line 20. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Future ModelService.fetchModule(String,String) + +### Procedure Id: +cn.vertxup.ambient.service.ModelService.fetchModule(java.lang.String,java.lang.String):io.vertx.core.f6edaab4ac445c346abf1fa11d07808d + +### File: +vertx-pin/zero-ambient/src/main/java/cn/vertxup/ambient/service/ModelService.java + +### Key: +ModelService.java|fetchModule|NULL_DEREFERENCE + +### Node Key: +e59d4f13a13a32109c447461abe95ea0 + +### Hash: +5476fd19b911cb60e3c570c59572a5ba + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6635/instruction.md b/inferredbugs-6635/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..56a93bca0287be50227a6fb055baf476c0749560 --- /dev/null +++ b/inferredbugs-6635/instruction.md @@ -0,0 +1,187 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** super-csv +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.supercsv.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.supercsv.TestConstants.ANONYMOUS_CSVCONTEXT; + +import org.junit.Test; +import org.supercsv.cellprocessor.ift.CellProcessor; +import org.supercsv.mock.IdentityTransform; +import org.supercsv.util.CSVContext; + +/** + * Test the NullInputException class. + * + * @author James Bassett + */ +public class NullInputExceptionTest { + + private static final String MSG = "Ahhhh a null!"; + private static final Throwable THROWABLE = new RuntimeException("Muhahahahah I'm null"); + private static final CellProcessor PROCESSOR = new IdentityTransform(); + private static final String CONCATENATED_MSG = THROWABLE.getMessage() + "\n" + MSG; + + /** + * Tests the first constructor. + */ + @Test + public void testConstructor1() { + NullInputException e = new NullInputException(MSG); + assertEquals(MSG, e.getMessage()); + e.printStackTrace(); + + // test with null msg + e = new NullInputException(null); + assertNull(e.getMessage()); + e.printStackTrace(); + } + + /** + * Tests the second constructor. + */ + @Test + public void testConstructor2() { + NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE); + assertEquals(CONCATENATED_MSG, e.getMessage()); + assertEquals(PROCESSOR, e.getOffendingProcessor()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null msg, processor and throwable + e = new NullInputException(null, (CellProcessor) null, (Throwable) null); + assertNull(e.getMessage()); + assertNull(e.getOffendingProcessor()); + assertNull(e.getCause()); + e.printStackTrace(); + } + + /** + * Tests the third constructor. + */ + @Test + public void testConstructor3() { + NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE); + assertEquals(CONCATENATED_MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(THROWABLE, e.getCause()); + e.printStackTrace(); + + // test with null msg, context and throwable + e = new NullInputException(null, (CSVContext) null, (Throwable) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getCause()); + e.printStackTrace(); + } + + /** + * Tests the fourth constructor. + */ + @Test + public void testConstructor4() { + NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR); + assertEquals(MSG, e.getMessage()); + assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext()); + assertEquals(PROCESSOR, e.getOffendingProcessor()); + e.printStackTrace(); + + // test with null msg, context and processor + e = new NullInputException(null, (CSVContext) null, (CellProcessor) null); + assertNull(e.getMessage()); + assertNull(e.getCsvContext()); + assertNull(e.getOffendingProcessor()); + e.printStackTrace(); + } + + /** + * Tests the fifth constructor. + */ + @Test + public void testConstructor5() { + NullInputException e = new NullInputException(MSG, PROCESSOR); + assertEquals(MSG, e.getMessage()); + assertEquals(PROCESSOR, e.getOffendingProcessor()); + e.printStackTrace(); + + // test with null msg and processor + e = new NullInputException(null, null); + assertNull(e.getMessage()); + assertNull(e.getOffendingProcessor()); + e.printStackTrace(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `NullInputException(...)` at line 70. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NullInputExceptionTest.testConstructor3() + +### Procedure Id: +org.supercsv.exception.NullInputExceptionTest.testConstructor3():void.3b363f3a437b39551c936dd23d892150 + +### File: +src/test/java/org/supercsv/exception/NullInputExceptionTest.java + +### Key: +NullInputExceptionTest.java|testConstructor3|NULL_DEREFERENCE + +### Node Key: +47d1bd2a0b318b83bd2a989115cad1cc + +### Hash: +2fb195c0db8b5e12758c68806d4a1b68 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6650/instruction.md b/inferredbugs-6650/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..907cbb83d093ff33b31592c0d4294f0f597213e9 --- /dev/null +++ b/inferredbugs-6650/instruction.md @@ -0,0 +1,935 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright for portions of OpenUnirest/uniresr-java are held by Mashape (c) 2013 as part of Kong/unirest-java. +All other copyright for OpenUnirest/unirest-java are held by OpenUnirest (c) 2018. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package io.github.openunirest.http; + +import io.github.openunirest.http.async.Callback; +import io.github.openunirest.http.options.Options; +import io.github.openunirest.request.body.MultipartBody; +import io.github.openunirest.http.exceptions.UnirestException; +import io.github.openunirest.request.GetRequest; +import io.github.openunirest.request.HttpRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; + +import java.io.*; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +public class UnirestTest { + + private CountDownLatch lock; + private boolean status; + + @BeforeClass + public static void suiteSetUp(){ + MockServer.start(); + } + + @AfterClass + public static void suiteTearDown(){ + MockServer.shutdown(); + } + + @Before + public void setUp() { + MockServer.reset(); + lock = new CountDownLatch(1); + status = false; + } + + @Test + public void postFormReturnJson() throws JSONException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POSTJSON) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + FormCapture json = TestUtils.read(jsonResponse, FormCapture.class); + json.assertHeader("Accept", "application/json"); + json.assertQuery("param1", "value1"); + json.assertQuery("param2", "bye"); + } + + @Test + public void canPassQueryParamsOnStringOrWithForm() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=mark") + .header("accept", "application/json") + .asJson(); + + FormCapture json = TestUtils.read(response, FormCapture.class); + json.assertQuery("name", "mark"); + + response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("name", "mark2") + .asJson(); + + json = TestUtils.read(response, FormCapture.class); + json.assertQuery("name", "mark2"); + } + + @Test + public void multipleParams() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=ringo") + .header("accept", "application/json") + .queryString("name", "paul") + .queryString("name", "john") + .asJson(); + + FormCapture json = TestUtils.read(response, FormCapture.class); + json.assertQuery("name", "ringo"); + json.assertQuery("name", "paul"); + json.assertQuery("name", "john"); + } + + @Test + public void testGetUTF8() { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("param3", "こんにちは") + .asJson(); + + FormCapture json = TestUtils.read(response, FormCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostUTF8() { + HttpResponse response = Unirest.post(MockServer.POSTJSON) + .header("accept", "application/json") + .field("param3", "こんにちは") + .asJson(); + + FormCapture json = TestUtils.read(response, FormCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostBinaryUTF8() throws URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").field("file", new File(getClass().getResource("/test").toURI())).asJson(); + + assertEquals("This is a test file", response.getBody().getObject().getJSONObject("files").getString("file")); + assertEquals("こんにちは", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testPostRawBody() { + String sourceString = "'\"@こんにちは-test-123-" + Math.random(); + byte[] sentBytes = sourceString.getBytes(); + + HttpResponse response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); + + assertEquals(sourceString, response.getBody().getObject().getString("data")); + } + + @Test + public void testCustomUserAgent() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); + assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); + + GetRequest getRequest = Unirest.get("http"); + for (Object current : Arrays.asList(0, 1, 2)) { + getRequest.queryString("name", current); + } + + } + + @Test + public void testGetMultiple() throws JSONException, UnirestException { + for (int i = 1; i <= 20; i++) { + HttpResponse response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); + } + } + + @Test + public void testGetFields() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "mark").queryString("nick", "thefosk").asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("nick"), "thefosk"); + } + + @Test + public void testGetFields2() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("email", "hello@hello.com").asJson(); + assertEquals("hello@hello.com", response.getBody().getObject().getJSONObject("args").getString("email")); + } + + @Test + public void testQueryStringEncoding() throws JSONException, UnirestException { + String testKey = "email2=someKey&email"; + String testValue = "hello@hello.com"; + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); + assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); + } + + @Test + public void testDelete() throws JSONException, UnirestException { + HttpResponse response = Unirest.delete("http://httpbin.org/delete").asJson(); + assertEquals(200, response.getStatus()); + + response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); + assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testDeleteBody() throws JSONException, UnirestException { + String body = "{\"jsonString\":{\"members\":\"members1\"}}"; + HttpResponse response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); + assertEquals(200, response.getStatus()); + assertEquals(body, response.getBody().getObject().getString("data")); + } + + @Test + public void testBasicAuth() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); + assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); + } + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); + + assertNotNull(future); + HttpResponse jsonResponse = future.get(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + + @Test + public void testAsyncCallback() throws JSONException, InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("value1", json.getObject().getJSONObject("form").getString("param1")); + assertEquals("bye", json.getObject().getJSONObject("form").getString("param2")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipart() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartContentType() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:image/jpeg")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { + FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + MultipartBody request = Unirest.post(MockServer.HOST + "/post") + .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) + .field("name", "Mark") + .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); + + HttpResponse jsonResponse = request + .asJson(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + JSONObject object = json.getObject(); + assertNotNull(object); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(object.getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, URISyntaxException, FileNotFoundException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "image.jpg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGzip() throws JSONException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testGzipAsync() throws JSONException, InterruptedException, ExecutionException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJsonAsync().get(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testDefaultHeaders() throws JSONException { + Unirest.setDefaultHeader("X-Custom-Header", "hello"); + Unirest.setDefaultHeader("user-agent", "foobar"); + + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", json.getObject().getJSONObject("headers").getString("X-Custom-Header")); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("User-Agent")); + assertEquals("foobar", json.getObject().getJSONObject("headers").getString("User-Agent")); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", jsonResponse.getBody().getObject().getJSONObject("headers").getString("X-Custom-Header")); + + Unirest.clearDefaultHeaders(); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertFalse(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + } + + @Test + public void testSetTimeouts() throws IOException { + String address = "http://" + findAvailableIpAddress() + "/"; + long start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution + fail(); + } + } + Unirest.setTimeouts(2000, 10000); + start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution + fail(); + } + } + } + + @Test + public void testPathParameters() { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/{method}").routeParam("method", "get").queryString("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + } + + @Test + public void testQueryAndBodyParameters() { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/{method}").routeParam("method", "post").queryString("name", "Mark").field("wot", "wat").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("wot"), "wat"); + } + + @Test + public void testPathParameters2() { + HttpResponse jsonResponse = Unirest.patch("http://httpbin.org/{method}").routeParam("method", "patch").field("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals("OK", jsonResponse.getStatusText()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("name"), "Mark"); + } + + @Test + public void testMissingPathParameter() { + try { + Unirest.get("http://httpbin.org/{method}").routeParam("method222", "get").queryString("name", "Mark").asJson(); + fail(); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void parallelTest() throws InterruptedException { + Unirest.setConcurrency(10, 5); + + long start = System.currentTimeMillis(); + makeParallelRequests(); + long smallerConcurrencyTime = (System.currentTimeMillis() - start); + + Unirest.setConcurrency(200, 20); + start = System.currentTimeMillis(); + makeParallelRequests(); + long higherConcurrencyTime = (System.currentTimeMillis() - start); + + assertTrue(higherConcurrencyTime < smallerConcurrencyTime); + } + + private void makeParallelRequests() throws InterruptedException { + ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); + final AtomicInteger counter = new AtomicInteger(0); + for (int i = 0; i < 200; i++) { + newFixedThreadPool.execute(() -> { + try { + Unirest.get(MockServer.HOST + "/get").queryString("index", counter.incrementAndGet()).asString(); + } catch (UnirestException e) { + throw new RuntimeException(e); + } + }); + } + + newFixedThreadPool.shutdown(); + newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); + } + + @Test + public void testAsyncCustomContentType() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); + assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); + + assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGetQuerystringArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostMultipleFiles() throws JSONException, URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); + + JSONObject names = response.getBody().getObject().getJSONObject("files"); + assertEquals(2, names.length()); + + assertEquals("This is a test file", names.getString("file1")); + assertEquals("This is a test file", names.getString("file2")); + + assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testGetArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostCollection() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testCaseInsensitiveHeaders() { + GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); + assertEquals("Marco", headers.getString("Name")); + + request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("John", request.getHeaders().get("name").get(1)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("John", request.getHeaders().get("NAme").get(1)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + assertEquals("John", request.getHeaders().get("Name").get(1)); + } + + @Test + public void setTimeoutsAndCustomClient() { + try { + Unirest.setTimeouts(1000, 2000); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + + try { + Unirest.setHttpClient(HttpClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + } + + @Test + public void testObjectMapperRead() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse getResponseMock = new GetResponse(); + getResponseMock.setUrl("http://httpbin.org/get"); + + HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); + + assertEquals(200, getResponse.getStatus()); + assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); + } + + @Test + public void testObjectMapperWrite() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse postResponseMock = new GetResponse(); + postResponseMock.setUrl("http://httpbin.org/post"); + + HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); + + assertEquals(200, postResponse.getStatus()); + assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); + } + + @Test + public void testPostProvidesSortedParams() throws IOException { + // Verify that fields are encoded into the body in sorted order. + HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); + + InputStream content = httpRequest.getBody().getEntity().getContent(); + String body = IOUtils.toString(content, "UTF-8"); + assertEquals("x=X&y=Y&z=Z", body); + } + + @Test + public void testHeaderNamesCaseSensitive() { + // Verify that header names are the same as server (case sensitive) + final Headers headers = new Headers(); + headers.put("Content-Type", Arrays.asList("application/json")); + + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); + assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); + } + + + private String findAvailableIpAddress() throws IOException { + for (int i = 100; i <= 255; i++) { + String ip = "192.168.1." + i; + if (!InetAddress.getByName(ip).isReachable(1000)) { + return ip; + } + } + + throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `jsonResponse.getHeaders()` could be null and is dereferenced at line 336. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testMultipartInputStreamContentType() + +### Procedure Id: +io.github.openunirest.http.UnirestTest.testMultipartInputStreamContentType():void.513e0e5d751eb76227739c99e9380ea6 + +### File: +src/test/java/io/github/openunirest/http/UnirestTest.java + +### Key: +UnirestTest.java|testMultipartInputStreamContentType|NULL_DEREFERENCE + +### Node Key: +18086a76ec6f499138a84f176568ec09 + +### Hash: +cbec719adf54a7920543835184142c4a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6651/instruction.md b/inferredbugs-6651/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..408a0cd759b1860cb67493f941aaee6f6c44bc32 --- /dev/null +++ b/inferredbugs-6651/instruction.md @@ -0,0 +1,949 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright for portions of OpenUnirest/uniresr-java are held by Mashape (c) 2013 as part of Kong/unirest-java. +All other copyright for OpenUnirest/unirest-java are held by OpenUnirest (c) 2018. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package io.github.openunirest.http; + +import io.github.openunirest.http.async.Callback; +import io.github.openunirest.http.options.Options; +import io.github.openunirest.request.body.MultipartBody; +import io.github.openunirest.http.exceptions.UnirestException; +import io.github.openunirest.request.GetRequest; +import io.github.openunirest.request.HttpRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; + +import java.io.*; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static io.github.openunirest.http.TestUtils.read; +import static org.junit.Assert.*; + +public class UnirestTest { + + private CountDownLatch lock; + private boolean status; + + @BeforeClass + public static void suiteSetUp(){ + MockServer.start(); + } + + @AfterClass + public static void suiteTearDown(){ + MockServer.shutdown(); + } + + @Before + public void setUp() { + MockServer.reset(); + lock = new CountDownLatch(1); + status = false; + } + + @Test + public void postFormReturnJson() throws JSONException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = parse(jsonResponse); + json.assertHeader("Accept", "application/json"); + json.assertQuery("param1", "value1"); + json.assertQuery("param2", "bye"); + } + + @Test + public void canPassQueryParamsOnStringOrWithForm() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=mark") + .header("accept", "application/json") + .asJson(); + + RequestCapture json = parse(response); + json.assertQuery("name", "mark"); + + response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("name", "mark2") + .asJson(); + + json = parse(response); + json.assertQuery("name", "mark2"); + } + + @Test + public void multipleParams() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=ringo") + .header("accept", "application/json") + .queryString("name", "paul") + .queryString("name", "john") + .asJson(); + + RequestCapture json = parse(response); + json.assertQuery("name", "ringo"); + json.assertQuery("name", "paul"); + json.assertQuery("name", "john"); + } + + @Test + public void testGetUTF8() { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("param3", "こんにちは") + .asJson(); + + RequestCapture json = parse(response); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostUTF8() { + HttpResponse response = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param3", "こんにちは") + .asJson(); + + RequestCapture json = parse(response); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostBinaryUTF8() throws URISyntaxException { + HttpResponse response = Unirest.post(MockServer.POST) + .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) + .field("param3", "こんにちは") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJson(); + + RequestCapture json = parse(response); + json.assertQuery("param3", "こんにちは"); + json.getFile("test").assertBody("This is a test file"); + } + + @Test + public void testPostRawBody() { + String sourceString = "'\"@こんにちは-test-123-" + Math.random(); + byte[] sentBytes = sourceString.getBytes(); + + HttpResponse response = Unirest.post(MockServer.POST) + .body(sentBytes) + .asJson(); + + RequestCapture json = parse(response); + json.asserBody(sourceString); + } + + @Test + public void testCustomUserAgent() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .header("user-agent", "hello-world") + .asJson(); + + RequestCapture json = parse(response); + json.assertHeader("User-Agent", "hello-world"); + } + + @Test + public void testGetMultiple() throws JSONException, UnirestException { + for (int i = 1; i <= 20; i++) { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?try=" + i).asJson(); + parse(response).assertQuery("try", String.valueOf(i)); + } + } + + @Test + public void testGetFields() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .queryString("name", "mark") + .queryString("nick", "thefosk") + .asJson(); + + RequestCapture parse = parse(response); + parse.assertQuery("name", "mark"); + parse.assertQuery("nick", "thefosk"); + } + + @Test + public void testGetFields2() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .queryString("email", "hello@hello.com") + .asJson(); + + parse(response).assertQuery("email", "hello@hello.com"); + } + + @Test + public void testQueryStringEncoding() throws JSONException, UnirestException { + String testKey = "email2=someKey&email"; + String testValue = "hello@hello.com"; + + HttpResponse response = Unirest.get(MockServer.GETJSON) + .queryString(testKey, testValue) + .asJson(); + + parse(response).assertQuery(testKey, testValue); + } + + @Test + public void testDelete() throws JSONException, UnirestException { + HttpResponse response = Unirest.delete("http://httpbin.org/delete").asJson(); + assertEquals(200, response.getStatus()); + + response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); + assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testDeleteBody() throws JSONException, UnirestException { + String body = "{\"jsonString\":{\"members\":\"members1\"}}"; + HttpResponse response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); + assertEquals(200, response.getStatus()); + assertEquals(body, response.getBody().getObject().getString("data")); + } + + @Test + public void testBasicAuth() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); + assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); + } + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); + + assertNotNull(future); + HttpResponse jsonResponse = future.get(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + + @Test + public void testAsyncCallback() throws JSONException, InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("value1", json.getObject().getJSONObject("form").getString("param1")); + assertEquals("bye", json.getObject().getJSONObject("form").getString("param2")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipart() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartContentType() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:image/jpeg")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { + FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + + MultipartBody request = Unirest.post(MockServer.HOST + "/post") + .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) + .field("name", "Mark") + .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); + + HttpResponse jsonResponse = request + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = parse(jsonResponse); + json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); + json.assertQuery("name", "Mark"); + assertEquals("application/octet-stream", json.getFile("image.jpg").type); + } + + @Test + public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, URISyntaxException, FileNotFoundException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "image.jpg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGzip() throws JSONException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testGzipAsync() throws JSONException, InterruptedException, ExecutionException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJsonAsync().get(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testDefaultHeaders() throws JSONException { + Unirest.setDefaultHeader("X-Custom-Header", "hello"); + Unirest.setDefaultHeader("user-agent", "foobar"); + + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", json.getObject().getJSONObject("headers").getString("X-Custom-Header")); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("User-Agent")); + assertEquals("foobar", json.getObject().getJSONObject("headers").getString("User-Agent")); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", jsonResponse.getBody().getObject().getJSONObject("headers").getString("X-Custom-Header")); + + Unirest.clearDefaultHeaders(); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertFalse(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + } + + @Test + public void testSetTimeouts() throws IOException { + String address = "http://" + findAvailableIpAddress() + "/"; + long start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution + fail(); + } + } + Unirest.setTimeouts(2000, 10000); + start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution + fail(); + } + } + } + + @Test + public void testPathParameters() { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/{method}").routeParam("method", "get").queryString("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + } + + @Test + public void testQueryAndBodyParameters() { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/{method}").routeParam("method", "post").queryString("name", "Mark").field("wot", "wat").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("wot"), "wat"); + } + + @Test + public void testPathParameters2() { + HttpResponse jsonResponse = Unirest.patch("http://httpbin.org/{method}").routeParam("method", "patch").field("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals("OK", jsonResponse.getStatusText()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("name"), "Mark"); + } + + @Test + public void testMissingPathParameter() { + try { + Unirest.get("http://httpbin.org/{method}").routeParam("method222", "get").queryString("name", "Mark").asJson(); + fail(); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void parallelTest() throws InterruptedException { + Unirest.setConcurrency(10, 5); + + long start = System.currentTimeMillis(); + makeParallelRequests(); + long smallerConcurrencyTime = (System.currentTimeMillis() - start); + + Unirest.setConcurrency(200, 20); + start = System.currentTimeMillis(); + makeParallelRequests(); + long higherConcurrencyTime = (System.currentTimeMillis() - start); + + assertTrue(higherConcurrencyTime < smallerConcurrencyTime); + } + + private void makeParallelRequests() throws InterruptedException { + ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); + final AtomicInteger counter = new AtomicInteger(0); + for (int i = 0; i < 200; i++) { + newFixedThreadPool.execute(() -> { + try { + Unirest.get(MockServer.HOST + "/get").queryString("index", counter.incrementAndGet()).asString(); + } catch (UnirestException e) { + throw new RuntimeException(e); + } + }); + } + + newFixedThreadPool.shutdown(); + newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); + } + + @Test + public void testAsyncCustomContentType() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); + assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); + + assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGetQuerystringArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostMultipleFiles() throws JSONException, URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); + + JSONObject names = response.getBody().getObject().getJSONObject("files"); + assertEquals(2, names.length()); + + assertEquals("This is a test file", names.getString("file1")); + assertEquals("This is a test file", names.getString("file2")); + + assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testGetArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostCollection() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testCaseInsensitiveHeaders() { + GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); + assertEquals("Marco", headers.getString("Name")); + + request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("John", request.getHeaders().get("name").get(1)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("John", request.getHeaders().get("NAme").get(1)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + assertEquals("John", request.getHeaders().get("Name").get(1)); + } + + @Test + public void setTimeoutsAndCustomClient() { + try { + Unirest.setTimeouts(1000, 2000); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + + try { + Unirest.setHttpClient(HttpClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + } + + @Test + public void testObjectMapperRead() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse getResponseMock = new GetResponse(); + getResponseMock.setUrl("http://httpbin.org/get"); + + HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); + + assertEquals(200, getResponse.getStatus()); + assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); + } + + @Test + public void testObjectMapperWrite() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse postResponseMock = new GetResponse(); + postResponseMock.setUrl("http://httpbin.org/post"); + + HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); + + assertEquals(200, postResponse.getStatus()); + assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); + } + + @Test + public void testPostProvidesSortedParams() throws IOException { + // Verify that fields are encoded into the body in sorted order. + HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); + + InputStream content = httpRequest.getBody().getEntity().getContent(); + String body = IOUtils.toString(content, "UTF-8"); + assertEquals("x=X&y=Y&z=Z", body); + } + + @Test + public void testHeaderNamesCaseSensitive() { + // Verify that header names are the same as server (case sensitive) + final Headers headers = new Headers(); + headers.put("Content-Type", Arrays.asList("application/json")); + + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); + assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); + } + + + private String findAvailableIpAddress() throws IOException { + for (int i = 100; i <= 255; i++) { + String ip = "192.168.1." + i; + if (!InetAddress.getByName(ip).isReachable(1000)) { + return ip; + } + } + + throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); + } + + private RequestCapture parse(HttpResponse response) { + return read(response, RequestCapture.class); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `response.getBody()` could be null and is dereferenced at line 244. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testBasicAuth() + +### Procedure Id: +io.github.openunirest.http.UnirestTest.testBasicAuth():void.7ba06c84fa837f294488238edf707182 + +### File: +src/test/java/io/github/openunirest/http/UnirestTest.java + +### Key: +UnirestTest.java|testBasicAuth|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +fb11bc497e65c18e6d2348fca3bc7866 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6656/instruction.md b/inferredbugs-6656/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3048adc557b631c62bef0ec3b616bed168f1542d --- /dev/null +++ b/inferredbugs-6656/instruction.md @@ -0,0 +1,904 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright for portions of OpenUnirest/uniresr-java are held by Mashape (c) 2013 as part of Kong/unirest-java. +All other copyright for OpenUnirest/unirest-java are held by OpenUnirest (c) 2018. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package io.github.openunirest.http; + +import io.github.openunirest.http.async.Callback; +import io.github.openunirest.http.options.Options; +import io.github.openunirest.http.exceptions.UnirestException; +import io.github.openunirest.request.GetRequest; +import io.github.openunirest.request.HttpRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; + +import java.io.*; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static io.github.openunirest.http.TestUtils.read; +import static org.junit.Assert.*; + +public class UnirestTest { + + private CountDownLatch lock; + private boolean status; + + @BeforeClass + public static void suiteSetUp() { + MockServer.start(); + } + + @AfterClass + public static void suiteTearDown() { + MockServer.shutdown(); + } + + @Before + public void setUp() { + MockServer.reset(); + lock = new CountDownLatch(1); + status = false; + } + + @Test + public void postFormReturnJson() throws JSONException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = parse(jsonResponse); + json.assertHeader("Accept", "application/json"); + json.assertParam("param1", "value1"); + json.assertParam("param2", "bye"); + } + + @Test + public void canPassQueryParamsOnStringOrWithForm() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET + "?name=mark") + .header("accept", "application/json") + .asJson(); + + RequestCapture json = parse(response); + json.assertParam("name", "mark"); + + response = Unirest.get(MockServer.GET) + .header("accept", "application/json") + .queryString("name", "mark2") + .asJson(); + + json = parse(response); + json.assertParam("name", "mark2"); + } + + @Test + public void multipleParams() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET + "?name=ringo") + .header("accept", "application/json") + .queryString("name", "paul") + .queryString("name", "john") + .asJson(); + + RequestCapture json = parse(response); + json.assertParam("name", "ringo"); + json.assertParam("name", "paul"); + json.assertParam("name", "john"); + } + + @Test + public void testGetUTF8() { + HttpResponse response = Unirest.get(MockServer.GET) + .header("accept", "application/json") + .queryString("param3", "こんにちは") + .asJson(); + + RequestCapture json = parse(response); + json.assertParam("param3", "こんにちは"); + } + + @Test + public void testPostUTF8() { + HttpResponse response = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param3", "こんにちは") + .asJson(); + + RequestCapture json = parse(response); + json.assertParam("param3", "こんにちは"); + } + + @Test + public void testPostBinaryUTF8() throws URISyntaxException { + HttpResponse response = Unirest.post(MockServer.POST) + .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) + .field("param3", "こんにちは") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJson(); + + RequestCapture json = parse(response); + json.assertParam("param3", "こんにちは"); + json.getFile("test").assertBody("This is a test file"); + } + + @Test + public void testPostRawBody() { + String sourceString = "'\"@こんにちは-test-123-" + Math.random(); + byte[] sentBytes = sourceString.getBytes(); + + HttpResponse response = Unirest.post(MockServer.POST) + .body(sentBytes) + .asJson(); + + RequestCapture json = parse(response); + json.asserBody(sourceString); + } + + @Test + public void testCustomUserAgent() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET) + .header("user-agent", "hello-world") + .asJson(); + + RequestCapture json = parse(response); + json.assertHeader("User-Agent", "hello-world"); + } + + @Test + public void testGetMultiple() throws JSONException, UnirestException { + for (int i = 1; i <= 20; i++) { + HttpResponse response = Unirest.get(MockServer.GET + "?try=" + i).asJson(); + parse(response).assertParam("try", String.valueOf(i)); + } + } + + @Test + public void testGetFields() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET) + .queryString("name", "mark") + .queryString("nick", "thefosk") + .asJson(); + + RequestCapture parse = parse(response); + parse.assertParam("name", "mark"); + parse.assertParam("nick", "thefosk"); + } + + @Test + public void testGetFields2() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET) + .queryString("email", "hello@hello.com") + .asJson(); + + parse(response).assertParam("email", "hello@hello.com"); + } + + @Test + public void testQueryStringEncoding() throws JSONException, UnirestException { + String testKey = "email2=someKey&email"; + String testValue = "hello@hello.com"; + + HttpResponse response = Unirest.get(MockServer.GET) + .queryString(testKey, testValue) + .asJson(); + + parse(response).assertParam(testKey, testValue); + } + + @Test + public void testDelete() throws JSONException, UnirestException { + HttpResponse response = Unirest.delete(MockServer.DELETE).asJson(); + assertEquals(200, response.getStatus()); + + response = Unirest.delete(MockServer.DELETE) + .field("name", "mark") + .field("foo", "bar") + .asJson(); + + RequestCapture parse = parse(response); + parse.assertParam("name", "mark"); + parse.assertParam("foo", "bar"); + } + + @Test + public void testDeleteBody() throws JSONException, UnirestException { + String body = "{\"jsonString\":{\"members\":\"members1\"}}"; + HttpResponse response = Unirest.delete(MockServer.DELETE) + .body(body) + .asJson(); + + assertEquals(200, response.getStatus()); + parse(response).asserBody(body); + } + + @Test + public void testBasicAuth() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GET) + .basicAuth("user", "test") + .asJson(); + + parse(response).assertHeader("Authorization", "Basic dXNlcjp0ZXN0"); + } + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJsonAsync(); + + assertNotNull(future); + + RequestCapture req = parse(future.get()); + req.assertParam("param1", "value1"); + req.assertParam("param2", "bye"); + } + + @Test + public void testAsyncCallback() throws JSONException, InterruptedException { + Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + RequestCapture req = parse(jsonResponse); + req.assertParam("param1", "value1"); + req.assertParam("param2", "bye"); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipart() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJson(); + + RequestCapture res = parse(jsonResponse); + res.getFile("test").assertBody("This is a test file"); + res.getFile("test").assertFileType("application/octet-stream"); + + res.assertParam("name", "Mark"); + } + + @Test + public void testMultipartContentType() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg") + .asJson(); + + RequestCapture res = parse(jsonResponse); + res.getFile("image.jpg").assertFileType("image/jpeg"); + res.assertParam("name", "Mark"); + } + + @Test + public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { + FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + + HttpResponse request = Unirest.post(MockServer.POST) + .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) + .field("name", "Mark") + .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg") + .asJson(); + + assertEquals(200, request.getStatus()); + + RequestCapture json = parse(request); + json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); + json.assertParam("name", "Mark"); + json.getFile("image.jpg").assertFileType("application/octet-stream"); + } + + @Test + public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, URISyntaxException, FileNotFoundException { + Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + RequestCapture json = parse(response); + json.assertParam("name", "Mark"); + json.getFile("test").assertFileType("application/octet-stream"); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartByteContentType() throws JSONException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", bytes, "image.jpg") + .asJson(); + + RequestCapture parse = parse(jsonResponse); + parse.getFile("image.jpg").assertFileType("application/octet-stream"); + parse.assertParam("name", "Mark"); + } + + @Test + public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + + Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", bytes, "test") + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + RequestCapture parse = parse(response); + parse.getFile("test").assertFileType("application/octet-stream"); + parse.assertParam("name", "Mark"); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { + Unirest.post(MockServer.POST) + .field("name", "Mark") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + RequestCapture parse = parse(response); + parse.getFile("test").assertFileType("application/octet-stream"); + parse.getFile("test").assertBody("This is a test file"); + parse.assertParam("name", "Mark"); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGzip() throws JSONException { + HttpResponse jsonResponse = Unirest.get(MockServer.GZIP) + .queryString("zipme", "up") + .asJson(); + + parse(jsonResponse).assertParam("zipme", "up"); + } + + @Test + public void testGzipAsync() throws JSONException, InterruptedException, ExecutionException { + HttpResponse jsonResponse = Unirest.get(MockServer.GZIP) + .queryString("zipme", "up") + .asJsonAsync() + .get(); + + parse(jsonResponse).assertParam("zipme", "up"); + } + + @Test + public void testDefaultHeaders() throws JSONException { + Unirest.setDefaultHeader("X-Custom-Header", "hello"); + Unirest.setDefaultHeader("user-agent", "foobar"); + + HttpResponse jsonResponse = Unirest.get(MockServer.GET).asJson(); + + RequestCapture r = parse(jsonResponse); + r.assertHeader("X-Custom-Header", "hello"); + r.assertHeader("User-Agent", "foobar"); + + jsonResponse = Unirest.get(MockServer.GET).asJson(); + r = parse(jsonResponse); + r.assertHeader("X-Custom-Header", "hello"); + r.assertHeader("User-Agent", "foobar"); + + Unirest.clearDefaultHeaders(); + + jsonResponse = Unirest.get(MockServer.GET).asJson(); + r = parse(jsonResponse); + r.assertNoHeader("X-Custom-Header"); + } + + @Test + public void testSetTimeouts() throws IOException { + String address = "http://" + findAvailableIpAddress() + "/"; + long start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution + fail(); + } + } + Unirest.setTimeouts(2000, 10000); + start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution + fail(); + } + } + } + + @Test + public void testPathParameters() { + HttpResponse jsonResponse = Unirest.get(MockServer.HOST + "/{method}") + .routeParam("method", "get") + .queryString("name", "Mark") + .asJson(); + + parse(jsonResponse) + .assertParam("name", "Mark"); + } + + @Test + public void testQueryAndBodyParameters() { + HttpResponse jsonResponse = Unirest.post(MockServer.HOST + "/{method}") + .routeParam("method", "post") + .queryString("name", "Mark") + .field("wot", "wat") + .asJson(); + + parse(jsonResponse) + .assertParam("name", "Mark") + .assertParam("wot", "wat"); + } + + @Test + public void testPathParameters2() { + HttpResponse jsonResponse = Unirest.patch(MockServer.HOST + "/{method}") + .routeParam("method", "patch") + .field("name", "Mark") + .asJson(); + + parse(jsonResponse) + .assertParam("name", "Mark"); + } + + @Test + public void testMissingPathParameter() { + try { + Unirest.get(MockServer.HOST + "/{method}") + .routeParam("method222", "get") + .queryString("name", "Mark") + .asJson(); + + fail(); + } catch (RuntimeException e) { + assertEquals("Can't find route parameter name \"method222\"", e.getMessage()); + } + } + + @Test + public void parallelTest() throws InterruptedException { + Unirest.setConcurrency(10, 5); + + long start = System.currentTimeMillis(); + makeParallelRequests(); + long smallerConcurrencyTime = (System.currentTimeMillis() - start); + + Unirest.setConcurrency(200, 20); + start = System.currentTimeMillis(); + makeParallelRequests(); + long higherConcurrencyTime = (System.currentTimeMillis() - start); + + assertTrue(higherConcurrencyTime < smallerConcurrencyTime); + } + + private void makeParallelRequests() throws InterruptedException { + ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); + final AtomicInteger counter = new AtomicInteger(0); + for (int i = 0; i < 200; i++) { + newFixedThreadPool.execute(() -> { + try { + Unirest.get(MockServer.HOST + "/get").queryString("index", counter.incrementAndGet()).asString(); + } catch (UnirestException e) { + throw new RuntimeException(e); + } + }); + } + + newFixedThreadPool.shutdown(); + newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); + } + + @Test + public void testAsyncCustomContentType() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); + assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); + + assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGetQuerystringArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostMultipleFiles() throws JSONException, URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); + + JSONObject names = response.getBody().getObject().getJSONObject("files"); + assertEquals(2, names.length()); + + assertEquals("This is a test file", names.getString("file1")); + assertEquals("This is a test file", names.getString("file2")); + + assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testGetArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostCollection() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testCaseInsensitiveHeaders() { + GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); + assertEquals("Marco", headers.getString("Name")); + + request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("John", request.getHeaders().get("name").get(1)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("John", request.getHeaders().get("NAme").get(1)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + assertEquals("John", request.getHeaders().get("Name").get(1)); + } + + @Test + public void setTimeoutsAndCustomClient() { + try { + Unirest.setTimeouts(1000, 2000); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + + try { + Unirest.setHttpClient(HttpClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + } + + @Test + public void testObjectMapperRead() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse getResponseMock = new GetResponse(); + getResponseMock.setUrl("http://httpbin.org/get"); + + HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); + + assertEquals(200, getResponse.getStatus()); + assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); + } + + @Test + public void testObjectMapperWrite() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse postResponseMock = new GetResponse(); + postResponseMock.setUrl("http://httpbin.org/post"); + + HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); + + assertEquals(200, postResponse.getStatus()); + assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); + } + + @Test + public void testPostProvidesSortedParams() throws IOException { + // Verify that fields are encoded into the body in sorted order. + HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); + + InputStream content = httpRequest.getBody().getEntity().getContent(); + String body = IOUtils.toString(content, "UTF-8"); + assertEquals("x=X&y=Y&z=Z", body); + } + + @Test + public void testHeaderNamesCaseSensitive() { + // Verify that header names are the same as server (case sensitive) + final Headers headers = new Headers(); + headers.put("Content-Type", Arrays.asList("application/json")); + + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); + assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); + } + + + private String findAvailableIpAddress() throws IOException { + for (int i = 100; i <= 255; i++) { + String ip = "192.168.1." + i; + if (!InetAddress.getByName(ip).isReachable(1000)) { + return ip; + } + } + + throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); + } + + private RequestCapture parse(HttpResponse response) { + assertEquals(200, response.getStatus()); + return read(response, RequestCapture.class); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `response.getBody()` could be null and is dereferenced at line 687. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testGetArray() + +### Procedure Id: +io.github.openunirest.http.UnirestTest.testGetArray():void.93cc13ec03e28927235063f3d8836c8c + +### File: +src/test/java/io/github/openunirest/http/UnirestTest.java + +### Key: +UnirestTest.java|testGetArray|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +dc357b3c4ab72771c78729f8026fe474 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6658/instruction.md b/inferredbugs-6658/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38987d1537aa13bec7357618afbf494274038e3f --- /dev/null +++ b/inferredbugs-6658/instruction.md @@ -0,0 +1,934 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 15 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright for portions of OpenUnirest/uniresr-java are held by Mashape (c) 2013 as part of Kong/unirest-java. +All other copyright for OpenUnirest/unirest-java are held by OpenUnirest (c) 2018. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package io.github.openunirest.http; + +import io.github.openunirest.http.async.Callback; +import io.github.openunirest.http.options.Options; +import io.github.openunirest.request.body.MultipartBody; +import io.github.openunirest.http.exceptions.UnirestException; +import io.github.openunirest.request.GetRequest; +import io.github.openunirest.request.HttpRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; + +import java.io.*; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +public class UnirestTest { + + private CountDownLatch lock; + private boolean status; + + @BeforeClass + public static void suiteSetUp(){ + MockServer.start(); + } + + @AfterClass + public static void suiteTearDown(){ + MockServer.shutdown(); + } + + @Before + public void setUp() { + MockServer.reset(); + lock = new CountDownLatch(1); + status = false; + } + + @Test + public void postFormReturnJson() throws JSONException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = TestUtils.read(jsonResponse, RequestCapture.class); + json.assertHeader("Accept", "application/json"); + json.assertQuery("param1", "value1"); + json.assertQuery("param2", "bye"); + } + + @Test + public void canPassQueryParamsOnStringOrWithForm() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=mark") + .header("accept", "application/json") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "mark"); + + response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("name", "mark2") + .asJson(); + + json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "mark2"); + } + + @Test + public void multipleParams() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=ringo") + .header("accept", "application/json") + .queryString("name", "paul") + .queryString("name", "john") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "ringo"); + json.assertQuery("name", "paul"); + json.assertQuery("name", "john"); + } + + @Test + public void testGetUTF8() { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("param3", "こんにちは") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostUTF8() { + HttpResponse response = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param3", "こんにちは") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostBinaryUTF8() throws URISyntaxException { + HttpResponse response = Unirest.post(MockServer.POST) + .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) + .field("param3", "こんにちは") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + json.getFile("test").assertBody("This is a test file"); + } + + @Test + public void testPostRawBody() { + String sourceString = "'\"@こんにちは-test-123-" + Math.random(); + byte[] sentBytes = sourceString.getBytes(); + + HttpResponse response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); + + assertEquals(sourceString, response.getBody().getObject().getString("data")); + } + + @Test + public void testCustomUserAgent() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); + assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); + + GetRequest getRequest = Unirest.get("http"); + for (Object current : Arrays.asList(0, 1, 2)) { + getRequest.queryString("name", current); + } + + } + + @Test + public void testGetMultiple() throws JSONException, UnirestException { + for (int i = 1; i <= 20; i++) { + HttpResponse response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); + } + } + + @Test + public void testGetFields() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "mark").queryString("nick", "thefosk").asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("nick"), "thefosk"); + } + + @Test + public void testGetFields2() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("email", "hello@hello.com").asJson(); + assertEquals("hello@hello.com", response.getBody().getObject().getJSONObject("args").getString("email")); + } + + @Test + public void testQueryStringEncoding() throws JSONException, UnirestException { + String testKey = "email2=someKey&email"; + String testValue = "hello@hello.com"; + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); + assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); + } + + @Test + public void testDelete() throws JSONException, UnirestException { + HttpResponse response = Unirest.delete("http://httpbin.org/delete").asJson(); + assertEquals(200, response.getStatus()); + + response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); + assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testDeleteBody() throws JSONException, UnirestException { + String body = "{\"jsonString\":{\"members\":\"members1\"}}"; + HttpResponse response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); + assertEquals(200, response.getStatus()); + assertEquals(body, response.getBody().getObject().getString("data")); + } + + @Test + public void testBasicAuth() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); + assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); + } + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); + + assertNotNull(future); + HttpResponse jsonResponse = future.get(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + + @Test + public void testAsyncCallback() throws JSONException, InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("value1", json.getObject().getJSONObject("form").getString("param1")); + assertEquals("bye", json.getObject().getJSONObject("form").getString("param2")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipart() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartContentType() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:image/jpeg")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { + FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + MultipartBody request = Unirest.post(MockServer.HOST + "/post") + .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) + .field("name", "Mark") + .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); + + HttpResponse jsonResponse = request + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = TestUtils.read(jsonResponse, RequestCapture.class); + json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); + json.assertQuery("name", "Mark"); + assertEquals("application/octet-stream", json.getFile("image.jpg").type); + + +// assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); +// assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, URISyntaxException, FileNotFoundException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "image.jpg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGzip() throws JSONException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testGzipAsync() throws JSONException, InterruptedException, ExecutionException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJsonAsync().get(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testDefaultHeaders() throws JSONException { + Unirest.setDefaultHeader("X-Custom-Header", "hello"); + Unirest.setDefaultHeader("user-agent", "foobar"); + + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", json.getObject().getJSONObject("headers").getString("X-Custom-Header")); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("User-Agent")); + assertEquals("foobar", json.getObject().getJSONObject("headers").getString("User-Agent")); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", jsonResponse.getBody().getObject().getJSONObject("headers").getString("X-Custom-Header")); + + Unirest.clearDefaultHeaders(); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertFalse(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + } + + @Test + public void testSetTimeouts() throws IOException { + String address = "http://" + findAvailableIpAddress() + "/"; + long start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution + fail(); + } + } + Unirest.setTimeouts(2000, 10000); + start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution + fail(); + } + } + } + + @Test + public void testPathParameters() { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/{method}").routeParam("method", "get").queryString("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + } + + @Test + public void testQueryAndBodyParameters() { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/{method}").routeParam("method", "post").queryString("name", "Mark").field("wot", "wat").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("wot"), "wat"); + } + + @Test + public void testPathParameters2() { + HttpResponse jsonResponse = Unirest.patch("http://httpbin.org/{method}").routeParam("method", "patch").field("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals("OK", jsonResponse.getStatusText()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("name"), "Mark"); + } + + @Test + public void testMissingPathParameter() { + try { + Unirest.get("http://httpbin.org/{method}").routeParam("method222", "get").queryString("name", "Mark").asJson(); + fail(); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void parallelTest() throws InterruptedException { + Unirest.setConcurrency(10, 5); + + long start = System.currentTimeMillis(); + makeParallelRequests(); + long smallerConcurrencyTime = (System.currentTimeMillis() - start); + + Unirest.setConcurrency(200, 20); + start = System.currentTimeMillis(); + makeParallelRequests(); + long higherConcurrencyTime = (System.currentTimeMillis() - start); + + assertTrue(higherConcurrencyTime < smallerConcurrencyTime); + } + + private void makeParallelRequests() throws InterruptedException { + ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); + final AtomicInteger counter = new AtomicInteger(0); + for (int i = 0; i < 200; i++) { + newFixedThreadPool.execute(() -> { + try { + Unirest.get(MockServer.HOST + "/get").queryString("index", counter.incrementAndGet()).asString(); + } catch (UnirestException e) { + throw new RuntimeException(e); + } + }); + } + + newFixedThreadPool.shutdown(); + newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); + } + + @Test + public void testAsyncCustomContentType() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); + assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); + + assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGetQuerystringArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostMultipleFiles() throws JSONException, URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); + + JSONObject names = response.getBody().getObject().getJSONObject("files"); + assertEquals(2, names.length()); + + assertEquals("This is a test file", names.getString("file1")); + assertEquals("This is a test file", names.getString("file2")); + + assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testGetArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostCollection() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testCaseInsensitiveHeaders() { + GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); + assertEquals("Marco", headers.getString("Name")); + + request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("John", request.getHeaders().get("name").get(1)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("John", request.getHeaders().get("NAme").get(1)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + assertEquals("John", request.getHeaders().get("Name").get(1)); + } + + @Test + public void setTimeoutsAndCustomClient() { + try { + Unirest.setTimeouts(1000, 2000); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + + try { + Unirest.setHttpClient(HttpClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + } + + @Test + public void testObjectMapperRead() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse getResponseMock = new GetResponse(); + getResponseMock.setUrl("http://httpbin.org/get"); + + HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); + + assertEquals(200, getResponse.getStatus()); + assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); + } + + @Test + public void testObjectMapperWrite() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse postResponseMock = new GetResponse(); + postResponseMock.setUrl("http://httpbin.org/post"); + + HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); + + assertEquals(200, postResponse.getStatus()); + assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); + } + + @Test + public void testPostProvidesSortedParams() throws IOException { + // Verify that fields are encoded into the body in sorted order. + HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); + + InputStream content = httpRequest.getBody().getEntity().getContent(); + String body = IOUtils.toString(content, "UTF-8"); + assertEquals("x=X&y=Y&z=Z", body); + } + + @Test + public void testHeaderNamesCaseSensitive() { + // Verify that header names are the same as server (case sensitive) + final Headers headers = new Headers(); + headers.put("Content-Type", Arrays.asList("application/json")); + + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); + assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); + } + + + private String findAvailableIpAddress() throws IOException { + for (int i = 100; i <= 255; i++) { + String ip = "192.168.1." + i; + if (!InetAddress.getByName(ip).isReachable(1000)) { + return ip; + } + } + + throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `response.getBody()` could be null and is dereferenced at line 199. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testGetFields2() + +### Procedure Id: +io.github.openunirest.http.UnirestTest.testGetFields2():void.7a9915b67a2e6a918a6a060f0c278128 + +### File: +src/test/java/io/github/openunirest/http/UnirestTest.java + +### Key: +UnirestTest.java|testGetFields2|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +605a7966255146bcd7d0a488757eea08 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6659/instruction.md b/inferredbugs-6659/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70bc2e5a20daee9c1c855f864ca07d494ec11509 --- /dev/null +++ b/inferredbugs-6659/instruction.md @@ -0,0 +1,164 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright (c) 2013 Mashape (http://mashape.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package com.mashape.unirest.test.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import org.json.JSONException; +import org.junit.Test; + +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; + +public class UnirestTest { + + @Test + public void testRequests() throws JSONException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") + .header("accept", "application/json") + .field("param1", "value1") + .field("param2","bye") + .asJson(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getCode()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post("http://httpbin.org/post") + .header("accept", "application/json") + .field("param1", "value1") + .field("param2","bye") + .asJsonAsync(); + + assertNotNull(future); + HttpResponse jsonResponse = future.get(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getCode()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `jsonResponse.getHeaders()` could be null and is dereferenced at line 78. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testAsync() + +### Procedure Id: +com.mashape.unirest.test.http.UnirestTest.testAsync():void.a4fd18513bc7093c2ffa7a26010ffc4a + +### File: +src/test/java/com/mashape/unirest/test/http/UnirestTest.java + +### Key: +UnirestTest.java|testAsync|NULL_DEREFERENCE + +### Node Key: +18086a76ec6f499138a84f176568ec09 + +### Hash: +797fbb1db759f340b74d1e0a6e78043e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6660/instruction.md b/inferredbugs-6660/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cf5fcb164997e7f72ab58565b6be25c79b529f56 --- /dev/null +++ b/inferredbugs-6660/instruction.md @@ -0,0 +1,934 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright for portions of OpenUnirest/uniresr-java are held by Mashape (c) 2013 as part of Kong/unirest-java. +All other copyright for OpenUnirest/unirest-java are held by OpenUnirest (c) 2018. + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package io.github.openunirest.http; + +import io.github.openunirest.http.async.Callback; +import io.github.openunirest.http.options.Options; +import io.github.openunirest.request.body.MultipartBody; +import io.github.openunirest.http.exceptions.UnirestException; +import io.github.openunirest.request.GetRequest; +import io.github.openunirest.request.HttpRequest; + +import org.apache.commons.io.IOUtils; +import org.apache.http.entity.ContentType; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.*; + +import java.io.*; +import java.net.InetAddress; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.*; + +public class UnirestTest { + + private CountDownLatch lock; + private boolean status; + + @BeforeClass + public static void suiteSetUp(){ + MockServer.start(); + } + + @AfterClass + public static void suiteTearDown(){ + MockServer.shutdown(); + } + + @Before + public void setUp() { + MockServer.reset(); + lock = new CountDownLatch(1); + status = false; + } + + @Test + public void postFormReturnJson() throws JSONException, UnirestException { + HttpResponse jsonResponse = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param1", "value1") + .field("param2", "bye") + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = TestUtils.read(jsonResponse, RequestCapture.class); + json.assertHeader("Accept", "application/json"); + json.assertQuery("param1", "value1"); + json.assertQuery("param2", "bye"); + } + + @Test + public void canPassQueryParamsOnStringOrWithForm() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=mark") + .header("accept", "application/json") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "mark"); + + response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("name", "mark2") + .asJson(); + + json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "mark2"); + } + + @Test + public void multipleParams() throws JSONException, UnirestException { + HttpResponse response = Unirest.get(MockServer.GETJSON + "?name=ringo") + .header("accept", "application/json") + .queryString("name", "paul") + .queryString("name", "john") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("name", "ringo"); + json.assertQuery("name", "paul"); + json.assertQuery("name", "john"); + } + + @Test + public void testGetUTF8() { + HttpResponse response = Unirest.get(MockServer.GETJSON) + .header("accept", "application/json") + .queryString("param3", "こんにちは") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostUTF8() { + HttpResponse response = Unirest.post(MockServer.POST) + .header("accept", "application/json") + .field("param3", "こんにちは") + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + } + + @Test + public void testPostBinaryUTF8() throws URISyntaxException { + HttpResponse response = Unirest.post(MockServer.POST) + .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) + .field("param3", "こんにちは") + .field("file", new File(getClass().getResource("/test").toURI())) + .asJson(); + + RequestCapture json = TestUtils.read(response, RequestCapture.class); + json.assertQuery("param3", "こんにちは"); + json.getFile("test").assertBody("This is a test file"); + } + + @Test + public void testPostRawBody() { + String sourceString = "'\"@こんにちは-test-123-" + Math.random(); + byte[] sentBytes = sourceString.getBytes(); + + HttpResponse response = Unirest.post("http://httpbin.org/post").body(sentBytes).asJson(); + + assertEquals(sourceString, response.getBody().getObject().getString("data")); + } + + @Test + public void testCustomUserAgent() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); + assertEquals("hello-world", response.getBody().getObject().getJSONObject("headers").getString("User-Agent")); + + GetRequest getRequest = Unirest.get("http"); + for (Object current : Arrays.asList(0, 1, 2)) { + getRequest.queryString("name", current); + } + + } + + @Test + public void testGetMultiple() throws JSONException, UnirestException { + for (int i = 1; i <= 20; i++) { + HttpResponse response = Unirest.get("http://httpbin.org/get?try=" + i).asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("try"), ((Integer) i).toString()); + } + } + + @Test + public void testGetFields() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "mark").queryString("nick", "thefosk").asJson(); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("name"), "mark"); + assertEquals(response.getBody().getObject().getJSONObject("args").getString("nick"), "thefosk"); + } + + @Test + public void testGetFields2() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("email", "hello@hello.com").asJson(); + assertEquals("hello@hello.com", response.getBody().getObject().getJSONObject("args").getString("email")); + } + + @Test + public void testQueryStringEncoding() throws JSONException, UnirestException { + String testKey = "email2=someKey&email"; + String testValue = "hello@hello.com"; + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString(testKey, testValue).asJson(); + assertEquals(testValue, response.getBody().getObject().getJSONObject("args").getString(testKey)); + } + + @Test + public void testDelete() throws JSONException, UnirestException { + HttpResponse response = Unirest.delete("http://httpbin.org/delete").asJson(); + assertEquals(200, response.getStatus()); + + response = Unirest.delete("http://httpbin.org/delete").field("name", "mark").asJson(); + assertEquals("mark", response.getBody().getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testDeleteBody() throws JSONException, UnirestException { + String body = "{\"jsonString\":{\"members\":\"members1\"}}"; + HttpResponse response = Unirest.delete("http://httpbin.org/delete").body(body).asJson(); + assertEquals(200, response.getStatus()); + assertEquals(body, response.getBody().getObject().getString("data")); + } + + @Test + public void testBasicAuth() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/headers").basicAuth("user", "test").asJson(); + assertEquals("Basic dXNlcjp0ZXN0", response.getBody().getObject().getJSONObject("headers").getString("Authorization")); + } + + @Test + public void testAsync() throws JSONException, InterruptedException, ExecutionException { + Future> future = Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(); + + assertNotNull(future); + HttpResponse jsonResponse = future.get(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + + @Test + public void testAsyncCallback() throws JSONException, InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").field("param1", "value1").field("param2", "bye").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("value1", json.getObject().getJSONObject("form").getString("param1")); + assertEquals("bye", json.getObject().getJSONObject("form").getString("param2")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipart() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartContentType() throws JSONException, URISyntaxException, UnirestException { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/image.jpg").toURI()), "image/jpeg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:image/jpeg")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentType() throws JSONException, URISyntaxException, FileNotFoundException { + FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + MultipartBody request = Unirest.post(MockServer.HOST + "/post") + .header("accept", ContentType.MULTIPART_FORM_DATA.toString()) + .field("name", "Mark") + .field("file", stream, ContentType.APPLICATION_OCTET_STREAM, "image.jpg"); + + HttpResponse jsonResponse = request + .asJson(); + + assertEquals(200, jsonResponse.getStatus()); + + RequestCapture json = TestUtils.read(jsonResponse, RequestCapture.class); + json.assertHeader("Accept", ContentType.MULTIPART_FORM_DATA.toString()); + json.assertQuery("name", "Mark"); + assertEquals("application/octet-stream", json.getFile("image.jpg").type); + + +// assertTrue(json.getObject().getJSONObject("files").getString("type").contains("application/octet-stream")); +// assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartInputStreamContentTypeAsync() throws JSONException, InterruptedException, URISyntaxException, FileNotFoundException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new FileInputStream(new File(getClass().getResource("/test").toURI())), ContentType.APPLICATION_OCTET_STREAM, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartByteContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "image.jpg").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + assertNotNull(json.getObject().getJSONObject("files")); + + assertTrue(json.getObject().getJSONObject("files").getString("file").contains("data:application/octet-stream")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + } + + @Test + public void testMultipartByteContentTypeAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, IOException { + final InputStream stream = new FileInputStream(new File(getClass().getResource("/test").toURI())); + final byte[] bytes = new byte[stream.available()]; + stream.read(bytes); + stream.close(); + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", bytes, "test").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testMultipartAsync() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException { + Unirest.post("http://httpbin.org/post").field("name", "Mark").field("file", new File(getClass().getResource("/test").toURI())).asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse response) { + assertTrue(response.getHeaders().size() > 0); + assertTrue(response.getBody().toString().length() > 0); + assertFalse(response.getRawBody() == null); + assertEquals(200, response.getStatus()); + + JsonNode json = response.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + + assertEquals("This is a test file", json.getObject().getJSONObject("files").getString("file")); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGzip() throws JSONException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testGzipAsync() throws JSONException, InterruptedException, ExecutionException { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/gzip").asJsonAsync().get(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(json.getObject().getBoolean("gzipped")); + } + + @Test + public void testDefaultHeaders() throws JSONException { + Unirest.setDefaultHeader("X-Custom-Header", "hello"); + Unirest.setDefaultHeader("user-agent", "foobar"); + + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getStatus()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", json.getObject().getJSONObject("headers").getString("X-Custom-Header")); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("User-Agent")); + assertEquals("foobar", json.getObject().getJSONObject("headers").getString("User-Agent")); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertTrue(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + assertEquals("hello", jsonResponse.getBody().getObject().getJSONObject("headers").getString("X-Custom-Header")); + + Unirest.clearDefaultHeaders(); + + jsonResponse = Unirest.get("http://httpbin.org/headers").asJson(); + assertFalse(jsonResponse.getBody().getObject().getJSONObject("headers").has("X-Custom-Header")); + } + + @Test + public void testSetTimeouts() throws IOException { + String address = "http://" + findAvailableIpAddress() + "/"; + long start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > Options.CONNECTION_TIMEOUT + 100) { // Add 100ms for code execution + fail(); + } + } + Unirest.setTimeouts(2000, 10000); + start = System.currentTimeMillis(); + try { + Unirest.get("http://" + address + "/").asString(); + } catch (Exception e) { + if (System.currentTimeMillis() - start > 2100) { // Add 100ms for code execution + fail(); + } + } + } + + @Test + public void testPathParameters() { + HttpResponse jsonResponse = Unirest.get("http://httpbin.org/{method}").routeParam("method", "get").queryString("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + } + + @Test + public void testQueryAndBodyParameters() { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/{method}").routeParam("method", "post").queryString("name", "Mark").field("wot", "wat").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("args").getString("name"), "Mark"); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("wot"), "wat"); + } + + @Test + public void testPathParameters2() { + HttpResponse jsonResponse = Unirest.patch("http://httpbin.org/{method}").routeParam("method", "patch").field("name", "Mark").asJson(); + + assertEquals(200, jsonResponse.getStatus()); + assertEquals("OK", jsonResponse.getStatusText()); + assertEquals(jsonResponse.getBody().getObject().getJSONObject("form").getString("name"), "Mark"); + } + + @Test + public void testMissingPathParameter() { + try { + Unirest.get("http://httpbin.org/{method}").routeParam("method222", "get").queryString("name", "Mark").asJson(); + fail(); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void parallelTest() throws InterruptedException { + Unirest.setConcurrency(10, 5); + + long start = System.currentTimeMillis(); + makeParallelRequests(); + long smallerConcurrencyTime = (System.currentTimeMillis() - start); + + Unirest.setConcurrency(200, 20); + start = System.currentTimeMillis(); + makeParallelRequests(); + long higherConcurrencyTime = (System.currentTimeMillis() - start); + + assertTrue(higherConcurrencyTime < smallerConcurrencyTime); + } + + private void makeParallelRequests() throws InterruptedException { + ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(10); + final AtomicInteger counter = new AtomicInteger(0); + for (int i = 0; i < 200; i++) { + newFixedThreadPool.execute(() -> { + try { + Unirest.get(MockServer.HOST + "/get").queryString("index", counter.incrementAndGet()).asString(); + } catch (UnirestException e) { + throw new RuntimeException(e); + } + }); + } + + newFixedThreadPool.shutdown(); + newFixedThreadPool.awaitTermination(10, TimeUnit.MINUTES); + } + + @Test + public void testAsyncCustomContentType() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/json").body("{\"hello\":\"world\"}").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("{\"hello\":\"world\"}", json.getObject().getString("data")); + assertEquals("application/json", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testAsyncCustomContentTypeAndFormParams() throws InterruptedException { + Unirest.post("http://httpbin.org/post").header("accept", "application/json").header("Content-Type", "application/x-www-form-urlencoded").field("name", "Mark").field("hello", "world").asJsonAsync(new Callback() { + + public void failed(UnirestException e) { + fail(); + } + + public void completed(HttpResponse jsonResponse) { + JsonNode json = jsonResponse.getBody(); + assertEquals("Mark", json.getObject().getJSONObject("form").getString("name")); + assertEquals("world", json.getObject().getJSONObject("form").getString("hello")); + + assertEquals("application/x-www-form-urlencoded", json.getObject().getJSONObject("headers").getString("Content-Type")); + + status = true; + lock.countDown(); + } + + public void cancelled() { + fail(); + } + }); + + lock.await(10, TimeUnit.SECONDS); + assertTrue(status); + } + + @Test + public void testGetQuerystringArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", "Mark").queryString("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostMultipleFiles() throws JSONException, URISyntaxException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("param3", "wot").field("file1", new File(getClass().getResource("/test").toURI())).field("file2", new File(getClass().getResource("/test").toURI())).asJson(); + + JSONObject names = response.getBody().getObject().getJSONObject("files"); + assertEquals(2, names.length()); + + assertEquals("This is a test file", names.getString("file1")); + assertEquals("This is a test file", names.getString("file2")); + + assertEquals("wot", response.getBody().getObject().getJSONObject("form").getString("param3")); + } + + @Test + public void testGetArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.get("http://httpbin.org/get").queryString("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("args").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostArray() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", "Mark").field("name", "Tom").asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testPostCollection() throws JSONException, UnirestException { + HttpResponse response = Unirest.post("http://httpbin.org/post").field("name", Arrays.asList("Mark", "Tom")).asJson(); + + JSONArray names = response.getBody().getObject().getJSONObject("form").getJSONArray("name"); + assertEquals(2, names.length()); + + assertEquals("Mark", names.getString(0)); + assertEquals("Tom", names.getString(1)); + } + + @Test + public void testCaseInsensitiveHeaders() { + GetRequest request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + JSONObject headers = request.asJson().getBody().getObject().getJSONObject("headers"); + assertEquals("Marco", headers.getString("Name")); + + request = Unirest.get("http://httpbin.org/headers").header("Name", "Marco").header("Name", "John"); + assertEquals(1, request.getHeaders().size()); + assertEquals("Marco", request.getHeaders().get("name").get(0)); + assertEquals("John", request.getHeaders().get("name").get(1)); + assertEquals("Marco", request.getHeaders().get("NAme").get(0)); + assertEquals("John", request.getHeaders().get("NAme").get(1)); + assertEquals("Marco", request.getHeaders().get("Name").get(0)); + assertEquals("John", request.getHeaders().get("Name").get(1)); + } + + @Test + public void setTimeoutsAndCustomClient() { + try { + Unirest.setTimeouts(1000, 2000); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + } catch (Exception e) { + fail(); + } + + try { + Unirest.setAsyncHttpClient(HttpAsyncClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + + try { + Unirest.setHttpClient(HttpClientBuilder.create().build()); + Unirest.setTimeouts(1000, 2000); + fail(); + } catch (Exception e) { + // Ok + } + } + + @Test + public void testObjectMapperRead() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse getResponseMock = new GetResponse(); + getResponseMock.setUrl("http://httpbin.org/get"); + + HttpResponse getResponse = Unirest.get(getResponseMock.getUrl()).asObject(GetResponse.class); + + assertEquals(200, getResponse.getStatus()); + assertEquals(getResponse.getBody().getUrl(), getResponseMock.getUrl()); + } + + @Test + public void testObjectMapperWrite() { + Unirest.setObjectMapper(new JacksonObjectMapper()); + + GetResponse postResponseMock = new GetResponse(); + postResponseMock.setUrl("http://httpbin.org/post"); + + HttpResponse postResponse = Unirest.post(postResponseMock.getUrl()).header("accept", "application/json").header("Content-Type", "application/json").body(postResponseMock).asJson(); + + assertEquals(200, postResponse.getStatus()); + assertEquals(postResponse.getBody().getObject().getString("data"), "{\"url\":\"http://httpbin.org/post\"}"); + } + + @Test + public void testPostProvidesSortedParams() throws IOException { + // Verify that fields are encoded into the body in sorted order. + HttpRequest httpRequest = Unirest.post("test").field("z", "Z").field("y", "Y").field("x", "X").getHttpRequest(); + + InputStream content = httpRequest.getBody().getEntity().getContent(); + String body = IOUtils.toString(content, "UTF-8"); + assertEquals("x=X&y=Y&z=Z", body); + } + + @Test + public void testHeaderNamesCaseSensitive() { + // Verify that header names are the same as server (case sensitive) + final Headers headers = new Headers(); + headers.put("Content-Type", Arrays.asList("application/json")); + + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("cOnTeNt-TyPe")); + assertEquals("Only header \"Content-Type\" should exist", null, headers.getFirst("content-type")); + assertEquals("Only header \"Content-Type\" should exist", "application/json", headers.getFirst("Content-Type")); + } + + + private String findAvailableIpAddress() throws IOException { + for (int i = 100; i <= 255; i++) { + String ip = "192.168.1." + i; + if (!InetAddress.getByName(ip).isReachable(1000)) { + return ip; + } + } + + throw new RuntimeException("Couldn't find an available IP address in the range of 192.168.0.100-255"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `response.getBody()` could be null and is dereferenced at line 172. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testCustomUserAgent() + +### Procedure Id: +io.github.openunirest.http.UnirestTest.testCustomUserAgent():void.0f7d07fb96afc740f67e7daad0f46533 + +### File: +src/test/java/io/github/openunirest/http/UnirestTest.java + +### Key: +UnirestTest.java|testCustomUserAgent|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +72a6136f7ff67b8d0daf3a300586089b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6661/instruction.md b/inferredbugs-6661/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51efeccbf4741cebb42d3cf0519308c0f4422207 --- /dev/null +++ b/inferredbugs-6661/instruction.md @@ -0,0 +1,136 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** unirest-java +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +The MIT License + +Copyright (c) 2013 Mashape (http://mashape.com) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +package com.mashape.unirest.test.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; + +public class UnirestTest { + + @Test + public void testRequests() throws Exception { + HttpResponse jsonResponse = Unirest.post("http://httpbin.org/post") + .header("accept", "application/json") + .field("param1", "value1") + .field("param2","bye") + .asJson(); + + assertTrue(jsonResponse.getHeaders().size() > 0); + assertTrue(jsonResponse.getBody().toString().length() > 0); + assertFalse(jsonResponse.getRawBody() == null); + assertEquals(200, jsonResponse.getCode()); + + JsonNode json = jsonResponse.getBody(); + assertFalse(json.isArray()); + assertNotNull(json.getObject()); + assertNotNull(json.getArray()); + assertEquals(1, json.getArray().length()); + assertNotNull(json.getArray().get(0)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `jsonResponse.getBody().toString()` could be null and is dereferenced at line 50. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UnirestTest.testRequests() + +### Procedure Id: +com.mashape.unirest.test.http.UnirestTest.testRequests():void.1d7ba79a911f0042671a96828feb0d01 + +### File: +src/test/java/com/mashape/unirest/test/http/UnirestTest.java + +### Key: +UnirestTest.java|testRequests|NULL_DEREFERENCE + +### Node Key: +81212f82040a551aee038b8efb433836 + +### Hash: +0b954727481090c2397c5553ea5bd218 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6667/instruction.md b/inferredbugs-6667/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f1e0e98f7096bd749f6025df9612f861894c4968 --- /dev/null +++ b/inferredbugs-6667/instruction.md @@ -0,0 +1,424 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +Copyright 2017 The Kubernetes Authors. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + */ +package io.kubernetes.client.util; + +import static io.kubernetes.client.util.Config.ENV_KUBECONFIG; +import static io.kubernetes.client.util.Config.ENV_SERVICE_HOST; +import static io.kubernetes.client.util.Config.ENV_SERVICE_PORT; +import static io.kubernetes.client.util.Config.SERVICEACCOUNT_CA_PATH; +import static io.kubernetes.client.util.Config.SERVICEACCOUNT_TOKEN_PATH; +import static io.kubernetes.client.util.KubeConfig.ENV_HOME; +import static io.kubernetes.client.util.KubeConfig.KUBECONFIG; +import static io.kubernetes.client.util.KubeConfig.KUBEDIR; + +import com.google.common.base.Strings; +import com.squareup.okhttp.*; +import io.kubernetes.client.ApiClient; +import io.kubernetes.client.util.credentials.AccessTokenAuthentication; +import io.kubernetes.client.util.credentials.Authentication; +import io.kubernetes.client.util.credentials.KubeconfigAuthentication; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** A Builder which allows the construction of {@link ApiClient}s in a fluent fashion. */ +public class ClientBuilder { + private static final Logger log = LoggerFactory.getLogger(ClientBuilder.class); + + private String basePath = Config.DEFAULT_FALLBACK_HOST; + private byte[] caCertBytes = null; + private boolean verifyingSsl = true; + private String overridePatchFormat; + private Authentication authentication; + + /** + * Creates an {@link ApiClient} by calling {@link #standard()} and {@link #build()}. + * + * @return An ApiClient configured using the precedence specified for {@link + * #standard()}. + * @throws IOException if the configuration file or a file specified in a configuration file + * cannot be read. + */ + public static ApiClient defaultClient() throws IOException { + return ClientBuilder.standard().build(); + } + + /** + * Creates a builder which is pre-configured in the following way + * + *
    + *
  • If $KUBECONFIG is defined, use that config file. + *
  • If $HOME/.kube/config can be found, use that. + *
  • If the in-cluster service account can be found, assume in cluster config. + *
  • Default to localhost:8080 as a last resort. + *
+ * + * @return ClientBuilder pre-configured using the above precedence + * @throws IOException if the configuration file or a file specified in a configuration file + * cannot be read. + */ + public static ClientBuilder standard() throws IOException { + return standard(true); + } + + public static ClientBuilder standard(boolean persistConfig) throws IOException { + final File kubeConfig = findConfigFromEnv(); + if (kubeConfig != null) { + try (BufferedReader kubeConfigReader = + new BufferedReader( + new InputStreamReader( + new FileInputStream(kubeConfig), StandardCharsets.UTF_8.name()))) { + KubeConfig kc = KubeConfig.loadKubeConfig(kubeConfigReader); + if (persistConfig) { + kc.setPersistConfig(new FilePersister(kubeConfig)); + } + kc.setFile(kubeConfig); + return kubeconfig(kc); + } + } + final File config = findConfigInHomeDir(); + if (config != null) { + try (BufferedReader configReader = + new BufferedReader( + new InputStreamReader(new FileInputStream(config), StandardCharsets.UTF_8.name()))) { + KubeConfig kc = KubeConfig.loadKubeConfig(configReader); + if (persistConfig) { + kc.setPersistConfig(new FilePersister(config)); + } + kc.setFile(config); + return kubeconfig(kc); + } + } + final File clusterCa = new File(SERVICEACCOUNT_CA_PATH); + if (clusterCa.exists()) { + return cluster(); + } + return new ClientBuilder(); + } + + private static File findConfigFromEnv() { + final KubeConfigEnvParser kubeConfigEnvParser = new KubeConfigEnvParser(); + + final String kubeConfigPath = + kubeConfigEnvParser.parseKubeConfigPath(System.getenv(ENV_KUBECONFIG)); + if (kubeConfigPath == null) { + return null; + } + + final File kubeConfig = new File(kubeConfigPath); + if (kubeConfig.exists()) { + return kubeConfig; + } else { + log.debug("Could not find file specified in $KUBECONFIG"); + return null; + } + } + + private static class KubeConfigEnvParser { + private String parseKubeConfigPath(String kubeConfigEnv) { + if (kubeConfigEnv == null) { + return null; + } + + final String[] filePaths = kubeConfigEnv.split(File.pathSeparator); + final String kubeConfigPath = filePaths[0]; + if (filePaths.length > 1) { + log.warn( + "Found multiple kubeconfigs files, $KUBECONFIG: " + kubeConfigEnv + " using first: {}", + kubeConfigPath); + } + + return kubeConfigPath; + } + } + + private static File findHomeDir() { + final String envHome = System.getenv(ENV_HOME); + if (envHome != null && envHome.length() > 0) { + final File config = new File(envHome); + if (config.exists()) { + return config; + } + } + if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { + String homeDrive = System.getenv("HOMEDRIVE"); + String homePath = System.getenv("HOMEPATH"); + if (homeDrive != null + && homeDrive.length() > 0 + && homePath != null + && homePath.length() > 0) { + File homeDir = new File(new File(homeDrive), homePath); + if (homeDir.exists()) { + return homeDir; + } + } + String userProfile = System.getenv("USERPROFILE"); + if (userProfile != null && userProfile.length() > 0) { + File profileDir = new File(userProfile); + if (profileDir.exists()) { + return profileDir; + } + } + } + return null; + } + + private static File findConfigInHomeDir() { + final File homeDir = findHomeDir(); + if (homeDir != null) { + final File config = new File(new File(homeDir, KUBEDIR), KUBECONFIG); + if (config.exists()) { + return config; + } + } + log.debug("Could not find ~/.kube/config"); + return null; + } + + /** + * Creates a builder which is pre-configured from the cluster configuration. + * + * @return ClientBuilder configured from the cluster configuration. + * @throws IOException if the Service Account Token Path or CA Path is not readable. + */ + public static ClientBuilder cluster() throws IOException { + final ClientBuilder builder = new ClientBuilder(); + + final String host = System.getenv(ENV_SERVICE_HOST); + final String port = System.getenv(ENV_SERVICE_PORT); + builder.setBasePath("https://" + host + ":" + port); + + final String token = + new String( + Files.readAllBytes(Paths.get(SERVICEACCOUNT_TOKEN_PATH)), Charset.defaultCharset()); + builder.setCertificateAuthority(Files.readAllBytes(Paths.get(SERVICEACCOUNT_CA_PATH))); + builder.setAuthentication(new AccessTokenAuthentication(token)); + + return builder; + } + + /** + * Creates a builder which is pre-configured from a {@link KubeConfig}. + * + *

To load a KubeConfig, see {@link KubeConfig#loadKubeConfig(Reader)}. + * + * @param config The {@link KubeConfig} to configure the builder from. + * @return ClientBuilder configured from the provided KubeConfig + * @throws IOException if the files specified in the provided KubeConfig are not readable + */ + public static ClientBuilder kubeconfig(KubeConfig config) throws IOException { + final ClientBuilder builder = new ClientBuilder(); + + String server = config.getServer(); + if (!server.contains("://")) { + if (server.contains(":443")) { + server = "https://" + server; + } else { + server = "http://" + server; + } + } + + final byte[] caBytes = + KubeConfig.getDataOrFile( + config.getCertificateAuthorityData(), config.getCertificateAuthorityFile()); + if (caBytes != null) { + builder.setCertificateAuthority(caBytes); + } + builder.setVerifyingSsl(config.verifySSL()); + + builder.setBasePath(server); + builder.setAuthentication(new KubeconfigAuthentication(config)); + return builder; + } + + public String getBasePath() { + return basePath; + } + + public ClientBuilder setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public Authentication getAuthentication() { + return authentication; + } + + public ClientBuilder setAuthentication(final Authentication authentication) { + this.authentication = authentication; + return this; + } + + public ClientBuilder setCertificateAuthority(final byte[] caCertBytes) { + this.caCertBytes = caCertBytes; + return this; + } + + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + public ClientBuilder setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + return this; + } + + public String overridePatchFormat() { + return overridePatchFormat; + } + + public ClientBuilder setOverridePatchFormat(String patchFormat) { + this.overridePatchFormat = patchFormat; + return this; + } + + public ApiClient build() { + final ApiClient client = new ApiClient(); + + if (basePath != null) { + if (basePath.endsWith("/")) { + basePath = basePath.substring(0, basePath.length() - 1); + } + client.setBasePath(basePath); + } + + client.setVerifyingSsl(verifyingSsl); + + if (authentication != null) { + authentication.provide(client); + } + + // NOTE: this ordering is important. The API Client re-evaluates the CA certificate every + // time the SSL info changes, which means that if this comes after the following call + // you will try to load a certificate with an exhausted InputStream. So setting the CA + // certificate _has_ to be the last thing that you do related to SSL. + // + // TODO: this (imho) is broken in the generate Java Swagger Client code. We should fix it + // upstream and remove this dependency. + // + // TODO: Add a test to ensure that this works correctly... + if (caCertBytes != null) { + client.setSslCaCert(new ByteArrayInputStream(caCertBytes)); + } + + if (!Strings.isNullOrEmpty(overridePatchFormat)) { + client + .getHttpClient() + .interceptors() + .add( + new Interceptor() { + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + if ("PATCH".equals(request.method())) { + + Request newRequest = + request + .newBuilder() + .patch( + new ProxyContentTypeRequestBody( + request.body(), overridePatchFormat)) + .build(); + return chain.proceed(newRequest); + } + return chain.proceed(request); + } + }); + } + return client; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 100 is not released after line 102. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ClientBuilder ClientBuilder.standard(boolean) + +### Procedure Id: +io.kubernetes.client.util.ClientBuilder.standard(boolean):io.kubernetes.client.util.ClientBuilder.b3673515cb8006dbbe1ebaa4be57a6c8 + +### File: +util/src/main/java/io/kubernetes/client/util/ClientBuilder.java + +### Key: +ClientBuilder.java|standard|RESOURCE_LEAK + +### Node Key: +1f1b2173a97ffabeb5165088501bfc2f + +### Hash: +7d7b6c90e5b7cdfb70226fdad3d2b7df + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6668/instruction.md b/inferredbugs-6668/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4acbd0b46f6b0062e94dd5d79ed258af0def7162 --- /dev/null +++ b/inferredbugs-6668/instruction.md @@ -0,0 +1,456 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +Copyright 2017, 2018 The Kubernetes Authors. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package io.kubernetes.client; + +import static io.kubernetes.client.KubernetesConstants.*; + +import com.google.common.io.CharStreams; +import com.google.gson.reflect.TypeToken; +import io.kubernetes.client.openapi.ApiClient; +import io.kubernetes.client.openapi.ApiException; +import io.kubernetes.client.openapi.Configuration; +import io.kubernetes.client.openapi.apis.CoreV1Api; +import io.kubernetes.client.openapi.models.V1Pod; +import io.kubernetes.client.openapi.models.V1Status; +import io.kubernetes.client.openapi.models.V1StatusCause; +import io.kubernetes.client.openapi.models.V1StatusDetails; +import io.kubernetes.client.util.WebSocketStreamHandler; +import io.kubernetes.client.util.WebSockets; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URLEncoder; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Exec { + private static final Logger log = LoggerFactory.getLogger(Exec.class); + + private ApiClient apiClient; + + /** Simple Exec API constructor, uses default configuration */ + public Exec() { + this(Configuration.getDefaultApiClient()); + } + + /** + * Exec API Constructor + * + * @param apiClient The api client to use. + */ + public Exec(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Get the API client for these exec operations. + * + * @return The API client that will be used. + */ + public ApiClient getApiClient() { + return apiClient; + } + + /** + * Set the API client for subsequent exec operations. + * + * @param apiClient The new API client to use. + */ + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + private String makePath( + String namespace, + String name, + String[] command, + String container, + boolean stdin, + boolean tty) { + for (int i = 0; i < command.length; i++) { + try { + command[i] = URLEncoder.encode(command[i], "UTF-8"); + } catch (UnsupportedEncodingException ex) { + throw new RuntimeException("some thing wrong happend: " + ex.getMessage()); + } + } + String path = + "/api/v1/namespaces/" + + namespace + + "/pods/" + + name + + "/exec?" + + "stdin=" + + stdin + + "&stdout=true" + + "&stderr=true" + + "&tty=" + + tty + + (container != null ? "&container=" + container : "") + + "&command=" + + StringUtils.join(command, "&command="); + return path; + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param namespace The namespace of the Pod + * @param name The name of the Pod + * @param command The command to run + * @param stdin If true, pass a stdin stream into the container + */ + public Process exec(String namespace, String name, String[] command, boolean stdin) + throws ApiException, IOException { + return exec(namespace, name, command, null, stdin, false); + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param pod The pod where the command is run. + * @param command The command to run + * @param stdin If true, pass a stdin stream into the container + */ + public Process exec(V1Pod pod, String[] command, boolean stdin) throws ApiException, IOException { + return exec(pod, command, pod.getSpec().getContainers().get(0).getName(), stdin, false); + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param namespace The namespace of the Pod + * @param name The name of the Pod + * @param command The command to run + * @param stdin If true, pass a stdin stream into the container + * @param tty If true, stdin is a tty. + */ + public Process exec(String namespace, String name, String[] command, boolean stdin, boolean tty) + throws ApiException, IOException { + return exec(namespace, name, command, null, stdin, tty); + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param pod The pod where the command is run. + * @param command The command to run + * @param stdin If true, pass a stdin stream into the container + * @param tty If true, stdin is a tty. + */ + public Process exec(V1Pod pod, String[] command, boolean stdin, boolean tty) + throws ApiException, IOException { + return exec(pod, command, pod.getSpec().getContainers().get(0).getName(), stdin, tty); + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param pod The pod where the command is run. + * @param command The command to run + * @param container The container in the Pod where the command is run. + * @param stdin If true, pass a stdin stream into the container. + * @param tty If true, stdin is a TTY (only applies if stdin is true) + */ + public Process exec(V1Pod pod, String[] command, String container, boolean stdin, boolean tty) + throws ApiException, IOException { + if (container == null) { + container = pod.getSpec().getContainers().get(0).getName(); + } + return exec( + pod.getMetadata().getNamespace(), + pod.getMetadata().getName(), + command, + container, + stdin, + tty); + } + + /** + * Execute a command in a container. If there are multiple containers in the pod, uses the first + * container in the Pod. + * + * @param namespace The namespace of the Pod + * @param name The name of the Pod + * @param command The command to run + * @param container The container in the Pod where the command is run. + * @param stdin If true, pass a stdin stream into the container. + * @param tty If true, stdin is a TTY (only applies if stdin is true) + */ + public Process exec( + String namespace, String name, String[] command, String container, boolean stdin, boolean tty) + throws ApiException, IOException { + if (container == null) { + CoreV1Api api = new CoreV1Api(apiClient); + V1Pod pod = api.readNamespacedPod(name, namespace, "false", null, null); + container = pod.getSpec().getContainers().get(0).getName(); + } + String path = makePath(namespace, name, command, container, stdin, tty); + + ExecProcess exec = new ExecProcess(apiClient); + WebSocketStreamHandler handler = exec.getHandler(); + WebSockets.stream(path, "GET", apiClient, handler); + + return exec; + } + + static int parseExitCode(ApiClient client, InputStream inputStream) { + try { + Type returnType = new TypeToken() {}.getType(); + String body; + try (final Reader reader = new InputStreamReader(inputStream)) { + body = CharStreams.toString(reader); + } + + V1Status status = client.getJSON().deserialize(body, returnType); + if (status == null) { + return -1; + } + if (V1STATUS_SUCCESS.equals(status.getStatus())) return 0; + + if (V1STATUS_REASON_NONZEROEXITCODE.equals(status.getReason())) { + V1StatusDetails details = status.getDetails(); + if (details != null) { + List causes = details.getCauses(); + if (causes != null) { + for (V1StatusCause cause : causes) { + if (V1STATUS_CAUSE_REASON_EXITCODE.equals(cause.getReason())) { + try { + return Integer.parseInt(cause.getMessage()); + } catch (NumberFormatException nfe) { + log.error("Error parsing exit code from status channel response", nfe); + } + } + } + } + } + } + } catch (Throwable t) { + log.error("Error parsing exit code from status channel response", t); + } + + // Unable to parse the exit code from the content + return -1; + } + + protected static class ExecProcess extends Process { + private final WebSocketStreamHandler streamHandler; + private int statusCode = -1; + private boolean isAlive = true; + private final Map input = new HashMap<>(); + + public ExecProcess(final ApiClient apiClient) throws IOException { + this.streamHandler = + new WebSocketStreamHandler() { + @Override + protected void handleMessage(int stream, InputStream inStream) throws IOException { + if (stream == 3) { + int exitCode = parseExitCode(apiClient, inStream); + if (exitCode >= 0) { + // notify of process completion + synchronized (ExecProcess.this) { + statusCode = exitCode; + isAlive = false; + ExecProcess.this.notifyAll(); + } + } + inStream.close(); + } else super.handleMessage(stream, inStream); + } + + @Override + public void failure(Throwable ex) { + super.failure(ex); + // TODO, it's possible we should suppress this error message, but currently there's + // no good place to surface the message, and without it, this will be really hard to + // debug. + ex.printStackTrace(); + synchronized (ExecProcess.this) { + // Try for a pretty unique error code, so if someone searches they'll find this + // code. + statusCode = -1975219; + isAlive = false; + ExecProcess.this.notifyAll(); + } + } + + @Override + public void close() { + // notify of process completion + synchronized (ExecProcess.this) { + if (isAlive) { + isAlive = false; + ExecProcess.this.notifyAll(); + } + } + + super.close(); + } + }; + } + + // Protected to facilitate unit testing. + protected WebSocketStreamHandler getHandler() { + return streamHandler; + } + + @Override + public OutputStream getOutputStream() { + return streamHandler.getOutputStream(0); + } + + @Override + public InputStream getInputStream() { + return getInputStream(1); + } + + @Override + public InputStream getErrorStream() { + return getInputStream(2); + } + + private synchronized InputStream getInputStream(int stream) { + if (!input.containsKey(stream)) { + input.put(stream, streamHandler.getInputStream(stream)); + } + return input.get(stream); + } + + @Override + public int waitFor() throws InterruptedException { + synchronized (this) { + this.wait(); + return statusCode; + } + } + + @Override + public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException { + synchronized (this) { + this.wait(TimeUnit.MILLISECONDS.convert(timeout, unit)); + return !isAlive(); + } + } + + @Override + public synchronized int exitValue() { + if (isAlive) throw new IllegalThreadStateException(); + return statusCode; + } + + @Override + public synchronized boolean isAlive() { + return isAlive; + } + + @Override + public void destroy() { + streamHandler.close(); + for (InputStream in : input.values()) { + try { + in.close(); + } catch (IOException ex) { + log.error("Error on close", ex); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `pod.getSpec()` at line 210. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Process Exec.exec(String,String,java.lang.String[],String,boolean,boolean) + +### Procedure Id: +io.kubernetes.client.Exec.exec(java.lang.String,java.lang.String,java.lang.String[],java.lang.String.fb7fe3774ec723a14eb143243b59062b + +### File: +util/src/main/java/io/kubernetes/client/Exec.java + +### Key: +Exec.java|exec|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +a5828bddbe1683d9bb22bbd4854b1555 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6669/instruction.md b/inferredbugs-6669/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27afbcbbd1626a131924d5e4cd87b93b8f8a0093 --- /dev/null +++ b/inferredbugs-6669/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +Copyright 2017 The Kubernetes Authors. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ +package io.kubernetes.client.util; + +import io.kubernetes.client.ApiClient; +import io.kubernetes.client.util.credentials.AccessTokenAuthentication; +import io.kubernetes.client.util.credentials.UsernamePasswordAuthentication; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class Config { + private static final Logger log = LoggerFactory.getLogger(Config.class); + + public static final String SERVICEACCOUNT_ROOT = "/var/run/secrets/kubernetes.io/serviceaccount"; + public static final String SERVICEACCOUNT_CA_PATH = SERVICEACCOUNT_ROOT + "/ca.crt"; + public static final String SERVICEACCOUNT_TOKEN_PATH = SERVICEACCOUNT_ROOT + "/token"; + public static final String ENV_KUBECONFIG = "KUBECONFIG"; + public static final String ENV_SERVICE_HOST = "KUBERNETES_SERVICE_HOST"; + public static final String ENV_SERVICE_PORT = "KUBERNETES_SERVICE_PORT"; + // The last resort host to try + public static final String DEFAULT_FALLBACK_HOST = "http://localhost:8080"; + + public static ApiClient fromCluster() throws IOException { + return ClientBuilder.cluster().build(); + } + + public static ApiClient fromUrl(String url) { + return fromUrl(url, true); + } + + public static ApiClient fromUrl(String url, boolean validateSSL) { + return new ApiClient().setBasePath(url).setVerifyingSsl(validateSSL); + } + + public static ApiClient fromUserPassword(String url, String user, String password) { + return fromUserPassword(url, user, password, true); + } + + public static ApiClient fromUserPassword( + String url, String user, String password, boolean validateSSL) { + return new ClientBuilder() + .setBasePath(url) + .setAuthentication(new UsernamePasswordAuthentication(user, password)) + .setVerifyingSsl(validateSSL) + .build(); + } + + public static ApiClient fromToken(String url, String token) { + return fromToken(url, token, true); + } + + public static ApiClient fromToken(String url, String token, boolean validateSSL) { + return new ClientBuilder() + .setBasePath(url) + .setAuthentication(new AccessTokenAuthentication(token)) + .setVerifyingSsl(validateSSL) + .build(); + } + + public static ApiClient fromConfig(String fileName) throws IOException { + return fromConfig(new FileReader(fileName)); + } + + public static ApiClient fromConfig(InputStream stream) throws IOException { + return fromConfig(new InputStreamReader(stream)); + } + + public static ApiClient fromConfig(Reader input) throws IOException { + return fromConfig(KubeConfig.loadKubeConfig(input)); + } + + public static ApiClient fromConfig(KubeConfig config) throws IOException { + return ClientBuilder.kubeconfig(config).build(); + } + + /** + * Easy client creation, follows this plan + * + *

    + *
  • If $KUBECONFIG is defined, use that config file. + *
  • If $HOME/.kube/config can be found, use that. + *
  • If the in-cluster service account can be found, assume in cluster config. + *
  • Default to localhost:8080 as a last resort. + *
+ * + * @return The best APIClient given the previously described rules + */ + public static ApiClient defaultClient() throws IOException { + return ClientBuilder.standard().build(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileReader` acquired by call to `new()` at line 76 is not released after line 76. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ApiClient Config.fromConfig(String) + +### Procedure Id: +io.kubernetes.client.util.Config.fromConfig(java.lang.String):io.kubernetes.client.ApiClient.64363b46bc73c95e3728fb3f3d39ed21 + +### File: +util/src/main/java/io/kubernetes/client/util/Config.java + +### Key: +Config.java|fromConfig|RESOURCE_LEAK + +### Node Key: +f09f436fb0f5a58e4eb6c6bcc0fb6b8e + +### Hash: +2769f1977a0d059c627dca769cb950ec + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6692/instruction.md b/inferredbugs-6692/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..334f8fe4df690d07e048c9d81abf614f70ed5f5a --- /dev/null +++ b/inferredbugs-6692/instruction.md @@ -0,0 +1,209 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mina-sshd +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.sshd.agent; + +import org.apache.tomcat.jni.Library; +import org.apache.tomcat.jni.Pool; + +import java.io.File; +import java.io.IOException; + + +/** + * Internal singleton used for initializing correctly the APR native library + * and the associated root memory pool. + * + * It'll finalize nicely the native resources (libraries and memory pools). + * + * Each memory pool used in the APR transport module needs to be children of the + * root pool {@link AprLibrary#getRootPool()}. + * + * @author Apache MINA Project + */ +class AprLibrary { + + // is APR library was initialized (load of native libraries) + private static AprLibrary library = null; + + /** + * get the shared instance of APR library, if none, initialize one + * @return the current APR library singleton + */ + static synchronized AprLibrary getInstance() { + if (!isInitialized()) + initialize(); + return library; + } + + /** + * initialize the APR Library by loading the associated native libraries + * and creating the associated singleton + */ + private static synchronized void initialize() { + if (library == null) + library = new AprLibrary(); + } + + /** + * is the APR library was initialized. + * @return true if the Library is initialized, false otherwise + */ + static synchronized boolean isInitialized() { + return library != null; + } + + // APR memory pool (package wide mother pool) + private final long pool; + + /** + * APR library singleton constructor. Called only when accessing the + * singleton the first time. + * It's initializing an APR memory pool for the whole package (a.k.a mother or root pool). + */ + private AprLibrary() { + try { + Library.initialize(null); + } catch (Exception e) { + throw new RuntimeException( + "Error loading Apache Portable Runtime (APR).", e); + } + pool = Pool.create(0); + } + + @Override + protected void finalize() throws Throwable { + library = null; + Pool.destroy(pool); + Library.terminate(); + super.finalize(); + } + + /** + * get the package wide root pool, the mother of all the pool created + * in APR transport module. + * @return number identifying the root pool + */ + long getRootPool() { + return pool; + } + + static String createLocalSocketAddress() throws IOException { + String name; + String os = System.getProperty("os.name").toLowerCase(); + if (os.indexOf("windows") < 0) { + File socket = File.createTempFile("mina", "apr"); + socket.delete(); + name = socket.getAbsolutePath(); + } else { + File socket = File.createTempFile("mina", "apr"); + socket.delete(); + name = "\\\\.\\pipe\\" + socket.getName(); + } + return name; + } + + static void secureLocalSocket(String authSocket, long handle) throws IOException { + String os = System.getProperty("os.name").toLowerCase(); + if (os.indexOf("windows") < 0) { + File file = new File(authSocket); + if (!file.setReadable(false, false) || !file.setReadable(true, true) + || !file.setExecutable(false, false) || !file.setExecutable(true, true)) { + throw new IOException("Unable to secure local socket"); + } + + } else { + // should be ok on windows + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 109. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String AprLibrary.createLocalSocketAddress() + +### Procedure Id: +org.apache.sshd.agent.AprLibrary.createLocalSocketAddress():java.lang.String.962ff4d84f8f052ee19fa13ca045579e + +### File: +sshd-core/src/main/java/org/apache/sshd/agent/AprLibrary.java + +### Key: +AprLibrary.java|createLocalSocketAddress|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +fe14c9b7604d0dfe3d3ee958fc018e2f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6693/instruction.md b/inferredbugs-6693/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6b3e222a33ce6979a06c164a024dca302ab05301 --- /dev/null +++ b/inferredbugs-6693/instruction.md @@ -0,0 +1,412 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mina-sshd +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sshd.server.command; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Arrays; + +import org.apache.sshd.server.CommandFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This commands provide SCP support on both server and client side. + * Permissions and preservation of access / modification times on files + * are not supported. + * + * @author Apache MINA SSHD Project + */ +public class ScpCommand implements CommandFactory.Command, Runnable { + + private static final Logger log = LoggerFactory.getLogger(ScpCommand.class); + + private boolean optR; + private boolean optT; + private boolean optF; + private boolean optV; + private boolean optP; + private File root; + private InputStream in; + private OutputStream out; + private OutputStream err; + private CommandFactory.ExitCallback callback; + private IOException error; + + public ScpCommand(String[] args) { + if (log.isDebugEnabled()) { + log.debug("Executing command {}", Arrays.asList(args)); + } + root = new File("."); + for (int i = 1; i < args.length; i++) { + if (args[i].charAt(0) == '-') { + for (int j = 1; j < args[i].length(); j++) { + switch (args[i].charAt(j)) { + case 'f': + optF = true; + break; + case 'p': + optP = true; + break; + case 'r': + optR = true; + break; + case 't': + optT = true; + break; + case 'v': + optV = true; + break; +// default: +// error = new IOException("Unsupported option: " + args[i].charAt(j)); +// return; + } + } + } else if (i == args.length - 1) { + root = new File(args[args.length - 1]); + } + if (!optF && !optT) { + error = new IOException("Either -f or -t option should be set"); + } + } + } + + public void setInputStream(InputStream in) { + this.in = in; + } + + public void setOutputStream(OutputStream out) { + this.out = out; + } + + public void setErrorStream(OutputStream err) { + this.err = err; + } + + public void setExitCallback(CommandFactory.ExitCallback callback) { + this.callback = callback; + } + + public void start() throws IOException { + if (error != null) { + throw error; + } + new Thread(this).start(); + } + + public void run() { + try { + if (optT && !optR) { + ack(); + writeFile(readLine(), root); + } else if (optT && optR) { + ack(); + writeDir(readLine(), root); + } else if (optF) { + if (!root.exists()) { + throw new IOException(root + ": no such file or directory"); + } + if (root.isFile()) { + readFile(root); + } else if (root.isDirectory()) { + if (!optR) { + throw new IOException(root + " not a regular file"); + } else { + readDir(root); + } + } else { + throw new IOException(root + ": unknown file type"); + } + } else { + throw new IOException("Unsupported mode"); + } + } catch (IOException e) { + try { + out.write(2); + out.write(e.getMessage().getBytes()); + out.write('\n'); + out.flush(); + } catch (IOException e2) { + // Ignore + } + log.info("Error in scp command", e); + } finally { + callback.onExit(0); + } + } + + private void writeDir(String header, File path) throws IOException { + if (log.isDebugEnabled()) { + log.debug("Writing dir {}", path); + } + if (!header.startsWith("D")) { + throw new IOException("Expected a D message but got '" + header + "'"); + } + + String perms = header.substring(1, 5); + int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); + String name = header.substring(header.indexOf(' ', 6) + 1); + + if (length != 0) { + throw new IOException("Expected 0 length for directory but got " + length); + } + File file; + if (path.exists() && path.isDirectory()) { + file = new File(path, name); + } else if (!path.exists() && path.getParentFile().exists() && path.getParentFile().isDirectory()) { + file = path; + } else { + throw new IOException("Can not write to " + path); + } + if (!(file.exists() && file.isDirectory()) && !file.mkdir()) { + throw new IOException("Could not create directory " + file); + } + + ack(); + + for (;;) { + header = readLine(); + if (header.startsWith("C")) { + writeFile(header, file); + } else if (header.startsWith("D")) { + writeDir(header, file); + } else if (header.equals("E")) { + ack(); + break; + } else { + throw new IOException("Unexpected message: '" + header + "'"); + } + } + + } + + private void writeFile(String header, File path) throws IOException { + if (log.isDebugEnabled()) { + log.debug("Writing file {}", path); + } + if (!header.startsWith("C")) { + throw new IOException("Expected a C message but got '" + header + "'"); + } + + String perms = header.substring(1, 5); + int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); + String name = header.substring(header.indexOf(' ', 6) + 1); + + File file; + if (path.exists() && path.isDirectory()) { + file = new File(path, name); + } else if (path.exists() && path.isFile()) { + file = path; + } else if (!path.exists() && path.getParentFile().exists() && path.getParentFile().isDirectory()) { + file = path; + } else { + throw new IOException("Can not write to " + path); + } + OutputStream os = new FileOutputStream(file); + + ack(); + + byte[] buffer = new byte[8192]; + while (length > 0) { + int len = Math.min(length, buffer.length); + len = in.read(buffer, 0, len); + if (len <= 0) { + throw new IOException("End of stream reached"); + } + os.write(buffer, 0, len); + length -= len; + } + os.close(); + + ack(); + readAck(); + } + + private String readLine() throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + for (;;) { + int c = in.read(); + if (c == '\n') { + return baos.toString(); + } else if (c == -1) { + throw new IOException("End of stream"); + } else { + baos.write(c); + } + } + } + + private void readFile(File path) throws IOException { + if (log.isDebugEnabled()) { + log.debug("Reading file {}", path); + } + StringBuffer buf = new StringBuffer(); + buf.append("C"); + buf.append("0644"); // what about perms + buf.append(" "); + buf.append(path.length()); // length + buf.append(" "); + buf.append(path.getName()); + buf.append("\n"); + out.write(buf.toString().getBytes()); + out.flush(); + readAck(); + + InputStream is = new FileInputStream(path); + byte[] buffer = new byte[8192]; + for (;;) { + int len = is.read(buffer, 0, buffer.length); + if (len == -1) { + break; + } + out.write(buffer, 0, len); + } + is.close(); + ack(); + readAck(); + } + + private void readDir(File path) throws IOException { + if (log.isDebugEnabled()) { + log.debug("Reading directory {}", path); + } + StringBuffer buf = new StringBuffer(); + buf.append("D"); + buf.append("0755"); // what about perms + buf.append(" "); + buf.append("0"); // length + buf.append(" "); + buf.append(path.getName()); + buf.append("\n"); + out.write(buf.toString().getBytes()); + out.flush(); + readAck(); + + for (File child : path.listFiles()) { + if (child.isFile()) { + readFile(child); + } else if (child.isDirectory()) { + readDir(child); + } + } + + out.write("E\n".getBytes()); + out.flush(); + readAck(); + } + + private void ack() throws IOException { + out.write(0); + out.flush(); + } + + private void readAck() throws IOException { + int c = in.read(); + switch (c) { + case 0: + break; + case 1: + System.out.println("Received warning: " + readLine()); + break; + case 2: + throw new IOException("Received nack: " + readLine()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `FileInputStream(...)` at line 276 is not released after line 288. +**Note**: potential exception at line 279 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ScpCommand.readFile(File) + +### Procedure Id: +org.apache.sshd.server.command.ScpCommand.readFile(java.io.File):void.ba8563bfddb6e9e720f96a7b64c31669 + +### File: +sshd-core/src/main/java/org/apache/sshd/server/command/ScpCommand.java + +### Key: +ScpCommand.java|readFile|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +c26f569bb551a6ac31dbbdb1cedf09e9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6694/instruction.md b/inferredbugs-6694/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2bf4737aaab73fa3ccb8ef3f322554048b91be88 --- /dev/null +++ b/inferredbugs-6694/instruction.md @@ -0,0 +1,263 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mina-sshd +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sshd; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.security.KeyPair; +import java.security.PublicKey; +import java.util.List; + +import org.apache.sshd.agent.SshAgent; +import org.apache.sshd.agent.local.ProxyAgentFactory; +import org.apache.sshd.agent.local.LocalAgentFactory; +import org.apache.sshd.agent.unix.AgentClient; +import org.apache.sshd.agent.unix.AgentServer; +import org.apache.sshd.client.channel.ChannelShell; +import org.apache.sshd.common.KeyPairProvider; +import org.apache.sshd.server.Command; +import org.apache.sshd.server.Environment; +import org.apache.sshd.util.*; +import org.junit.Test; + +import static org.apache.sshd.util.Utils.createTestKeyPairProvider; +import static org.apache.sshd.util.Utils.getFreePort; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assume.assumeThat; + +public class AgentTest { + + @Test + public void testAgent() throws Exception { + AgentServer agent = new AgentServer(); + String authSocket; + try { + authSocket = agent.start(); + } catch (UnsatisfiedLinkError e) { + // the native library is not available, so these tests should be skipped + authSocket = null; + } + assumeThat(authSocket, notNullValue()); + + SshAgent client = new AgentClient(authSocket); + List> keys = client.getIdentities(); + assertNotNull(keys); + assertEquals(0, keys.size()); + + KeyPair[] k = Utils.createTestHostKeyProvider().loadKeys(); + client.addIdentity(k[0], ""); + keys = client.getIdentities(); + assertNotNull(keys); + assertEquals(1, keys.size()); + + client.removeIdentity(k[0].getPublic()); + keys = client.getIdentities(); + assertNotNull(keys); + assertEquals(0, keys.size()); + + client.removeAllIdentities(); + + client.close(); + + agent.close(); + } + + @Test + public void testAgentForwarding() throws Exception { + + int port1 = getFreePort(); + int port2 = getFreePort(); + + TestEchoShellFactory shellFactory = new TestEchoShellFactory(); + ProxyAgentFactory agentFactory = new ProxyAgentFactory(); + LocalAgentFactory localAgentFactory = new LocalAgentFactory(); + + KeyPair pair = createTestKeyPairProvider("dsaprivkey.pem").loadKey(KeyPairProvider.SSH_DSS); + localAgentFactory.getAgent().addIdentity(pair, "smx"); + + SshServer sshd1 = SshServer.setUpDefaultServer(); + sshd1.setPort(port1); + sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider()); + sshd1.setShellFactory(shellFactory); + sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator()); + sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator()); + sshd1.setAgentFactory(agentFactory); + sshd1.start(); + + SshServer sshd2 = SshServer.setUpDefaultServer(); + sshd2.setPort(port2); + sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider()); + sshd2.setShellFactory(new TestEchoShellFactory()); + sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator()); + sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator()); + sshd2.setAgentFactory(new ProxyAgentFactory()); + sshd2.start(); + + SshClient client1 = SshClient.setUpDefaultClient(); + client1.setAgentFactory(localAgentFactory); + client1.start(); + ClientSession session1 = client1.connect("localhost", port1).await().getSession(); + assertTrue(session1.authAgent("smx").await().isSuccess()); + ChannelShell channel1 = session1.createShellChannel(); + ByteArrayOutputStream sent = new ByteArrayOutputStream(); + PipedOutputStream pipedIn = new TeePipedOutputStream(sent); + channel1.setIn(new PipedInputStream(pipedIn)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream(); + channel1.setOut(out); + channel1.setErr(err); + channel1.setAgentForwarding(true); + channel1.open().await(); + + synchronized (shellFactory.shell) { + System.out.println("Possibly waiting for remote shell to start"); + if (!shellFactory.shell.started) { + shellFactory.shell.wait(); + } + } + + SshClient client2 = SshClient.setUpDefaultClient(); + client2.setAgentFactory(agentFactory); + client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv()); + client2.start(); + ClientSession session2 = client2.connect("localhost", port2).await().getSession(); + assertTrue(session2.authAgent("smx").await().isSuccess()); + ChannelShell channel2 = session2.createShellChannel(); + channel2.setIn(shellFactory.shell.getIn()); + channel2.setOut(shellFactory.shell.getOut()); + channel2.setErr(shellFactory.shell.getErr()); + channel2.setAgentForwarding(true); + channel2.open().await(); + + pipedIn.write("foo\n".getBytes()); + pipedIn.flush(); + + Thread.sleep(1000); + + System.out.println(out.toString()); + System.err.println(err.toString()); + + } + + public static class TestEchoShellFactory extends EchoShellFactory { + + TestEchoShell shell = new TestEchoShell(); + + @Override + public Command create() { + return shell; + } + + public class TestEchoShell extends EchoShell { + + boolean started; + + @Override + public synchronized void start(Environment env) throws IOException { + super.start(env); + started = true; + notifyAll(); + } + + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.sshd.AgentTest.testAgentForwarding` indirectly writes to field `channel1.org.apache.sshd.client.channel.AbstractClientChannel.in` outside of synchronization. + Reporting because this access may occur on a background thread. + +Note that the prefix path channel1 has been contaminated during the execution, so the reported race on channel1.org.apache.sshd.client.channel.AbstractClientChannel.in might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AgentTest.testAgentForwarding() + +### Procedure Id: +org.apache.sshd.AgentTest.testAgentForwarding():void.5128deb4780ec458305f41d6c33f48cf + +### File: +sshd-core/src/test/java/org/apache/sshd/AgentTest.java + +### Key: +AgentTest.java|testAgentForwarding|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +feac7d6690acf6a734a9baaa18a2382b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6695/instruction.md b/inferredbugs-6695/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f5d78234c77c90f18a2d1f5d647d8dcf8e0973f --- /dev/null +++ b/inferredbugs-6695/instruction.md @@ -0,0 +1,209 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mina-sshd +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.sshd.agent; + +import org.apache.tomcat.jni.Library; +import org.apache.tomcat.jni.Pool; + +import java.io.File; +import java.io.IOException; + + +/** + * Internal singleton used for initializing correctly the APR native library + * and the associated root memory pool. + * + * It'll finalize nicely the native resources (libraries and memory pools). + * + * Each memory pool used in the APR transport module needs to be children of the + * root pool {@link AprLibrary#getRootPool()}. + * + * @author Apache MINA Project + */ +class AprLibrary { + + // is APR library was initialized (load of native libraries) + private static AprLibrary library = null; + + /** + * get the shared instance of APR library, if none, initialize one + * @return the current APR library singleton + */ + static synchronized AprLibrary getInstance() { + if (!isInitialized()) + initialize(); + return library; + } + + /** + * initialize the APR Library by loading the associated native libraries + * and creating the associated singleton + */ + private static synchronized void initialize() { + if (library == null) + library = new AprLibrary(); + } + + /** + * is the APR library was initialized. + * @return true if the Library is initialized, false otherwise + */ + static synchronized boolean isInitialized() { + return library != null; + } + + // APR memory pool (package wide mother pool) + private final long pool; + + /** + * APR library singleton constructor. Called only when accessing the + * singleton the first time. + * It's initializing an APR memory pool for the whole package (a.k.a mother or root pool). + */ + private AprLibrary() { + try { + Library.initialize(null); + } catch (Exception e) { + throw new RuntimeException( + "Error loading Apache Portable Runtime (APR).", e); + } + pool = Pool.create(0); + } + + @Override + protected void finalize() throws Throwable { + library = null; + Pool.destroy(pool); + Library.terminate(); + super.finalize(); + } + + /** + * get the package wide root pool, the mother of all the pool created + * in APR transport module. + * @return number identifying the root pool + */ + long getRootPool() { + return pool; + } + + static String createLocalSocketAddress() throws IOException { + String name; + String os = System.getProperty("os.name").toLowerCase(); + if (os.indexOf("windows") < 0) { + File socket = File.createTempFile("mina", "apr"); + socket.delete(); + name = socket.getAbsolutePath(); + } else { + File socket = File.createTempFile("mina", "apr"); + socket.delete(); + name = "\\\\.\\pipe\\" + socket.getName(); + } + return name; + } + + static void secureLocalSocket(String authSocket, long handle) throws IOException { + String os = System.getProperty("os.name").toLowerCase(); + if (os.indexOf("windows") < 0) { + File file = new File(authSocket); + if (!file.setReadable(false, false) || !file.setReadable(true, true) + || !file.setExecutable(false, false) || !file.setExecutable(true, true)) { + throw new IOException("Unable to secure local socket"); + } + + } else { + // should be ok on windows + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 123. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AprLibrary.secureLocalSocket(String,long) + +### Procedure Id: +org.apache.sshd.agent.AprLibrary.secureLocalSocket(java.lang.String,long):void.2316151b197416009f4dedb301e0c03a + +### File: +sshd-core/src/main/java/org/apache/sshd/agent/AprLibrary.java + +### Key: +AprLibrary.java|secureLocalSocket|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +12d538cbecb77c52c7b88ec0eb2ee30d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6722/instruction.md b/inferredbugs-6722/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61af0e6aa24e2af2cd536a996cc52eacf8da9116 --- /dev/null +++ b/inferredbugs-6722/instruction.md @@ -0,0 +1,450 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** server +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.dna.mqtt.moquette.server; + +import org.eclipse.paho.client.mqttv3.*; +import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; +import org.junit.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +import static org.junit.Assert.*; + +public class ServerIntegrationPahoTest { + static class TestCallback implements MqttCallback { + + private MqttMessage m_message; + private String m_topic; + private CountDownLatch m_latch = new CountDownLatch(1); + + public MqttMessage getMessage() { + try { + m_latch.await(1, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + return m_message; + } + + public String getTopic() { + try { + m_latch.await(5, TimeUnit.SECONDS); + } catch (InterruptedException e) { + e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. + } + return m_topic; + } + + void reinit() { + m_latch = new CountDownLatch(1); + m_message = null; + m_topic = null; + } + + public void connectionLost(Throwable cause) { + //To change body of implemented methods use File | Settings | File Templates. + } + + public void messageArrived(String topic, MqttMessage message) throws Exception { + m_message = message; + m_topic = topic; + m_latch.countDown(); + } + + public void deliveryComplete(IMqttDeliveryToken token) { + //To change body of implemented methods use File | Settings | File Templates. + } + } + + private static final Logger LOG = LoggerFactory.getLogger(ServerIntegrationPahoTest.class); + + static MqttClientPersistence s_dataStore; + static MqttClientPersistence s_pubDataStore; + + + Server m_server; + IMqttClient m_client; + TestCallback m_callback; + + @BeforeClass + public static void beforeTests() { + String tmpDir = System.getProperty("java.io.tmpdir"); + s_dataStore = new MqttDefaultFilePersistence(tmpDir); + s_pubDataStore = new MqttDefaultFilePersistence(tmpDir + File.separator + "publisher"); + } + + protected void startServer() throws IOException { + m_server = new Server(); + m_server.startServer(); + } + + @Before + public void setUp() throws Exception { + startServer(); + + m_client = new MqttClient("tcp://localhost:1883", "TestClient", s_dataStore); + m_callback = new TestCallback(); + m_client.setCallback(m_callback); + } + + @After + public void tearDown() throws Exception { + if (m_client.isConnected()) { + m_client.disconnect(); + } + + m_server.stopServer(); + File dbFile = new File(Server.STORAGE_FILE_PATH); + if (dbFile.exists()) { + dbFile.delete(); + } + } + + @Test + public void testSubscribe() throws Exception { + LOG.info("*** testSubscribe ***"); + m_client.connect(); + m_client.subscribe("/topic", 0); + + MqttMessage message = new MqttMessage("Hello world!!".getBytes()); + message.setQos(0); + message.setRetained(false); + m_client.publish("/topic", message); + + assertEquals("/topic", m_callback.getTopic()); + } + + + @Test + public void testCleanSession_maintainClientSubscriptions() throws Exception { + LOG.info("*** testCleanSession_maintainClientSubscriptions ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.disconnect(); + + //reconnect and publish + MqttClient anotherClient = new MqttClient("tcp://localhost:1883", "TestClient", s_dataStore); + m_callback = new TestCallback(); + anotherClient.setCallback(m_callback); + anotherClient.connect(options); + anotherClient.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertEquals("/topic", m_callback.getTopic()); + } + + + @Test + public void testCleanSession_maintainClientSubscriptions_againstClientDestruction() throws Exception { + LOG.info("*** testCleanSession_maintainClientSubscriptions_againstClientDestruction ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.disconnect(); + + //reconnect and publish + m_client.connect(options); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertEquals("/topic", m_callback.getTopic()); + } + + /** + * Check that after a client has connected with clean session false, subscribed + * to some topic and exited, if it reconnect with clean session true, the m_server + * correctly cleanup every previous subscription + */ + @Test + public void testCleanSession_correctlyClientSubscriptions() throws Exception { + LOG.info("*** testCleanSession_correctlyClientSubscriptions ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.disconnect(); + + //reconnect and publish + m_client.connect(); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertNull(m_callback.getMessage()); + } + + @Test + public void testCleanSession_maintainClientSubscriptions_withServerRestart() throws Exception { + LOG.info("*** testCleanSession_maintainClientSubscriptions_withServerRestart ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.disconnect(); + + m_server.stopServer(); + + m_server.startServer(); + + //reconnect and publish + m_client.connect(options); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertEquals("/topic", m_callback.getTopic()); + } + + @Test + public void testRetain_maintainMessage_againstClientDestruction() throws Exception { + LOG.info("*** testRetain_maintainMessage_againstClientDestruction ***"); + m_client.connect(); + m_client.publish("/topic", "Test my payload".getBytes(), 0, true); + + m_client.disconnect(); + + //reconnect and publish + m_client.connect(); + m_client.subscribe("/topic", 0); + + assertEquals("/topic", m_callback.getTopic()); + } + + @Test + public void testUnsubscribe_do_not_notify_anymore_same_session() throws Exception { + LOG.info("*** testUnsubscribe_do_not_notify_anymore_same_session ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + //m_client.disconnect(); + assertEquals("/topic", m_callback.getTopic()); + + m_client.unsubscribe("/topic"); + m_callback.reinit(); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertNull(m_callback.getMessage()); + } + + @Test + public void testUnsubscribe_do_not_notify_anymore_new_session() throws Exception { + LOG.info("*** testUnsubscribe_do_not_notify_anymore_new_session ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 0); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + //m_client.disconnect(); + assertEquals("/topic", m_callback.getTopic()); + + m_client.unsubscribe("/topic"); + m_client.disconnect(); + + m_callback.reinit(); + m_client.connect(options); + m_client.publish("/topic", "Test my payload".getBytes(), 0, false); + + assertNull(m_callback.getMessage()); + } + + @Test + public void testPublishWithQoS1() throws Exception { + LOG.info("*** testPublishWithQoS1 ***"); + m_client.connect(); + m_client.subscribe("/topic", 1); + m_client.publish("/topic", "Hello MQTT".getBytes(), 1, false); + m_client.disconnect(); + + //reconnect and publish + assertEquals("Hello MQTT", m_callback.getMessage().toString()); + assertEquals(1, m_callback.getMessage().getQos()); + } + + @Test + public void testPublishWithQoS1_notCleanSession() throws Exception { + LOG.info("*** testPublishWithQoS1_notCleanSession ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 1); + m_client.disconnect(); + + //publish a QoS 1 message another client publish a message on the topic + publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 1); + + m_client.connect(options); + + assertEquals("Hello MQTT", m_callback.getMessage().toString()); + } + + @Test + public void checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession() throws Exception { + LOG.info("*** checkReceivePublishedMessage_after_a_reconnect_with_notCleanSession ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 1); + m_client.disconnect(); + + m_client.connect(options); + m_client.subscribe("/topic", 1); + + //publish a QoS 1 message another client publish a message on the topic + publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 1); + + //Verify that after a reconnection the client receive the message + assertNotNull(m_callback.getMessage()); + assertEquals("Hello MQTT", m_callback.getMessage().toString()); + } + + private void publishFromAnotherClient(String topic, byte[] payload, int qos) throws Exception { + IMqttClient anotherClient = new MqttClient("tcp://localhost:1883", "TestClientPUB", s_pubDataStore); + anotherClient.connect(); + anotherClient.publish(topic, payload, qos, false); + anotherClient.disconnect(); + } + + //BUG + @Test + public void testPublishWithQoS2() throws Exception { + LOG.info("*** testPublishWithQoS2 ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 2); + m_client.disconnect(); + + //publish a QoS 1 message another client publish a message on the topic + publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); + m_callback.reinit(); + m_client.connect(options); + + assertEquals("Hello MQTT", m_callback.getMessage().toString()); + assertEquals(2, m_callback.getMessage().getQos()); + } + + @Test + public void testPublishReceiveWithQoS2() throws Exception { + LOG.info("*** testPublishReceiveWithQoS2 ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 2); + m_client.disconnect(); + + //publish a QoS 2 message another client publish a message on the topic + publishFromAnotherClient("/topic", "Hello MQTT".getBytes(), 2); + m_callback.reinit(); + m_client.connect(options); + + assertNotNull(m_callback); + assertNotNull(m_callback.getMessage()); + assertEquals("Hello MQTT", m_callback.getMessage().toString()); + } + + @Test + public void avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1() throws Exception { + LOG.info("*** avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1, issue #16 ***"); + MqttConnectOptions options = new MqttConnectOptions(); + options.setCleanSession(false); + m_client.connect(options); + m_client.subscribe("/topic", 1); + m_client.disconnect(); + + publishFromAnotherClient("/topic", "Hello MQTT 1".getBytes(), 1); + m_callback.reinit(); + m_client.connect(options); + + assertNotNull(m_callback); + assertNotNull(m_callback.getMessage()); + assertEquals("Hello MQTT 1", m_callback.getMessage().toString()); + m_client.disconnect(); + + //publish other message + publishFromAnotherClient("/topic", "Hello MQTT 2".getBytes(), 1); + + //reconnect the second time + m_callback.reinit(); + m_client.connect(options); + assertNotNull(m_callback); + assertNotNull(m_callback.getMessage()); + assertEquals("Hello MQTT 2", m_callback.getMessage().toString()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `ServerIntegrationPahoTest.m_callback.getMessage()` could be null and is dereferenced at line 362. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ServerIntegrationPahoTest.avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1() + +### Procedure Id: +org.dna.mqtt.moquette.server.ServerIntegrationPahoTest.avoidMultipleNotificationsAfterMultipleReconn.ce22a8fb48aad29ba5a3532da0ece281 + +### File: +broker/src/test/java/org/dna/mqtt/moquette/server/ServerIntegrationPahoTest.java + +### Key: +ServerIntegrationPahoTest.java|avoidMultipleNotificationsAfterMultipleReconnection_cleanSessionFalseQoS1|NULL_DEREFERENCE + +### Node Key: +b36a47f8c37a83daf33a009ca0f8c797 + +### Hash: +2a8b3de93b80ea8730b265809afa8207 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6802/instruction.md b/inferredbugs-6802/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3d0f90933c9a8bccd985b432dedbe4a8da0fa47 --- /dev/null +++ b/inferredbugs-6802/instruction.md @@ -0,0 +1,471 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rrd4j +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.rrd4j.core; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; + +/** + * This class should be used to synchronize access to RRD files + * in a multithreaded environment. This class should be also used to prevent opening of + * too many RRD files at the same time (thus avoiding operating system limits). + *

+ * It's much more scalable than the previous pool + */ +public class RrdDbPool { + private static class RrdDbPoolSingletonHolder { + static final RrdDbPool instance = new RrdDbPool(); + } + + /** + * Initial capacity of the pool i.e. maximum number of simultaneously open RRD files. The pool will + * never open too many RRD files at the same time. + */ + public static final int INITIAL_CAPACITY = 200; + + static private class RrdEntry { + RrdDb rrdDb = null; + int count = 0; + final CountDownLatch waitempty; + final CountDownLatch inuse; + final boolean placeholder; + final String canonicalPath; + RrdEntry(boolean placeholder, String canonicalPath) { + this.placeholder = placeholder; + this.canonicalPath = canonicalPath; + if( placeholder) { + inuse = new CountDownLatch(1); + waitempty = null; + } else { + inuse = null; + waitempty = new CountDownLatch(1); + } + } + @Override + public String toString() { + return placeholder + "@" + canonicalPath; + } + } + + /** + * Creates a single instance of the class on the first call, + * or returns already existing one. Uses Initialization On Demand Holder idiom. + * + * @return Single instance of this class + * @throws java.lang.RuntimeException Thrown if the default RRD backend is not derived from the {@link org.rrd4j.core.RrdFileBackendFactory} + */ + public static RrdDbPool getInstance() { + return RrdDbPoolSingletonHolder.instance; + } + + private Semaphore capacity; + private int maxCapacity = INITIAL_CAPACITY; + + private final ConcurrentMap pool = new ConcurrentHashMap(INITIAL_CAPACITY); + + /** + *

Constructor for RrdDbPool.

+ * + * Not private, used by junit tests + */ + RrdDbPool() { + if (!(RrdBackendFactory.getDefaultFactory() instanceof RrdFileBackendFactory)) { + throw new RuntimeException("Cannot create instance of " + getClass().getName() + " with " + + "a default backend factory not derived from RrdFileBackendFactory"); + } + capacity = new Semaphore(maxCapacity, true); + } + + /** + * Returns the number of open RRD files. + * + * @return Number of currently open RRD files held in the pool. + */ + public int getOpenFileCount() { + return maxCapacity - capacity.availablePermits(); + } + + /** + * Returns an array of open file names. + * + * @return Array with canonical paths to open RRD files held in the pool. + */ + public String[] getOpenFiles() { + //Direct toarray from keySet can fail + Set files = new HashSet(); + files.addAll(pool.keySet()); + return files.toArray(new String[0]); + } + + private RrdEntry getEntry(String path, boolean cancreate) throws IOException, InterruptedException { + String canonicalPath = Util.getCanonicalPath(path); + RrdEntry ref = null; + while(ref == null || ref.placeholder) { + ref = pool.get(canonicalPath); + if(ref == null) { + //Slot empty + //If still absent put a place holder, and create the entry + ref = pool.putIfAbsent(canonicalPath, new RrdEntry(true, canonicalPath)); + if(ref == null) { + return cancreate ? new RrdEntry(false, canonicalPath) : null; + } + } else if(! ref.placeholder) { + // Real entry, try to put a place holder if some one did'nt get it meanwhile + if(pool.replace(canonicalPath, ref, new RrdEntry(true, canonicalPath))) { + return ref; + } + } + // Reached only if a place holder and not null + // Wait for other tasks to be finished + ref.inuse.await(); + } + return ref; + } + + private enum ACTION { + SWAP, DROP; + }; + + private void passNext(ACTION a, RrdEntry e) { + RrdEntry o = null; + switch (a) { + case SWAP: + o = pool.put(e.canonicalPath, e); + break; + case DROP: + o = pool.remove(e.canonicalPath); + break; + } + //task finished, waiting on a place holder can go on + if(o != null) { + o.inuse.countDown(); + } + + } + + /** + * Releases RrdDb reference previously obtained from the pool. When a reference is released, its usage + * count is decremented by one. If usage count drops to zero, the underlying RRD file will be closed. + * + * @param rrdDb RrdDb reference to be returned to the pool + * @throws java.io.IOException Thrown in case of I/O error + */ + public void release(RrdDb rrdDb) throws IOException { + // null pointer should not kill the thread, just ignore it + if (rrdDb == null) { + return; + } + + RrdEntry ref; + try { + ref = getEntry(rrdDb.getPath(), false); + } catch (InterruptedException e) { + throw new RuntimeException("release interrupted for " + rrdDb, e); + } + if(ref == null) { + return; + } + + if (ref.count <= 0) { + passNext(ACTION.DROP, ref); + throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], the file was never requested"); + } + if (--ref.count == 0) { + if(ref.rrdDb == null) { + passNext(ACTION.DROP, ref); + throw new IllegalStateException("Could not release [" + rrdDb.getPath() + "], pool corruption"); + } + ref.rrdDb.close(); + capacity.release(); + passNext(ACTION.DROP, ref); + //If someone is waiting for an empty entry, signal it + ref.waitempty.countDown(); + } else { + passNext(ACTION.SWAP, ref); + } + } + + /** + * Requests a RrdDb reference for the given RRD file path.

+ *

    + *
  • If the file is already open, previously returned RrdDb reference will be returned. Its usage count + * will be incremented by one. + *
  • If the file is not already open and the number of already open RRD files is less than + * {@link #INITIAL_CAPACITY}, the file will be open and a new RrdDb reference will be returned. + * If the file is not already open and the number of already open RRD files is equal to + * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. + *
+ * + * @param path Path to existing RRD file + * @return reference for the give RRD file + * @throws java.io.IOException Thrown in case of I/O error + */ + public RrdDb requestRrdDb(String path) throws IOException { + RrdEntry ref; + try { + ref = getEntry(path, true); + } catch (InterruptedException e) { + throw new RuntimeException("request interrupted for " + path, e); + } + + try { + //Not opened + if(ref.count == 0) { + try { + capacity.acquire(); + } catch (InterruptedException e) { + throw new RuntimeException("RrdDb acquire interrupted", e); + } + try { + ref.rrdDb = new RrdDb(path); + } catch (IOException e) { + capacity.release(); + throw e; + } + } + ref.count++; + return ref.rrdDb; + } finally { + passNext(ACTION.SWAP, ref); + } + } + + /** + * Requests a RrdDb reference for the given RRD file definition object.

+ *

    + *
  • If the file with the path specified in the RrdDef object is already open, + * the method blocks until the file is closed. + *
  • If the file is not already open and the number of already open RRD files is less than + * {@link #INITIAL_CAPACITY}, a new RRD file will be created and a its RrdDb reference will be returned. + * If the file is not already open and the number of already open RRD files is equal to + * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. + *
+ * + * @param rrdDef Definition of the RRD file to be created + * @return Reference to the newly created RRD file + * @throws java.io.IOException Thrown in case of I/O error + */ + public RrdDb requestRrdDb(RrdDef rrdDef) throws IOException { + RrdEntry ref = null; + try { + do { + ref = getEntry(rrdDef.getPath(), true); + if(ref.count != 0) { + //Not empty, give it back, but wait for signal + passNext(ACTION.SWAP, ref); + ref.waitempty.await(); + // ref is not a real reference (not replaced by a placeholder + // So must try a get entry before carry on + ref = null; //might be checked by the catch + continue; + } + } while(ref == null || ref.count != 0); + } catch (InterruptedException e) { + if(ref != null) { + passNext(ACTION.SWAP, ref); + } + throw new RuntimeException("request interrupted for new rrdDef " + rrdDef.getPath(), e); + } + try { + ref.rrdDb = new RrdDb(rrdDef); + ref.count = 1; + capacity.acquire(); + return ref.rrdDb; + } catch (InterruptedException e) { + throw new RuntimeException("request interrupted for new rrdDef " + rrdDef.getPath(), e); + } finally { + passNext(ACTION.SWAP, ref); + } + } + + /** + * Requests a RrdDb reference for the given path. The file will be created from + * external data (from XML dump, RRD file or RRDTool's binary RRD file).

+ *

    + *
  • If the file with the path specified is already open, + * the method blocks until the file is closed. + *
  • If the file is not already open and the number of already open RRD files is less than + * {@link #INITIAL_CAPACITY}, a new RRD file will be created and a its RrdDb reference will be returned. + * If the file is not already open and the number of already open RRD files is equal to + * {@link #INITIAL_CAPACITY}, the method blocks until some RRD file is closed. + *
+ * + * @param path Path to RRD file which should be created + * @param sourcePath Path to external data which is to be converted to Rrd4j's native RRD file format + * @return Reference to the newly created RRD file + * @throws java.io.IOException Thrown in case of I/O error + */ + public RrdDb requestRrdDb(String path, String sourcePath) + throws IOException { + RrdEntry ref = null; + try { + do { + ref = getEntry(path, true); + if(ref.count != 0) { + //Not empty, give it back, but wait for signal + passNext(ACTION.SWAP, ref); + ref.waitempty.await(); + // ref is not a real reference (not replaced by a placeholder + // So must try a get entry before carry on + ref = null; //might be checked by the catch + continue; + } + } while(ref.count != 0); + } catch (InterruptedException e) { + if(ref != null) { + passNext(ACTION.SWAP, ref); + } + throw new RuntimeException("request interrupted for new rrd " + path, e); + } + + try { + ref.rrdDb = new RrdDb(path, sourcePath); + ref.count = 1; + capacity.acquire(); + return ref.rrdDb; + } catch (InterruptedException e) { + throw new RuntimeException("request interrupted for new rrd " + path, e); + } finally { + passNext(ACTION.SWAP, ref); + } + } + + /** + * Sets the maximum number of simultaneously open RRD files. + * + * @param newCapacity Maximum number of simultaneously open RRD files. + */ + public void setCapacity(int newCapacity) { + int available = capacity.drainPermits(); + if (available != maxCapacity) { + capacity.release(available); + throw new RuntimeException("Can only be done on a empty pool"); + } + else { + capacity = new Semaphore(newCapacity, true); + } + maxCapacity = newCapacity; + } + + /** + * Returns the maximum number of simultaneously open RRD files. + * + * @return maximum number of simultaneously open RRD files + */ + public int getCapacity() { + return maxCapacity; + } + + /** + * Returns the number of usage for a RRD. + * + * @param rrdDb RrdDb reference for which informations is needed. + * @return the number of request for this rrd + * @throws java.io.IOException if any. + */ + public int getOpenCount(RrdDb rrdDb) throws IOException { + return getOpenCount(rrdDb.getPath()); + } + + /** + * Returns the number of usage for a RRD. + * + * @param path RRD file for which informations is needed. + * @return the number of request for this file + * @throws java.io.IOException if any. + */ + public int getOpenCount(String path) throws IOException { + RrdEntry ref = null; + try { + ref = getEntry(path, false); + if(ref == null) + return 0; + else { + return ref.count; + } + } catch (InterruptedException e) { + throw new RuntimeException("getOpenCount interrupted", e); + } finally { + if(ref != null) { + passNext(ACTION.SWAP, ref); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `ref` last assigned on line 313 could be null and is dereferenced at line 316. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +RrdDb RrdDbPool.requestRrdDb(String,String) + +### Procedure Id: +org.rrd4j.core.RrdDbPool.requestRrdDb(java.lang.String,java.lang.String):org.rrd4j.core.RrdDb.7f7d8a4f7d845eccf1a1d7e6187e7f96 + +### File: +src/main/java/org/rrd4j/core/RrdDbPool.java + +### Key: +RrdDbPool.java|requestRrdDb|NULL_DEREFERENCE + +### Node Key: +3df05d068ed6e5a593b8c0e2733790a3 + +### Hash: +5ca623bcd4324999c70d4a099742a39e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6803/instruction.md b/inferredbugs-6803/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2c18622b79c7b3bc3c6741443b09e0c65a3197a4 --- /dev/null +++ b/inferredbugs-6803/instruction.md @@ -0,0 +1,399 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rrd4j +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2011 The OpenNMS Group, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + *******************************************************************************/ +package org.rrd4j.graph; + +import static org.easymock.EasyMock.anyInt; +import static org.easymock.EasyMock.eq; +import static org.easymock.EasyMock.gt; +import static org.easymock.EasyMock.lt; +import static org.easymock.EasyMock.same; + +import java.awt.FontFormatException; +import java.io.IOException; +import java.util.Date; + +import org.junit.Test; +import org.rrd4j.core.RrdDb; +import org.rrd4j.core.Sample; + + +/** + * The form of these tests is fairly generic, using a Mock ImageWorker to see if the expected + * sort of calls were made. We generally don't check co-ordinates. Rather, we check for a certain + * number of major grid lines, with the right string labels, and a certain number of minor lines. + * Presumably if there are the right number of lines they'll probably be around the right locations + * This will test the actual complex behaviour of ValueAxis which is working out how many lines to + * draw and at what major values. Subtleties like the actual pixel values are generally less important. + * If we find a specific bug with placement of the grid lines, then we can writes tests to check + * for specific co-ordinates, knowing exactly why we're checking + * + * @author cmiskell + * + */ + +public class ValueAxisTest extends AxisTester { + + @Override + void setupGraphDef() { + } + + @Override + ValueAxis makeAxis(RrdGraph rrdGraph) { + return new ValueAxis(rrdGraph, imageWorker); + } + + public void checkForBasicGraph() { + expectMajorGridLine(" 0.0"); + + expectMinorGridLines(4); + + expectMajorGridLine(" 0.5"); + + expectMinorGridLines(4); + + expectMajorGridLine(" 1.0"); + + run(); + } + + private void expectMajorGridLine(String label) { + //We don't care what y value is used for any of the gridlines; the fact that they're there + // is good enough. Our expectations for any given graph will be a certain set of grid lines + // in a certain order, which pretty much implies y values. If we find a bug where that + // assumption is wrong, a more specific test can be written to find that. + //The x-values of the lines are important though, to be sure they've been drawn correctly + + //Note the use of "same" for the strokes; in RrdGraphConstants, these are both BasicStroke(1) + // so we want to be sure exactly the same object was used + + int quarterX = imageParameters.xgif/4; + int midX = imageParameters.xgif/2; + int threeQuartersX = quarterX*3; + + imageWorker.drawString(eq(label), lt(quarterX), anyInt(), eq(graphDef.getFont(RrdGraphDef.FONTTAG_AXIS)), eq(RrdGraphDef.DEFAULT_FONT_COLOR)); + //Horizontal tick on the left + imageWorker.drawLine(lt(quarterX), anyInt(), lt(midX), anyInt(), eq(RrdGraphDef.DEFAULT_MGRID_COLOR), same(RrdGraphDef.TICK_STROKE)); + //Horizontal tick on the right + imageWorker.drawLine(gt(threeQuartersX), anyInt(), gt(threeQuartersX), anyInt(), eq(RrdGraphDef.DEFAULT_MGRID_COLOR), same(RrdGraphDef.TICK_STROKE)); + //Line in between the ticks (but overlapping a bit) + imageWorker.drawLine(lt(quarterX), anyInt(), gt(midX),anyInt(), eq(RrdGraphDef.DEFAULT_MGRID_COLOR), same(RrdGraphDef.GRID_STROKE)); + + } + + private void expectMinorGridLines(int count) { + //Note the use of "same" for the strokes; in RrdGraphConstants, these are both BasicStroke(1) + // so we want to be sure exactly the same object was used + + int quarterX = imageParameters.xgif/4; + int midX = quarterX*2; + int threeQuartersX = quarterX*3; + + for(int i=0; iSSLBasedProxyServer is a test class to start a SSL based SOCKS5 proxy + * server. + * + * @author Youchao Feng + * @version 1.0 + * @since 1.0 + */ +public class SSLBasedProxyServer { + + private static final Logger logger = LoggerFactory.getLogger(SSLBasedProxyServer.class); + + public static void main(String[] args) throws IOException { + Timer.open(); + SSLConfiguration configuration = SSLConfiguration.loadClassPath("server-ssl.properties"); + SocksProxyServer proxyServer = new SSLSocksProxyServer(Socks5Handler.class, configuration); + proxyServer.setBindPort(1081); + proxyServer.setSupportMethods(new NoAuthenticationRequiredMethod()); + try { + proxyServer.start(); + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.ServerSocket` acquired by call to `start()` at line 47 is not released after line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SSLBasedProxyServer.main(java.lang.String[]) + +### Procedure Id: +fucksocks.test.SSLBasedProxyServer.main(java.lang.String[]):void.56e3e74a6c60505397a1b21443875585 + +### File: +src/test/java/fucksocks/test/SSLBasedProxyServer.java + +### Key: +SSLBasedProxyServer.java|main|RESOURCE_LEAK + +### Node Key: +f65387f92aac9b561150293d56227830 + +### Hash: +9b1b15194177896b6db9a4a35531d051 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6833/instruction.md b/inferredbugs-6833/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2e06f441853d053c890bbd64a087cc1ec3c6fe5b --- /dev/null +++ b/inferredbugs-6833/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sockslib +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015-2025 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package fucksocks.server; + +import fucksocks.client.SocksProxy; +import fucksocks.common.methods.SocksMethod; +import fucksocks.common.net.MonitorSocketWrapper; +import fucksocks.common.net.NetworkMonitor; +import fucksocks.server.filters.SessionFilter; +import fucksocks.server.filters.SessionFilterChain; +import fucksocks.server.filters.SocksCommandFilter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static com.google.common.base.Preconditions.checkNotNull; + +/** + * The class BasicSocksProxyServer is a implementation of {@link SocksProxyServer} + * .
+ * You can build a SOCKS5 server easily by following codes:
+ *
+ * ProxyServer proxyServer = new BasicSocksProxyServer(Socks5Handler.class);
+ * proxyServer.start(); // Create a SOCKS5 server bind at 1080.
+ * 
+ *

+ * If you want change the port, you can using following codes: + *

+ *
+ * proxyServer.start(9999);
+ * 
+ * + * @author Youchao Feng + * @version 1.0 + * @date Apr 19, 2015 1:10:17 PM + */ +public class BasicSocksProxyServer implements SocksProxyServer, Runnable { + + protected static final Logger logger = LoggerFactory.getLogger(BasicSocksProxyServer.class); + + /** + * Number of threads in thread pool. + */ + protected static final int THREAD_NUMBER = 100; + + /** + * Thread pool used to process each connection. + */ + private ExecutorService executorService; + + /** + * The next session's ID. + */ + private long nextSessionId = 0; + + /** + * Server socket. + */ + private ServerSocket serverSocket; + + /** + * SOCKS socket handler class. + */ + private Class socksHandlerClass; + + /** + * Sessions that server managed. + */ + private Map sessions; + + /** + * A flag. + */ + private boolean stop = false; + + /** + * Thread that start the server. + */ + private Thread thread; + + /** + * Session filter chain. + */ + private SessionFilterChain sessionFilterChain = new SessionFilterChain(); + + /** + * Timeout for a session. + */ + private int timeout = 10000; + + private boolean daemon = false; + + /** + * Method selector. + */ + private MethodSelector methodSelector = new SocksMethodSelector(); + + /** + * Buffer size. + */ + private int bufferSize = 1024 * 1024 * 5; + + /** + * SOCKS listeners. + */ + private List socksListeners; + + private int bindPort = DEFAULT_SOCKS_PORT; + + private SocksProxy proxy; + + private NetworkMonitor networkMonitor = new NetworkMonitor(); + + + /** + * Constructs a {@link BasicSocksProxyServer} by a {@link SocksHandler} class. The bind port is + * 1080. + * + * @param socketHandlerClass {@link SocksHandler} class. + */ + public BasicSocksProxyServer(Class socketHandlerClass) { + this(socketHandlerClass, DEFAULT_SOCKS_PORT, Executors.newFixedThreadPool(THREAD_NUMBER)); + } + + /** + * Constructs a {@link BasicSocksProxyServer} by a {@link SocksHandler} class and a port. + * + * @param socketHandlerClass {@link SocksHandler} class. + * @param port The port that SOCKS server will listen. + */ + public BasicSocksProxyServer(Class socketHandlerClass, int port) { + this(socketHandlerClass, port, Executors.newFixedThreadPool(THREAD_NUMBER)); + } + + /** + * Constructs a {@link BasicSocksProxyServer} by a {@link SocksHandler} class and a + * ExecutorService. + * + * @param socketHandlerClass {@link SocksHandler} class. + * @param executorService Thread pool. + */ + public BasicSocksProxyServer(Class socketHandlerClass, ExecutorService + executorService) { + this(socketHandlerClass, DEFAULT_SOCKS_PORT, executorService); + } + + /** + * Constructs a {@link BasicSocksProxyServer} by a {@link SocksHandler} class , a port and a + * ExecutorService. + * + * @param socketHandlerClass {@link SocksHandler} class. + * @param port The port that SOCKS server will listen. + * @param executorService Thread pool. + */ + public BasicSocksProxyServer(Class socketHandlerClass, int port, + ExecutorService executorService) { + this.socksHandlerClass = + checkNotNull(socketHandlerClass, "Argument [socksHandlerClass] may not be null"); + this.executorService = + checkNotNull(executorService, "Argument [executorService] may not be null"); + this.bindPort = port; + sessions = new HashMap<>(); + } + + @Override + public void run() { + logger.info("Start proxy server at port:{}", bindPort); + while (!stop) { + try { + Socket socket = serverSocket.accept(); + socket = processSocketBeforeUse(socket); + socket.setSoTimeout(timeout); + Session session = new SocksSession(getNextSessionId(), socket, sessions); + sessions.put(session.getId(), session); + logger.info("Create SESSION[{}] for {}", session.getId(), session.getClientAddress()); + + try { + sessionFilterChain.doFilterChain(session); + } catch (InterruptedException e) { + session.close(); + logger.info(e.getMessage()); + continue; + } + + SocksHandler socksHandler = createSocksHandler(); + + /* initialize socks handler */ + socksHandler.setSession(session); + initializeSocksHandler(socksHandler); + + executorService.execute(socksHandler); + + } catch (IOException e) { + // Catches the exception that cause by shutdown method. + if (e.getMessage().equals("Socket closed") && stop) { + logger.debug("Server shutdown"); + return; + } + logger.debug(e.getMessage(), e); + } + } + } + + @Override + public void shutdown() { + stop = true; + executorService.shutdown(); + if (thread != null) { + thread.interrupt(); + } + try { + closeAllSession(); + if (serverSocket != null && serverSocket.isBound()) { + serverSocket.close(); + } + } catch (IOException e) { + logger.error(e.getMessage(), e); + } + } + + @Override + public void start() throws IOException { + serverSocket = createServerSocket(bindPort); + thread = new Thread(this); + thread.setName("fs-thread"); + thread.setDaemon(daemon); + thread.start(); + } + + protected ServerSocket createServerSocket(int bindPort) throws IOException { + return new ServerSocket(bindPort); + } + + @Override + public SocksHandler createSocksHandler() { + try { + return socksHandlerClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + logger.error(e.getMessage(), e); + } + return null; + } + + @Override + public void initializeSocksHandler(SocksHandler socksHandler) { + socksHandler.setMethodSelector(methodSelector); + socksHandler.setBufferSize(bufferSize); + socksHandler.setSocksCommandFilters(socksListeners); + socksHandler.setProxy(proxy); + } + + /** + * Closes all sessions. + */ + protected void closeAllSession() { + for (long key : sessions.keySet()) { + sessions.get(key).close(); + } + + } + + public ExecutorService getExecutorService() { + return executorService; + } + + public void setExecutorService(ExecutorService executorService) { + this.executorService = executorService; + } + + private synchronized long getNextSessionId() { + nextSessionId++; + return nextSessionId; + } + + @Override + public Map getManagedSessions() { + return sessions; + } + + @Override + public void setSupportMethods(SocksMethod... methods) { + methodSelector.setSupportMethod(methods); + + } + + @Override + public int getTimeout() { + return timeout; + } + + + @Override + public void setTimeout(int timeout) { + this.timeout = timeout; + } + + @Override + public int getBufferSize() { + return bufferSize; + } + + @Override + public void setBufferSize(int bufferSize) { + this.bufferSize = bufferSize; + } + + @Override + public void addSocksCommandFilter(SocksCommandFilter socksListener) { + if (socksListeners == null) { + socksListeners = new ArrayList<>(); + } + socksListeners.add(socksListener); + } + + @Override + public void removeSocksCommandFilter(SocksCommandFilter socksListener) { + if (socksListener == null) { + return; + } + socksListeners.remove(socksListener); + } + + @Override + public void addSessionFilter(SessionFilter sessionFilter) { + sessionFilterChain.addFilter(sessionFilter); + } + + @Override + public void removeSessionFilter(SessionFilter sessionFilter) { + sessionFilterChain.remoteFilter(sessionFilter); + } + + @Override + public SocksProxy getProxy() { + return proxy; + } + + @Override + public void setProxy(SocksProxy proxy) { + this.proxy = proxy; + } + + @Override + public int getBindPort() { + return bindPort; + } + + @Override + public void setBindPort(int bindPort) { + this.bindPort = bindPort; + } + + @Override + public boolean isDaemon() { + return daemon; + } + + @Override + public void setDaemon(boolean daemon) { + this.daemon = daemon; + } + + public SessionFilterChain getSessionFilterChain() { + return sessionFilterChain; + } + + public void setSessionFilterChain(SessionFilterChain sessionFilterChain) { + this.sessionFilterChain = sessionFilterChain; + } + + public Thread getServerThread() { + return thread; + } + + public NetworkMonitor getNetworkMonitor() { + return networkMonitor; + } + + public void setNetworkMonitor(NetworkMonitor networkMonitor) { + this.networkMonitor = checkNotNull(networkMonitor); + } + + protected Socket processSocketBeforeUse(Socket socket) { + return new MonitorSocketWrapper(socket, networkMonitor); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStream` acquired by call to `accept()` at line 191 is not released after line 209. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BasicSocksProxyServer.run() + +### Procedure Id: +fucksocks.server.BasicSocksProxyServer.run():void.8af232339a0444a8074fe4da36e1135f + +### File: +src/main/java/fucksocks/server/BasicSocksProxyServer.java + +### Key: +BasicSocksProxyServer.java|run|RESOURCE_LEAK + +### Node Key: +83959e9fcc38091e8a449c880f85c5ad + +### Hash: +8d055565e8e7fa9525642b5db1fdfc32 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6834/instruction.md b/inferredbugs-6834/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5395c370f4fa6cbc310fc6b595d37bd3ef71d10e --- /dev/null +++ b/inferredbugs-6834/instruction.md @@ -0,0 +1,149 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sockslib +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015-2025 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package fucksocks.test; + +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; + +import fucksocks.client.Socks5; +import fucksocks.client.SocksProxy; +import fucksocks.client.SocksSocket; +import fucksocks.common.methods.NoAuthencationRequiredMethod; +import fucksocks.common.methods.SocksMethod; +import fucksocks.utils.SocksClientSSLUtil; + +/** + * SSL Client + * + * @author Leo + */ +public class SSLSocketClient { + + public static void main(String[] args) throws Exception { + + SocksClientSSLUtil sslUtil = SocksClientSSLUtil.loadClassPath("client-ssl.properties"); + + SocksProxy proxy = new Socks5(new InetSocketAddress("localhost", 1080)); + List methods = new ArrayList(); + methods.add(new NoAuthencationRequiredMethod()); + proxy.setAcceptableMethods(methods); + SocksSocket socket = sslUtil.create(proxy); + + socket.connect("whois.internic.net", 43); + InputStream inputStream = socket.getInputStream(); + OutputStream outputStream = socket.getOutputStream(); + PrintWriter printWriter = new PrintWriter(outputStream); + printWriter.print("domain google.com\r\n"); + printWriter.flush(); + + byte[] whoisrecords = new byte[2048]; + java.util.List bytelist = new ArrayList<>(1024 * 6); + int size = 0; + while ((size = inputStream.read(whoisrecords)) > 0) { + for (int i = 0; i < size; i++) { + bytelist.add(whoisrecords[i]); + } + } + byte[] resultbyte = new byte[bytelist.size()]; + for (int i = 0; i < resultbyte.length; i++) { + resultbyte[i] = bytelist.get(i); + } + String string = new String(resultbyte); + System.out.println(string); + + inputStream.close(); + outputStream.close(); + socket.close(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStream` acquired by call to `create(...)` at line 46 is not released after line 72. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SSLSocketClient.main(java.lang.String[]) + +### Procedure Id: +fucksocks.test.SSLSocketClient.main(java.lang.String[]):void.77e6d61c45d08a83b933342f47d1e462 + +### File: +src/test/java/fucksocks/test/SSLSocketClient.java + +### Key: +SSLSocketClient.java|main|RESOURCE_LEAK + +### Node Key: +389a9726c2e2b00b3641ff005ae31cea + +### Hash: +14ec99ce0673055c83a5c3893a1bbc60 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6835/instruction.md b/inferredbugs-6835/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb9c678a10e5390d613b49305a60ad2d719766e7 --- /dev/null +++ b/inferredbugs-6835/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sockslib +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package fucksocks.quickstart; + +import fucksocks.common.methods.NoAuthenticationRequiredMethod; +import fucksocks.common.methods.UsernamePasswordMethod; +import fucksocks.common.net.NetworkMonitor; +import fucksocks.server.BasicSocksProxyServer; +import fucksocks.server.SocksProxyServer; +import fucksocks.server.SocksServerBuilder; +import fucksocks.server.manager.MemoryBasedUserManager; +import fucksocks.server.manager.User; +import fucksocks.server.manager.UserManager; +import fucksocks.utils.ArgUtil; +import fucksocks.utils.Timer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.annotation.Nullable; +import java.io.IOException; + +/** + * The class Socks5Server can create a simple Socks5 server. + * + * @author Youchao Feng + * @version 1.0 + * @date Sep 24, 2015 11:25 AM + */ +public class Socks5Server { + + private static final Logger logger = LoggerFactory.getLogger(Socks5Server.class); + private SocksProxyServer server; + + /** + * Run a SOCKS5 server. Same as @{@link #start(String[])}. + * + * @param args Some arguments. + * @throws IOException + */ + public static void main(@Nullable String[] args) throws IOException, InterruptedException { + Timer.open(); + Socks5Server socks5Server = new Socks5Server(); + socks5Server.start(args); + BasicSocksProxyServer server = (BasicSocksProxyServer) socks5Server.server; + NetworkMonitor monitor = server.getNetworkMonitor(); + while (true) { + logger.info(monitor.toString()); + Thread.sleep(5000); + } + + } + + /** + * Start a SOCKS5 server with some options. + * + * @param args Arguments.Support "--h --help --port --auth" + * @throws IOException + */ + public void start(@Nullable String[] args) throws IOException { + int port = 1080; + String authValue = null; + if (args != null) { + for (String arg : args) { + if (arg.equals("-h") || arg.equals("--help")) { + showHelp(); + System.exit(0); + } else if (arg.startsWith("--port=")) { + port = ArgUtil.intValueOf(arg); + } else if (arg.startsWith("--auth=")) { + authValue = ArgUtil.valueOf(arg); + } else { + logger.error("Unknown argument[{}]", arg); + return; + } + } + } + if (authValue == null) { + server = + SocksServerBuilder.newSocks5ServerBuilder().setSocksMethods(new + NoAuthenticationRequiredMethod()).setBindPort(port).build(); + } else { + UserManager userManager = new MemoryBasedUserManager(); + for (String user : authValue.split(",")) { + String[] userPassword = user.split(":"); + String username = userPassword[0]; + String password = userPassword[1]; + userManager.create(new User(username, password)); + } + server = + SocksServerBuilder.newSocks5ServerBuilder().setSocksMethods(new UsernamePasswordMethod + ()).setUserManager(userManager).setBindPort(port).build(); + } + final SocksProxyServer finalServer = server; + Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { + @Override + public void run() { + finalServer.shutdown(); + logger.info("SOCKS5 sever shutdown"); + } + })); + server.start(); + } + + /** + * Print help information. + */ + public void showHelp() { + System.out.println("Usage: [Options]"); + System.out.println(" --port= Server bind port"); + System.out.println(" --auth= Use username/password authentication"); + System.out.println(" Example: --auth=admin:1234"); + System.out.println(" --auth=admin:1234,root:1234"); + System.out.println(" -h or --help Show help"); + } + + /** + * Shutdown SOCKS5 server. + */ + public void shutdown() { + if (server != null) { + server.shutdown(); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `server` last assigned on line 42 could be null and is dereferenced at line 43. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Socks5Server.main(java.lang.String[]) + +### Procedure Id: +fucksocks.quickstart.Socks5Server.main(java.lang.String[]):void.2d56cc903f451f877ee9b3de6f5f3274 + +### File: +src/main/java/fucksocks/quickstart/Socks5Server.java + +### Key: +Socks5Server.java|main|NULL_DEREFERENCE + +### Node Key: +d46e1684de2ca326ba231ad8a5b48143 + +### Hash: +c29502f06e81f31c3859b63d6d6b9139 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6851/instruction.md b/inferredbugs-6851/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10ddc6c2d326ad43f3abcabe10f37ce4ebf1fb15 --- /dev/null +++ b/inferredbugs-6851/instruction.md @@ -0,0 +1,277 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** walkmod-core +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + Copyright (C) 2013 Raquel Pau and Albert Coroleu. + + Walkmod is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Walkmod is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with Walkmod. If not, see .*/ +package org.walkmod.commands; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.walkmod.OptionsBuilder; +import org.walkmod.WalkModFacade; +import org.walkmod.conf.entities.Configuration; +import org.walkmod.conf.entities.PluginConfig; +import org.walkmod.conf.entities.impl.PluginConfigImpl; +import org.walkmod.exceptions.WalkModException; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.fastjson.parser.DefaultJSONParser; +import com.beust.jcommander.JCommander; +import com.beust.jcommander.Parameter; +import com.beust.jcommander.Parameters; + +import de.vandermeer.asciitable.v2.V2_AsciiTable; + +@Parameters(separators = "=", commandDescription = "Shows the available walkmod plugins created by the community.") +public class PrintPluginsCommand implements Command, AsciiTableAware { + + public final static String MVN_SEARCH_URL = "https://search.maven.org/solrsearch/select?q=walkmod&&rows=50&&wt=json"; + + public final static String ARTIFACT_DETAILS_URL = "https://search.maven.org/remotecontent?filepath="; + + @Parameter(names = "--help", help = true, hidden = true) + private boolean help; + + private JCommander command; + + private V2_AsciiTable at = null; + + public PrintPluginsCommand(JCommander command) { + this.command = command; + } + + public void execute() { + if (help) { + command.usage("init"); + } else { + try { + WalkModFacade facade = new WalkModFacade(OptionsBuilder.options()); + Configuration cfg = facade.getConfiguration(); + Collection installedPlugins = cfg.getPlugins(); + URL searchURL = new URL(MVN_SEARCH_URL); + InputStream is = null; + Map installedList = new LinkedHashMap(); + Map pluginsList = new LinkedHashMap(); + Map pluginsURLs = new LinkedHashMap(); + try { + is = searchURL.openStream(); + + String content = readInputStreamAsString(is); + DefaultJSONParser parser = new DefaultJSONParser(content); + JSONObject object = parser.parseObject(); + parser.close(); + + JSONArray artifactList = (object.getJSONObject("response")).getJSONArray("docs"); + + for (int i = 0; i < artifactList.size(); i++) { + JSONObject artifact = artifactList.getJSONObject(i); + String artifactId = artifact.getString("a"); + if (artifactId.startsWith("walkmod-") && artifactId.endsWith("-plugin")) { + String groupId = artifact.getString("g"); + String latestVersion = artifact.getString("latestVersion"); + String pom = artifactId + "-" + latestVersion + ".pom"; + String directory = groupId.replaceAll("\\.", "/"); + + URL artifactDetailsURL = new URL(ARTIFACT_DETAILS_URL + directory + "/" + artifactId + "/" + + latestVersion + "/" + pom); + + InputStream projectIs = artifactDetailsURL.openStream(); + + try { + DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); + Document doc = dBuilder.parse(projectIs); + + NodeList nList = doc.getElementsByTagName("description"); + String description = "unavailable description"; + if (nList.getLength() == 1) { + description = nList.item(0).getTextContent(); + } + String id = ""; + if (!groupId.equals("org.walkmod")) { + id = groupId + ":"; + } + id += artifactId.substring("walkmod-".length(), + artifactId.length() - "-plugin".length()); + + if (Character.isLowerCase(description.charAt(0))) { + description = Character.toUpperCase(description.charAt(0)) + + description.substring(1, description.length()); + } + if (!description.endsWith(".")) { + description = description + "."; + } + pluginsList.put(id, description); + nList = doc.getChildNodes().item(0).getChildNodes(); + int max = nList.getLength(); + String url = "unavailable url"; + + for (int j = 0; j < max; j++) { + String name = nList.item(j).getNodeName(); + if (name.equals("url")) { + url = nList.item(j).getTextContent(); + j = max; + } + } + + pluginsURLs.put(id, url); + + PluginConfig equivalentPluginCfg = new PluginConfigImpl(); + equivalentPluginCfg.setGroupId(groupId); + equivalentPluginCfg.setArtifactId(artifactId); + + boolean isInstalled = (installedPlugins != null && installedPlugins + .contains(equivalentPluginCfg)); + + installedList.put(id, isInstalled); + + } finally { + projectIs.close(); + } + } + } + } finally { + is.close(); + } + Set keys = pluginsList.keySet(); + List sortedKeys = new LinkedList(keys); + Collections.sort(sortedKeys); + + at = new V2_AsciiTable(); + at.addRule(); + at.addRow("PLUGIN NAME (ID)", "INSTALLED", "URL (DOCUMENTATION)", "DESCRIPTION"); + at.addStrongRule(); + for (String key : sortedKeys) { + String installed = ""; + if (installedList.get(key)) { + installed = "*"; + } + at.addRow(key, installed, pluginsURLs.get(key), pluginsList.get(key)); + } + at.addRule(); + + } catch (Exception e) { + throw new WalkModException("Invalid plugins URL", e); + } + } + } + + private String readInputStreamAsString(InputStream is) throws IOException { + InputStreamReader reader = new InputStreamReader(is); + BufferedReader br = new BufferedReader(reader); + String line = br.readLine(); + String response = ""; + while (line != null) { + response += line + '\n'; + line = br.readLine(); + } + return response; + } + + @Override + public V2_AsciiTable getTable() { + return at; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `cfg` last assigned on line 76 could be null and is dereferenced at line 77. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PrintPluginsCommand.execute() + +### Procedure Id: +org.walkmod.commands.PrintPluginsCommand.execute():void.346c15478b583b4bacf0b1d02fb52e71 + +### File: +src/main/java/org/walkmod/commands/PrintPluginsCommand.java + +### Key: +PrintPluginsCommand.java|execute|NULL_DEREFERENCE + +### Node Key: +21bbf00bf52cbb29c85ade37dbbc751f + +### Hash: +bc004945b14f927a551885c4087d596f + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6856/instruction.md b/inferredbugs-6856/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dad1f6ed075648c672b69702a657ed37b64d9fb6 --- /dev/null +++ b/inferredbugs-6856/instruction.md @@ -0,0 +1,242 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webcam-capture +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.sarxos.webcam; + +import java.awt.Graphics; +import java.awt.image.BufferedImage; + +import javax.swing.JPanel; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * Simply implementation of JPanel allowing users to render pictures taken with + * webcam. + * + * @author Bartosz Firyn (SarXos) + */ +public class WebcamPanel extends JPanel implements WebcamListener { + + private static final long serialVersionUID = 5792962512394656227L; + + private static final Logger LOG = LoggerFactory.getLogger(WebcamPanel.class); + + private double frequency = 5; // Hz + + private class Repainter extends Thread { + + public Repainter() { + setDaemon(true); + } + + @Override + public void run() { + super.run(); + + while (webcam.isOpen()) { + + image = webcam.getImage(); + if (image == null) { + LOG.error("Image is null"); + } + + try { + if (paused) { + synchronized (this) { + this.wait(); + } + } + + Thread.sleep((long) (1000 / frequency)); + + } catch (InterruptedException e) { + LOG.error("Nasty interrupted exception"); + } + + repaint(); + } + } + } + + private Webcam webcam = null; + private BufferedImage image = null; + private Repainter repainter = null; + + public WebcamPanel(Webcam webcam) { + + this.webcam = webcam; + this.webcam.addWebcamListener(this); + + if (!webcam.isOpen()) { + webcam.open(); + } + + setPreferredSize(webcam.getViewSize()); + + if (repainter == null) { + repainter = new Repainter(); + repainter.start(); + } + } + + @Override + protected void paintComponent(Graphics g) { + + super.paintComponent(g); + + if (image == null) { + return; + } + + g.drawImage(image, 0, 0, null); + } + + @Override + public void webcamOpen(WebcamEvent we) { + if (repainter == null) { + repainter = new Repainter(); + repainter.start(); + } + setPreferredSize(webcam.getViewSize()); + } + + @Override + public void webcamClosed(WebcamEvent we) { + if (repainter != null) { + if (repainter.isAlive()) { + try { + repainter.join(1000); + } catch (InterruptedException e) { + throw new WebcamException("Thread interrupted", e); + } + } + repainter = null; + } + } + + private volatile boolean paused = false; + + /** + * Pause rendering. + */ + public void pause() { + if (paused) { + return; + } + paused = true; + } + + /** + * Resume rendering. + */ + public void resume() { + if (!paused) { + return; + } + synchronized (repainter) { + repainter.notifyAll(); + } + paused = false; + } + + /** + * @return Rendering frequency (in Hz or FPS). + */ + public double getFrequency() { + return frequency; + } + + private static final double MIN_FREQUENCY = 0.016; // 1 frame per minute + private static final double MAX_FREQUENCY = 25; // 25 frames per second + + /** + * Set rendering frequency (in Hz or FPS). Minimum frequency is 0.016 (1 + * frame per minute) and maximum is 25 (25 frames per second). + * + * @param frequency the frequency + */ + public void setFPS(double frequency) { + if (frequency > MAX_FREQUENCY) { + frequency = MAX_FREQUENCY; + } + if (frequency < MIN_FREQUENCY) { + frequency = MIN_FREQUENCY; + } + this.frequency = frequency; + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.sarxos.webcam.WebcamPanel.resume` reads without synchronization from `this.com.github.sarxos.webcam.WebcamPanel.repainter`. Potentially races with write in method `WebcamPanel.webcamOpen(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WebcamPanel.resume() + +### Procedure Id: +com.github.sarxos.webcam.WebcamPanel.resume():void.88c163150d914d0093fd1088d7e0f5ee + +### File: +webcam-capture/src/main/java/com/github/sarxos/webcam/WebcamPanel.java + +### Key: +WebcamPanel.java|resume|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6a6906d6b7d7f1c5b2e5a657fcbecbd1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6858/instruction.md b/inferredbugs-6858/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2b2d66fa72a29ff7d375948d74f4bf275aca4bc9 --- /dev/null +++ b/inferredbugs-6858/instruction.md @@ -0,0 +1,483 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webcam-capture +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.sarxos.webcam.ds.gstreamer; + +import java.awt.Dimension; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.io.File; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.bridj.Platform; +import org.gstreamer.Caps; +import org.gstreamer.Element; +import org.gstreamer.ElementFactory; +import org.gstreamer.Pad; +import org.gstreamer.Pipeline; +import org.gstreamer.State; +import org.gstreamer.Structure; +import org.gstreamer.elements.RGBDataSink; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.sarxos.webcam.WebcamDevice; +import com.github.sarxos.webcam.WebcamResolution; + + +public class GStreamerDevice implements WebcamDevice, RGBDataSink.Listener, WebcamDevice.FPSSource { + + /** + * Logger. + */ + private static final Logger LOG = LoggerFactory.getLogger(GStreamerDevice.class); + + /** + * Limit the lateness of frames to no more than 20ms (half a frame at 25fps) + */ + private static final long LATENESS = 20; // ms + + /** + * First formats are better. For example video/x-raw-rgb gives 30 FPS on HD720p where + * video/x-raw-yuv only 10 FPS on the same resolution. The goal is to use these "better" formats + * first, and then fallback to less efficient when not available. + */ + private static final String[] BEST_FORMATS = { + "video/x-raw-rgb", + "video/x-raw-yuv", + }; + + /** + * Video format to capture. + */ + private String format; + + /** + * All possible resolutions - populated while initialization phase. + */ + private Dimension[] resolutions = null; + + /** + * Device name, immutable. Used only on Windows platform. + */ + private final String name; + /** + * Device name, immutable. Used only on Linux platform. + */ + private final File vfile; + + /* gstreamer stuff */ + + private Pipeline pipe = null; + private Element source = null; + private Element filter = null; + private RGBDataSink sink = null; + + private Caps caps = null; + + /* logic */ + + private AtomicBoolean open = new AtomicBoolean(false); + private AtomicBoolean disposed = new AtomicBoolean(false); + private AtomicBoolean starting = new AtomicBoolean(false); + private AtomicBoolean initialized = new AtomicBoolean(false); + private Dimension resolution = WebcamResolution.VGA.getSize(); + private BufferedImage image = null; + + /* used to calculate fps */ + + private long t1 = -1; + private long t2 = -1; + + private volatile double fps = 0; + + /** + * Create GStreamer webcam device. + * + * @param name the name of webcam device + */ + protected GStreamerDevice(String name) { + this.name = name; + this.vfile = null; + } + + protected GStreamerDevice(File vfile) { + this.name = null; + this.vfile = vfile; + } + + /** + * Initialize webcam device. + */ + private synchronized void init() { + + if (!initialized.compareAndSet(false, true)) { + return; + } + + LOG.debug("GStreamer webcam device initialization"); + + pipe = new Pipeline(name); + + if (Platform.isWindows()) { + source = ElementFactory.make("dshowvideosrc", "source"); + source.set("device-name", name); + } else if (Platform.isLinux()) { + source = ElementFactory.make("v4l2src", "source"); + source.set("device", vfile.getAbsolutePath()); + } + + sink = new RGBDataSink(name, this); + sink.setPassDirectBuffer(true); + sink.getSinkElement().setMaximumLateness(LATENESS, TimeUnit.MILLISECONDS); + sink.getSinkElement().setQOSEnabled(true); + + filter = ElementFactory.make("capsfilter", "filter"); + + if (Platform.isLinux()) { + pipe.addMany(source, filter, sink); + Element.linkMany(source, filter, sink); + pipe.setState(State.READY); + } + + resolutions = parseResolutions(source.getPads().get(0)); + + if (Platform.isLinux()) { + pipe.setState(State.NULL); + Element.unlinkMany(source, filter, sink); + pipe.removeMany(source, filter, sink); + } + } + + /** + * Use GStreamer to get all possible resolutions. + * + * @param pad the pad to get resolutions from + * @return Array of resolutions supported by device connected with pad + */ + private Dimension[] parseResolutions(Pad pad) { + + Caps caps = pad.getCaps(); + + format = findBestFormat(caps); + + LOG.debug("Best format is {}", format); + + Dimension r = null; + Structure s = null; + String mime = null; + + int n = caps.size(); + int i = 0; + + Map map = new HashMap(); + + do { + + s = caps.getStructure(i++); + + LOG.debug("Found format structure {}", s); + + mime = s.getName(); + + if (mime.equals(format)) { + if ((r = capStructToResolution(s)) != null) { + map.put(r.width + "x" + r.height, r); + } + } + + } while (i < n); + + Dimension[] resolutions = new ArrayList(map.values()).toArray(new Dimension[map.size()]); + + if (LOG.isDebugEnabled()) { + for (Dimension d : resolutions) { + LOG.debug("Resolution detected {}", d); + } + } + + return resolutions; + } + + private static String findBestFormat(Caps caps) { + for (String f : BEST_FORMATS) { + for (int i = 0, n = caps.size(); i < n; i++) { + if (f.equals(caps.getStructure(i).getName())) { + return f; + } + } + } + return null; + } + + private static Dimension capStructToResolution(Structure structure) { + + int w = -1; + int h = -1; + + if (Platform.isWindows()) { + w = structure.getRange("width").getMinInt(); + h = structure.getRange("height").getMinInt(); + } else if (Platform.isLinux()) { + w = structure.getInteger("width"); + h = structure.getInteger("height"); + } + + if (w > 0 && h > 0) { + return new Dimension(w, h); + } else { + return null; + } + } + + @Override + public String getName() { + if (Platform.isWindows()) { + return name; + } else if (Platform.isLinux()) { + return vfile.getAbsolutePath(); + } else { + throw new RuntimeException("Platform not supported by GStreamer capture driver"); + } + } + + @Override + public Dimension[] getResolutions() { + init(); + return resolutions; + } + + @Override + public Dimension getResolution() { + return resolution; + } + + @Override + public void setResolution(Dimension size) { + this.resolution = size; + } + + @Override + public BufferedImage getImage() { + return image; + } + + @Override + public void open() { + + if (!open.compareAndSet(false, true)) { + return; + } + + LOG.debug("Opening GStreamer device"); + + init(); + + starting.set(true); + + Dimension size = getResolution(); + + image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + image.setAccelerationPriority(0); + image.flush(); + + if (caps != null) { + caps.dispose(); + } + + caps = Caps.fromString(String.format("%s,width=%d,height=%d", format, size.width, size.height)); + + filter.setCaps(caps); + + LOG.debug("Link elements"); + + pipe.addMany(source, filter, sink); + Element.linkMany(source, filter, sink); + pipe.setState(State.PLAYING); + + // wait max 20s for image to appear + synchronized (this) { + LOG.debug("Wait for device to be ready"); + try { + this.wait(20000); + } catch (InterruptedException e) { + return; + } + } + } + + @Override + public void close() { + + if (!open.compareAndSet(true, false)) { + return; + } + + LOG.debug("Closing GStreamer device"); + + image = null; + + LOG.debug("Unlink elements"); + + pipe.setState(State.NULL); + Element.unlinkMany(source, filter, sink); + pipe.removeMany(source, filter, sink); + } + + @Override + public void dispose() { + + if (!disposed.compareAndSet(false, true)) { + return; + } + + LOG.debug("Disposing GStreamer device"); + + close(); + + filter.dispose(); + source.dispose(); + sink.dispose(); + pipe.dispose(); + caps.dispose(); + } + + @Override + public boolean isOpen() { + return open.get(); + } + + @Override + public void rgbFrame(boolean preroll, int width, int height, IntBuffer rgb) { + + LOG.trace("New RGB frame"); + + if (t1 == -1 || t2 == -1) { + t1 = System.currentTimeMillis(); + t2 = System.currentTimeMillis(); + } + + BufferedImage tmp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + tmp.setAccelerationPriority(0); + rgb.get(((DataBufferInt) tmp.getRaster().getDataBuffer()).getData(), 0, width * height); + tmp.flush(); + + image = tmp; + + if (starting.compareAndSet(true, false)) { + + synchronized (this) { + this.notifyAll(); + } + + LOG.debug("GStreamer device ready"); + } + + t1 = t2; + t2 = System.currentTimeMillis(); + + fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5; + } + + @Override + public double getFPS() { + return fps; + } + + public Pipeline getPipe() { + return pipe; + } + + public Element getSource() { + return source; + } + + public Element getFilter() { + return filter; + } + + public RGBDataSink getSink() { + return sink; + } + + public Caps getCaps() { + return caps; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.dispose` indirectly writes to field `this.com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.image` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GStreamerDevice.dispose() + +### Procedure Id: +com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.dispose():void.664cce93066d1f38fb38544c1fbfc122 + +### File: +webcam-capture-drivers/driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDevice.java + +### Key: +GStreamerDevice.java|dispose|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +d8bc6fd5bed83f6954eda379df7213f5 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6860/instruction.md b/inferredbugs-6860/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7faaf7446d6070219f9c7bb67f79aa97db041316 --- /dev/null +++ b/inferredbugs-6860/instruction.md @@ -0,0 +1,483 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** webcam-capture +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.sarxos.webcam.ds.gstreamer; + +import java.awt.Dimension; +import java.awt.image.BufferedImage; +import java.awt.image.DataBufferInt; +import java.io.File; +import java.nio.IntBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.bridj.Platform; +import org.gstreamer.Caps; +import org.gstreamer.Element; +import org.gstreamer.ElementFactory; +import org.gstreamer.Pad; +import org.gstreamer.Pipeline; +import org.gstreamer.State; +import org.gstreamer.Structure; +import org.gstreamer.elements.RGBDataSink; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.sarxos.webcam.WebcamDevice; +import com.github.sarxos.webcam.WebcamResolution; + + +public class GStreamerDevice implements WebcamDevice, RGBDataSink.Listener, WebcamDevice.FPSSource { + + /** + * Logger. + */ + private static final Logger LOG = LoggerFactory.getLogger(GStreamerDevice.class); + + /** + * Limit the lateness of frames to no more than 20ms (half a frame at 25fps) + */ + private static final long LATENESS = 20; // ms + + /** + * First formats are better. For example video/x-raw-rgb gives 30 FPS on HD720p where + * video/x-raw-yuv only 10 FPS on the same resolution. The goal is to use these "better" formats + * first, and then fallback to less efficient when not available. + */ + private static final String[] BEST_FORMATS = { + "video/x-raw-rgb", + "video/x-raw-yuv", + }; + + /** + * Video format to capture. + */ + private String format; + + /** + * All possible resolutions - populated while initialization phase. + */ + private Dimension[] resolutions = null; + + /** + * Device name, immutable. Used only on Windows platform. + */ + private final String name; + /** + * Device name, immutable. Used only on Linux platform. + */ + private final File vfile; + + /* gstreamer stuff */ + + private Pipeline pipe = null; + private Element source = null; + private Element filter = null; + private RGBDataSink sink = null; + + private Caps caps = null; + + /* logic */ + + private AtomicBoolean open = new AtomicBoolean(false); + private AtomicBoolean disposed = new AtomicBoolean(false); + private AtomicBoolean starting = new AtomicBoolean(false); + private AtomicBoolean initialized = new AtomicBoolean(false); + private Dimension resolution = WebcamResolution.VGA.getSize(); + private BufferedImage image = null; + + /* used to calculate fps */ + + private long t1 = -1; + private long t2 = -1; + + private volatile double fps = 0; + + /** + * Create GStreamer webcam device. + * + * @param name the name of webcam device + */ + protected GStreamerDevice(String name) { + this.name = name; + this.vfile = null; + } + + protected GStreamerDevice(File vfile) { + this.name = null; + this.vfile = vfile; + } + + /** + * Initialize webcam device. + */ + private synchronized void init() { + + if (!initialized.compareAndSet(false, true)) { + return; + } + + LOG.debug("GStreamer webcam device initialization"); + + pipe = new Pipeline(name); + + if (Platform.isWindows()) { + source = ElementFactory.make("dshowvideosrc", "source"); + source.set("device-name", name); + } else if (Platform.isLinux()) { + source = ElementFactory.make("v4l2src", "source"); + source.set("device", vfile.getAbsolutePath()); + } + + sink = new RGBDataSink(name, this); + sink.setPassDirectBuffer(true); + sink.getSinkElement().setMaximumLateness(LATENESS, TimeUnit.MILLISECONDS); + sink.getSinkElement().setQOSEnabled(true); + + filter = ElementFactory.make("capsfilter", "filter"); + + if (Platform.isLinux()) { + pipe.addMany(source, filter, sink); + Element.linkMany(source, filter, sink); + pipe.setState(State.READY); + } + + resolutions = parseResolutions(source.getPads().get(0)); + + if (Platform.isLinux()) { + pipe.setState(State.NULL); + Element.unlinkMany(source, filter, sink); + pipe.removeMany(source, filter, sink); + } + } + + /** + * Use GStreamer to get all possible resolutions. + * + * @param pad the pad to get resolutions from + * @return Array of resolutions supported by device connected with pad + */ + private Dimension[] parseResolutions(Pad pad) { + + Caps caps = pad.getCaps(); + + format = findBestFormat(caps); + + LOG.debug("Best format is {}", format); + + Dimension r = null; + Structure s = null; + String mime = null; + + int n = caps.size(); + int i = 0; + + Map map = new HashMap(); + + do { + + s = caps.getStructure(i++); + + LOG.debug("Found format structure {}", s); + + mime = s.getName(); + + if (mime.equals(format)) { + if ((r = capStructToResolution(s)) != null) { + map.put(r.width + "x" + r.height, r); + } + } + + } while (i < n); + + Dimension[] resolutions = new ArrayList(map.values()).toArray(new Dimension[map.size()]); + + if (LOG.isDebugEnabled()) { + for (Dimension d : resolutions) { + LOG.debug("Resolution detected {}", d); + } + } + + return resolutions; + } + + private static String findBestFormat(Caps caps) { + for (String f : BEST_FORMATS) { + for (int i = 0, n = caps.size(); i < n; i++) { + if (f.equals(caps.getStructure(i).getName())) { + return f; + } + } + } + return null; + } + + private static Dimension capStructToResolution(Structure structure) { + + int w = -1; + int h = -1; + + if (Platform.isWindows()) { + w = structure.getRange("width").getMinInt(); + h = structure.getRange("height").getMinInt(); + } else if (Platform.isLinux()) { + w = structure.getInteger("width"); + h = structure.getInteger("height"); + } + + if (w > 0 && h > 0) { + return new Dimension(w, h); + } else { + return null; + } + } + + @Override + public String getName() { + if (Platform.isWindows()) { + return name; + } else if (Platform.isLinux()) { + return vfile.getAbsolutePath(); + } else { + throw new RuntimeException("Platform not supported by GStreamer capture driver"); + } + } + + @Override + public Dimension[] getResolutions() { + init(); + return resolutions; + } + + @Override + public Dimension getResolution() { + return resolution; + } + + @Override + public void setResolution(Dimension size) { + this.resolution = size; + } + + @Override + public BufferedImage getImage() { + return image; + } + + @Override + public void open() { + + if (!open.compareAndSet(false, true)) { + return; + } + + LOG.debug("Opening GStreamer device"); + + init(); + + starting.set(true); + + Dimension size = getResolution(); + + image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); + image.setAccelerationPriority(0); + image.flush(); + + if (caps != null) { + caps.dispose(); + } + + caps = Caps.fromString(String.format("%s,width=%d,height=%d", format, size.width, size.height)); + + filter.setCaps(caps); + + LOG.debug("Link elements"); + + pipe.addMany(source, filter, sink); + Element.linkMany(source, filter, sink); + pipe.setState(State.PLAYING); + + // wait max 20s for image to appear + synchronized (this) { + LOG.debug("Wait for device to be ready"); + try { + this.wait(20000); + } catch (InterruptedException e) { + return; + } + } + } + + @Override + public void close() { + + if (!open.compareAndSet(true, false)) { + return; + } + + LOG.debug("Closing GStreamer device"); + + image = null; + + LOG.debug("Unlink elements"); + + pipe.setState(State.NULL); + Element.unlinkMany(source, filter, sink); + pipe.removeMany(source, filter, sink); + } + + @Override + public void dispose() { + + if (!disposed.compareAndSet(false, true)) { + return; + } + + LOG.debug("Disposing GStreamer device"); + + close(); + + filter.dispose(); + source.dispose(); + sink.dispose(); + pipe.dispose(); + caps.dispose(); + } + + @Override + public boolean isOpen() { + return open.get(); + } + + @Override + public void rgbFrame(boolean preroll, int width, int height, IntBuffer rgb) { + + LOG.trace("New RGB frame"); + + if (t1 == -1 || t2 == -1) { + t1 = System.currentTimeMillis(); + t2 = System.currentTimeMillis(); + } + + BufferedImage tmp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + tmp.setAccelerationPriority(0); + rgb.get(((DataBufferInt) tmp.getRaster().getDataBuffer()).getData(), 0, width * height); + tmp.flush(); + + image = tmp; + + if (starting.compareAndSet(true, false)) { + + synchronized (this) { + this.notifyAll(); + } + + LOG.debug("GStreamer device ready"); + } + + t1 = t2; + t2 = System.currentTimeMillis(); + + fps = (4 * fps + 1000 / (t2 - t1 + 1)) / 5; + } + + @Override + public double getFPS() { + return fps; + } + + public Pipeline getPipe() { + return pipe; + } + + public Element getSource() { + return source; + } + + public Element getFilter() { + return filter; + } + + public RGBDataSink getSink() { + return sink; + } + + public Caps getCaps() { + return caps; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.open` reads without synchronization from `this.com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.sink`. Potentially races with write in method `GStreamerDevice.open()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GStreamerDevice.open() + +### Procedure Id: +com.github.sarxos.webcam.ds.gstreamer.GStreamerDevice.open():void.dfec049d772f6ef69be774e4cb67ce48 + +### File: +webcam-capture-drivers/driver-gstreamer/src/main/java/com/github/sarxos/webcam/ds/gstreamer/GStreamerDevice.java + +### Key: +GStreamerDevice.java|open|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +49840db43338981323e15beb834c3359 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6867/instruction.md b/inferredbugs-6867/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b15611ed97ed1c4b485cb0e4ed3d668cb11271d6 --- /dev/null +++ b/inferredbugs-6867/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** brave +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.kristofa.brave; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.Random; + +import com.github.kristofa.brave.example.TestServerClientAndLocalSpanStateCompilation; +import com.github.kristofa.brave.internal.Util; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.twitter.zipkin.gen.Endpoint; +import com.twitter.zipkin.gen.Span; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AnnotationSubmitter.class, LocalTracer.class}) +public class LocalTracerTest { + + private static final long PARENT_TRACE_ID = 105; + private static final long PARENT_SPAN_ID = 103; + private static final String COMPONENT_NAME = "componentname"; + private static final String OPERATION_NAME = "operationname"; + + private ServerClientAndLocalSpanState state; + private Random mockRandom; + private SpanCollector mockCollector; + private LocalTracer localTracer; + + @Before + public void setup() { + mockRandom = mock(Random.class); + when(mockRandom.nextLong()).thenReturn(555L); + + mockCollector = mock(SpanCollector.class); + + PowerMockito.mockStatic(System.class); + state = new TestServerClientAndLocalSpanStateCompilation(); + localTracer = LocalTracer.builder() + .spanAndEndpoint(SpanAndEndpoint.LocalSpanAndEndpoint.create(state)) + .randomGenerator(mockRandom) + .spanCollector(mockCollector) + .allowNestedLocalSpans(false) + .traceSampler(Sampler.create(1.0f)) + .clock(AnnotationSubmitter.DefaultClock.INSTANCE) + .build(); + } + + /** + * When a local span is started without a timestamp, microseconds and a tick are recorded for + * duration calculation. A binary annotation is added for search by component. + *

+ *

Ex. + *

+     * localTracer.startNewSpan(component, operation); // internally time and nanos are recorded
+     * 
+ */ + @Test + public void startNewSpan() { + state.setCurrentServerSpan(ServerSpan.create(PARENT_TRACE_ID, PARENT_SPAN_ID, null, "name")); + + PowerMockito.when(System.currentTimeMillis()).thenReturn(1L); + PowerMockito.when(System.nanoTime()).thenReturn(500L); + + SpanId expectedSpanId = + SpanId.builder().traceId(PARENT_TRACE_ID).spanId(555L).parentId(PARENT_SPAN_ID).build(); + + assertEquals(expectedSpanId, localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME)); + + Span started = state.getCurrentLocalSpan(); + + assertEquals(1000L, started.getTimestamp().longValue()); + assertEquals(500L, started.startTick.longValue()); + assertEquals("lc", started.getBinary_annotations().get(0).getKey()); + assertEquals(COMPONENT_NAME, new String(started.getBinary_annotations().get(0).getValue(), Util.UTF_8)); + assertEquals(state.endpoint(), started.getBinary_annotations().get(0).host); + assertEquals(OPERATION_NAME, started.getName()); + } + + /** + * When a span is started with a timestamp, we can't use nanotime for duration as we don't + * know the nanotime value for that timestamp. + *

+ *

Ex. + *

+     * localTracer.startNewSpan(component, operation, startTime);
+     *
+     * 
+ */ + @Test + public void startSpan_userSuppliedTimestamp() { + state.setCurrentServerSpan(ServerSpan.create(PARENT_TRACE_ID, PARENT_SPAN_ID, null, "name")); + + localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME, 1000L); + + Span started = state.getCurrentLocalSpan(); + assertEquals(1000L, started.getTimestamp().longValue()); + assertNull(started.startTick); + } + + @Test + public void startSpan_unsampled() { + localTracer = LocalTracer + .builder(localTracer) + .traceSampler(Sampler.create(0.0f)).build(); + + assertNull(localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME)); + } + + /** + * When finish is called without a duration, the startTick from start is used in duration calculation. + *

+ *

Ex. + *

+     * localTracer.startSpan(component, operation); // internally nanos is recorded with system time.
+     * ...
+     * localTracer.finishSpan(); // above nanos is used to make a precise duration
+     * 
+ */ + @Test + public void finishSpan() { + Span finished = new Span().setTimestamp(1000L); // set in start span + finished.startTick = 500000L; // set in start span + state.setCurrentLocalSpan(finished); + + PowerMockito.when(System.nanoTime()).thenReturn(1000000L); + + localTracer.finishSpan(); + + verify(mockCollector).collect(finished); + verifyNoMoreInteractions(mockCollector); + + assertEquals(500L, finished.getDuration().longValue()); + } + + /** Duration of less than one microsecond is confusing to plot and could coerce to null. */ + @Test + public void finishSpan_lessThanMicrosRoundUp() { + Span finished = new Span().setTimestamp(1000L); // set in start span + finished.startTick = 500L; // set in start span + state.setCurrentLocalSpan(finished); + + PowerMockito.when(System.nanoTime()).thenReturn(1000L); + + localTracer.finishSpan(); + + verify(mockCollector).collect(finished); + verifyNoMoreInteractions(mockCollector); + + assertEquals(1L, finished.getDuration().longValue()); + } + + /** + * When a span is started with a timestamp, nanos aren't known, so duration calculation falls back to system time. + *

+ *

Ex. + *

+     * localTracer.startSpan(component, operation, startTime); // no tick was recorded
+     * ...
+     * localTracer.finishSpan(); // can't know which nanos startTime was associated with!
+     * 
+ */ + @Test + public void finishSpan_userSuppliedTimestamp() { + Span finished = new Span().setTimestamp(1000L); // Set by user + state.setCurrentLocalSpan(finished); + + PowerMockito.when(System.currentTimeMillis()).thenReturn(2L); + + localTracer.finishSpan(); + + verify(mockCollector).collect(finished); + verifyNoMoreInteractions(mockCollector); + + assertEquals(1000L, finished.getDuration().longValue()); + } + + /** + * When a local span completes with a user supplied duration, startTick is ignored. + *

+ *

Ex. + *

+     * localTracer.startSpan(component, operation); // startTick was recorded, but ignored
+     * ...
+     * localTracer.finishSpan(duration); // user calculated duration out-of-band, ex with a stop watch.
+     * 
+ */ + @Test + public void finishSpan_userSuppliedDuration() { + Span finished = new Span().setTimestamp(1000L); // set in start span + finished.startTick = 500L; // set in start span + state.setCurrentLocalSpan(finished); + + localTracer.finishSpan(500L); + + verify(mockCollector).collect(finished); + verifyNoMoreInteractions(mockCollector); + + assertEquals(500L, finished.getDuration().longValue()); + } + + /** + * When a span starts and finishes with user-supplied timestamp and duration, nanotime is used + *

+ *

Ex. + *

+     * localTracer.startSpan(component, operation, startTime); // startTick was recorded
+     * ...
+     * localTracer.finishSpan(duration); // nanoTime - startTick = duration
+     * 
+ */ + @Test + public void finishSpan_userSuppliedTimestampAndDuration() { + Span finished = new Span().setTimestamp(1000L); // Set by user + state.setCurrentLocalSpan(finished); + + localTracer.finishSpan(500L); + + verify(mockCollector).collect(finished); + verifyNoMoreInteractions(mockCollector); + + assertEquals(500L, finished.getDuration().longValue()); + } + + @Test + public void finishSpan_unsampled() { + state.setCurrentLocalSpan(null); + + localTracer.finishSpan(); + + verifyNoMoreInteractions(mockCollector); + } + + @Test + public void finishSpan_unsampled_userSuppliedDuration() { + state.setCurrentLocalSpan(null); + + localTracer.finishSpan(5000L); + + verifyNoMoreInteractions(mockCollector); + } + + @Test + public void startSpan_with_inheritable_nested_local_spans() { + state = new InheritableServerClientAndLocalSpanState(Endpoint.create("test-service", 127 << 24 | 1)); + localTracer = LocalTracer + .builder(localTracer) + .spanAndEndpoint(SpanAndEndpoint.LocalSpanAndEndpoint.create(state)) + .allowNestedLocalSpans(true) + .build(); + + assertNull(localTracer.getNewSpanParent()); + state.setCurrentServerSpan(ServerSpan.create(PARENT_TRACE_ID, PARENT_SPAN_ID, null, "name")); + + SpanId span1 = localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME); + assertEquals(SpanId.builder().traceId(PARENT_TRACE_ID).spanId(555L).parentId(PARENT_SPAN_ID).build(), span1); + assertEquals(span1.spanId, localTracer.getNewSpanParent().getId()); + + SpanId span2 = localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME); + assertEquals(SpanId.builder().traceId(PARENT_TRACE_ID).spanId(555L).parentId(span1.spanId).build(), span2); + assertEquals(span2.spanId, localTracer.getNewSpanParent().getId()); + + assertEquals(span2.spanId, state.getCurrentLocalSpan().getId()); + localTracer.finishSpan(); + assertEquals(span1.spanId, state.getCurrentLocalSpan().getId()); + localTracer.finishSpan(); + assertNull(state.getCurrentLocalSpan()); + } + + @Test + public void startSpan_nested_local_spans_disabled() { + state = new InheritableServerClientAndLocalSpanState(Endpoint.create("test-service", 127 << 24 | 1)); + localTracer = LocalTracer + .builder(localTracer) + .spanAndEndpoint(SpanAndEndpoint.LocalSpanAndEndpoint.create(state)) + .allowNestedLocalSpans(false) + .build(); + + assertNull(localTracer.getNewSpanParent()); + final ServerSpan serverSpan = ServerSpan.create(PARENT_TRACE_ID, PARENT_SPAN_ID, null, "name"); + state.setCurrentServerSpan(serverSpan); + + SpanId span1 = localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME); + assertEquals(SpanId.builder().traceId(PARENT_TRACE_ID).spanId(555L).parentId(PARENT_SPAN_ID).build(), span1); + assertEquals(serverSpan.getSpan(), localTracer.getNewSpanParent()); + + SpanId span2 = localTracer.startNewSpan(COMPONENT_NAME, OPERATION_NAME); + assertEquals(SpanId.builder().traceId(PARENT_TRACE_ID).spanId(555L).parentId(PARENT_SPAN_ID).build(), span2); + assertEquals(serverSpan.getSpan(), localTracer.getNewSpanParent()); + + assertEquals(span2.spanId, state.getCurrentLocalSpan().getId()); + localTracer.finishSpan(); + assertEquals(span1.spanId, state.getCurrentLocalSpan().getId()); + localTracer.finishSpan(); + assertNull(state.getCurrentLocalSpan()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `finished.getDuration()` could be null and is dereferenced at line 186. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LocalTracerTest.finishSpan_userSuppliedTimestamp() + +### Procedure Id: +com.github.kristofa.brave.LocalTracerTest.finishSpan_userSuppliedTimestamp():void.e65bb70c22e84ce0ef7bd330aee526d5 + +### File: +brave-core/src/test/java/com/github/kristofa/brave/LocalTracerTest.java + +### Key: +LocalTracerTest.java|finishSpan_userSuppliedTimestamp|NULL_DEREFERENCE + +### Node Key: +aa66545b443e053e1949db82c636558b + +### Hash: +5ae91cac0db2dfa12054c61811e25d6a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6869/instruction.md b/inferredbugs-6869/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4960b0b9bcc011eb91ac889659fa52c00b5c8052 --- /dev/null +++ b/inferredbugs-6869/instruction.md @@ -0,0 +1,127 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** brave +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.kristofa.brave; + +import java.util.concurrent.Callable; + +import com.github.kristofa.brave.internal.Nullable; +import com.google.auto.value.AutoValue; + +/** + * Callable implementation that wraps another Callable and makes sure the wrapped Callable will be executed in the same + * Span/Trace context as the thread from which the Callable was executed. + *

+ * Is used by {@link BraveExecutorService}. + * + * @author kristof + * @param Return type. + * @see BraveExecutorService + */ +@AutoValue +public abstract class BraveCallable implements Callable { + + /** + * Creates a new instance. + * + * @param wrappedCallable The wrapped Callable. + * @param serverSpanThreadBinder ServerSpan thread binder. + */ + public static BraveCallable create(Callable wrappedCallable, ServerSpanThreadBinder serverSpanThreadBinder) { + return new AutoValue_BraveCallable(wrappedCallable, serverSpanThreadBinder, serverSpanThreadBinder.getCurrentServerSpan()); + } + + abstract Callable wrappedCallable(); + abstract ServerSpanThreadBinder serverSpanThreadBinder(); + @Nullable + abstract ServerSpan currentServerSpan(); + + /** + * {@inheritDoc} + */ + @Override + public T call() throws Exception { + serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); + final long start = System.currentTimeMillis(); + try { + return wrappedCallable().call(); + } finally { + final long duration = System.currentTimeMillis() - start; + currentServerSpan().incThreadDuration(duration); + } + } + + BraveCallable() { + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `currentServerSpan()` at line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object BraveCallable.call() + +### Procedure Id: +com.github.kristofa.brave.BraveCallable.call():java.lang.Object.328271754033364cf7dcc007ef14eebc + +### File: +brave-core/src/main/java/com/github/kristofa/brave/BraveCallable.java + +### Key: +BraveCallable.java|call|NULL_DEREFERENCE + +### Node Key: +471a2edb901e769be3ae46e5651fb0cc + +### Hash: +ddff594af07762a63b1c2216bae6d1c6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6893/instruction.md b/inferredbugs-6893/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f5b5bb2db2296b7b50f4f296dbc9267da27b15a --- /dev/null +++ b/inferredbugs-6893/instruction.md @@ -0,0 +1,227 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openpojo +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2010-2015 Osman Shoukry + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License or any + * later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . + */ + +package com.openpojo.random.impl; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Date; +import java.util.Random; + +import com.openpojo.random.RandomFactory; +import com.openpojo.random.RandomGenerator; + +/** + * This is the most basic random generator, it handles all basic java types (20 in total).
+ * Namely:
+ * 1. boolean & Boolean
+ * 2. int & Integer
+ * 3. float & Float
+ * 4. double & Double
+ * 5. long & Long
+ * 6. short & Short
+ * 7. byte & Byte
+ * 8. char & Character
+ * 9. String
+ * 10. Date
+ * 11. Calendar
+ * 12. java.math.BigDecimal
+ * 13. java.math.BigInteger
+ *
+ * You can overwrite any of those types with your own generator and register it with the RandomFactory.
+ * Note:
+ * 1. char & Character random generation is currently limited to the following set of + * characters A-Z, a-z and 0-9.
+ * 2. String random generation relies on the Character random generation, all strings are generated as random sequence + * of characters with length between 1 and 32 inclusive. So If you over-write the Character generator, + * you will implicitly be modifying the types of character the random characters a random String is made of. + * + * @author oshoukry + */ +public final class BasicRandomGenerator implements RandomGenerator { + private static final Random RANDOM = new Random(new Date().getTime()); + private static final int MAX_RANDOM_STRING_LENGTH = 32; + + private BasicRandomGenerator() { + + } + + public static RandomGenerator getInstance() { + return Instance.INSTANCE; + } + + private static final Class[] TYPES = new Class[]{ boolean.class, Boolean.class, int.class, Integer.class, + float.class, Float.class, double.class, Double.class, long.class, Long.class, short.class, Short.class, + byte.class, Byte.class, char.class, Character.class, String.class, Date.class, Calendar.class, BigDecimal.class, + BigInteger.class }; + + private static final char[] CHARACTERS = new char[]{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', + 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', + 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', + '2', '3', '4', '5', '6', '7', '8', '9' }; + + public Object doGenerate(final Class type) { + if (type == boolean.class || type == Boolean.class) { + return RANDOM.nextBoolean(); + } + + if (type == int.class || type == Integer.class) { + return RANDOM.nextInt(); + } + + if (type == BigInteger.class) { + return BigInteger.valueOf(RANDOM.nextLong()); + } + + if (type == float.class || type == Float.class) { + return RANDOM.nextFloat(); + } + + if (type == double.class || type == Double.class) { + return RANDOM.nextDouble(); + } + + if (type == BigDecimal.class) { + return BigDecimal.valueOf(RANDOM.nextDouble()); + } + + if (type == long.class || type == Long.class) { + return RANDOM.nextLong(); + } + + if (type == short.class || type == Short.class) { + return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1)); + } + + if (type == byte.class || type == Byte.class) { + final byte[] randombyte = new byte[1]; + RANDOM.nextBytes(randombyte); + return randombyte[0]; + } + + if (type == char.class || type == Character.class) { + return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)]; + } + + if (type == String.class) { + String randomString = ""; + + /* prevent zero length string lengths */ + for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) { + randomString += RandomFactory.getRandomValue(Character.class); + } + return randomString; + } + + if (type == Date.class) { + return new Date(RandomFactory.getRandomValue(Long.class)); + } + + if (type == Calendar.class) { + final Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class)); + return calendar; + } + + return null; + } + + public Collection> getTypes() { + return Arrays.asList(TYPES); + } + + private static class Instance { + private static final RandomGenerator INSTANCE = new BasicRandomGenerator(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getRandomValue(java.lang.Long)` could be null and is dereferenced at line 134. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object BasicRandomGenerator.doGenerate(Class) + +### Procedure Id: +com.openpojo.random.impl.BasicRandomGenerator.doGenerate(java.lang.Class):java.lang.Object.fa2f088e9087e5e854c279bdf26982f2 + +### File: +src/main/java/com/openpojo/random/impl/BasicRandomGenerator.java + +### Key: +BasicRandomGenerator.java|doGenerate|NULL_DEREFERENCE + +### Node Key: +2ac7bddff590d88d7a98b73e82eb1263 + +### Hash: +275cf54c064961febd8e76165b846a2b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6894/instruction.md b/inferredbugs-6894/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34f90fe97563a59a4fd9ee15faf317423a5744d6 --- /dev/null +++ b/inferredbugs-6894/instruction.md @@ -0,0 +1,203 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openpojo +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2010 Osman Shoukry + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package com.openpojo.reflection.impl; + +import java.io.File; +import java.lang.annotation.Annotation; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import com.openpojo.reflection.PojoClass; +import com.openpojo.reflection.PojoClassFilter; +import com.openpojo.reflection.PojoPackage; +import com.openpojo.reflection.exception.ReflectionException; +import com.openpojo.reflection.utils.PackageHelper; + +/** + * This class represents the abstraction of a JAVA Package as PojoPackageImpl. + * + * @author oshoukry + */ +class PojoPackageImpl implements PojoPackage { + + private final String packageName; + private final PojoClass packageInfoPojoClass; + + public String getName() { + return packageName; + } + + public PojoPackageImpl(final String packageName) { + + this.packageName = packageName; + if (packageName == null) { + throw new IllegalArgumentException("PackageName can not be null"); + } + + validatePackage(); + + Class infoClass = null; + try { + infoClass = Class.forName(packageName + PojoPackage.PACKAGE_DELIMETER + PojoPackage.PACKAGE_INFO); + } catch (ClassNotFoundException e) { + } + if (infoClass != null) { + packageInfoPojoClass = PojoClassFactory.getPojoClass(infoClass); + } else { + packageInfoPojoClass = null; + } + } + + private void validatePackage() { + File packageDirectory; + try { + packageDirectory = PackageHelper.getPackageAsDirectory(packageName); + } catch (ReflectionException re) { + throw re; + } + if (packageDirectory == null || !packageDirectory.exists()) { + throw ReflectionException.getInstance(String.format("[%s] is not a valid package", packageName)); + } + } + + public List getPojoClasses() { + return getPojoClasses(null); + } + + public List getPojoClasses(final PojoClassFilter filter) { + List pojoClasses = new LinkedList(); + + for (Class clazz : PackageHelper.getClasses(packageName)) { + PojoClass pojoClass = PojoClassFactory.getPojoClass(clazz); + if (filter == null || filter.include(pojoClass)) { + pojoClasses.add(pojoClass); + } + } + + return pojoClasses; + } + + public List getPojoSubPackages() { + List pojoPackageSubPackages = new LinkedList(); + + File directory = PackageHelper.getPackageAsDirectory(packageName); + for (File entry : directory.listFiles()) { + if (entry.isDirectory()) { + String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName(); + pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName)); + } + } + + return pojoPackageSubPackages; + } + + public T getAnnotation(final Class annotationClass) { + if (packageInfoPojoClass == null) { + return null; + } + return packageInfoPojoClass.getAnnotation(annotationClass); + } + + public List getAnnotations() { + if (packageInfoPojoClass == null) { + return Collections.emptyList(); + } + return packageInfoPojoClass.getAnnotations(); + } + + @Override + public String toString() { + return String.format("PojoPackageImpl [packageName=%s]", packageName); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `directory.listFiles()` could be null and is dereferenced at line 100. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List PojoPackageImpl.getPojoSubPackages() + +### Procedure Id: +com.openpojo.reflection.impl.PojoPackageImpl.getPojoSubPackages():java.util.List.660140134a5e52d64d29a2ca341e0d4d + +### File: +src/main/java/com/openpojo/reflection/impl/PojoPackageImpl.java + +### Key: +PojoPackageImpl.java|getPojoSubPackages|NULL_DEREFERENCE + +### Node Key: +24ee14a57e8a90ab88fc833015223ecd + +### Hash: +2d7477d9fc2f3903c2ce67215f6f046e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6948/instruction.md b/inferredbugs-6948/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..304eaf1e7b9b1b7ebac13decb5c8e9dc0aaa637f --- /dev/null +++ b/inferredbugs-6948/instruction.md @@ -0,0 +1,206 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jboot +**Bug ID:** 48 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2015-2019, Michael Yang 杨福海 (fuhai999@gmail.com). + *

+ * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + *

+ * http://www.apache.org/licenses/LICENSE-2.0 + *

+ * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.jboot.utils; + +import com.jfinal.core.JFinal; +import com.jfinal.kit.PathKit; + +import java.io.*; +import java.util.Enumeration; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + + +public class FileUtil { + + public static String getSuffix(String fileName) { + if (fileName != null && fileName.contains(".")) { + return fileName.substring(fileName.lastIndexOf(".")); + } + return null; + } + + + public static String removePrefix(String src, String prefix) { + if (src != null && src.startsWith(prefix)) { + return src.substring(prefix.length()); + } + return src; + } + + + public static String removeRootPath(String src){ + return removePrefix(src, PathKit.getWebRootPath()); + } + + public static String readString(File file) { + ByteArrayOutputStream baos = null; + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + baos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + for (int len = 0; (len = fis.read(buffer)) > 0;) { + baos.write(buffer, 0, len); + } + return new String(baos.toByteArray(), JFinal.me().getConstants().getEncoding()); + } catch (Exception e) { + } finally { + close(fis, baos); + } + return null; + } + + public static void writeString(File file, String string) { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(file, false); + fos.write(string.getBytes(JFinal.me().getConstants().getEncoding())); + } catch (Exception e) { + } finally { + close(null, fos); + } + } + + private static void close(InputStream is, OutputStream os) { + if (is != null) + try { + is.close(); + } catch (IOException e) { + } + if (os != null) + try { + os.close(); + } catch (IOException e) { + } + } + + public static void unzip(String zipFilePath) throws IOException { + String targetPath = zipFilePath.substring(0, zipFilePath.lastIndexOf(".")); + unzip(zipFilePath, targetPath); + } + + public static void unzip(String zipFilePath, String targetPath) throws IOException { + ZipFile zipFile = new ZipFile(zipFilePath); + try{ + Enumeration entryEnum = zipFile.entries(); + if (null != entryEnum) { + while (entryEnum.hasMoreElements()) { + OutputStream os = null; + InputStream is = null; + try { + ZipEntry zipEntry = (ZipEntry) entryEnum.nextElement(); + if (!zipEntry.isDirectory()) { + File targetFile = new File(targetPath + File.separator + zipEntry.getName()); + if (!targetFile.getParentFile().exists()) { + targetFile.getParentFile().mkdirs(); + } + os = new BufferedOutputStream(new FileOutputStream(targetFile)); + is = zipFile.getInputStream(zipEntry); + byte[] buffer = new byte[4096]; + int readLen = 0; + while ((readLen = is.read(buffer, 0, 4096)) > 0) { + os.write(buffer, 0, readLen); + } + } + } finally { + if (is != null) + is.close(); + if (os != null) + os.close(); + } + } + } + }finally{ + zipFile.close(); + } + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired by call to `FileOutputStream(...)` at line 111 is not released after line 128. +**Note**: potential exception at line 115 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileUtil.unzip(String,String) + +### Procedure Id: +io.jboot.utils.FileUtil.unzip(java.lang.String,java.lang.String):void.568256d67e6e101f5afe85087353de91 + +### File: +src/main/java/io/jboot/utils/FileUtil.java + +### Key: +FileUtil.java|unzip|RESOURCE_LEAK + +### Node Key: +6d15c9608e0b7a140ecfdba5dce92676 + +### Hash: +f7024a87613d42ccd71d86f5e3da60dc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6977/instruction.md b/inferredbugs-6977/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb5b1f3d68a5ee22cc4e672b3d701c64a8b228b6 --- /dev/null +++ b/inferredbugs-6977/instruction.md @@ -0,0 +1,1465 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** aviator +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java + +/** + * Copyright (C) 2010 dennis zhuang (killme2008@gmail.com) + * + * This library is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version + * 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + **/ +package com.googlecode.aviator; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.nio.charset.Charset; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.FutureTask; +import com.googlecode.aviator.Options.Value; +import com.googlecode.aviator.annotation.Function; +import com.googlecode.aviator.annotation.Ignore; +import com.googlecode.aviator.annotation.Import; +import com.googlecode.aviator.annotation.ImportScope; +import com.googlecode.aviator.asm.Opcodes; +import com.googlecode.aviator.code.CodeGenerator; +import com.googlecode.aviator.code.OptimizeCodeGenerator; +import com.googlecode.aviator.code.asm.ASMCodeGenerator; +import com.googlecode.aviator.exception.CompileExpressionErrorException; +import com.googlecode.aviator.exception.ExpressionNotFoundException; +import com.googlecode.aviator.exception.ExpressionSyntaxErrorException; +import com.googlecode.aviator.lexer.ExpressionLexer; +import com.googlecode.aviator.lexer.SymbolTable; +import com.googlecode.aviator.lexer.token.OperatorType; +import com.googlecode.aviator.parser.AviatorClassLoader; +import com.googlecode.aviator.parser.ExpressionParser; +import com.googlecode.aviator.runtime.function.ClassMethodFunction; +import com.googlecode.aviator.runtime.function.internal.IfCallccFunction; +import com.googlecode.aviator.runtime.function.internal.ReducerBreakFunction; +import com.googlecode.aviator.runtime.function.internal.ReducerContFunction; +import com.googlecode.aviator.runtime.function.internal.ReducerFunction; +import com.googlecode.aviator.runtime.function.internal.ReducerReturnFunction; +import com.googlecode.aviator.runtime.function.math.MathAbsFunction; +import com.googlecode.aviator.runtime.function.math.MathCosFunction; +import com.googlecode.aviator.runtime.function.math.MathLog10Function; +import com.googlecode.aviator.runtime.function.math.MathLogFunction; +import com.googlecode.aviator.runtime.function.math.MathPowFunction; +import com.googlecode.aviator.runtime.function.math.MathRoundFunction; +import com.googlecode.aviator.runtime.function.math.MathSinFunction; +import com.googlecode.aviator.runtime.function.math.MathSqrtFunction; +import com.googlecode.aviator.runtime.function.math.MathTanFunction; +import com.googlecode.aviator.runtime.function.seq.SeqAddFunction; +import com.googlecode.aviator.runtime.function.seq.SeqArrayFunction; +import com.googlecode.aviator.runtime.function.seq.SeqCompsitePredFunFunction; +import com.googlecode.aviator.runtime.function.seq.SeqCompsitePredFunFunction.LogicOp; +import com.googlecode.aviator.runtime.function.seq.SeqContainsKeyFunction; +import com.googlecode.aviator.runtime.function.seq.SeqCountFunction; +import com.googlecode.aviator.runtime.function.seq.SeqEveryFunction; +import com.googlecode.aviator.runtime.function.seq.SeqFilterFunction; +import com.googlecode.aviator.runtime.function.seq.SeqGetFunction; +import com.googlecode.aviator.runtime.function.seq.SeqIncludeFunction; +import com.googlecode.aviator.runtime.function.seq.SeqIntoFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMakePredicateFunFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMapEntryFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMapFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMaxFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMinFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNewArrayFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNewListFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNewMapFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNewSetFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNotAnyFunction; +import com.googlecode.aviator.runtime.function.seq.SeqPutFunction; +import com.googlecode.aviator.runtime.function.seq.SeqReduceFunction; +import com.googlecode.aviator.runtime.function.seq.SeqRemoveFunction; +import com.googlecode.aviator.runtime.function.seq.SeqSomeFunction; +import com.googlecode.aviator.runtime.function.seq.SeqSortFunction; +import com.googlecode.aviator.runtime.function.string.StringContainsFunction; +import com.googlecode.aviator.runtime.function.string.StringEndsWithFunction; +import com.googlecode.aviator.runtime.function.string.StringIndexOfFunction; +import com.googlecode.aviator.runtime.function.string.StringJoinFunction; +import com.googlecode.aviator.runtime.function.string.StringLengthFunction; +import com.googlecode.aviator.runtime.function.string.StringReplaceAllFunction; +import com.googlecode.aviator.runtime.function.string.StringReplaceFirstFunction; +import com.googlecode.aviator.runtime.function.string.StringSplitFunction; +import com.googlecode.aviator.runtime.function.string.StringStartsWithFunction; +import com.googlecode.aviator.runtime.function.string.StringSubStringFunction; +import com.googlecode.aviator.runtime.function.system.AssertFunction; +import com.googlecode.aviator.runtime.function.system.BinaryFunction; +import com.googlecode.aviator.runtime.function.system.BooleanFunction; +import com.googlecode.aviator.runtime.function.system.CompareFunction; +import com.googlecode.aviator.runtime.function.system.Date2StringFunction; +import com.googlecode.aviator.runtime.function.system.DoubleFunction; +import com.googlecode.aviator.runtime.function.system.IdentityFunction; +import com.googlecode.aviator.runtime.function.system.IsDefFunction; +import com.googlecode.aviator.runtime.function.system.LoadFunction; +import com.googlecode.aviator.runtime.function.system.LongFunction; +import com.googlecode.aviator.runtime.function.system.MaxFunction; +import com.googlecode.aviator.runtime.function.system.MinFunction; +import com.googlecode.aviator.runtime.function.system.NowFunction; +import com.googlecode.aviator.runtime.function.system.PrintFunction; +import com.googlecode.aviator.runtime.function.system.PrintlnFunction; +import com.googlecode.aviator.runtime.function.system.RandomFunction; +import com.googlecode.aviator.runtime.function.system.RangeFunction; +import com.googlecode.aviator.runtime.function.system.RequireFunction; +import com.googlecode.aviator.runtime.function.system.StrFunction; +import com.googlecode.aviator.runtime.function.system.String2DateFunction; +import com.googlecode.aviator.runtime.function.system.SysDateFunction; +import com.googlecode.aviator.runtime.function.system.TupleFunction; +import com.googlecode.aviator.runtime.function.system.TypeFunction; +import com.googlecode.aviator.runtime.function.system.UndefFunction; +import com.googlecode.aviator.runtime.module.IoModule; +import com.googlecode.aviator.runtime.type.AviatorBoolean; +import com.googlecode.aviator.runtime.type.AviatorFunction; +import com.googlecode.aviator.runtime.type.AviatorNil; +import com.googlecode.aviator.utils.Constants; +import com.googlecode.aviator.utils.Env; +import com.googlecode.aviator.utils.LRUMap; +import com.googlecode.aviator.utils.Reflector; +import com.googlecode.aviator.utils.Utils; + + +/** + * A aviator evaluator instance + * + * @since 4.0.0 + * @author dennis + * + */ +public final class AviatorEvaluatorInstance { + + private volatile AviatorClassLoader aviatorClassLoader = initAviatorClassLoader(); + + private OutputStream traceOutputStream = System.out; + + private FunctionMissing functionMissing; + + /** + * Generated java class version,default 1.7 + */ + private int bytecodeVersion = Opcodes.V1_7; + + /** + * Options + */ + private volatile Map options = new IdentityHashMap(); + + + /** function loader list */ + private List functionLoaders; + + + /** + * Adds a function loader + * + * @see FunctionLoader + * @since 4.0.0 + * @param loader + */ + public void addFunctionLoader(final FunctionLoader loader) { + if (this.functionLoaders == null) { + this.functionLoaders = new ArrayList(); + } + this.functionLoaders.add(loader); + } + + /** + * Compile a script file into expression. + * + * @param file the script file path + * @param cached whether to cached the compiled result with key is script file's absolute path. + * @since 5.0.0 + * @return the compiled expression instance. + */ + public Expression compileScript(final String path, final boolean cached) throws IOException { + File file = tryFindScriptFile(path); + return compileScript(file.getAbsolutePath(), file, cached); + } + + /** + * Compile a script into expression. + * + * @param cacheKey caching key when cached is true. + * @param file the script file + * @param cached whether to cache the expression instance by cacheKey. + * @return the compiled expression instance. + * @since 5.0.0 + * @throws IOException + */ + public Expression compileScript(final String cacheKey, final File file, final boolean cached) + throws IOException { + try (InputStream in = new FileInputStream(file); + Reader reader = new InputStreamReader(in, Charset.forName("utf-8"));) { + + return compile(cacheKey, Utils.readFully(reader), cached); + } + } + + private File tryFindScriptFile(final String path) throws IOException { + // 1. absolute path + File file = new File(path); + if (file.exists()) { + return file; + } + // 2. from context classloader + ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); + file = tryFindFileFromClassLoader(path, contextLoader); + if (file != null) { + return file; + } + // 3. from current class loader + contextLoader = getClass().getClassLoader(); + file = tryFindFileFromClassLoader(path, contextLoader); + if (file != null) { + return file; + } + throw new FileNotFoundException("File not found: " + path); + } + + /** + * Set a custom aviator class loader + * + * @since 5.0.0 + * @param aviatorClassLoader + */ + public void setAviatorClassLoader(final AviatorClassLoader aviatorClassLoader) { + this.aviatorClassLoader = aviatorClassLoader; + } + + private File tryFindFileFromClassLoader(final String path, final ClassLoader contextLoader) { + URL url = contextLoader.getResource(path); + if (url != null) { + return new File(url.getPath()); + } + if (!path.startsWith("/")) { + url = contextLoader.getResource("/" + path); + } + return null; + } + + /** + * Loads a script from path and return it's exports. + * + * @param path + * @param args arguments to execute the script. + * @throws IOException + * @return the exports map. + * @since 5.0.0 + */ + public Map loadScript(final String path) throws IOException { + final File file = tryFindScriptFile(path); + final String abPath = file.getAbsolutePath(); + return loadScript0(abPath); + } + + @SuppressWarnings("unchecked") + private Map loadScript0(final String abPath) throws IOException { + Expression exp = this.compileScript(abPath); + final Env exports = new Env(); + final Map module = exp.newEnv("exports", exports, "path", abPath); + Map env = exp.newEnv("__MODULE__", module, "exports", exports); + exp.execute(env); + exports.setInstance(this); + return (Map) module.get("exports"); + } + + + /** + * Loads a script from path and return it's exports with module caching. + * + * @param path + * @param args arguments to execute the script. + * @throws IOException + * @return the exports map + * @since 5.0.0 + */ + public Map requireScript(final String path) throws IOException { + File file = tryFindScriptFile(path); + final String abPath = file.getAbsolutePath(); + Map exports = (Env) this.moduleCache.get(abPath); + if (exports != null) { + return exports; + } else { + // TODO better lock + synchronized (abPath.intern()) { + exports = (Env) this.moduleCache.get(abPath); + if (exports != null) { + return exports; + } + exports = loadScript0(abPath); + this.moduleCache.put(abPath, exports); + return exports; + } + } + } + + /** + * Adds a module class and import it's public static methods as module's exports into module + * cache, return the exports map. + * + * @param moduleClazz + * @return the exports map + * @since 5.0.0 + */ + public Env addModule(final Class moduleClazz) + throws NoSuchMethodException, IllegalAccessException { + String namespace = moduleClazz.getSimpleName(); + + Import importAnt = moduleClazz.getAnnotation(Import.class); + + if (importAnt != null) { + namespace = importAnt.ns(); + if (namespace == null || namespace.isEmpty() + || !ExpressionParser.isJavaIdentifier(namespace)) { + throw new IllegalArgumentException("Invalid namespace in Import annotation: " + namespace); + } + } + + Env exports = null; + synchronized (namespace.intern()) { + exports = (Env) this.moduleCache.get(namespace); + if (exports != null) { + return exports; + } + exports = loadModule(moduleClazz); + this.moduleCache.put(namespace, exports); + return exports; + } + } + + private Env loadModule(final Class moduleClazz) + throws IllegalAccessException, NoSuchMethodException { + Map> methodMap = findMethodsFromClass(true, moduleClazz); + + if (methodMap == null || methodMap.isEmpty()) { + throw new IllegalArgumentException("Empty module"); + } + + Env exports = new Env(); + + for (Map.Entry> entry : methodMap.entrySet()) { + exports.put(entry.getKey(), new ClassMethodFunction(moduleClazz, true, entry.getKey(), + entry.getKey(), entry.getValue())); + } + exports.setInstance(this); + return exports; + } + + public Map getModuleCache() { + return this.moduleCache; + } + + /** + * Compile a script file into expression, it doesn't cache the compiled result. + * + * @param file the script file path + * @return + */ + public Expression compileScript(final String path) throws IOException { + return this.compileScript(path, false); + } + + + /** + * Returns the function missing handler, null if not set. + * + * @since 4.2.5 + * @return + */ + public FunctionMissing getFunctionMissing() { + return this.functionMissing; + } + + + /** + * Configure a function missing handler. + * + * @since 4.2.5 + * @param functionMissing + */ + public void setFunctionMissing(final FunctionMissing functionMissing) { + if (this.functionMissing != null) { + throw new IllegalArgumentException("functionMissing already set:" + this.functionMissing); + } + this.functionMissing = functionMissing; + } + + + + /** + * Adds all public instance methods in the class as custom functions into evaluator except those + * have {@link Ignore} annotation, all these functions will keep the same name as method name, but + * prefixed with namespace, the function name can be renamed by {@link Function} annotation. And + * the function will have more than one argument than the method, the function's first argument is + * always the instance object(this pointer). + * + * @since 4.2.3 + * @see Ignore + * @see Function + * @param namespace the functions namespace + * @param clazz the class + * @return the added function list. + */ + public List addInstanceFunctions(final String namespace, final Class clazz) + throws IllegalAccessException, NoSuchMethodException { + return addMethodFunctions(namespace, false, clazz); + } + + private List addMethodFunctions(final String namespace, final boolean isStatic, + final Class clazz) throws IllegalAccessException, NoSuchMethodException { + Map> methodMap = findMethodsFromClass(isStatic, clazz); + List added = new ArrayList<>(); + + for (Map.Entry> entry : methodMap.entrySet()) { + String methodName = entry.getKey(); + String name = namespace + "." + methodName; + this.addFunction( + new ClassMethodFunction(clazz, isStatic, name, methodName, entry.getValue())); + added.add(name); + } + return added; + } + + /** + * Adds all public static methods in the class as custom functions into evaluator except those + * have {@link Ignore} annotation, all these functions will keep the same name as method name, but + * prefixed with namespace, the function name can be renamed by {@link Function} annotation. + * + * @since 4.2.2 + * @see Ignore + * @see Function + * @param namespace the functions namespace + * @param clazz the class + * @return the added function list. + */ + public List addStaticFunctions(final String namespace, final Class clazz) + throws IllegalAccessException, NoSuchMethodException { + + return addMethodFunctions(namespace, true, clazz); + } + + /** + * Import the class public methods into aviator evaluator as custom functions. The function's + * namespace is the class name by default, and the scopes are both static and instance methods. + * The namespace and scope can be set by {@link Import} annotation. + * + * @since 4.2.2 + * @see Import + * @param clazz the class + * @return the added function list. + * @throws NoSuchMethodException + * @throws IllegalAccessException + */ + public List importFunctions(final Class clazz) + throws IllegalAccessException, NoSuchMethodException { + + String namespace = clazz.getSimpleName(); + ImportScope[] scopes = {ImportScope.Static, ImportScope.Instance}; + + Import importAnt = clazz.getAnnotation(Import.class); + + if (importAnt != null) { + namespace = importAnt.ns(); + if (namespace == null || namespace.isEmpty() + || !ExpressionParser.isJavaIdentifier(namespace)) { + throw new IllegalArgumentException("Invalid namespace in Import annotation: " + namespace); + } + scopes = importAnt.scopes(); + if (scopes == null || scopes.length == 0) { + throw new IllegalArgumentException("Empty scopes in Import annotation"); + } + } + + List result = new ArrayList<>(); + for (ImportScope scope : scopes) { + switch (scope) { + case Static: + result.addAll(addStaticFunctions(namespace, clazz)); + break; + case Instance: + result.addAll(addInstanceFunctions(namespace, clazz)); + break; + default: + throw new IllegalStateException("Invalid import scope: " + scope); + } + } + return result; + } + + private Map> findMethodsFromClass(final boolean isStatic, + final Class clazz) { + Map> methodMap = new HashMap<>(); + + for (Method method : clazz.getMethods()) { + int modifiers = method.getModifiers(); + if (Modifier.isPublic(modifiers)) { + if (isStatic) { + if (!Modifier.isStatic(modifiers)) { + continue; + } + } else { + if (Modifier.isStatic(modifiers)) { + continue; + } + } + + if (method.getAnnotation(Ignore.class) != null) { + continue; + } + + + String methodName = method.getName(); + Function func = method.getAnnotation(Function.class); + if (func != null) { + String rename = func.rename(); + if (!rename.isEmpty()) { + if (!ExpressionParser.isJavaIdentifier(rename)) { + throw new IllegalArgumentException("Invalid rename `" + rename + "` for method " + + method.getName() + " in class " + clazz); + } + methodName = func.rename(); + } + } + + List methods = methodMap.get(methodName); + if (methods == null) { + methods = new ArrayList<>(3); + methodMap.put(methodName, methods); + } + methods.add(method); + } + } + + return methodMap; + } + + /** + * Remove a function loader + * + * @since 4.0.0 + * @param loader + */ + public void removeFunctionLoader(final FunctionLoader loader) { + if (this.functionLoaders == null) { + return; + } + this.functionLoaders.remove(loader); + } + + /** + * Adds a evaluator option + * + * @since 2.3.4 + * @see Options + * @param opt + * @param val + */ + public void setOption(final Options opt, final Object val) { + if (opt == null || val == null) { + throw new IllegalArgumentException("Option and value should not be null."); + } + if (!opt.isValidValue(val)) { + throw new IllegalArgumentException("Invalid value for option:" + opt.name()); + } + Map newOpts = new IdentityHashMap<>(this.options); + newOpts.put(opt, opt.intoValue(val)); + this.options = newOpts; + + if (opt == Options.ENABLE_REQUIRE_LOAD_SCRIPTS) { + if (getOptionValue(opt).bool) { + addLoadAndRequireFunction(); + } else { + removeLoadAndRequireFunction(); + } + } + } + + private void removeLoadAndRequireFunction() { + this.removeFunction(Constants.LOAD_FN); + this.removeFunction(Constants.REQUIRE_FN); + } + + + /** + * Returns the current evaluator option value, returns null if missing. + * + * @param opt + * @return + */ + @Deprecated + @SuppressWarnings("unchecked") + public T getOption(final Options opt) { + Value val = this.options.get(opt); + if (val == null) { + val = opt.getDefaultValueObject(); + } + + return (T) opt.intoObject(val); + } + + /** + * Returns the current evaluator option value union, returns null if missing. + * + * @param opt + * @return the option value, null if missing. + */ + public Value getOptionValue(final Options opt) { + Value val = this.options.get(opt); + assert (val != null); + return val; + } + + + /** + * Returns the generated java classes byte code version, 1.6 by defualt. + * + * @return the bytecode version. + */ + public int getBytecodeVersion() { + return this.bytecodeVersion; + } + + + /** + * Set the generated java classes java byte code version. + * + * @see Opcodes#V1_6 + * @param bytecodeVersion + */ + public void setBytecodeVersion(final int bytecodeVersion) { + this.bytecodeVersion = bytecodeVersion; + } + + + /** + * Get the evaluator instance options + * + * @return + */ + public Map getOptions() { + Map ret = new HashMap<>(); + for (Map.Entry entry : this.options.entrySet()) { + ret.put(entry.getKey(), entry.getKey().intoObject(entry.getValue())); + } + return ret; + } + + + /** + * Returns the functions map + * + * @return + */ + public Map getFuncMap() { + return this.funcMap; + } + + + /** + * Returns the operators map. + * + * @return + */ + public Map getOpsMap() { + return this.opsMap; + } + + + /** + * Get current trace output stream,default is System.out + * + * @return + */ + public OutputStream getTraceOutputStream() { + return this.traceOutputStream; + } + + + /** + * Set trace output stream + * + * @param traceOutputStream + */ + public void setTraceOutputStream(final OutputStream traceOutputStream) { + this.traceOutputStream = traceOutputStream; + } + + private AviatorClassLoader initAviatorClassLoader() { + return AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public AviatorClassLoader run() { + return new AviatorClassLoader(AviatorEvaluatorInstance.class.getClassLoader()); + } + + }); + } + + private final Map funcMap = new HashMap(); + + private final ConcurrentHashMap moduleCache = + new ConcurrentHashMap<>(); + + private final Map opsMap = + new IdentityHashMap(); + + private void loadModule() { + try { + addModule(IoModule.class); + } catch (Exception e) { + System.err.println("Fail to load internal modules."); + System.exit(1); + } + } + + + private void loadLib() { + // Load internal functions + // load sys lib + addFunction(new CompareFunction()); + addFunction(new SysDateFunction()); + addFunction(new PrintlnFunction()); + addFunction(new PrintFunction()); + addFunction(new RandomFunction()); + addFunction(new NowFunction()); + addFunction(new LongFunction()); + addFunction(new BooleanFunction()); + addFunction(new DoubleFunction()); + addFunction(new StrFunction()); + addFunction(new Date2StringFunction()); + addFunction(new String2DateFunction()); + addFunction(new BinaryFunction(OperatorType.ADD)); + addFunction(new BinaryFunction(OperatorType.SUB)); + addFunction(new BinaryFunction(OperatorType.MULT)); + addFunction(new BinaryFunction(OperatorType.DIV)); + addFunction(new BinaryFunction(OperatorType.MOD)); + addFunction(new BinaryFunction(OperatorType.NEG)); + addFunction(new BinaryFunction(OperatorType.NOT)); + addFunction(new BinaryFunction(OperatorType.BIT_AND)); + addFunction(new BinaryFunction(OperatorType.BIT_OR)); + addFunction(new BinaryFunction(OperatorType.BIT_XOR)); + addFunction(new BinaryFunction(OperatorType.BIT_NOT)); + addFunction(new TupleFunction()); + addFunction(new MinFunction()); + addFunction(new MaxFunction()); + addFunction(new IdentityFunction()); + addFunction(new AssertFunction()); + addFunction(new RangeFunction()); + addFunction(new IsDefFunction()); + addFunction(new UndefFunction()); + addFunction(new TypeFunction()); + + // for-loop and if statement supporting + addFunction(new ReducerFunction()); + addFunction(new ReducerReturnFunction()); + addFunction(new ReducerContFunction()); + addFunction(new ReducerBreakFunction()); + addFunction(new IfCallccFunction()); + + // load string lib + addFunction(new StringContainsFunction()); + addFunction(new StringIndexOfFunction()); + addFunction(new StringStartsWithFunction()); + addFunction(new StringEndsWithFunction()); + addFunction(new StringSubStringFunction()); + addFunction(new StringLengthFunction()); + addFunction(new StringSplitFunction()); + addFunction(new StringJoinFunction()); + addFunction(new StringReplaceFirstFunction()); + addFunction(new StringReplaceAllFunction()); + + // load math lib + addFunction(new MathAbsFunction()); + addFunction(new MathRoundFunction()); + addFunction(new MathPowFunction()); + addFunction(new MathSqrtFunction()); + addFunction(new MathLog10Function()); + addFunction(new MathLogFunction()); + addFunction(new MathSinFunction()); + addFunction(new MathCosFunction()); + addFunction(new MathTanFunction()); + + // seq lib + addFunction(new SeqNewArrayFunction()); + addFunction(new SeqArrayFunction()); + addFunction(new SeqNewListFunction()); + addFunction(new SeqNewMapFunction()); + addFunction(new SeqNewSetFunction()); + addFunction(new SeqMapEntryFunction()); + addFunction(new SeqIntoFunction()); + addFunction(new SeqAddFunction()); + addFunction(new SeqRemoveFunction()); + addFunction(new SeqGetFunction()); + addFunction(new SeqPutFunction()); + addFunction(new SeqMinFunction()); + addFunction(new SeqMaxFunction()); + addFunction(new SeqMapFunction()); + addFunction(new SeqReduceFunction()); + addFunction(new SeqFilterFunction()); + addFunction(new SeqSortFunction()); + addFunction(new SeqIncludeFunction()); + addFunction(new SeqContainsKeyFunction()); + addFunction(new SeqCountFunction()); + addFunction(new SeqEveryFunction()); + addFunction(new SeqNotAnyFunction()); + addFunction(new SeqSomeFunction()); + addFunction(new SeqMakePredicateFunFunction("seq.eq", OperatorType.EQ)); + addFunction(new SeqMakePredicateFunFunction("seq.neq", OperatorType.NEQ)); + addFunction(new SeqMakePredicateFunFunction("seq.lt", OperatorType.LT)); + addFunction(new SeqMakePredicateFunFunction("seq.le", OperatorType.LE)); + addFunction(new SeqMakePredicateFunFunction("seq.gt", OperatorType.GT)); + addFunction(new SeqMakePredicateFunFunction("seq.ge", OperatorType.GE)); + addFunction(new SeqCompsitePredFunFunction("seq.and", LogicOp.AND)); + addFunction(new SeqCompsitePredFunFunction("seq.or", LogicOp.OR)); + addFunction(new SeqMakePredicateFunFunction("seq.true", OperatorType.EQ, AviatorBoolean.TRUE)); + addFunction( + new SeqMakePredicateFunFunction("seq.false", OperatorType.EQ, AviatorBoolean.FALSE)); + addFunction(new SeqMakePredicateFunFunction("seq.nil", OperatorType.EQ, AviatorNil.NIL)); + addFunction(new SeqMakePredicateFunFunction("seq.exists", OperatorType.NEQ, AviatorNil.NIL)); + } + + private void addLoadAndRequireFunction() { + // load and require + addFunction(new RequireFunction()); + addFunction(new LoadFunction()); + } + + /** + * Compiled Expression cache + */ + private final ConcurrentHashMap/* + * Compiled + * expression + * task + */> expressionCache = + new ConcurrentHashMap>(); + + private LRUMap> expressionLRUCache; + + + + /** + * Create a aviator evaluator instance. + */ + AviatorEvaluatorInstance() { + loadLib(); + loadModule(); + addFunctionLoader(ClassPathConfigFunctionLoader.getInstance()); + for (Options opt : Options.values()) { + this.options.put(opt, opt.getDefaultValueObject()); + } + } + + /** + * Use {@link LRUMap} as expression caching.It should be called when initializing the evaluator + * instance. + * + * @since 5.0.0 + * @param capacity + * @return the evaluator instance itself. + */ + public AviatorEvaluatorInstance useLRUExpressionCache(final int capacity) { + this.expressionLRUCache = new LRUMap<>(capacity); + return this; + } + + + /** + * Clear all cached compiled expression + */ + public void clearExpressionCache() { + resetClassLoader(); + if (this.expressionLRUCache != null) { + synchronized (this.expressionLRUCache) { + this.expressionLRUCache.clear(); + } + } else { + this.expressionCache.clear(); + } + } + + /** + * Reset the classloader to a new instance. + * + * @since 5.0.0 + */ + public void resetClassLoader() { + this.aviatorClassLoader = initAviatorClassLoader(); + } + + + /** + * Returns classloader + * + * @return + */ + public AviatorClassLoader getAviatorClassLoader() { + return getAviatorClassLoader(false); + } + + + /** + * Returns classloader + * + * @return + */ + public AviatorClassLoader getAviatorClassLoader(final boolean cached) { + if (cached) { + return this.aviatorClassLoader; + } else { + return new AviatorClassLoader(Thread.currentThread().getContextClassLoader()); + } + } + + + /** + * Add an aviator function,it's not thread-safe. + * + * @param function + */ + public void addFunction(final AviatorFunction function) { + final String name = function.getName(); + addFunction(name, function); + } + + /** + * Adds a function with the name + * + * @param name + * @param function + */ + public void addFunction(final String name, final AviatorFunction function) { + if ("lambda".equals(name)) { + throw new IllegalArgumentException("Invalid function name, lambda is a keyword."); + } + if (this.funcMap.containsKey(name)) { + System.out.println("[Aviator WARN] The function '" + name + + "' is already exists, but is replaced with new one."); + } + this.funcMap.put(name, function); + } + + /** + * Define a function by name and expression. + * + * @param name the function name + * @param expression the expression to be executed and it's result must be a function. + * @since 4.0.0 + */ + public void defineFunction(final String name, final String expression) { + this.defineFunction(name, expression, null); + } + + /** + * Define a function by name and expression with the execution env. + * + * @param name the function name + * @param expression the expression to be executed and it's result must be a function. + * @param env the expression execution env + * @since 4.0.0 + */ + public void defineFunction(final String name, final String expression, + final Map env) { + AviatorFunction function = (AviatorFunction) this.execute(expression, env); + this.addFunction(name, function); + } + + + /** + * Remove an aviator function by name,it's not thread-safe. + * + * @param name + * @return + */ + public AviatorFunction removeFunction(final String name) { + return (AviatorFunction) this.funcMap.remove(name); + } + + /** + * @see #getFunction(String, SymbolTable) + * @param name + * @return + */ + public AviatorFunction getFunction(final String name) { + return this.getFunction(name, null); + } + + /** + * Retrieve an aviator function by name,throw exception if not found or null.It's not thread-safe. + * + * @param name + * @param symbolTablee + * @return + */ + public AviatorFunction getFunction(final String name, final SymbolTable symbolTable) { + AviatorFunction function = (AviatorFunction) this.funcMap.get(name); + if (function == null && this.functionLoaders != null) { + for (FunctionLoader loader : this.functionLoaders) { + if (loader != null) { + function = loader.onFunctionNotFound(name); + } + if (function != null) { + break; + } + } + } + if (function == null) { + // Returns a delegate function that will try to find the function from runtime env. + function = new RuntimeFunctionDelegator(name, symbolTable, this.functionMissing); + } + return function; + } + + /** + * Add an operator aviator function,it's not thread-safe. + * + * @param function + */ + public void addOpFunction(final OperatorType opType, final AviatorFunction function) { + this.opsMap.put(opType, function); + } + + + /** + * Retrieve an operator aviator function by op type, return null if not found.It's not + * thread-safe. + * + * @since 3.3 + * @param opType + * @return + */ + public AviatorFunction getOpFunction(final OperatorType opType) { + return this.opsMap.get(opType); + } + + /** + * Remove an operator aviator function by op type, it's not thread-safe. + * + * @since 3.3 + * @param opType + * @return + */ + public AviatorFunction removeOpFunction(final OperatorType opType) { + return this.opsMap.remove(opType); + } + + + /** + * Check if the function is existed in aviator + * + * @param name + * @return + */ + public boolean containsFunction(final String name) { + return this.funcMap.containsKey(name); + } + + /** + * Remove a aviator function + * + * @param function + * @return + */ + public AviatorFunction removeFunction(final AviatorFunction function) { + return removeFunction(function.getName()); + } + + + /** + * Returns a compiled expression in cache + * + * @param expression + * @return + */ + public Expression getCachedExpression(final String expression) { + return getCachedExpressionByKey(expression); + } + + /** + * Returns a compiled expression in cache by cacheKey. + * + * @param cacheKey + * @return + */ + public Expression getCachedExpressionByKey(final String cacheKey) { + FutureTask task = null; + if (this.expressionLRUCache != null) { + synchronized (this.expressionLRUCache) { + task = this.expressionLRUCache.get(cacheKey); + } + } else { + task = this.expressionCache.get(cacheKey); + } + if (task != null) { + return getCompiledExpression(cacheKey, task); + } else { + return null; + } + } + + /** + * Returns true when the expression is in cache. + * + * @param expression + * @return + * @since 4.0.0 + */ + public boolean isExpressionCached(final String expression) { + return getCachedExpression(expression) != null; + } + + /** + * Returns the number of cached expressions. + * + * @since 4.0.0 + * @return + */ + public int getExpressionCacheSize() { + if (this.expressionLRUCache != null) { + synchronized (this.expressionLRUCache) { + return this.expressionLRUCache.size(); + } + } + return this.expressionCache.size(); + } + + + /** + * Compile a text expression to Expression object + * + * @param expression text expression + * @param cached Whether to cache the compiled result,make true to cache it. + * @return + */ + public Expression compile(final String expression, final boolean cached) { + return this.compile(expression, expression, cached); + } + + /** + * Compile a text expression to Expression object + * + * @param cacheKey unique key for caching. + * @param expression text expression + * @param cached Whether to cache the compiled result,make true to cache it. + * @return + */ + public Expression compile(final String cacheKey, final String expression, final boolean cached) { + if (expression == null || expression.trim().length() == 0) { + throw new CompileExpressionErrorException("Blank expression"); + } + if (cacheKey == null || cacheKey.trim().length() == 0) { + throw new CompileExpressionErrorException("Blank cacheKey"); + } + + if (cached) { + FutureTask existedTask = null; + if (this.expressionLRUCache != null) { + boolean runTask = false; + synchronized (this.expressionLRUCache) { + existedTask = this.expressionLRUCache.get(cacheKey); + if (existedTask == null) { + existedTask = newCompileTask(expression, cached); + runTask = true; + this.expressionLRUCache.put(cacheKey, existedTask); + } + } + if (runTask) { + existedTask.run(); + } + } else { + FutureTask task = this.expressionCache.get(cacheKey); + if (task != null) { + return getCompiledExpression(expression, task); + } + task = newCompileTask(expression, cached); + existedTask = this.expressionCache.putIfAbsent(cacheKey, task); + if (existedTask == null) { + existedTask = task; + existedTask.run(); + } + } + return getCompiledExpression(cacheKey, existedTask); + + } else { + return innerCompile(expression, cached); + } + + } + + private FutureTask newCompileTask(final String expression, final boolean cached) { + return new FutureTask<>(new Callable() { + @Override + public Expression call() throws Exception { + return innerCompile(expression, cached); + } + + }); + } + + + private Expression getCompiledExpression(final String cacheKey, + final FutureTask task) { + try { + return task.get(); + } catch (Throwable t) { + invalidateCacheByKey(cacheKey); + final Throwable cause = t.getCause(); + if (cause instanceof ExpressionSyntaxErrorException + || cause instanceof CompileExpressionErrorException) { + Reflector.sneakyThrow(cause); + } + throw new CompileExpressionErrorException("Compile expression failure, cacheKey=" + cacheKey, + t); + } + } + + + private Expression innerCompile(final String expression, final boolean cached) { + ExpressionLexer lexer = new ExpressionLexer(this, expression); + CodeGenerator codeGenerator = newCodeGenerator(cached); + ExpressionParser parser = new ExpressionParser(this, lexer, codeGenerator); + Expression exp = parser.parse(); + if (getOptionValue(Options.TRACE_EVAL).bool) { + ((BaseExpression) exp).setExpression(expression); + } + return exp; + } + + private int getOptimizeLevel() { + return getOptionValue(Options.OPTIMIZE_LEVEL).number; + } + + + public CodeGenerator newCodeGenerator(final boolean cached) { + AviatorClassLoader classLoader = getAviatorClassLoader(cached); + return newCodeGenerator(classLoader); + + } + + public CodeGenerator newCodeGenerator(final AviatorClassLoader classLoader) { + switch (getOptimizeLevel()) { + case AviatorEvaluator.COMPILE: + ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, + this.traceOutputStream, getOptionValue(Options.TRACE).bool); + asmCodeGenerator.start(); + return asmCodeGenerator; + case AviatorEvaluator.EVAL: + return new OptimizeCodeGenerator(this, classLoader, this.traceOutputStream, + getOptionValue(Options.TRACE).bool); + default: + throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); + } + } + + + /** + * Compile a text expression to Expression Object without caching + * + * @param expression + * @return + */ + public Expression compile(final String expression) { + return compile(expression, false); + } + + + /** + * Execute a text expression with values that are variables order in the expression.It only runs + * in EVAL mode,and it will cache the compiled expression.It's deprecated, please use + * {@link #execute(String, Map)} instead. + * + * @param expression + * @param values + * @return + */ + @Deprecated + public Object exec(final String expression, final Object... values) { + if (getOptimizeLevel() != AviatorEvaluator.EVAL) { + throw new IllegalStateException("Aviator evaluator is not in EVAL mode."); + } + Expression compiledExpression = compile(expression, true); + if (compiledExpression != null) { + List vars = compiledExpression.getVariableNames(); + if (!vars.isEmpty()) { + int valLen = values == null ? 0 : values.length; + if (valLen != vars.size()) { + throw new IllegalArgumentException("Expect " + vars.size() + " values,but has " + valLen); + } + Map env = new HashMap(); + int i = 0; + for (String var : vars) { + env.put(var, values[i++]); + } + return compiledExpression.execute(env); + } else { + return compiledExpression.execute(); + } + } else { + throw new ExpressionNotFoundException("Null compiled expression for " + expression); + } + } + + + /** + * Execute a text expression with environment + * + * @param expression text expression + * @param env Binding variable environment + * @param cached Whether to cache the compiled result,make true to cache it. + */ + public Object execute(final String expression, final Map env, + final boolean cached) { + Expression compiledExpression = compile(expression, cached); + if (compiledExpression != null) { + return compiledExpression.execute(env); + } else { + throw new ExpressionNotFoundException("Null compiled expression for " + expression); + } + } + + + /** + * Execute a text expression without caching + * + * @param expression + * @param env + * @return + */ + public Object execute(final String expression, final Map env) { + return execute(expression, env, false); + } + + + /** + * Invalidate expression cache + * + * @param expression + */ + public void invalidateCache(final String expression) { + invalidateCacheByKey(expression); + } + + /** + * Invalidate expression cache by cacheKey + * + * @param cacheKey + */ + public void invalidateCacheByKey(final String cacheKey) { + if (this.expressionLRUCache != null) { + synchronized (this.expressionLRUCache) { + this.expressionLRUCache.remove(cacheKey); + } + } else { + this.expressionCache.remove(cacheKey); + } + } + + + /** + * Execute a text expression without caching and env map. + * + * @param expression + * @return + */ + public Object execute(final String expression) { + return execute(expression, (Map) null); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.googlecode.aviator.AviatorEvaluatorInstance.newCodeGenerator` indirectly reads without synchronization from `n$12.com.googlecode.aviator.asm.ByteVector.data`. Potentially races with write in method `AviatorEvaluatorInstance.requireScript(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CodeGenerator AviatorEvaluatorInstance.newCodeGenerator(AviatorClassLoader) + +### Procedure Id: +com.googlecode.aviator.AviatorEvaluatorInstance.newCodeGenerator(com.googlecode.aviator.parser.Aviat.466162e4dda6d94cbcaa27c218a5c092 + +### File: +src/main/java/com/googlecode/aviator/AviatorEvaluatorInstance.java + +### Key: +AviatorEvaluatorInstance.java|newCodeGenerator|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +702c191141e6bfb4fc887df0f8f3ab2c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6983/instruction.md b/inferredbugs-6983/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0fbb1fb41d4ac4a619d1d88fb49acaa67a82155e --- /dev/null +++ b/inferredbugs-6983/instruction.md @@ -0,0 +1,826 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** aviator +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java + +/** + * Copyright (C) 2010 dennis zhuang (killme2008@gmail.com) + * + * This library is free software; you can redistribute it and/or modify it under the terms of the + * GNU Lesser General Public License as published by the Free Software Foundation; either version + * 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License along with this program; + * if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + **/ +package com.googlecode.aviator; + + +import java.io.OutputStream; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.FutureTask; +import com.googlecode.aviator.asm.Opcodes; +import com.googlecode.aviator.code.CodeGenerator; +import com.googlecode.aviator.code.OptimizeCodeGenerator; +import com.googlecode.aviator.code.asm.ASMCodeGenerator; +import com.googlecode.aviator.exception.CompileExpressionErrorException; +import com.googlecode.aviator.exception.ExpressionRuntimeException; +import com.googlecode.aviator.lexer.ExpressionLexer; +import com.googlecode.aviator.lexer.token.OperatorType; +import com.googlecode.aviator.parser.AviatorClassLoader; +import com.googlecode.aviator.parser.ExpressionParser; +import com.googlecode.aviator.runtime.function.math.MathAbsFunction; +import com.googlecode.aviator.runtime.function.math.MathCosFunction; +import com.googlecode.aviator.runtime.function.math.MathLog10Function; +import com.googlecode.aviator.runtime.function.math.MathLogFunction; +import com.googlecode.aviator.runtime.function.math.MathPowFunction; +import com.googlecode.aviator.runtime.function.math.MathRoundFunction; +import com.googlecode.aviator.runtime.function.math.MathSinFunction; +import com.googlecode.aviator.runtime.function.math.MathSqrtFunction; +import com.googlecode.aviator.runtime.function.math.MathTanFunction; +import com.googlecode.aviator.runtime.function.seq.SeqCompsitePredFunFunction; +import com.googlecode.aviator.runtime.function.seq.SeqCompsitePredFunFunction.LogicOp; +import com.googlecode.aviator.runtime.function.seq.SeqCountFunction; +import com.googlecode.aviator.runtime.function.seq.SeqEveryFunction; +import com.googlecode.aviator.runtime.function.seq.SeqFilterFunction; +import com.googlecode.aviator.runtime.function.seq.SeqIncludeFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMakePredicateFunFunction; +import com.googlecode.aviator.runtime.function.seq.SeqMapFunction; +import com.googlecode.aviator.runtime.function.seq.SeqNotAnyFunction; +import com.googlecode.aviator.runtime.function.seq.SeqReduceFunction; +import com.googlecode.aviator.runtime.function.seq.SeqSomeFunction; +import com.googlecode.aviator.runtime.function.seq.SeqSortFunction; +import com.googlecode.aviator.runtime.function.string.StringContainsFunction; +import com.googlecode.aviator.runtime.function.string.StringEndsWithFunction; +import com.googlecode.aviator.runtime.function.string.StringIndexOfFunction; +import com.googlecode.aviator.runtime.function.string.StringJoinFunction; +import com.googlecode.aviator.runtime.function.string.StringLengthFunction; +import com.googlecode.aviator.runtime.function.string.StringReplaceAllFunction; +import com.googlecode.aviator.runtime.function.string.StringReplaceFirstFunction; +import com.googlecode.aviator.runtime.function.string.StringSplitFunction; +import com.googlecode.aviator.runtime.function.string.StringStartsWithFunction; +import com.googlecode.aviator.runtime.function.string.StringSubStringFunction; +import com.googlecode.aviator.runtime.function.system.BinaryFunction; +import com.googlecode.aviator.runtime.function.system.BooleanFunction; +import com.googlecode.aviator.runtime.function.system.Date2StringFunction; +import com.googlecode.aviator.runtime.function.system.DoubleFunction; +import com.googlecode.aviator.runtime.function.system.LongFunction; +import com.googlecode.aviator.runtime.function.system.NowFunction; +import com.googlecode.aviator.runtime.function.system.PrintFunction; +import com.googlecode.aviator.runtime.function.system.PrintlnFunction; +import com.googlecode.aviator.runtime.function.system.RandomFunction; +import com.googlecode.aviator.runtime.function.system.StrFunction; +import com.googlecode.aviator.runtime.function.system.String2DateFunction; +import com.googlecode.aviator.runtime.function.system.SysDateFunction; +import com.googlecode.aviator.runtime.function.system.TupleFunction; +import com.googlecode.aviator.runtime.type.AviatorBoolean; +import com.googlecode.aviator.runtime.type.AviatorFunction; +import com.googlecode.aviator.runtime.type.AviatorNil; + + +/** + * A aviator evaluator instance + * + * @since 4.0.0 + * @author dennis + * + */ +public final class AviatorEvaluatorInstance { + + private AviatorClassLoader aviatorClassLoader; + + private OutputStream traceOutputStream = System.out; + + /** + * Generated java class version,default 1.6 + */ + public int bytecodeVersion = Opcodes.V1_6; + + private volatile Map options = new IdentityHashMap(); + /** function loader list */ + private List functionLoaders; + + + /** + * Adds a function loader + * + * @see FunctionLoader + * @since 4.0.0 + * @param loader + */ + public void addFunctionLoader(FunctionLoader loader) { + if (this.functionLoaders == null) { + functionLoaders = new ArrayList(); + } + functionLoaders.add(loader); + } + + /** + * Remove a function loader + * + * @since 4.0.0 + * @param loader + */ + public void removeFunctionLoader(FunctionLoader loader) { + if (this.functionLoaders == null) { + return; + } + this.functionLoaders.remove(loader); + } + + /** + * Adds a evaluator option + * + * @since 2.3.4 + * @see Options + * @param opt + * @param val + */ + public void setOption(Options opt, Object val) { + if (opt == null || val == null) { + throw new IllegalArgumentException("Option and value should not be null."); + } + if (!opt.isValidValue(val)) { + throw new IllegalArgumentException("Invalid value for option:" + opt.name()); + } + Map newOpts = new IdentityHashMap<>(this.options); + newOpts.put(opt, val); + this.options = newOpts; + } + + + /** + * Returns the current evaluator option value, returns null if missing. + * + * @param opt + * @return + */ + @SuppressWarnings("unchecked") + public T getOption(Options opt) { + Object val = options.get(opt); + if (val == null) { + val = opt.getDefaultValue(); + } + return (T) val; + } + + + /** + * Returns the generated java classes byte code version, 1.6 by defualt. + * + * @return + */ + public int getBytecodeVersion() { + return bytecodeVersion; + } + + + /** + * Set the generated java classes java byte code version. + * + * @see Opcodes#V1_6 + * @param bytecodeVersion + */ + public void setBytecodeVersion(int bytecodeVersion) { + this.bytecodeVersion = bytecodeVersion; + } + + + /** + * Get the evaluator instance options + * + * @return + */ + public Map getOptions() { + return options; + } + + + /** + * Returns the functions map + * + * @return + */ + public Map getFuncMap() { + return funcMap; + } + + + /** + * Returns the operators map. + * + * @return + */ + public Map getOpsMap() { + return opsMap; + } + + + /** + * Get current trace output stream,default is System.out + * + * @return + */ + public OutputStream getTraceOutputStream() { + return traceOutputStream; + } + + + /** + * Set trace output stream + * + * @param traceOutputStream + */ + public void setTraceOutputStream(OutputStream traceOutputStream) { + this.traceOutputStream = traceOutputStream; + } + + { + aviatorClassLoader = AccessController.doPrivileged(new PrivilegedAction() { + + @Override + public AviatorClassLoader run() { + return new AviatorClassLoader(AviatorEvaluatorInstance.class.getClassLoader()); + } + + }); + } + + private final Map funcMap = new HashMap(); + + private final Map opsMap = + new IdentityHashMap(); + + + private void loadLib() { + // Load internal functions + // load sys lib + addFunction(new SysDateFunction()); + addFunction(new PrintlnFunction()); + addFunction(new PrintFunction()); + addFunction(new RandomFunction()); + addFunction(new NowFunction()); + addFunction(new LongFunction()); + addFunction(new BooleanFunction()); + addFunction(new DoubleFunction()); + addFunction(new StrFunction()); + addFunction(new Date2StringFunction()); + addFunction(new String2DateFunction()); + addFunction(new BinaryFunction(OperatorType.ADD)); + addFunction(new BinaryFunction(OperatorType.SUB)); + addFunction(new BinaryFunction(OperatorType.MULT)); + addFunction(new BinaryFunction(OperatorType.DIV)); + addFunction(new BinaryFunction(OperatorType.MOD)); + addFunction(new BinaryFunction(OperatorType.NEG)); + addFunction(new BinaryFunction(OperatorType.NOT)); + addFunction(new BinaryFunction(OperatorType.BIT_AND)); + addFunction(new BinaryFunction(OperatorType.BIT_OR)); + addFunction(new BinaryFunction(OperatorType.BIT_XOR)); + addFunction(new BinaryFunction(OperatorType.BIT_NOT)); + addFunction(new TupleFunction()); + + // load string lib + addFunction(new StringContainsFunction()); + addFunction(new StringIndexOfFunction()); + addFunction(new StringStartsWithFunction()); + addFunction(new StringEndsWithFunction()); + addFunction(new StringSubStringFunction()); + addFunction(new StringLengthFunction()); + addFunction(new StringSplitFunction()); + addFunction(new StringJoinFunction()); + addFunction(new StringReplaceFirstFunction()); + addFunction(new StringReplaceAllFunction()); + + // load math lib + addFunction(new MathAbsFunction()); + addFunction(new MathRoundFunction()); + addFunction(new MathPowFunction()); + addFunction(new MathSqrtFunction()); + addFunction(new MathLog10Function()); + addFunction(new MathLogFunction()); + addFunction(new MathSinFunction()); + addFunction(new MathCosFunction()); + addFunction(new MathTanFunction()); + + // seq lib + addFunction(new SeqMapFunction()); + addFunction(new SeqReduceFunction()); + addFunction(new SeqFilterFunction()); + addFunction(new SeqSortFunction()); + addFunction(new SeqIncludeFunction()); + addFunction(new SeqCountFunction()); + addFunction(new SeqEveryFunction()); + addFunction(new SeqNotAnyFunction()); + addFunction(new SeqSomeFunction()); + addFunction(new SeqMakePredicateFunFunction("seq.eq", OperatorType.EQ)); + addFunction(new SeqMakePredicateFunFunction("seq.neq", OperatorType.NEQ)); + addFunction(new SeqMakePredicateFunFunction("seq.lt", OperatorType.LT)); + addFunction(new SeqMakePredicateFunFunction("seq.le", OperatorType.LE)); + addFunction(new SeqMakePredicateFunFunction("seq.gt", OperatorType.GT)); + addFunction(new SeqMakePredicateFunFunction("seq.ge", OperatorType.GE)); + addFunction(new SeqCompsitePredFunFunction("seq.and", LogicOp.AND)); + addFunction(new SeqCompsitePredFunFunction("seq.or", LogicOp.OR)); + addFunction(new SeqMakePredicateFunFunction("seq.true", OperatorType.EQ, AviatorBoolean.TRUE)); + addFunction( + new SeqMakePredicateFunFunction("seq.false", OperatorType.EQ, AviatorBoolean.FALSE)); + addFunction(new SeqMakePredicateFunFunction("seq.nil", OperatorType.EQ, AviatorNil.NIL)); + addFunction(new SeqMakePredicateFunFunction("seq.exists", OperatorType.NEQ, AviatorNil.NIL)); + } + + /** + * Compiled Expression cache + */ + private final ConcurrentHashMap/* + * Compiled + * expression + * task + */> cacheExpressions = + new ConcurrentHashMap>(); + + + + /** + * Create a aviator evaluator instance. + */ + AviatorEvaluatorInstance() { + this.loadLib(); + this.addFunctionLoader(ClassPathConfigFunctionLoader.getInstance()); + } + + /** + * Clear all cached compiled expression + */ + public void clearExpressionCache() { + cacheExpressions.clear(); + } + + + /** + * Returns classloader + * + * @return + */ + public AviatorClassLoader getAviatorClassLoader() { + return getAviatorClassLoader(false); + } + + + /** + * Returns classloader + * + * @return + */ + public AviatorClassLoader getAviatorClassLoader(boolean cached) { + if (cached) { + return aviatorClassLoader; + } else { + return new AviatorClassLoader(Thread.currentThread().getContextClassLoader()); + } + } + + + /** + * Add an aviator function,it's not thread-safe. + * + * @param function + */ + public void addFunction(AviatorFunction function) { + final String name = function.getName(); + addFunction(name, function); + } + + /** + * Adds a function with the name + * + * @param name + * @param function + */ + public void addFunction(final String name, AviatorFunction function) { + if ("lambda".equals(name)) { + throw new IllegalArgumentException("Invalid function name, lambda is a keyword."); + } + if (funcMap.containsKey(name)) { + System.out.println("[Aviator WARN] The function '" + name + + "' is already exists, but is replaced with new one."); + } + funcMap.put(name, function); + } + + /** + * Define a function by name and expression. + * + * @param name the function name + * @param expression the expression to be executed and it's result must be a function. + * @since 4.0.0 + */ + public void defineFunction(String name, String expression) { + this.defineFunction(name, expression, null); + } + + /** + * Define a function by name and expression with the execution env. + * + * @param name the function name + * @param expression the expression to be executed and it's result must be a function. + * @param env the expression execution env + * @since 4.0.0 + */ + public void defineFunction(String name, String expression, Map env) { + AviatorFunction function = (AviatorFunction) this.execute(expression, env); + this.addFunction(name, function); + } + + + /** + * Remove an aviator function by name,it's not thread-safe. + * + * @param name + * @return + */ + public AviatorFunction removeFunction(String name) { + return (AviatorFunction) funcMap.remove(name); + } + + + /** + * Retrieve an aviator function by name,throw exception if not found or null.It's not thread-safe. + * + * @param name + * @return + */ + public AviatorFunction getFunction(final String name) { + AviatorFunction function = (AviatorFunction) funcMap.get(name); + if (function == null && functionLoaders != null) { + for (FunctionLoader loader : functionLoaders) { + if (loader != null) { + function = loader.onFunctionNotFound(name); + } + if (function != null) { + break; + } + } + } + if (function == null) { + // Returns a delegate function that will try to find the function from runtime env. + function = new RuntimeFunctionDelegator(name); + } + return function; + } + + /** + * Add an operator aviator function,it's not thread-safe. + * + * @param function + */ + public void addOpFunction(OperatorType opType, AviatorFunction function) { + opsMap.put(opType, function); + } + + + /** + * Retrieve an operator aviator function by op type, return null if not found.It's not + * thread-safe. + * + * @since 3.3 + * @param opType + * @return + */ + public AviatorFunction getOpFunction(OperatorType opType) { + return opsMap.get(opType); + } + + /** + * Remove an operator aviator function by op type, it's not thread-safe. + * + * @since 3.3 + * @param opType + * @return + */ + public AviatorFunction removeOpFunction(OperatorType opType) { + return opsMap.remove(opType); + } + + + /** + * Check if the function is existed in aviator + * + * @param name + * @return + */ + public boolean containsFunction(String name) { + return funcMap.containsKey(name); + } + + /** + * Remove a aviator function + * + * @param function + * @return + */ + public AviatorFunction removeFunction(AviatorFunction function) { + return removeFunction(function.getName()); + } + + + /** + * Returns a compiled expression in cache + * + * @param expression + * @return + */ + public Expression getCachedExpression(String expression) { + FutureTask task = cacheExpressions.get(expression); + if (task != null) { + return getCompiledExpression(expression, task); + } else { + return null; + } + } + + /** + * Returns true when the expression is in cache. + * + * @param expression + * @return + * @since 4.0.0 + */ + public boolean isExpressionCached(String expression) { + return this.getCachedExpression(expression) != null; + } + + /** + * Returns the number of cached expressions. + * + * @since 4.0.0 + * @return + */ + public int getExpressionCacheSize() { + return this.cacheExpressions.size(); + } + + + + /** + * Compile a text expression to Expression object + * + * @param expression text expression + * @param cached Whether to cache the compiled result,make true to cache it. + * @return + */ + public Expression compile(final String expression, final boolean cached) { + if (expression == null || expression.trim().length() == 0) { + throw new CompileExpressionErrorException("Blank expression"); + } + + if (cached) { + FutureTask task = cacheExpressions.get(expression); + if (task != null) { + return getCompiledExpression(expression, task); + } + task = new FutureTask(new Callable() { + @Override + public Expression call() throws Exception { + return innerCompile(expression, cached); + } + + }); + FutureTask existedTask = cacheExpressions.putIfAbsent(expression, task); + if (existedTask == null) { + existedTask = task; + existedTask.run(); + } + return getCompiledExpression(expression, existedTask); + + } else { + return innerCompile(expression, cached); + } + + } + + + private Expression getCompiledExpression(final String expression, FutureTask task) { + try { + return task.get(); + } catch (Exception e) { + cacheExpressions.remove(expression); + throw new CompileExpressionErrorException("Compile expression failure:" + expression, e); + } + } + + + private Expression innerCompile(final String expression, boolean cached) { + ExpressionLexer lexer = new ExpressionLexer(this, expression); + CodeGenerator codeGenerator = newCodeGenerator(cached); + ExpressionParser parser = new ExpressionParser(this, lexer, codeGenerator); + Expression exp = parser.parse(); + if ((boolean) getOption(Options.TRACE_EVAL)) { + ((BaseExpression) exp).setExpression(expression); + } + return exp; + } + + private int getOptimizeLevel() { + return getOption(Options.OPTIMIZE_LEVEL); + } + + + public CodeGenerator newCodeGenerator(boolean cached) { + AviatorClassLoader classLoader = getAviatorClassLoader(cached); + return newCodeGenerator(classLoader); + + } + + public CodeGenerator newCodeGenerator(AviatorClassLoader classLoader) { + switch (getOptimizeLevel()) { + case AviatorEvaluator.COMPILE: + ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader, + traceOutputStream, (Boolean) getOption(Options.TRACE)); + asmCodeGenerator.start(); + return asmCodeGenerator; + case AviatorEvaluator.EVAL: + return new OptimizeCodeGenerator(this, classLoader, traceOutputStream, + (Boolean) getOption(Options.TRACE)); + default: + throw new IllegalArgumentException("Unknow option " + getOptimizeLevel()); + } + } + + + /** + * Compile a text expression to Expression Object without caching + * + * @param expression + * @return + */ + public Expression compile(String expression) { + return compile(expression, false); + } + + + /** + * Execute a text expression with values that are variables order in the expression.It only runs + * in EVAL mode,and it will cache the compiled expression. + * + * @param expression + * @param values + * @return + */ + public Object exec(String expression, Object... values) { + if (getOptimizeLevel() != AviatorEvaluator.EVAL) { + throw new IllegalStateException("Aviator evaluator is not in EVAL mode."); + } + Expression compiledExpression = compile(expression, true); + if (compiledExpression != null) { + List vars = compiledExpression.getVariableNames(); + if (!vars.isEmpty()) { + int valLen = values == null ? 0 : values.length; + if (valLen != vars.size()) { + throw new IllegalArgumentException("Expect " + vars.size() + " values,but has " + valLen); + } + Map env = new HashMap(); + int i = 0; + for (String var : vars) { + env.put(var, values[i++]); + } + return compiledExpression.execute(env); + } else { + return compiledExpression.execute(); + } + } else { + throw new ExpressionRuntimeException("Null compiled expression for " + expression); + } + } + + + /** + * Execute a text expression with environment + * + * @param expression text expression + * @param env Binding variable environment + * @param cached Whether to cache the compiled result,make true to cache it. + */ + public Object execute(String expression, Map env, boolean cached) { + Expression compiledExpression = compile(expression, cached); + if (compiledExpression != null) { + return compiledExpression.execute(env); + } else { + throw new ExpressionRuntimeException("Null compiled expression for " + expression); + } + } + + + /** + * Execute a text expression without caching + * + * @param expression + * @param env + * @return + */ + public Object execute(String expression, Map env) { + return execute(expression, env, false); + } + + + /** + * Invalidate expression cache + * + * @param expression + */ + public void invalidateCache(String expression) { + cacheExpressions.remove(expression); + } + + + /** + * Execute a text expression without caching and env map. + * + * @param expression + * @return + */ + public Object execute(String expression) { + return execute(expression, (Map) null); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getOption(com.googlecode.aviator.Options.TRACE)` could be null and is dereferenced at line 646. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CodeGenerator AviatorEvaluatorInstance.newCodeGenerator(AviatorClassLoader) + +### Procedure Id: +com.googlecode.aviator.AviatorEvaluatorInstance.newCodeGenerator(com.googlecode.aviator.parser.Aviat.466162e4dda6d94cbcaa27c218a5c092 + +### File: +src/main/java/com/googlecode/aviator/AviatorEvaluatorInstance.java + +### Key: +AviatorEvaluatorInstance.java|newCodeGenerator|NULL_DEREFERENCE + +### Node Key: +0ae8f8fdedf9076643c28047fce31504 + +### Hash: +5644e3096604a84ff9554128669dfdac + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-6984/instruction.md b/inferredbugs-6984/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6049bf91ab523d48b8128efa4b890260e700dffa --- /dev/null +++ b/inferredbugs-6984/instruction.md @@ -0,0 +1,410 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jillegal +**Bug ID:** 61 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * @author SERKAN OZAL + * + * E-Mail: serkanozal86@hotmail.com + * GitHub: https://github.com/serkan-ozal + */ + +package tr.com.serkanozal.jillegal.offheap.pool.impl; + +import java.lang.reflect.Array; + +import tr.com.serkanozal.jillegal.offheap.OffHeapAwareObject; +import tr.com.serkanozal.jillegal.offheap.domain.model.pool.ArrayOffHeapPoolCreateParameter; +import tr.com.serkanozal.jillegal.offheap.memory.DirectMemoryService; +import tr.com.serkanozal.jillegal.offheap.pool.ContentAwareOffHeapPool; +import tr.com.serkanozal.jillegal.offheap.pool.DeeplyForkableArrayOffHeapPool; +import tr.com.serkanozal.jillegal.util.JvmUtil; + +public class ComplexTypeArrayOffHeapPool extends BaseOffHeapPool> + implements DeeplyForkableArrayOffHeapPool>, + ContentAwareOffHeapPool> { + + protected int length; + protected boolean initializeElements; + protected long objectSize; + protected long arraySize; + protected T sampleObject; + protected A sampleArray; + protected A objectArray; + protected long sampleObjectAddress; + protected long objStartAddress; + protected long arrayStartAddress; + protected long arrayIndexStartAddress; + protected int arrayIndexScale; + protected JvmAwareArrayElementAddressFinder jvmAwareArrayElementAddressFinder; + + public ComplexTypeArrayOffHeapPool(ArrayOffHeapPoolCreateParameter parameter) { + this(parameter.getElementType(), parameter.getLength(), parameter.isInitializeElements(), + parameter.getDirectMemoryService()); + } + + public ComplexTypeArrayOffHeapPool(Class elementType, int length, DirectMemoryService directMemoryService) { + this(elementType, length, false, directMemoryService); + } + + public ComplexTypeArrayOffHeapPool(Class elementType, int length, boolean initializeElements, DirectMemoryService directMemoryService) { + super(elementType, directMemoryService); + if (length <= 0) { + throw new IllegalArgumentException("\"length\" must be positive !"); + } + init(elementType, length, initializeElements, directMemoryService); + } + + @SuppressWarnings("unchecked") + @Override + protected void init() { + super.init(); + + if (initializeElements) { + // All index is object pool array header point to allocated objects + for (long l = 0; l < length; l++) { + directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), + JvmUtil.toJvmAddress((objStartAddress + (l * objectSize)))); + } + + // Copy sample object to allocated memory region for each object + for (long l = 0; l < length; l++) { + directMemoryService.copyMemory( + sampleObjectAddress, + objStartAddress + (l * objectSize), + objectSize); + } + + /* + long sourceAddress = sampleObjectAddress + 4; + long copySize = objectSize - 4; + // Copy sample object to allocated memory region for each object + for (long l = 0; l < length; l++) { + long targetAddress = objStartAddress + (l * objectSize); + directMemoryService.putInt(targetAddress, 0); + directMemoryService.copyMemory(sourceAddress, targetAddress + 4, copySize); + } + */ + } + else { + // All indexes in object pool array point to empty (null) object + for (long l = 0; l < length; l++) { + directMemoryService.putLong(arrayIndexStartAddress + (l * arrayIndexScale), 0L); + } + } + + this.objectArray = (A) directMemoryService.getObject(arrayStartAddress); + } + + public boolean isInitializeElements() { + return initializeElements; + } + + @Override + public int getLength() { + return length; + } + + @Override + public boolean isMine(T element) { + checkAvailability(); + if (element == null) { + return false; + } + else { + return isMine(directMemoryService.addressOf(element)); + } + } + + @Override + public boolean isMine(long address) { + checkAvailability(); + return isIn(address); + } + + @Override + public boolean isMe(A array) { + checkAvailability(); + return objectArray == array; + } + + @Override + public boolean isMeAsAddress(long arrayAddress) { + checkAvailability(); + return allocationStartAddress == arrayAddress; + } + + @SuppressWarnings("unchecked") + @Override + public T getAt(int index) { + checkAvailability(); + if (index < 0 || index > length) { + throw new IllegalArgumentException("Invalid index: " + index); + } + processObject( + jvmAwareArrayElementAddressFinder.findAddress( + arrayIndexStartAddress, arrayIndexScale, index)); + T obj = ((T[])(objectArray))[index]; + if (obj instanceof OffHeapAwareObject) { + ((OffHeapAwareObject) obj).onGet(offHeapService, directMemoryService); + } + return obj; + } + + @Override + public void setAt(T element, int index) { + checkAvailability(); + if (index >= 0 && index < length) { + // Make target index points to element + directMemoryService.putLong(arrayIndexStartAddress + (index * arrayIndexScale), + JvmUtil.toJvmAddress(directMemoryService.addressOf(element))); + } + else { + throw new IllegalArgumentException("Invalid index: " + index); + } + } + + @Override + public A getArray() { + checkAvailability(); + return objectArray; + } + + @Override + public long getArrayAsAddress() { + checkAvailability(); + return allocationStartAddress; + } + + @Override + public synchronized void reset() { + init(); + makeAvaiable(); + } + + @Override + public synchronized void free() { + checkAvailability(); + // TODO Iterate over all objects and call their "onFree" methods if they are instance of "OffHeapAwareObject" + directMemoryService.freeMemory(allocationStartAddress); + directMemoryService.freeMemory(sampleObjectAddress); + makeUnavaiable(); + } + + @Override + public void init(ArrayOffHeapPoolCreateParameter parameter) { + init(parameter.getElementType(), parameter.getLength(), parameter.isInitializeElements(), + parameter.getDirectMemoryService()); + } + + @SuppressWarnings("unchecked") + protected void init(Class elementType, int length, boolean initializeElements, DirectMemoryService directMemoryService) { + try { + this.elementType = elementType; + this.length = length; + this.initializeElements = initializeElements; + this.directMemoryService = directMemoryService; + + objectSize = directMemoryService.sizeOfClass(elementType); + arraySize = JvmUtil.sizeOfArray(elementType, length); + if (initializeElements) { + allocationSize = + arraySize + (length * objectSize) + + 2 * JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning + } + else { + allocationSize = + arraySize + + 2 * JvmUtil.OBJECT_ADDRESS_SENSIVITY; // Extra memory for possible aligning + } + allocationStartAddress = directMemoryService.allocateMemory(allocationSize); + allocationEndAddress = allocationStartAddress + allocationSize; + + sampleArray = (A) Array.newInstance(elementType, 0); + + if (initializeElements) { + sampleObject = JvmUtil.getSampleInstance(elementType); + if (sampleObject == null) { + throw new IllegalStateException("Unable to create a sample object for class " + elementType.getName()); + } + sampleObjectAddress = directMemoryService.allocateMemory(objectSize); + directMemoryService.copyMemory(sampleObject, 0L, null, sampleObjectAddress, objectSize); + } + + long addressMod; + + arrayStartAddress = allocationStartAddress; + addressMod = arrayStartAddress % JvmUtil.OBJECT_ADDRESS_SENSIVITY; + if (addressMod != 0) { + arrayStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); + } + + int arrayHeaderSize = JvmUtil.getArrayHeaderSize(); + arrayIndexScale = JvmUtil.arrayIndexScale(elementType); + arrayIndexStartAddress = arrayStartAddress + JvmUtil.arrayBaseOffset(elementType); + + if (initializeElements) { + objStartAddress = arrayStartAddress + JvmUtil.sizeOfArray(elementType, length); + + // Allocated objects must start aligned as address size from start address of allocated address + long diffBetweenArrayAndObjectStartAddresses = objStartAddress - arrayStartAddress; + addressMod = diffBetweenArrayAndObjectStartAddresses % JvmUtil.OBJECT_ADDRESS_SENSIVITY; + if (addressMod != 0) { + objStartAddress += (JvmUtil.OBJECT_ADDRESS_SENSIVITY - addressMod); + } + } + + // Copy sample array header to object pool array header + directMemoryService.copyMemory(sampleArray, 0L, null, arrayStartAddress, arrayHeaderSize); + + // Set length of array object pool array + JvmUtil.setArrayLength(arrayStartAddress, elementType, length); + + switch (JvmUtil.getAddressSize()) { + case JvmUtil.SIZE_32_BIT: + jvmAwareArrayElementAddressFinder = new Address32BitJvmAwareArrayElementAddressFinder(); + break; + case JvmUtil.SIZE_64_BIT: + int referenceSize = JvmUtil.getReferenceSize(); + switch (referenceSize) { + case JvmUtil.ADDRESSING_4_BYTE: + jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); + break; + case JvmUtil.ADDRESSING_8_BYTE: + jvmAwareArrayElementAddressFinder = new Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder(); + break; + default: + throw new AssertionError("Unsupported reference size: " + referenceSize); + } + break; + default: + throw new AssertionError("Unsupported address size: " + JvmUtil.getAddressSize()); + } + + init(); + + makeAvaiable(); + } + catch (IllegalArgumentException e) { + throw e; + } + catch (Throwable t) { + logger.error("Error occured while initializing \"ComplexTypeArrayOffHeapPool\"", t); + throw new IllegalStateException(t); + } + } + + @Override + public DeeplyForkableArrayOffHeapPool> fork() { + return + new ComplexTypeArrayOffHeapPool( + getElementType(), + length, + getDirectMemoryService()); + } + + protected interface JvmAwareArrayElementAddressFinder { + + long findAddress(long arrayIndexStartAddress, int arrayIndexScale, int index); + + } + + protected class Address32BitJvmAwareArrayElementAddressFinder implements JvmAwareArrayElementAddressFinder { + + @Override + public long findAddress(long arrayIndexStartAddress, int arrayIndexScale, int index) { + return directMemoryService.getAsIntAddress(arrayIndexStartAddress + (arrayIndexScale * index)); + } + + } + + protected class Address64BitWithoutCompressedOopsJvmAwareArrayElementAddressFinder implements JvmAwareArrayElementAddressFinder { + + @Override + public long findAddress(long arrayIndexStartAddress, int arrayIndexScale, int index) { + return directMemoryService.getLong(arrayIndexStartAddress + (arrayIndexScale * index)); + } + + } + + protected class Address64BitWithCompressedOopsJvmAwareArrayElementAddressFinder implements JvmAwareArrayElementAddressFinder { + + @Override + public long findAddress(long arrayIndexStartAddress, int arrayIndexScale, int index) { + return directMemoryService.getAsIntAddress(arrayIndexStartAddress + (arrayIndexScale * index)); + } + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `tr.com.serkanozal.jillegal.offheap.pool.impl.ComplexTypeArrayOffHeapPool.init` writes to field `this.tr.com.serkanozal.jillegal.offheap.pool.impl.ComplexTypeArrayOffHeapPool.objectArray` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ComplexTypeArrayOffHeapPool.init() + +### Procedure Id: +tr.com.serkanozal.jillegal.offheap.pool.impl.ComplexTypeArrayOffHeapPool.init():void.210faf44851d643a17b2c97169ecf2ff + +### File: +src/main/java/tr/com/serkanozal/jillegal/offheap/pool/impl/ComplexTypeArrayOffHeapPool.java + +### Key: +ComplexTypeArrayOffHeapPool.java|init|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +d18120dccd2a463a41c67281a04651fe + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7052/instruction.md b/inferredbugs-7052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..258a1cff4634d85df36c31ba171f4c15d23ee12f --- /dev/null +++ b/inferredbugs-7052/instruction.md @@ -0,0 +1,199 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** tcSlackBuildNotifier +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package slacknotifications.teamcity.settings; + +import jetbrains.buildServer.serverSide.SBuildServer; +import jetbrains.buildServer.serverSide.ServerPaths; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import slacknotifications.SlackNotificationProxyConfig; + +import java.io.File; +import java.io.IOException; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.apache.http.auth.Credentials; + +public class SlackNotificationMainSettingsTest { + SBuildServer server = mock(SBuildServer.class); + Integer proxyPort = 8080; + String proxyHost = "myproxy.mycompany.com"; + String defaultChannel = "#my-channel"; + String teamName = "myteam"; + String token = "thisismytoken"; + String iconUrl = "http://www.myicon.com/icon.gif"; + String botName = "Team City"; + + @After + @Before + public void deleteSlackConfigFile(){ + DeleteConfigFiles(); + } + + private void DeleteConfigFiles() { + File outputFile = new File("slack", "slack-config.xml"); + outputFile.delete(); + + File outputDir = new File("slack"); + outputDir.delete(); + } + + @Test + public void TestFullConfig(){ + String expectedConfigDirectory = "."; + ServerPaths serverPaths = mock(ServerPaths.class); + when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); + + SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); + whms.register(); + whms.readFrom(getFullConfigElement()); + String proxy = whms.getProxyForUrl("http://something.somecompany.com"); + SlackNotificationProxyConfig whpc = whms.getProxyConfigForUrl("http://something.somecompany.com"); + assertTrue(proxy.equals(this.proxyHost)); + assertTrue(whpc.getProxyHost().equals(this.proxyHost )); + assertTrue(whpc.getProxyPort().equals(this.proxyPort)); + assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); + assertTrue(whms.getTeamName().equals(this.teamName)); + assertTrue(whms.getToken().equals(this.token)); + assertTrue(whms.getIconUrl().equals(this.iconUrl)); + assertTrue(whms.getBotName().equals(this.botName)); + assertTrue(whms.getShowBuildAgent()); + assertTrue(whms.getShowElapsedBuildTime()); + assertFalse(whms.getShowCommits()); + assertEquals(15, whms.getMaxCommitsToDisplay()); + + Credentials credentials = whpc.getCreds(); + + assertEquals("some-username", credentials.getUserPrincipal().getName()); + assertEquals("some-password", credentials.getPassword()); + } + + @Test + public void TestEmptyDefaultsConfig(){ + String expectedConfigDirectory = "."; + ServerPaths serverPaths = mock(ServerPaths.class); + when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); + + SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); + whms.register(); + whms.readFrom(getEmptyDefaultsConfigElement()); + String proxy = whms.getProxyForUrl("http://something.somecompany.com"); + SlackNotificationProxyConfig whpc = whms.getProxyConfigForUrl("http://something.somecompany.com"); + assertTrue(proxy.equals(this.proxyHost)); + assertTrue(whpc.getProxyHost().equals(this.proxyHost )); + assertTrue(whpc.getProxyPort().equals(this.proxyPort)); + assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); + assertTrue(whms.getTeamName().equals(this.teamName)); + assertTrue(whms.getToken().equals(this.token)); + assertTrue(whms.getIconUrl().equals(this.iconUrl)); + assertTrue(whms.getBotName().equals(this.botName)); + assertNull(whms.getShowBuildAgent()); + assertNull(whms.getShowElapsedBuildTime()); + assertTrue(whms.getShowCommits()); + assertEquals(5, whms.getMaxCommitsToDisplay()); + } + + private Element getFullConfigElement(){ + return getElement("src/test/resources/main-config-full.xml"); + } + + private Element getEmptyDefaultsConfigElement(){ + return getElement("src/test/resources/main-config-empty-defaults.xml"); + } + + private Element getElement(String filePath){ + SAXBuilder builder = new SAXBuilder(); + builder.setIgnoringElementContentWhitespace(true); + try { + Document doc = builder.build(filePath); + return doc.getRootElement(); + } catch (JDOMException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `whpc` last assigned on line 87 could be null and is dereferenced at line 89. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SlackNotificationMainSettingsTest.TestEmptyDefaultsConfig() + +### Procedure Id: +slacknotifications.teamcity.settings.SlackNotificationMainSettingsTest.TestEmptyDefaultsConfig():voi.3e1816cc39d87472915c836a6891ae39 + +### File: +tcslackbuildnotifier-core/src/test/java/slacknotifications/teamcity/settings/SlackNotificationMainSettingsTest.java + +### Key: +SlackNotificationMainSettingsTest.java|TestEmptyDefaultsConfig|NULL_DEREFERENCE + +### Node Key: +6924af27a245a1c6bbfbeafd4fa4ae36 + +### Hash: +0d7a4d3a48e0b3365792383f2e14dc30 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7099/instruction.md b/inferredbugs-7099/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2e71c5526d422c28ec0453f06e7b7a297d9049b --- /dev/null +++ b/inferredbugs-7099/instruction.md @@ -0,0 +1,207 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rapidoid +**Bug ID:** 48 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.rapidoid.scan; + +import org.rapidoid.RapidoidThing; +import org.rapidoid.annotation.Authors; +import org.rapidoid.annotation.Since; +import org.rapidoid.lambda.Operation; +import org.rapidoid.log.Log; +import org.rapidoid.u.U; + +import java.lang.annotation.Annotation; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +/* + * #%L + * rapidoid-commons + * %% + * Copyright (C) 2014 - 2017 Nikolche Mihajlovski and contributors + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ + +@Authors("Nikolche Mihajlovski") +@Since("2.5.0") +public class ScanParams extends RapidoidThing { + + private String[] packages = null; + + private String matching = null; + + private Class[] annotated = null; + + private ClassLoader classLoader = null; + + public synchronized ScanParams in(String... packages) { + this.packages = packages; + return this; + } + + public synchronized ScanParams in(Iterable packages) { + return in(U.arrayOf(String.class, packages)); + } + + public synchronized String[] in() { + return this.packages; + } + + public synchronized ScanParams matching(String matching) { + this.matching = matching; + return this; + } + + public synchronized String matching() { + return this.matching; + } + + public synchronized ScanParams annotated(Class... annotated) { + this.annotated = annotated; + return this; + } + + @SuppressWarnings("unchecked") + public synchronized ScanParams annotated(Collection> annotated) { + return annotated(U.arrayOf(Class.class, annotated)); + } + + public synchronized Class[] annotated() { + return this.annotated; + } + + public synchronized ScanParams classLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + return this; + } + + public synchronized ClassLoader classLoader() { + return this.classLoader; + } + + public synchronized List getAll() { + return ClasspathUtil.getClasses(this); + } + + public synchronized List> loadAll() { + return ClasspathUtil.loadClasses(this); + } + + public synchronized void forEach(Operation> classOperation) { + for (Class cls : loadAll()) { + try { + classOperation.execute(cls); + } catch (Exception e) { + Log.error("Cannot process annotated class!", e); + } + } + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ScanParams that = (ScanParams) o; + + if (!Arrays.equals(packages, that.packages)) return false; + if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; + if (!Arrays.equals(annotated, that.annotated)) return false; + return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null; + } + + @Override + public int hashCode() { + int result = Arrays.hashCode(packages); + result = 31 * result + (matching != null ? matching.hashCode() : 0); + result = 31 * result + Arrays.hashCode(annotated); + result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); + return result; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.rapidoid.scan.ScanParams.equals` reads without synchronization from `this.org.rapidoid.scan.ScanParams.annotated`. Potentially races with write in method `ScanParams.annotated(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean ScanParams.equals(Object) + +### Procedure Id: +org.rapidoid.scan.ScanParams.equals(java.lang.Object):boolean.706e5db8c19dcb50fc0380c822e7fa90 + +### File: +rapidoid-commons/src/main/java/org/rapidoid/scan/ScanParams.java + +### Key: +ScanParams.java|equals|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a377b8fd3c24554fb93891e3ad9a87ca + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7110/instruction.md b/inferredbugs-7110/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5dfcc67c25a18735db518b4d34ef9d1614a88877 --- /dev/null +++ b/inferredbugs-7110/instruction.md @@ -0,0 +1,1064 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rapidoid +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.rapidoid.http; + +/* + * #%L + * rapidoid-http + * %% + * Copyright (C) 2014 Nikolche Mihajlovski + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ + +import java.io.File; +import java.io.OutputStream; +import java.net.URL; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.rapidoid.data.BinaryMultiData; +import org.rapidoid.data.Data; +import org.rapidoid.data.KeyValueRanges; +import org.rapidoid.data.MultiData; +import org.rapidoid.data.Range; +import org.rapidoid.data.Ranges; +import org.rapidoid.inject.IoC; +import org.rapidoid.net.impl.ConnState; +import org.rapidoid.net.impl.DefaultExchange; +import org.rapidoid.net.mime.MediaType; +import org.rapidoid.security.Secure; +import org.rapidoid.util.Cls; +import org.rapidoid.util.Constants; +import org.rapidoid.util.IUser; +import org.rapidoid.util.U; +import org.rapidoid.util.UTILS; +import org.rapidoid.wrap.Bool; + +public class HttpExchangeImpl extends DefaultExchange implements HttpExchange, + HttpInterception, Constants { + + protected static final String SESSION_USER = "_user"; + + private static final String SESSION_COOKIE = "JSESSIONID"; + + public static final String SESSION_PAGE_STACK = "_page_stack_"; + + private final static HttpParser PARSER = IoC.singleton(HttpParser.class); + + private static final byte[] HEADER_SEP = ": ".getBytes(); + + private static final Pattern STATIC_RESOURCE_PATTERN = Pattern.compile("^[a-zA-Z0-9_\\.\\-/]+$"); + + final Range uri = new Range(); + final Range verb = new Range(); + final Range path = new Range(); + final Range query = new Range(); + final Range protocol = new Range(); + + final Ranges headers = new Ranges(50); + + private final KeyValueRanges params = new KeyValueRanges(50); + private final KeyValueRanges headersKV = new KeyValueRanges(50); + private final KeyValueRanges cookies = new KeyValueRanges(50); + private final KeyValueRanges data = new KeyValueRanges(50); + private final KeyValueRanges files = new KeyValueRanges(50); + + final Range body = new Range(); + final Bool isGet = new Bool(); + final Bool isKeepAlive = new Bool(); + + private boolean parsedParams; + private boolean parsedHeaders; + private boolean parsedBody; + + private int bodyPos; + + private boolean writesBody; + private boolean hasContentType; + private int startingPos; + private HttpResponses responses; + private HttpSession session; + private Router router; + + final Range multipartBoundary = new Range(); + + /**********/ + + private final Range subpathRange = new Range(); + + private final Data _body; + private final Data _uri; + private final Data _verb; + private final Data _path; + private final Data _subpath; + private final Data _query; + private final Data _protocol; + private final MultiData _params; + private final MultiData _headers; + private final MultiData _cookies; + private final MultiData _data; + private final BinaryMultiData _files; + + private int responseCode; + private String redirectUrl; + private String sessionId; + private Throwable error; + private boolean complete; + + public HttpExchangeImpl() { + reset(); + + this._body = data(body); + this._uri = data(uri); + this._verb = data(verb); + this._path = decodedData(path); + this._subpath = decodedData(subpathRange); + this._query = decodedData(query); + this._protocol = data(protocol); + this._params = multiData(params); + this._headers = multiData(headersKV); + this._cookies = multiData(cookies); + this._data = multiData(data); + this._files = binaryMultiData(files); + } + + @Override + public synchronized void reset() { + super.reset(); + + isGet.value = false; + isKeepAlive.value = false; + + verb.reset(); + uri.reset(); + path.reset(); + query.reset(); + protocol.reset(); + body.reset(); + multipartBoundary.reset(); + + params.reset(); + headersKV.reset(); + headers.reset(); + cookies.reset(); + data.reset(); + files.reset(); + + parsedParams = false; + parsedHeaders = false; + parsedBody = false; + + sessionId = null; + + session = null; + router = null; + + resetResponse(); + } + + private void resetResponse() { + writesBody = false; + bodyPos = -1; + hasContentType = false; + responses = null; + responseCode = -1; + redirectUrl = null; + error = null; + complete = false; + } + + @Override + public synchronized MultiData params_() { + if (!parsedParams) { + if (!query.isEmpty()) { + PARSER.parseParams(input(), params, query_().range()); + } + + parsedParams = true; + } + + return _params; + } + + @Override + public synchronized MultiData headers_() { + if (!parsedHeaders) { + if (!headers.isEmpty()) { + PARSER.parseHeadersIntoKV(input(), headers, headersKV, cookies, helper()); + } + + parsedHeaders = true; + } + + return _headers; + } + + @Override + public synchronized MultiData cookies_() { + if (!parsedHeaders) { + if (!headers.isEmpty()) { + PARSER.parseHeadersIntoKV(input(), headers, headersKV, cookies, helper()); + } + + parsedHeaders = true; + } + + return _cookies; + } + + @Override + public synchronized MultiData data_() { + if (!parsedBody) { + PARSER.parseBody(input(), headersKV, body, data, files, helper()); + parsedBody = true; + } + + return _data; + } + + @Override + public synchronized BinaryMultiData files_() { + if (!parsedBody) { + PARSER.parseBody(input(), headersKV, body, data, files, helper()); + parsedBody = true; + } + + return _files; + } + + public synchronized Data subpath_() { + return _subpath; + } + + @Override + public synchronized Data body_() { + return _body; + } + + @Override + public synchronized Data uri_() { + return _uri; + } + + @Override + public synchronized Data verb_() { + return _verb; + } + + @Override + public synchronized Data path_() { + return _path; + } + + @Override + public synchronized Data protocol_() { + return _protocol; + } + + @Override + public synchronized Data query_() { + return _query; + } + + public synchronized void setSubpath(int start, int end) { + subpathRange.setInterval(start, end); + } + + @Override + public synchronized HttpExchangeImpl done() { + if (isAsync()) { + completeResponse(); + conn.done(); + } + return this; + } + + @Override + public synchronized HttpExchangeBody send() { + conn.send(); + return this; + } + + @Override + public synchronized String toString() { + return "HttpExchange [uri=" + uri() + ", verb=" + verb() + ", path=" + path() + ", subpath=" + subpath() + + ", query=" + query() + ", protocol=" + protocol() + ", body=" + body() + ", headers=" + headers() + + ", params=" + params() + ", cookies=" + cookies() + ", data=" + data() + ", files=" + files() + "]"; + } + + @Override + public synchronized String verb() { + return verb_().get(); + } + + @Override + public synchronized String uri() { + return uri_().get(); + } + + @Override + public synchronized String path() { + return path_().get(); + } + + @Override + public synchronized String subpath() { + return subpath_().get(); + } + + @Override + public synchronized String query() { + return query_().get(); + } + + @Override + public synchronized String protocol() { + return protocol_().get(); + } + + @Override + public synchronized String body() { + return body_().get(); + } + + @Override + public synchronized Map params() { + return params_().get(); + } + + @Override + public synchronized String param(String name) { + return U.notNull(params_().get(name), "PARAM[%s]", name); + } + + @Override + public String param(String name, String defaultValue) { + return U.or(params_().get(name), defaultValue); + } + + @Override + public synchronized Map headers() { + return headers_().get(); + } + + @Override + public synchronized String header(String name) { + return U.notNull(headers_().get(name), "HEADERS[%s]", name); + } + + @Override + public String header(String name, String defaultValue) { + return U.or(headers_().get(name), defaultValue); + } + + @Override + public synchronized Map cookies() { + return cookies_().get(); + } + + @Override + public synchronized String cookie(String name) { + return U.notNull(cookies_().get(name), "COOKIES[%s]", name); + } + + @Override + public synchronized String cookie(String name, String defaultValue) { + return U.or(cookies_().get(name), defaultValue); + } + + @Override + public synchronized Map data() { + return data_().get(); + } + + @Override + public synchronized String data(String name) { + return U.notNull(data_().get(name), "DATA[%s]", name); + } + + @Override + public String data(String name, String defaultValue) { + return U.or(data_().get(name), defaultValue); + } + + @Override + public synchronized Map files() { + return files_().get(); + } + + @Override + public synchronized byte[] file(String name) { + return U.notNull(files_().get(name), "FILE[%s]", name); + } + + @Override + public synchronized byte[] file(String name, byte[] defaultValue) { + return U.or(files_().get(name), defaultValue); + } + + @Override + public synchronized Data host_() { + return headers_().get_("host"); + } + + @Override + public synchronized String host() { + return headers_().get("host"); + } + + public synchronized void setResponses(HttpResponses responses) { + this.responses = responses; + } + + public synchronized void setSession(HttpSession session) { + this.session = session; + } + + @Override + public synchronized HttpExchange addHeader(byte[] name, byte[] value) { + if (responseCode <= 0) { + responseCode(200); + } + + super.write(name); + super.write(HEADER_SEP); + super.write(value); + super.write(CR_LF); + + return this; + } + + private HttpExchangeHeaders responseCode(int responseCode) { + if (this.responseCode > 0) { + assert startingPos >= 0; + output().deleteAfter(startingPos); + } + + this.responseCode = responseCode; + + startingPos = output().size(); + output().append(getResp(responseCode).bytes()); + hasContentType = false; + writesBody = false; + bodyPos = -1; + + return this; + } + + public synchronized void completeResponse() { + + // TODO find better solution + if (complete) { + // after async req is done, it might be called to complete again, so exit + return; + } + + U.must(responseCode >= 100); + + write(new byte[0]); + + U.must(bodyPos >= 0); + + long responseSize = output().size() - bodyPos; + U.must(responseSize <= Integer.MAX_VALUE, "Response too big!"); + + int pos = startingPos + getResp(responseCode).contentLengthPos + 10; + output().putNumAsText(pos, responseSize, false); + + closeIf(!isKeepAlive.value); + + complete = true; + } + + private HttpResponse getResp(int code) { + HttpResponse resp = responses.get(code, isKeepAlive.value); + assert resp != null; + return resp; + } + + @Override + public synchronized HttpExchange addHeader(HttpHeader name, String value) { + addHeader(name.getBytes(), value.getBytes()); + return this; + } + + @Override + public synchronized HttpExchange setCookie(String name, String value, String... extras) { + String cookie = name + "=" + value; + + if (extras.length > 0) { + cookie += "; " + U.join("; ", extras); + } + + addHeader(HttpHeader.SET_COOKIE, cookie); + return this; + } + + @Override + public synchronized HttpExchange setContentType(MediaType MediaType) { + U.must(!hasContentType, "Content type was already set!"); + + addHeader(HttpHeader.CONTENT_TYPE.getBytes(), MediaType.getBytes()); + + // this must be at the end of this method, because state might get restarted + hasContentType = true; + + return this; + } + + @Override + public synchronized HttpExchange plain() { + return setContentType(MediaType.PLAIN_TEXT_UTF_8); + } + + @Override + public synchronized HttpExchange html() { + return setContentType(MediaType.HTML_UTF_8); + } + + @Override + public synchronized HttpExchange json() { + return setContentType(MediaType.JSON_UTF_8); + } + + @Override + public synchronized HttpExchange binary() { + return setContentType(MediaType.BINARY); + } + + @Override + public synchronized HttpExchange download(String filename) { + addHeader(HttpHeader.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); + addHeader(HttpHeader.CACHE_CONTROL, "private"); + return binary(); + } + + public synchronized void ensureHeadersComplete() { + if (!writesBody) { + if (!hasContentType) { + html(); + } + writesBody = true; + write(CR_LF); + bodyPos = output().size(); + } + } + + @Override + public synchronized HttpExchangeBody write(String s) { + ensureHeadersComplete(); + return super.write(s); + } + + @Override + public synchronized HttpExchangeBody writeln(String s) { + ensureHeadersComplete(); + return super.writeln(s); + } + + @Override + public synchronized HttpExchangeBody write(byte[] bytes) { + ensureHeadersComplete(); + return super.write(bytes); + } + + @Override + public synchronized HttpExchangeBody write(byte[] bytes, int offset, int length) { + ensureHeadersComplete(); + return super.write(bytes, offset, length); + } + + @Override + public synchronized HttpExchangeBody write(ByteBuffer buf) { + ensureHeadersComplete(); + return super.write(buf); + } + + @Override + public synchronized HttpExchangeBody write(File file) { + if (!hasContentType()) { + download(file.getName()); + } + + ensureHeadersComplete(); + return super.write(file); + } + + @Override + public synchronized HttpExchangeBody writeJSON(Object value) { + if (!hasContentType()) { + json(); + } + + ensureHeadersComplete(); + return super.writeJSON(value); + } + + @Override + public synchronized boolean isInitial() { + return conn.isInitial(); + } + + @Override + public synchronized ConnState state() { + return conn.state(); + } + + public synchronized boolean hasContentType() { + return hasContentType; + } + + @Override + public synchronized HttpExchangeBody sendFile(File file) { + U.must(file.exists()); + setContentType(MediaType.getByFileName(file.getAbsolutePath())); + write(file); + return this; + } + + @Override + public synchronized HttpExchangeBody redirect(String url) { + responseCode(303); + addHeader(HttpHeader.LOCATION, url); + this.redirectUrl = url; + ensureHeadersComplete(); + return this; + } + + @Override + public synchronized String redirectUrl() { + return redirectUrl; + } + + @Override + public synchronized HttpExchangeHeaders response(int httpResponseCode) { + return response(httpResponseCode, null, null); + } + + @Override + public synchronized HttpExchangeHeaders response(int httpResponseCode, String response) { + return response(httpResponseCode, response, null); + } + + @Override + public synchronized HttpExchangeHeaders response(int httpResponseCode, String response, Throwable err) { + + responseCode(httpResponseCode); + ensureHeadersComplete(); + + if (U.production()) { + if (response != null) { + write(response); + } + } else { + String title = U.or(response, "Error occured!"); + if (err != null) { + if (devMode()) { + HTMLSnippets.writeErrorPage(this, title, err); + } else { + HTMLSnippets.writeFullPage(this, title, ""); + } + } else { + HTMLSnippets.writeFullPage(this, title, "

The requested page cannot be found!

"); + } + } + + return this; + } + + @Override + public synchronized HttpExchangeHeaders startResponse(int httpResponseCode) { + return responseCode(httpResponseCode); + } + + @Override + public synchronized String constructUrl(String path) { + return (U.hasOption("https") ? "https://" : "http://") + host() + path; + } + + @Override + public synchronized String sessionId() { + if (sessionId == null) { + sessionId = cookie(SESSION_COOKIE, null); + + if (sessionId != null && !session.exists(sessionId)) { + sessionId = null; + } + + if (sessionId == null) { + sessionId = U.rndStr(50); + setCookie(SESSION_COOKIE, sessionId, "path=/"); + session.openSession(sessionId); + } + } + + return sessionId; + } + + @Override + public synchronized Map session() { + return session.getSession(sessionId()); + } + + @Override + public synchronized HttpExchangeHeaders sessionSet(String name, Object value) { + if (value != null) { + session.setAttribute(sessionId(), name, value); + } else { + session.deleteAttribute(sessionId(), name); + } + + return this; + } + + @SuppressWarnings("unchecked") + @Override + public synchronized T session(String name, T defaultValue) { + return U.or((T) session.getAttribute(sessionId(), name), defaultValue); + } + + @SuppressWarnings("unchecked") + @Override + public synchronized T session(String name) { + T value = (T) session.getAttribute(sessionId(), name); + U.notNull(value, "session[" + name + "]"); + return value; + } + + @SuppressWarnings("unchecked") + @Override + public synchronized T sessionGetOrCreate(String name, Class valueClass, Object... constructorArgs) { + T value = (T) session.getAttribute(sessionId(), name); + + if (value == null) { + value = U.newInstance(valueClass, constructorArgs); + session.setAttribute(sessionId(), name, value); + } + + return value; + } + + @Override + public synchronized HttpExchangeHeaders closeSession() { + session.closeSession(sessionId()); + sessionId = null; + return this; + } + + @Override + public synchronized boolean hasSession() { + String sessId = cookie(SESSION_COOKIE, null); + return sessId != null && session.exists(sessId); + } + + @Override + public synchronized HttpExchangeHeaders notFound() { + return response(404, "Error: page not found!"); + } + + @Override + public synchronized boolean isLoggedIn() { + return hasSession() && session(SESSION_USER, null) != null; + } + + @Override + public synchronized IUser user() { + U.must(isLoggedIn(), "Must be logged in!"); + + return session(SESSION_USER); + } + + @Override + public synchronized T user(Class userClass) { + IUser user = user(); + + T user2 = U.newInstance(userClass); + + Cls.setPropValue(user2, "username", user.username()); + Cls.setPropValue(user2, "email", user.email()); + Cls.setPropValue(user2, "name", user.name()); + + return user2; + } + + @Override + public synchronized boolean isAdmin() { + if (!isLoggedIn()) { + return false; + } + + return Secure.isAdmin(username()); + } + + private String username() { + return isLoggedIn() ? user().username() : null; + } + + @Override + public synchronized boolean isManager() { + if (!isLoggedIn()) { + return false; + } + + return Secure.isManager(username()); + } + + @Override + public synchronized boolean isModerator() { + if (!isLoggedIn()) { + return false; + } + + return Secure.isModerator(username()); + } + + @Override + public synchronized boolean hasRole(String role) { + if (!isLoggedIn()) { + return false; + } + + return Secure.hasRole(username(), role); + } + + @Override + public synchronized boolean isGetReq() { + return isGet.value; + } + + @Override + public synchronized boolean isPostReq() { + return !isGet.value && verb().equals("POST"); + } + + @Override + public synchronized byte[] sessionSerialize() { + return UTILS.serialize(session); + } + + @Override + public synchronized void sessionDeserialize(byte[] bytes) { + session = (HttpSession) UTILS.deserialize(bytes); + } + + @Override + public synchronized OutputStream outputStream() { + return new HttpOutputStream(this); + } + + @Override + public synchronized boolean devMode() { + if (U.dev()) { + return true; + } + + if (U.production()) { + return false; + } + + String host = host(); + return host == null || host.equals("localhost") || host.equals("127.0.0.1") || host.startsWith("localhost:") + || host.startsWith("127.0.0.1:"); + } + + @Override + public int responseCode() { + return this.responseCode; + } + + @Override + public void run() { + router.dispatch(this); + } + + public void setRouter(Router router) { + this.router = router; + } + + @Override + public HttpExchange exchange() { + return this; + } + + @Override + public boolean hasError() { + return error != null; + } + + @Override + public Throwable error() { + return error; + } + + @Override + public String pathSegment(int segmentIndex) { + return path().substring(1).split("/")[segmentIndex]; + } + + @Override + public HttpExchangeHeaders accessDeniedIf(boolean accessDeniedCondition) { + if (accessDeniedCondition) { + throw new SecurityException("Access denied!"); + } + return this; + } + + @Override + public HttpExchangeHeaders errorResponse(Throwable err) { + Throwable cause = U.rootCause(err); + if (cause instanceof SecurityException) { + return response(500, "Access Denied!", cause); + } else { + return response(500, "Internal server error!", cause); + } + } + + @Override + public HttpExchangeHeaders authorize(Class clazz) { + return accessDeniedIf(!Secure.canAccessClass(username(), clazz)); + } + + @Override + public boolean serveStatic() { + if (isGetReq()) { + String filename = path().substring(1); + + if (filename.isEmpty()) { + filename = "index.html"; + } + + if (!filename.contains("..") && STATIC_RESOURCE_PATTERN.matcher(filename).matches()) { + URL res = U.resource("public/" + filename); + if (res != null) { + startResponse(200); + sendFile(new File(res.getFile())); + return true; + } + } + } + return false; + } + + @Override + public HttpExchangeBody goBack(int steps) { + + List stack = session(SESSION_PAGE_STACK, null); + String dest = !stack.isEmpty() ? stack.get(stack.size() - 1) : "/"; + + for (int i = 0; i < steps; i++) { + if (stack != null && !stack.isEmpty()) { + stack.remove(stack.size() - 1); + if (!stack.isEmpty()) { + dest = stack.remove(stack.size() - 1); + } + } + } + + return redirect(dest); + } + + @SuppressWarnings("unchecked") + public HttpExchangeBody addToPageStack() { + List stack = sessionGetOrCreate(SESSION_PAGE_STACK, ArrayList.class); + + String last = !stack.isEmpty() ? stack.get(stack.size() - 1) : null; + String current = uri(); + + if (!U.eq(current, last)) { + stack.add(current); + if (stack.size() > 7) { + stack.remove(0); + } + } + + return this; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `stack` last assigned on line 958 could be null and is dereferenced at line 959. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +HttpExchangeBody HttpExchangeImpl.goBack(int) + +### Procedure Id: +org.rapidoid.http.HttpExchangeImpl.goBack(int):org.rapidoid.http.HttpExchangeBody.295a84ec9b54bf2a8eb5bb01a34e15f6 + +### File: +rapidoid-http/src/main/java/org/rapidoid/http/HttpExchangeImpl.java + +### Key: +HttpExchangeImpl.java|goBack|NULL_DEREFERENCE + +### Node Key: +cbf4abef6a7d17d1b80dfb598ec521f3 + +### Hash: +2834125fa3c2545497a7bbd1cfc966dc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7111/instruction.md b/inferredbugs-7111/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e984095bafdeef8fcee794d6e7ffbfc671a3f8e1 --- /dev/null +++ b/inferredbugs-7111/instruction.md @@ -0,0 +1,656 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rapidoid +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.rapidoid.http; + +/* + * #%L + * rapidoid-http + * %% + * Copyright (C) 2014 Nikolche Mihajlovski + * %% + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * #L% + */ + +import java.io.File; +import java.nio.ByteBuffer; +import java.util.Map; + +import org.rapidoid.data.BinaryMultiData; +import org.rapidoid.data.Data; +import org.rapidoid.data.KeyValueRanges; +import org.rapidoid.data.MultiData; +import org.rapidoid.data.Range; +import org.rapidoid.data.Ranges; +import org.rapidoid.net.impl.ConnState; +import org.rapidoid.net.impl.DefaultExchange; +import org.rapidoid.net.mime.MediaType; +import org.rapidoid.util.Constants; +import org.rapidoid.util.U; +import org.rapidoid.wrap.Bool; + +public class HttpExchangeImpl extends DefaultExchange implements HttpExchange, + Constants { + + private final static HttpParser PARSER = U.singleton(HttpParser.class); + + private static final byte[] HEADER_SEP = ": ".getBytes(); + + final Range uri = new Range(); + final Range verb = new Range(); + final Range path = new Range(); + final Range query = new Range(); + final Range protocol = new Range(); + + final Ranges headers = new Ranges(50); + + private final KeyValueRanges params = new KeyValueRanges(50); + private final KeyValueRanges headersKV = new KeyValueRanges(50); + private final KeyValueRanges cookies = new KeyValueRanges(50); + private final KeyValueRanges data = new KeyValueRanges(50); + private final KeyValueRanges files = new KeyValueRanges(50); + + final Range body = new Range(); + final Bool isGet = new Bool(); + final Bool isKeepAlive = new Bool(); + + private boolean parsedParams; + private boolean parsedHeaders; + private boolean parsedBody; + + int total; + public int bodyPos; + private boolean writesBody; + private boolean hasContentType; + private int startingPos; + private HttpResponses responses; + + final Range multipartBoundary = new Range(); + + /**********/ + + private final Range subpathRange = new Range(); + + private final Data _body; + private final Data _uri; + private final Data _verb; + private final Data _path; + private final Data _subpath; + private final Data _query; + private final Data _protocol; + private final MultiData _params; + private final MultiData _headers; + private final MultiData _cookies; + private final MultiData _data; + private final BinaryMultiData _files; + + private int responseCode; + + public HttpExchangeImpl() { + reset(); + + this._body = data(body); + this._uri = data(uri); + this._verb = data(verb); + this._path = decodedData(path); + this._subpath = decodedData(subpathRange); + this._query = decodedData(query); + this._protocol = data(protocol); + this._params = multiData(params); + this._headers = multiData(headersKV); + this._cookies = multiData(cookies); + this._data = multiData(data); + this._files = binaryMultiData(files); + } + + @Override + public void reset() { + super.reset(); + + isGet.value = false; + isKeepAlive.value = false; + + verb.reset(); + uri.reset(); + path.reset(); + query.reset(); + protocol.reset(); + body.reset(); + multipartBoundary.reset(); + + params.reset(); + headersKV.reset(); + headers.reset(); + cookies.reset(); + data.reset(); + files.reset(); + + parsedParams = false; + parsedHeaders = false; + parsedBody = false; + + total = -1; + writesBody = false; + bodyPos = -1; + hasContentType = false; + responses = null; + responseCode = -1; + } + + @Override + public MultiData params_() { + if (!parsedParams) { + if (!query.isEmpty()) { + PARSER.parseParams(input(), params, query_().range()); + } + + parsedParams = true; + } + + return _params; + } + + @Override + public MultiData headers_() { + if (!parsedHeaders) { + if (!headers.isEmpty()) { + PARSER.parseHeadersIntoKV(input(), headers, headersKV, cookies, helper()); + } + + parsedHeaders = true; + } + + return _headers; + } + + @Override + public MultiData cookies_() { + if (!parsedHeaders) { + if (!headers.isEmpty()) { + PARSER.parseHeadersIntoKV(input(), headers, headersKV, cookies, helper()); + } + + parsedHeaders = true; + } + + return _cookies; + } + + @Override + public MultiData data_() { + if (!parsedBody) { + PARSER.parseBody(input(), headersKV, body, data, files, helper()); + parsedBody = true; + } + + return _data; + } + + @Override + public BinaryMultiData files_() { + if (!parsedBody) { + PARSER.parseBody(input(), headersKV, body, data, files, helper()); + parsedBody = true; + } + + return _files; + } + + public Data subpath_() { + return _subpath; + } + + @Override + public Data body_() { + return _body; + } + + @Override + public Data uri_() { + return _uri; + } + + @Override + public Data verb_() { + return _verb; + } + + @Override + public Data path_() { + return _path; + } + + @Override + public Data protocol_() { + return _protocol; + } + + @Override + public Data query_() { + return _query; + } + + public void setSubpath(int start, int end) { + subpathRange.setInterval(start, end); + } + + @Override + public HttpExchangeImpl done() { + conn.done(); + return this; + } + + @Override + public String toString() { + return "WebExchange [uri=" + uri() + ", verb=" + verb() + ", path=" + path() + ", subpath=" + subpath() + + ", query=" + query() + ", protocol=" + protocol() + ", body=" + body() + ", headers=" + headers() + + ", params=" + params() + ", cookies=" + cookies() + ", data=" + data() + ", files=" + files() + "]"; + } + + @Override + public String verb() { + return verb_().get(); + } + + @Override + public String uri() { + return uri_().get(); + } + + @Override + public String path() { + return path_().get(); + } + + @Override + public String subpath() { + return subpath_().get(); + } + + @Override + public String query() { + return query_().get(); + } + + @Override + public String protocol() { + return protocol_().get(); + } + + @Override + public String body() { + return body_().get(); + } + + @Override + public Map params() { + return params_().get(); + } + + @Override + public String param(String name) { + return params_().get(name); + } + + @Override + public Map headers() { + return headers_().get(); + } + + @Override + public String header(String name) { + return headers_().get(name); + } + + @Override + public Map cookies() { + return cookies_().get(); + } + + @Override + public String cookie(String name) { + return cookies_().get(name); + } + + @Override + public Map data() { + return data_().get(); + } + + @Override + public String data(String name) { + return data_().get(name); + } + + @Override + public Map files() { + return files_().get(); + } + + @Override + public byte[] file(String name) { + return files_().get(name); + } + + @Override + public Data host_() { + return headers_().get_("host"); + } + + @Override + public String host() { + return headers_().get("host"); + } + + public void setResponses(HttpResponses responses) { + this.responses = responses; + } + + @Override + public synchronized HttpExchange addHeader(byte[] name, byte[] value) { + if (responseCode <= 0) { + responseCode(200); + } + + super.write(name); + super.write(HEADER_SEP); + super.write(value); + super.write(CR_LF); + + return this; + } + + @Override + public synchronized HttpExchangeHeaders responseCode(int responseCode) { + if (responseCode > 0) { + assert startingPos >= 0; + output().deleteAfter(startingPos); + } + + this.responseCode = responseCode; + + startingPos = output().size(); + output().append(getResp(responseCode).bytes()); + hasContentType = false; + writesBody = false; + bodyPos = -1; + + return this; + } + + public void completeResponse() { + U.must(responseCode >= 100); + long wrote = output().size() - bodyPos; + U.must(wrote <= Integer.MAX_VALUE, "Response too big!"); + + int pos = startingPos + getResp(responseCode).contentLengthPos + 10; + output().putNumAsText(pos, wrote, false); + } + + private HttpResponse getResp(int code) { + HttpResponse resp = responses.get(code, isKeepAlive.value); + assert resp != null; + return resp; + } + + @Override + public HttpExchange addHeader(HttpHeader name, String value) { + addHeader(name.getBytes(), value.getBytes()); + return this; + } + + @Override + public HttpExchange setCookie(String name, String value) { + addHeader(HttpHeader.SET_COOKIE, name + "=" + value); + return this; + } + + @Override + public synchronized HttpExchange setContentType(MediaType MediaType) { + U.must(!hasContentType, "Content type was already set!"); + + addHeader(HttpHeader.CONTENT_TYPE.getBytes(), MediaType.getBytes()); + + // this must be at the end of this method, because state might get restarted + hasContentType = true; + + return this; + } + + @Override + public HttpExchange plain() { + return setContentType(MediaType.PLAIN_TEXT_UTF_8); + } + + @Override + public HttpExchange html() { + return setContentType(MediaType.HTML_UTF_8); + } + + @Override + public HttpExchange json() { + return setContentType(MediaType.JSON_UTF_8); + } + + @Override + public HttpExchange binary() { + return setContentType(MediaType.BINARY); + } + + @Override + public HttpExchange download(String filename) { + addHeader(HttpHeader.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\""); + addHeader(HttpHeader.CACHE_CONTROL, "private"); + return binary(); + } + + private synchronized void ensureHeadersComplete() { + if (!writesBody) { + if (!hasContentType) { + html(); + } + writesBody = true; + write(CR_LF); + bodyPos = output().size(); + } + } + + @Override + public HttpExchangeBody write(String s) { + ensureHeadersComplete(); + return super.write(s); + } + + @Override + public HttpExchangeBody write(byte[] bytes) { + ensureHeadersComplete(); + return super.write(bytes); + } + + @Override + public HttpExchangeBody write(byte[] bytes, int offset, int length) { + ensureHeadersComplete(); + return super.write(bytes, offset, length); + } + + @Override + public HttpExchangeBody write(ByteBuffer buf) { + ensureHeadersComplete(); + return super.write(buf); + } + + @Override + public HttpExchangeBody write(File file) { + if (!hasContentType()) { + download(file.getName()); + } + + ensureHeadersComplete(); + return super.write(file); + } + + @Override + public HttpExchangeBody writeJSON(Object value) { + if (!hasContentType()) { + json(); + } + + ensureHeadersComplete(); + return super.writeJSON(value); + } + + @Override + public boolean isInitial() { + return conn.isInitial(); + } + + @Override + public ConnState state() { + return conn.state(); + } + + public boolean hasContentType() { + return hasContentType; + } + + @Override + public HttpExchangeBody sendFile(File file) { + U.must(file.exists()); + setContentType(MediaType.getByFileName(file.getAbsolutePath())); + write(file); + return this; + } + + @Override + public HttpExchangeBody redirect(String url) { + responseCode(303); + addHeader(HttpHeader.LOCATION, url); + ensureHeadersComplete(); + done(); + return this; + } + + @Override + public HttpExchangeHeaders response(int httpResponseCode) { + return response(httpResponseCode, null, null); + } + + @Override + public HttpExchangeHeaders response(int httpResponseCode, String response) { + return response(httpResponseCode, response, null); + } + + @Override + public HttpExchangeHeaders response(int httpResponseCode, String response, Throwable err) { + responseCode(httpResponseCode); + ensureHeadersComplete(); + + if (U.production()) { + if (response != null) { + write(response); + } + } else { + if (err != null) { + String title = U.or(response, "Error occured!"); + HTMLSnippets.writeErrorPage(this, title, err); + } + } + + return this; + } + + @Override + public String constructUrl(String path) { + return (U.hasOption("https") ? "https://" : "http://") + host() + path; + } + + @Override + public String sessionId() { + // FIXME implement this + return null; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.rapidoid.http.HttpExchangeImpl.reset` writes to field `this.com.rapidoid.http.HttpExchangeImpl.hasContentType` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HttpExchangeImpl.reset() + +### Procedure Id: +com.rapidoid.http.HttpExchangeImpl.reset():void.2e503902d6cdb104bb4e40c57489d37a + +### File: +rapidoid-http/src/main/java/com/rapidoid/http/HttpExchangeImpl.java + +### Key: +HttpExchangeImpl.java|reset|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +11297072dac801b038a82d6e231336be + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7116/instruction.md b/inferredbugs-7116/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89c8ee3a2d47deec0a940f32e4ed850d9c6fe6f9 --- /dev/null +++ b/inferredbugs-7116/instruction.md @@ -0,0 +1,1113 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 50 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + AtomicInteger rc = new AtomicInteger(BKException.Code.OK); + Enumeration ls = null; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + + void setReturnCode(int rc) { + this.rc.compareAndSet(BKException.Code.OK, rc); + } + + int getReturnCode() { + return rc.get(); + } + + void setLedgerEntries(Enumeration ls) { + this.ls = ls; + } + + Enumeration getLedgerEntries() { + return ls; + } + } + + @Test(timeout=60000) + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test(timeout=60000) + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test(timeout=60000) + public void testReadWriteAsyncSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + Enumeration ls = sync.getLedgerEntries(); + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test(timeout=60000) + public void testReadWriteRangeAsyncSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + Enumeration ls = sync.getLedgerEntries(); + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + SyncObj sync = (SyncObj)ctx; + sync.setLedgerEntries(seq); + sync.setReturnCode(rc); + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + @Test(timeout=60000) + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test(timeout=60000) + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadWriteAsyncLength() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test(timeout=60000) + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setReturnCode(rc); + synchronized (sync) { + sync.counter++; + sync.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setLedgerEntries(seq); + sync.setReturnCode(rc); + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setReturnCode(rc); + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testReadFromOpenLedger` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.entriesSize`. Potentially races with write in method `BookieReadWriteTest.setUp()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testReadFromOpenLedger() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testReadFromOpenLedger():void.e4941468ede9eff97d224f8674396381 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testReadFromOpenLedger|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +345c56e0a86a85e242c7844a9c3a518a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7117/instruction.md b/inferredbugs-7117/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d5e947de35683f3c2d65cd7382d36e1428c784c --- /dev/null +++ b/inferredbugs-7117/instruction.md @@ -0,0 +1,1202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + Enumeration ls; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + // Synchronization + SyncObj sync; + Set syncObjs; + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + } + + @Test + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test + public void testReadWriteAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test + public void testReadWriteRangeAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) { + fail("Return code is not OK: " + rc); + } + + ls = seq; + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + /** + * Method for obtaining the available permits of a ledger handle + * using reflection to avoid adding a new public method to the + * class. + * + * @param lh + * @return + */ + @SuppressWarnings("unchecked") + int getAvailablePermits(LedgerHandle lh) throws + NoSuchFieldException, IllegalAccessException + { + Field field = LedgerHandle.class.getDeclaredField("opCounterSem"); + field.setAccessible(true); + return ((Semaphore)field.get(lh)).availablePermits(); + } + + @Test + public void testReadWriteAsyncSingleClientThrottle() throws + IOException, NoSuchFieldException, IllegalAccessException { + try { + + Integer throttle = 100; + ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); + // Create a ledger + bkc.getConf().setThrottleValue(throttle); + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + + numEntriesToWrite = 8000; + for (int i = 0; i < (numEntriesToWrite - 2000); i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + + for (int i = 0; i < 2000; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + sync.counter = 0; + for (int i = 0; i < numEntriesToWrite; i+=throttle) { + lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.info("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteAsyncLength() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + SyncObj x = (SyncObj) ctx; + + synchronized (x) { + x.counter++; + x.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + ls = seq; + + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + sync = new SyncObj(); // initialize the synchronization data structure + + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testReadWriteSyncSingleClient` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.ls`. Potentially races with write in method `BookieReadWriteTest.testSyncReadAsyncWriteStringsSingleClient()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testReadWriteSyncSingleClient() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testReadWriteSyncSingleClient():void.f4a12f4765052741caa0d8c3eae97942 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testReadWriteSyncSingleClient|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +90f66f1095b33ad3c82b00c2ceb0bbaa + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7118/instruction.md b/inferredbugs-7118/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ed1aca63e2275cdc0d8cf475353d248cf8cc0bc1 --- /dev/null +++ b/inferredbugs-7118/instruction.md @@ -0,0 +1,1202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + Enumeration ls; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + // Synchronization + SyncObj sync; + Set syncObjs; + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + } + + @Test + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test + public void testReadWriteAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test + public void testReadWriteRangeAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) { + fail("Return code is not OK: " + rc); + } + + ls = seq; + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + /** + * Method for obtaining the available permits of a ledger handle + * using reflection to avoid adding a new public method to the + * class. + * + * @param lh + * @return + */ + @SuppressWarnings("unchecked") + int getAvailablePermits(LedgerHandle lh) throws + NoSuchFieldException, IllegalAccessException + { + Field field = LedgerHandle.class.getDeclaredField("opCounterSem"); + field.setAccessible(true); + return ((Semaphore)field.get(lh)).availablePermits(); + } + + @Test + public void testReadWriteAsyncSingleClientThrottle() throws + IOException, NoSuchFieldException, IllegalAccessException { + try { + + Integer throttle = 100; + ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); + // Create a ledger + bkc.getConf().setThrottleValue(throttle); + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + + numEntriesToWrite = 8000; + for (int i = 0; i < (numEntriesToWrite - 2000); i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + + for (int i = 0; i < 2000; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + sync.counter = 0; + for (int i = 0; i < numEntriesToWrite; i+=throttle) { + lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.info("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteAsyncLength() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + SyncObj x = (SyncObj) ctx; + + synchronized (x) { + x.counter++; + x.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + ls = seq; + + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + sync = new SyncObj(); // initialize the synchronization data structure + + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testMultiLedger` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.ls`. Potentially races with write in method `BookieReadWriteTest.testSyncReadAsyncWriteStringsSingleClient()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testMultiLedger() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testMultiLedger():void.aa595d12cc6aadb0c47f083c66314661 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testMultiLedger|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +aeac84a48aaf191f75c26d6ddda717b5 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7119/instruction.md b/inferredbugs-7119/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62d6919841d1108224fcb23d898df63db6735d41 --- /dev/null +++ b/inferredbugs-7119/instruction.md @@ -0,0 +1,202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 56 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package org.apache.bookkeeper.stats; + +import java.net.InetSocketAddress; + +import com.codahale.metrics.CsvReporter; +import com.codahale.metrics.MetricFilter; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.ScheduledReporter; +import com.codahale.metrics.Slf4jReporter; +import com.google.common.base.Strings; +import com.google.common.net.HostAndPort; +import static com.codahale.metrics.MetricRegistry.name; +import com.codahale.metrics.graphite.Graphite; +import com.codahale.metrics.graphite.GraphiteReporter; + +import com.codahale.metrics.jvm.GarbageCollectorMetricSet; +import com.codahale.metrics.jvm.MemoryUsageGaugeSet; + +import org.apache.bookkeeper.stats.StatsLogger; +import org.apache.bookkeeper.stats.StatsProvider; +import org.apache.commons.configuration.Configuration; + +import java.util.List; +import java.util.ArrayList; +import java.util.concurrent.TimeUnit; + +import java.io.File; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CodahaleMetricsProvider implements StatsProvider { + + static final Logger LOG = LoggerFactory.getLogger(CodahaleMetricsProvider.class); + + MetricRegistry metrics = null; + List reporters = new ArrayList(); + + synchronized void initIfNecessary() { + if (metrics == null) { + metrics = new MetricRegistry(); + metrics.registerAll(new MemoryUsageGaugeSet()); + metrics.registerAll(new GarbageCollectorMetricSet()); + } + } + + @Override + public void start(Configuration conf) { + initIfNecessary(); + + int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60); + String prefix = conf.getString("codahaleStatsPrefix", ""); + String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint"); + String csvDir = conf.getString("codahaleStatsCSVEndpoint"); + String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint"); + + if (!Strings.isNullOrEmpty(graphiteHost)) { + LOG.info("Configuring stats with graphite"); + HostAndPort addr = HostAndPort.fromString(graphiteHost); + final Graphite graphite = new Graphite( + new InetSocketAddress(addr.getHostText(), addr.getPort())); + reporters.add(GraphiteReporter.forRegistry(metrics) + .prefixedWith(prefix) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .filter(MetricFilter.ALL) + .build(graphite)); + } + if (!Strings.isNullOrEmpty(csvDir)) { + // NOTE: 1/ metrics output files are exclusive to a given process + // 2/ the output directory must exist + // 3/ if output files already exist they are not overwritten and there is no metrics output + File outdir; + if (Strings.isNullOrEmpty(prefix)) { + outdir = new File(csvDir, prefix); + } else { + outdir = new File(csvDir); + } + LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath()); + reporters.add(CsvReporter.forRegistry(metrics) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build(outdir)); + } + if (!Strings.isNullOrEmpty(slf4jCat)) { + LOG.info("Configuring stats with slf4j"); + reporters.add(Slf4jReporter.forRegistry(metrics) + .outputTo(LoggerFactory.getLogger(slf4jCat)) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build()); + } + for (ScheduledReporter r : reporters) { + r.start(metricsOutputFrequency, TimeUnit.SECONDS); + } + } + + @Override + public void stop() { + for (ScheduledReporter r : reporters) { + r.report(); + r.stop(); + } + } + + @Override + public StatsLogger getStatsLogger(String name) { + initIfNecessary(); + return new CodahaleStatsLogger(metrics, name); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.stats.CodahaleMetricsProvider.getStatsLogger` reads without synchronization from `this.org.apache.bookkeeper.stats.CodahaleMetricsProvider.metrics`. Potentially races with write in method `CodahaleMetricsProvider.initIfNecessary()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +StatsLogger CodahaleMetricsProvider.getStatsLogger(String) + +### Procedure Id: +org.apache.bookkeeper.stats.CodahaleMetricsProvider.getStatsLogger(java.lang.String):org.apache.book.70acf931d610574751e0b62d633fb6ae + +### File: +bookkeeper-stats-providers/codahale-metrics-provider/src/main/java/org/apache/bookkeeper/stats/CodahaleMetricsProvider.java + +### Key: +CodahaleMetricsProvider.java|getStatsLogger|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +bf0ddea225cd73d06c33ad4ee6e9d4c7 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7120/instruction.md b/inferredbugs-7120/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a1bb901c24fe93cbdf2fc71e964bf0979165b1d --- /dev/null +++ b/inferredbugs-7120/instruction.md @@ -0,0 +1,1113 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 51 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + AtomicInteger rc = new AtomicInteger(BKException.Code.OK); + Enumeration ls = null; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + + void setReturnCode(int rc) { + this.rc.compareAndSet(BKException.Code.OK, rc); + } + + int getReturnCode() { + return rc.get(); + } + + void setLedgerEntries(Enumeration ls) { + this.ls = ls; + } + + Enumeration getLedgerEntries() { + return ls; + } + } + + @Test(timeout=60000) + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test(timeout=60000) + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test(timeout=60000) + public void testReadWriteAsyncSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + Enumeration ls = sync.getLedgerEntries(); + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test(timeout=60000) + public void testReadWriteRangeAsyncSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + Enumeration ls = sync.getLedgerEntries(); + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + SyncObj sync = (SyncObj)ctx; + sync.setLedgerEntries(seq); + sync.setReturnCode(rc); + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + @Test(timeout=60000) + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + SyncObj sync = new SyncObj(); + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test(timeout=60000) + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + Enumeration ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadWriteAsyncLength() throws IOException { + SyncObj sync = new SyncObj(); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + assertEquals("Error adding", BKException.Code.OK, sync.getReturnCode()); + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test(timeout=60000) + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test(timeout=60000) + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + assertEquals("Error reading", BKException.Code.OK, sync.getReturnCode()); + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setReturnCode(rc); + synchronized (sync) { + sync.counter++; + sync.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setLedgerEntries(seq); + sync.setReturnCode(rc); + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + sync.setReturnCode(rc); + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testLastConfirmedAdd` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.rng`. Potentially races with write in method `BookieReadWriteTest.setUp()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testLastConfirmedAdd() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testLastConfirmedAdd():void.916e4be23ad65a9ee13f63120c465a37 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testLastConfirmedAdd|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7c2086916ded2ea020cbe27960423cf6 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7121/instruction.md b/inferredbugs-7121/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..438a5c03eb17b161c74a871051b3ed86c68d525a --- /dev/null +++ b/inferredbugs-7121/instruction.md @@ -0,0 +1,1202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + Enumeration ls; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + // Synchronization + SyncObj sync; + Set syncObjs; + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + } + + @Test + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test + public void testReadWriteAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test + public void testReadWriteRangeAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) { + fail("Return code is not OK: " + rc); + } + + ls = seq; + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + /** + * Method for obtaining the available permits of a ledger handle + * using reflection to avoid adding a new public method to the + * class. + * + * @param lh + * @return + */ + @SuppressWarnings("unchecked") + int getAvailablePermits(LedgerHandle lh) throws + NoSuchFieldException, IllegalAccessException + { + Field field = LedgerHandle.class.getDeclaredField("opCounterSem"); + field.setAccessible(true); + return ((Semaphore)field.get(lh)).availablePermits(); + } + + @Test + public void testReadWriteAsyncSingleClientThrottle() throws + IOException, NoSuchFieldException, IllegalAccessException { + try { + + Integer throttle = 100; + ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); + // Create a ledger + bkc.getConf().setThrottleValue(throttle); + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + + numEntriesToWrite = 8000; + for (int i = 0; i < (numEntriesToWrite - 2000); i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + + for (int i = 0; i < 2000; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + sync.counter = 0; + for (int i = 0; i < numEntriesToWrite; i+=throttle) { + lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.info("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteAsyncLength() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + SyncObj x = (SyncObj) ctx; + + synchronized (x) { + x.counter++; + x.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + ls = seq; + + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + sync = new SyncObj(); // initialize the synchronization data structure + + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testMultiLedger` writes to field `this.org.apache.bookkeeper.test.BookieReadWriteTest.ls` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testMultiLedger() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testMultiLedger():void.aa595d12cc6aadb0c47f083c66314661 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testMultiLedger|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f9ba97f8f13374dc93ec511d94c1e66f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7126/instruction.md b/inferredbugs-7126/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e816fc677ea4819f29b8999c336643765848019 --- /dev/null +++ b/inferredbugs-7126/instruction.md @@ -0,0 +1,529 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.bookkeeper.bookie; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.bookkeeper.conf.ServerConfiguration; +import org.apache.bookkeeper.util.IOUtils; + +/** + * This class manages the writing of the bookkeeper entries. All the new + * entries are written to a common log. The LedgerCache will have pointers + * into files created by this class with offsets into the files to find + * the actual ledger entry. The entry log files created by this class are + * identified by a long. + */ +public class EntryLogger { + private static final Logger LOG = LoggerFactory.getLogger(EntryLogger.class); + private File dirs[]; + + long logId; + /** + * The maximum size of a entry logger file. + */ + final long logSizeLimit; + private volatile BufferedChannel logChannel; + /** + * The 1K block at the head of the entry logger file + * that contains the fingerprint and (future) meta-data + */ + final static int LOGFILE_HEADER_SIZE = 1024; + final ByteBuffer LOGFILE_HEADER = ByteBuffer.allocate(LOGFILE_HEADER_SIZE); + + final static long MB = 1024 * 1024; + + /** + * Scan entries in a entry log file. + */ + static interface EntryLogScanner { + /** + * Tests whether or not the entries belongs to the specified ledger + * should be processed. + * + * @param ledgerId + * Ledger ID. + * @return true if and only the entries of the ledger should be scanned. + */ + public boolean accept(long ledgerId); + + /** + * Process an entry. + * + * @param ledgerId + * Ledger ID. + * @param entry + * Entry ByteBuffer + * @throws IOException + */ + public void process(long ledgerId, ByteBuffer entry) throws IOException; + } + + /** + * Create an EntryLogger that stores it's log files in the given + * directories + */ + public EntryLogger(ServerConfiguration conf) throws IOException { + this.dirs = Bookie.getCurrentDirectories(conf.getLedgerDirs()); + // log size limit + this.logSizeLimit = conf.getEntryLogSizeLimit(); + + // Initialize the entry log header buffer. This cannot be a static object + // since in our unit tests, we run multiple Bookies and thus EntryLoggers + // within the same JVM. All of these Bookie instances access this header + // so there can be race conditions when entry logs are rolled over and + // this header buffer is cleared before writing it into the new logChannel. + LOGFILE_HEADER.put("BKLO".getBytes()); + // Find the largest logId + logId = -1; + for(File dir: dirs) { + if (!dir.exists()) { + throw new FileNotFoundException( + "Entry log directory does not exist"); + } + long lastLogId = getLastLogId(dir); + if (lastLogId > logId) { + logId = lastLogId; + } + } + createNewLog(); + } + + /** + * Maps entry log files to open channels. + */ + private ConcurrentHashMap channels = new ConcurrentHashMap(); + + /** + * Creates a new log file + */ + private void createNewLog() throws IOException { + List list = Arrays.asList(dirs); + Collections.shuffle(list); + if (logChannel != null) { + logChannel.flush(true); + } + + // It would better not to overwrite existing entry log files + File newLogFile = null; + do { + String logFileName = Long.toHexString(++logId) + ".log"; + for (File dir : list) { + newLogFile = new File(dir, logFileName); + if (newLogFile.exists()) { + LOG.warn("Found existed entry log " + newLogFile + + " when trying to create it as a new log."); + newLogFile = null; + break; + } + } + } while (newLogFile == null); + + logChannel = new BufferedChannel(new RandomAccessFile(newLogFile, "rw").getChannel(), 64*1024); + logChannel.write((ByteBuffer) LOGFILE_HEADER.clear()); + channels.put(logId, logChannel); + for(File f: dirs) { + setLastLogId(f, logId); + } + } + + /** + * Remove entry log. + * + * @param entryLogId + * Entry Log File Id + */ + protected boolean removeEntryLog(long entryLogId) { + BufferedChannel bc = channels.remove(entryLogId); + if (null != bc) { + // close its underlying file channel, so it could be deleted really + try { + bc.getFileChannel().close(); + } catch (IOException ie) { + LOG.warn("Exception while closing garbage collected entryLog file : ", ie); + } + } + File entryLogFile; + try { + entryLogFile = findFile(entryLogId); + } catch (FileNotFoundException e) { + LOG.error("Trying to delete an entryLog file that could not be found: " + + entryLogId + ".log"); + return false; + } + entryLogFile.delete(); + return true; + } + + /** + * writes the given id to the "lastId" file in the given directory. + */ + private void setLastLogId(File dir, long logId) throws IOException { + FileOutputStream fos; + fos = new FileOutputStream(new File(dir, "lastId")); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); + try { + bw.write(Long.toHexString(logId) + "\n"); + bw.flush(); + } finally { + try { + fos.close(); + } catch (IOException e) { + } + } + } + + private long getLastLogId(File dir) { + long id = readLastLogId(dir); + // read success + if (id > 0) { + return id; + } + // read failed, scan the ledger directories to find biggest log id + File[] logFiles = dir.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return file.getName().endsWith(".log"); + } + }); + List logs = new ArrayList(); + for (File lf : logFiles) { + String idString = lf.getName().split("\\.")[0]; + try { + long lid = Long.parseLong(idString, 16); + logs.add(lid); + } catch (NumberFormatException nfe) { + } + } + // no log file found in this directory + if (0 == logs.size()) { + return -1; + } + // order the collections + Collections.sort(logs); + return logs.get(logs.size() - 1); + } + + /** + * reads id from the "lastId" file in the given directory. + */ + private long readLastLogId(File f) { + FileInputStream fis; + try { + fis = new FileInputStream(new File(f, "lastId")); + } catch (FileNotFoundException e) { + return -1; + } + BufferedReader br = new BufferedReader(new InputStreamReader(fis)); + try { + String lastIdString = br.readLine(); + return Long.parseLong(lastIdString, 16); + } catch (IOException e) { + return -1; + } catch(NumberFormatException e) { + return -1; + } finally { + try { + fis.close(); + } catch (IOException e) { + } + } + } + + synchronized void flush() throws IOException { + if (logChannel != null) { + logChannel.flush(true); + } + } + synchronized long addEntry(long ledger, ByteBuffer entry) throws IOException { + if (logChannel.position() + entry.remaining() + 4 > logSizeLimit) { + createNewLog(); + } + ByteBuffer buff = ByteBuffer.allocate(4); + buff.putInt(entry.remaining()); + buff.flip(); + logChannel.write(buff); + long pos = logChannel.position(); + logChannel.write(entry); + //logChannel.flush(false); + + return (logId << 32L) | pos; + } + + byte[] readEntry(long ledgerId, long entryId, long location) throws IOException { + long entryLogId = location >> 32L; + long pos = location & 0xffffffffL; + ByteBuffer sizeBuff = ByteBuffer.allocate(4); + pos -= 4; // we want to get the ledgerId and length to check + BufferedChannel fc; + try { + fc = getChannelForLogId(entryLogId); + } catch (FileNotFoundException e) { + FileNotFoundException newe = new FileNotFoundException(e.getMessage() + " for " + ledgerId + " with location " + location); + newe.setStackTrace(e.getStackTrace()); + throw newe; + } + if (fc.read(sizeBuff, pos) != sizeBuff.capacity()) { + throw new IOException("Short read from entrylog " + entryLogId); + } + pos += 4; + sizeBuff.flip(); + int entrySize = sizeBuff.getInt(); + // entrySize does not include the ledgerId + if (entrySize > MB) { + LOG.error("Sanity check failed for entry size of " + entrySize + " at location " + pos + " in " + entryLogId); + + } + byte data[] = new byte[entrySize]; + ByteBuffer buff = ByteBuffer.wrap(data); + int rc = fc.read(buff, pos); + if ( rc != data.length) { + throw new IOException("Short read for " + ledgerId + "@" + entryId + " in " + entryLogId + "@" + pos + "("+rc+"!="+data.length+")"); + } + buff.flip(); + long thisLedgerId = buff.getLong(); + if (thisLedgerId != ledgerId) { + throw new IOException("problem found in " + entryLogId + "@" + entryId + " at position + " + pos + " entry belongs to " + thisLedgerId + " not " + ledgerId); + } + long thisEntryId = buff.getLong(); + if (thisEntryId != entryId) { + throw new IOException("problem found in " + entryLogId + "@" + entryId + " at position + " + pos + " entry is " + thisEntryId + " not " + entryId); + } + + return data; + } + + private BufferedChannel getChannelForLogId(long entryLogId) throws IOException { + BufferedChannel fc = channels.get(entryLogId); + if (fc != null) { + return fc; + } + File file = findFile(entryLogId); + // get channel is used to open an existing entry log file + // it would be better to open using read mode + FileChannel newFc = new RandomAccessFile(file, "r").getChannel(); + // If the file already exists before creating a BufferedChannel layer above it, + // set the FileChannel's position to the end so the write buffer knows where to start. + newFc.position(newFc.size()); + synchronized (channels) { + fc = channels.get(entryLogId); + if (fc != null) { + newFc.close(); + return fc; + } + fc = new BufferedChannel(newFc, 8192); + channels.put(entryLogId, fc); + return fc; + } + } + + private File findFile(long logId) throws FileNotFoundException { + for(File d: dirs) { + File f = new File(d, Long.toHexString(logId)+".log"); + if (f.exists()) { + return f; + } + } + throw new FileNotFoundException("No file for log " + Long.toHexString(logId)); + } + + /** + * Scan entry log + * + * @param entryLogId + * Entry Log Id + * @param scanner + * Entry Log Scanner + * @throws IOException + */ + protected void scanEntryLog(long entryLogId, EntryLogScanner scanner) throws IOException { + ByteBuffer sizeBuff = ByteBuffer.allocate(4); + ByteBuffer lidBuff = ByteBuffer.allocate(8); + BufferedChannel bc; + // Get the BufferedChannel for the current entry log file + try { + bc = getChannelForLogId(entryLogId); + } catch (IOException e) { + LOG.warn("Failed to get channel to scan entry log: " + entryLogId + ".log"); + throw e; + } + // Start the read position in the current entry log file to be after + // the header where all of the ledger entries are. + long pos = LOGFILE_HEADER_SIZE; + // Read through the entry log file and extract the ledger ID's. + while (true) { + // Check if we've finished reading the entry log file. + if (pos >= bc.size()) { + break; + } + if (bc.read(sizeBuff, pos) != sizeBuff.capacity()) { + throw new IOException("Short read for entry size from entrylog " + entryLogId); + } + pos += 4; + sizeBuff.flip(); + int entrySize = sizeBuff.getInt(); + if (entrySize > MB) { + LOG.warn("Found large size entry of " + entrySize + " at location " + pos + " in " + + entryLogId); + } + sizeBuff.clear(); + // try to read ledger id first + if (bc.read(lidBuff, pos) != lidBuff.capacity()) { + throw new IOException("Short read for ledger id from entrylog " + entryLogId); + } + lidBuff.flip(); + long lid = lidBuff.getLong(); + lidBuff.clear(); + if (!scanner.accept(lid)) { + // skip this entry + pos += entrySize; + continue; + } + // read the entry + byte data[] = new byte[entrySize]; + ByteBuffer buff = ByteBuffer.wrap(data); + int rc = bc.read(buff, pos); + if (rc != data.length) { + throw new IOException("Short read for ledger entry from entryLog " + entryLogId + + "@" + pos + "(" + rc + "!=" + data.length + ")"); + } + buff.flip(); + // process the entry + scanner.process(lid, buff); + // Advance position to the next entry + pos += entrySize; + } + } + + /** + * Shutdown method to gracefully stop entry logger. + */ + public void shutdown() { + // since logChannel is buffered channel, do flush when shutting down + try { + flush(); + logChannel.getFileChannel().close(); + } catch (IOException ie) { + // we have no idea how to avoid io exception during shutting down, so just ignore it + LOG.error("Error flush entry log during shutting down, which may cause entry log corrupted.", ie); + } finally { + if (logChannel.getFileChannel().isOpen()) { + IOUtils.close(LOG, logChannel.getFileChannel()); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 256 is not released after line 258. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +long EntryLogger.readLastLogId(File) + +### Procedure Id: +org.apache.bookkeeper.bookie.EntryLogger.readLastLogId(java.io.File):long.8ace8f450d71d906070c82d407c1ff4b + +### File: +bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/EntryLogger.java + +### Key: +EntryLogger.java|readLastLogId|RESOURCE_LEAK + +### Node Key: +5d3c6d99ff5b41e64b77061cdef5ab41 + +### Hash: +a02a56d7fb95e8131e936872cdff9352 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7127/instruction.md b/inferredbugs-7127/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e78a101760f0c4657339e64f91115c0e8cbc3b1a --- /dev/null +++ b/inferredbugs-7127/instruction.md @@ -0,0 +1,747 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.proto; + +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.ArrayDeque; +import java.util.Queue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicLong; + +import org.apache.bookkeeper.conf.ClientConfiguration; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback; +import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.WriteCallback; +import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.ReadEntryCallback; +import static org.apache.bookkeeper.proto.BookieProtocol.PacketHeader; +import org.apache.bookkeeper.util.OrderedSafeExecutor; +import org.apache.bookkeeper.util.SafeRunnable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.jboss.netty.util.Timer; +import org.jboss.netty.util.HashedWheelTimer; +import org.jboss.netty.bootstrap.ClientBootstrap; +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.Channel; +import org.jboss.netty.channel.ChannelFactory; +import org.jboss.netty.channel.ChannelFuture; +import org.jboss.netty.channel.ChannelFutureListener; +import org.jboss.netty.channel.ChannelHandlerContext; +import org.jboss.netty.channel.ChannelPipeline; +import org.jboss.netty.channel.ChannelPipelineCoverage; +import org.jboss.netty.channel.ChannelPipelineFactory; +import org.jboss.netty.channel.ChannelStateEvent; +import org.jboss.netty.channel.Channels; +import org.jboss.netty.channel.ExceptionEvent; +import org.jboss.netty.channel.MessageEvent; +import org.jboss.netty.channel.SimpleChannelHandler; +import org.jboss.netty.channel.socket.ClientSocketChannelFactory; +import org.jboss.netty.handler.codec.frame.CorruptedFrameException; +import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; +import org.jboss.netty.handler.codec.frame.TooLongFrameException; +import org.jboss.netty.handler.timeout.ReadTimeoutHandler; +import org.jboss.netty.handler.timeout.ReadTimeoutException; + +/** + * This class manages all details of connection to a particular bookie. It also + * has reconnect logic if a connection to a bookie fails. + * + */ + +@ChannelPipelineCoverage("one") +public class PerChannelBookieClient extends SimpleChannelHandler implements ChannelPipelineFactory { + + static final Logger LOG = LoggerFactory.getLogger(PerChannelBookieClient.class); + + static final long maxMemory = Runtime.getRuntime().maxMemory() / 5; + public static int MAX_FRAME_LENGTH = 2 * 1024 * 1024; // 2M + + InetSocketAddress addr; + Semaphore opCounterSem = new Semaphore(2000); + AtomicLong totalBytesOutstanding; + ClientSocketChannelFactory channelFactory; + OrderedSafeExecutor executor; + private Timer readTimeoutTimer; + + ConcurrentHashMap addCompletions = new ConcurrentHashMap(); + ConcurrentHashMap readCompletions = new ConcurrentHashMap(); + + /** + * The following member variables do not need to be concurrent, or volatile + * because they are always updated under a lock + */ + Queue> pendingOps = new ArrayDeque>(); + Channel channel = null; + + private enum ConnectionState { + DISCONNECTED, CONNECTING, CONNECTED + }; + + private ConnectionState state; + private final ClientConfiguration conf; + + public PerChannelBookieClient(OrderedSafeExecutor executor, ClientSocketChannelFactory channelFactory, + InetSocketAddress addr, AtomicLong totalBytesOutstanding) { + this(new ClientConfiguration(), executor, channelFactory, addr, totalBytesOutstanding); + } + + public PerChannelBookieClient(ClientConfiguration conf, OrderedSafeExecutor executor, ClientSocketChannelFactory channelFactory, + InetSocketAddress addr, AtomicLong totalBytesOutstanding) { + this.conf = conf; + this.addr = addr; + this.executor = executor; + this.totalBytesOutstanding = totalBytesOutstanding; + this.channelFactory = channelFactory; + this.state = ConnectionState.DISCONNECTED; + this.readTimeoutTimer = null; + } + + synchronized private void connect() { + if (state == ConnectionState.CONNECTING) { + return; + } + // Start the connection attempt to the input server host. + state = ConnectionState.CONNECTING; + + if (LOG.isDebugEnabled()) + LOG.debug("Connecting to bookie: " + addr); + + // Set up the ClientBootStrap so we can create a new Channel connection + // to the bookie. + ClientBootstrap bootstrap = new ClientBootstrap(channelFactory); + bootstrap.setPipelineFactory(this); + bootstrap.setOption("tcpNoDelay", conf.getClientTcpNoDelay()); + bootstrap.setOption("keepAlive", true); + + ChannelFuture future = bootstrap.connect(addr); + + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + int rc; + Queue> oldPendingOps; + + synchronized (PerChannelBookieClient.this) { + + if (future.isSuccess()) { + LOG.info("Successfully connected to bookie: " + addr); + rc = BKException.Code.OK; + channel = future.getChannel(); + state = ConnectionState.CONNECTED; + } else { + LOG.error("Could not connect to bookie: " + addr); + rc = BKException.Code.BookieHandleNotAvailableException; + channel = null; + state = ConnectionState.DISCONNECTED; + } + + PerChannelBookieClient.this.channel = channel; + + // trick to not do operations under the lock, take the list + // of pending ops and assign it to a new variable, while + // emptying the pending ops by just assigning it to a new + // list + oldPendingOps = pendingOps; + pendingOps = new ArrayDeque>(); + } + + for (GenericCallback pendingOp : oldPendingOps) { + pendingOp.operationComplete(rc, null); + } + } + }); + } + + void connectIfNeededAndDoOp(GenericCallback op) { + boolean doOpNow; + + // common case without lock first + if (channel != null && state == ConnectionState.CONNECTED) { + doOpNow = true; + } else { + + synchronized (this) { + // check again under lock + if (channel != null && state == ConnectionState.CONNECTED) { + doOpNow = true; + } else { + + // if reached here, channel is either null (first connection + // attempt), + // or the channel is disconnected + doOpNow = false; + + // connection attempt is still in progress, queue up this + // op. Op will be executed when connection attempt either + // fails + // or + // succeeds + pendingOps.add(op); + + connect(); + } + } + } + + if (doOpNow) { + op.operationComplete(BKException.Code.OK, null); + } + + } + + /** + * This method should be called only after connection has been checked for + * {@link #connectIfNeededAndDoOp(GenericCallback)} + * + * @param ledgerId + * @param masterKey + * @param entryId + * @param lastConfirmed + * @param macCode + * @param data + * @param cb + * @param ctx + */ + void addEntry(final long ledgerId, byte[] masterKey, final long entryId, ChannelBuffer toSend, WriteCallback cb, + Object ctx, final int options) { + final int entrySize = toSend.readableBytes(); + + final CompletionKey completionKey = new CompletionKey(ledgerId, entryId); + + addCompletions.put(completionKey, new AddCompletion(cb, entrySize, ctx)); + + int totalHeaderSize = 4 // for the length of the packet + + 4 // for the type of request + + BookieProtocol.MASTER_KEY_LENGTH; // for the master key + + try{ + ChannelBuffer header = channel.getConfig().getBufferFactory().getBuffer(totalHeaderSize); + + header.writeInt(totalHeaderSize - 4 + entrySize); + header.writeInt(new PacketHeader(BookieProtocol.CURRENT_PROTOCOL_VERSION, + BookieProtocol.ADDENTRY, (short)options).toInt()); + header.writeBytes(masterKey, 0, BookieProtocol.MASTER_KEY_LENGTH); + + ChannelBuffer wrappedBuffer = ChannelBuffers.wrappedBuffer(header, toSend); + + ChannelFuture future = channel.write(wrappedBuffer); + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isSuccess()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Successfully wrote request for adding entry: " + entryId + " ledger-id: " + ledgerId + + " bookie: " + channel.getRemoteAddress() + " entry length: " + entrySize); + } + // totalBytesOutstanding.addAndGet(entrySize); + } else { + errorOutAddKey(completionKey); + } + } + }); + } catch (Throwable e) { + LOG.warn("Add entry operation failed", e); + errorOutAddKey(completionKey); + } + } + + public void readEntryAndFenceLedger(final long ledgerId, byte[] masterKey, + final long entryId, + ReadEntryCallback cb, Object ctx) { + final CompletionKey key = new CompletionKey(ledgerId, entryId); + readCompletions.put(key, new ReadCompletion(cb, ctx)); + + int totalHeaderSize = 4 // for the length of the packet + + 4 // for request type + + 8 // for ledgerId + + 8 // for entryId + + BookieProtocol.MASTER_KEY_LENGTH; // for masterKey + + ChannelBuffer tmpEntry = channel.getConfig().getBufferFactory().getBuffer(totalHeaderSize); + tmpEntry.writeInt(totalHeaderSize - 4); + + tmpEntry.writeInt(new PacketHeader(BookieProtocol.CURRENT_PROTOCOL_VERSION, + BookieProtocol.READENTRY, + BookieProtocol.FLAG_DO_FENCING).toInt()); + tmpEntry.writeLong(ledgerId); + tmpEntry.writeLong(entryId); + tmpEntry.writeBytes(masterKey, 0, BookieProtocol.MASTER_KEY_LENGTH); + + ChannelFuture future = channel.write(tmpEntry); + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isSuccess()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Successfully wrote request for reading entry: " + entryId + " ledger-id: " + + ledgerId + " bookie: " + channel.getRemoteAddress()); + } + } else { + errorOutReadKey(key); + } + } + }); + } + + public void readEntry(final long ledgerId, final long entryId, ReadEntryCallback cb, Object ctx) { + final CompletionKey key = new CompletionKey(ledgerId, entryId); + readCompletions.put(key, new ReadCompletion(cb, ctx)); + + int totalHeaderSize = 4 // for the length of the packet + + 4 // for request type + + 8 // for ledgerId + + 8; // for entryId + + try{ + ChannelBuffer tmpEntry = channel.getConfig().getBufferFactory().getBuffer(totalHeaderSize); + tmpEntry.writeInt(totalHeaderSize - 4); + + tmpEntry.writeInt(new PacketHeader(BookieProtocol.CURRENT_PROTOCOL_VERSION, + BookieProtocol.READENTRY, BookieProtocol.FLAG_NONE).toInt()); + tmpEntry.writeLong(ledgerId); + tmpEntry.writeLong(entryId); + + ChannelFuture future = channel.write(tmpEntry); + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isSuccess()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Successfully wrote request for reading entry: " + entryId + " ledger-id: " + + ledgerId + " bookie: " + channel.getRemoteAddress()); + } + } else { + errorOutReadKey(key); + } + } + }); + } catch(Throwable e) { + LOG.warn("Read entry operation failed", e); + errorOutReadKey(key); + } + } + + public void close() { + if (channel != null) { + channel.close().awaitUninterruptibly(); + } + if (readTimeoutTimer != null) { + readTimeoutTimer.stop(); + readTimeoutTimer = null; + } + } + + void errorOutReadKey(final CompletionKey key) { + executor.submitOrdered(key.ledgerId, new SafeRunnable() { + @Override + public void safeRun() { + + ReadCompletion readCompletion = readCompletions.remove(key); + + if (readCompletion != null) { + LOG.error("Could not write request for reading entry: " + key.entryId + " ledger-id: " + + key.ledgerId + " bookie: " + channel.getRemoteAddress()); + + readCompletion.cb.readEntryComplete(BKException.Code.BookieHandleNotAvailableException, + key.ledgerId, key.entryId, null, readCompletion.ctx); + } + } + + }); + } + + void errorOutAddKey(final CompletionKey key) { + executor.submitOrdered(key.ledgerId, new SafeRunnable() { + @Override + public void safeRun() { + + AddCompletion addCompletion = addCompletions.remove(key); + + if (addCompletion != null) { + String bAddress = "null"; + if(channel != null) + bAddress = channel.getRemoteAddress().toString(); + LOG.error("Could not write request for adding entry: " + key.entryId + " ledger-id: " + + key.ledgerId + " bookie: " + bAddress); + + addCompletion.cb.writeComplete(BKException.Code.BookieHandleNotAvailableException, key.ledgerId, + key.entryId, addr, addCompletion.ctx); + LOG.error("Invoked callback method: " + key.entryId); + } + } + + }); + + } + + /** + * Errors out pending entries. We call this method from one thread to avoid + * concurrent executions to QuorumOpMonitor (implements callbacks). It seems + * simpler to call it from BookieHandle instead of calling directly from + * here. + */ + + void errorOutOutstandingEntries() { + + // DO NOT rewrite these using Map.Entry iterations. We want to iterate + // on keys and see if we are successfully able to remove the key from + // the map. Because the add and the read methods also do the same thing + // in case they get a write failure on the socket. The one who + // successfully removes the key from the map is the one responsible for + // calling the application callback. + + for (CompletionKey key : addCompletions.keySet()) { + errorOutAddKey(key); + } + + for (CompletionKey key : readCompletions.keySet()) { + errorOutReadKey(key); + } + } + + /** + * In the netty pipeline, we need to split packets based on length, so we + * use the {@link LengthFieldBasedFrameDecoder}. Other than that all actions + * are carried out in this class, e.g., making sense of received messages, + * prepending the length to outgoing packets etc. + */ + @Override + public ChannelPipeline getPipeline() throws Exception { + ChannelPipeline pipeline = Channels.pipeline(); + + if (readTimeoutTimer == null) { + readTimeoutTimer = new HashedWheelTimer(); + } + + pipeline.addLast("readTimeout", new ReadTimeoutHandler(readTimeoutTimer, + conf.getReadTimeout())); + pipeline.addLast("lengthbasedframedecoder", new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, 4, 0, 4)); + pipeline.addLast("mainhandler", this); + return pipeline; + } + + /** + * If our channel has disconnected, we just error out the pending entries + */ + @Override + public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { + LOG.info("Disconnected from bookie: " + addr); + errorOutOutstandingEntries(); + channel.close(); + state = ConnectionState.DISCONNECTED; + + // we don't want to reconnect right away. If someone sends a request to + // this address, we will reconnect. + } + + /** + * Called by netty when an exception happens in one of the netty threads + * (mostly due to what we do in the netty threads) + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { + Throwable t = e.getCause(); + if (t instanceof CorruptedFrameException || t instanceof TooLongFrameException) { + LOG.error("Corrupted fram received from bookie: " + + e.getChannel().getRemoteAddress()); + return; + } + if (t instanceof ReadTimeoutException) { + ctx.getChannel().disconnect(); + return; + } + + if (t instanceof IOException) { + // these are thrown when a bookie fails, logging them just pollutes + // the logs (the failure is logged from the listeners on the write + // operation), so I'll just ignore it here. + return; + } + + LOG.error("Unexpected exception caught by bookie client channel handler", t); + // Since we are a library, cant terminate App here, can we? + } + + /** + * Called by netty when a message is received on a channel + */ + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { + if (!(e.getMessage() instanceof ChannelBuffer)) { + ctx.sendUpstream(e); + return; + } + + final ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); + final int type, rc; + final long ledgerId, entryId; + final PacketHeader header; + + try { + header = PacketHeader.fromInt(buffer.readInt()); + rc = buffer.readInt(); + ledgerId = buffer.readLong(); + entryId = buffer.readLong(); + } catch (IndexOutOfBoundsException ex) { + LOG.error("Unparseable response from bookie: " + addr, ex); + return; + } + + executor.submitOrdered(ledgerId, new SafeRunnable() { + @Override + public void safeRun() { + switch (header.getOpCode()) { + case BookieProtocol.ADDENTRY: + handleAddResponse(ledgerId, entryId, rc); + break; + case BookieProtocol.READENTRY: + handleReadResponse(ledgerId, entryId, rc, buffer); + break; + default: + LOG.error("Unexpected response, type: " + header.getOpCode() + + " received from bookie: " + addr + " , ignoring"); + } + } + }); + } + + void handleAddResponse(long ledgerId, long entryId, int rc) { + if (LOG.isDebugEnabled()) { + LOG.debug("Got response for add request from bookie: " + addr + " for ledger: " + ledgerId + " entry: " + + entryId + " rc: " + rc); + } + + // convert to BKException code because thats what the uppper + // layers expect. This is UGLY, there should just be one set of + // error codes. + switch (rc) { + case BookieProtocol.EOK: + rc = BKException.Code.OK; + break; + case BookieProtocol.EBADVERSION: + rc = BKException.Code.ProtocolVersionException; + break; + case BookieProtocol.EFENCED: + rc = BKException.Code.LedgerFencedException; + break; + case BookieProtocol.EUA: + rc = BKException.Code.UnauthorizedAccessException; + break; + default: + LOG.error("Add for ledger: " + ledgerId + ", entry: " + entryId + " failed on bookie: " + addr + + " with code: " + rc); + rc = BKException.Code.WriteException; + break; + } + + AddCompletion ac; + ac = addCompletions.remove(new CompletionKey(ledgerId, entryId)); + if (ac == null) { + LOG.error("Unexpected add response received from bookie: " + addr + " for ledger: " + ledgerId + + ", entry: " + entryId + " , ignoring"); + return; + } + + // totalBytesOutstanding.addAndGet(-ac.size); + + ac.cb.writeComplete(rc, ledgerId, entryId, addr, ac.ctx); + + } + + void handleReadResponse(long ledgerId, long entryId, int rc, ChannelBuffer buffer) { + if (LOG.isDebugEnabled()) { + LOG.debug("Got response for read request from bookie: " + addr + " for ledger: " + ledgerId + " entry: " + + entryId + " rc: " + rc + "entry length: " + buffer.readableBytes()); + } + + // convert to BKException code because thats what the uppper + // layers expect. This is UGLY, there should just be one set of + // error codes. + if (rc == BookieProtocol.EOK) { + rc = BKException.Code.OK; + } else if (rc == BookieProtocol.ENOENTRY || rc == BookieProtocol.ENOLEDGER) { + rc = BKException.Code.NoSuchEntryException; + } else if (rc == BookieProtocol.EBADVERSION) { + rc = BKException.Code.ProtocolVersionException; + } else if (rc == BookieProtocol.EUA) { + rc = BKException.Code.UnauthorizedAccessException; + } else { + LOG.error("Read for ledger: " + ledgerId + ", entry: " + entryId + " failed on bookie: " + addr + + " with code: " + rc); + rc = BKException.Code.ReadException; + } + + CompletionKey key = new CompletionKey(ledgerId, entryId); + ReadCompletion readCompletion = readCompletions.remove(key); + + if (readCompletion == null) { + /* + * This is a special case. When recovering a ledger, a client + * submits a read request with id -1, and receives a response with a + * different entry id. + */ + + readCompletion = readCompletions.remove(new CompletionKey(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED)); + } + + if (readCompletion == null) { + LOG.error("Unexpected read response received from bookie: " + addr + " for ledger: " + ledgerId + + ", entry: " + entryId + " , ignoring"); + return; + } + + readCompletion.cb.readEntryComplete(rc, ledgerId, entryId, buffer.slice(), readCompletion.ctx); + } + + /** + * Boiler-plate wrapper classes follow + * + */ + // visible for testing + static class ReadCompletion { + final ReadEntryCallback cb; + final Object ctx; + + public ReadCompletion(ReadEntryCallback cb, Object ctx) { + this.cb = cb; + this.ctx = ctx; + } + } + + // visible for testing + static class AddCompletion { + final WriteCallback cb; + //final long size; + final Object ctx; + + public AddCompletion(WriteCallback cb, long size, Object ctx) { + this.cb = cb; + //this.size = size; + this.ctx = ctx; + } + } + + // visable for testing + static class CompletionKey { + long ledgerId; + long entryId; + + CompletionKey(long ledgerId, long entryId) { + this.ledgerId = ledgerId; + this.entryId = entryId; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof CompletionKey) || obj == null) { + return false; + } + CompletionKey that = (CompletionKey) obj; + return this.ledgerId == that.ledgerId && this.entryId == that.entryId; + } + + @Override + public int hashCode() { + return ((int) ledgerId << 16) ^ ((int) entryId); + } + + public String toString() { + return String.format("LedgerEntry(%d, %d)", ledgerId, entryId); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.bookkeeper.proto.PerChannelBookieClient.channelDisconnected` writes to field `this.org.apache.bookkeeper.proto.PerChannelBookieClient.state` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PerChannelBookieClient.channelDisconnected(ChannelHandlerContext,ChannelStateEvent) + +### Procedure Id: +org.apache.bookkeeper.proto.PerChannelBookieClient.channelDisconnected(org.jboss.netty.channel.Chann.d9b6dfaa61cbef36d034b9ef63ba9d03 + +### File: +bookkeeper-server/src/main/java/org/apache/bookkeeper/proto/PerChannelBookieClient.java + +### Key: +PerChannelBookieClient.java|channelDisconnected|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f6c34bad65a7505097eabb8d43db9d2c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7128/instruction.md b/inferredbugs-7128/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfc69f4475676053df730ffdfc67f268381626b9 --- /dev/null +++ b/inferredbugs-7128/instruction.md @@ -0,0 +1,529 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.bookkeeper.bookie; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.bookkeeper.conf.ServerConfiguration; +import org.apache.bookkeeper.util.IOUtils; + +/** + * This class manages the writing of the bookkeeper entries. All the new + * entries are written to a common log. The LedgerCache will have pointers + * into files created by this class with offsets into the files to find + * the actual ledger entry. The entry log files created by this class are + * identified by a long. + */ +public class EntryLogger { + private static final Logger LOG = LoggerFactory.getLogger(EntryLogger.class); + private File dirs[]; + + long logId; + /** + * The maximum size of a entry logger file. + */ + final long logSizeLimit; + private volatile BufferedChannel logChannel; + /** + * The 1K block at the head of the entry logger file + * that contains the fingerprint and (future) meta-data + */ + final static int LOGFILE_HEADER_SIZE = 1024; + final ByteBuffer LOGFILE_HEADER = ByteBuffer.allocate(LOGFILE_HEADER_SIZE); + + final static long MB = 1024 * 1024; + + /** + * Scan entries in a entry log file. + */ + static interface EntryLogScanner { + /** + * Tests whether or not the entries belongs to the specified ledger + * should be processed. + * + * @param ledgerId + * Ledger ID. + * @return true if and only the entries of the ledger should be scanned. + */ + public boolean accept(long ledgerId); + + /** + * Process an entry. + * + * @param ledgerId + * Ledger ID. + * @param entry + * Entry ByteBuffer + * @throws IOException + */ + public void process(long ledgerId, ByteBuffer entry) throws IOException; + } + + /** + * Create an EntryLogger that stores it's log files in the given + * directories + */ + public EntryLogger(ServerConfiguration conf) throws IOException { + this.dirs = Bookie.getCurrentDirectories(conf.getLedgerDirs()); + // log size limit + this.logSizeLimit = conf.getEntryLogSizeLimit(); + + // Initialize the entry log header buffer. This cannot be a static object + // since in our unit tests, we run multiple Bookies and thus EntryLoggers + // within the same JVM. All of these Bookie instances access this header + // so there can be race conditions when entry logs are rolled over and + // this header buffer is cleared before writing it into the new logChannel. + LOGFILE_HEADER.put("BKLO".getBytes()); + // Find the largest logId + logId = -1; + for(File dir: dirs) { + if (!dir.exists()) { + throw new FileNotFoundException( + "Entry log directory does not exist"); + } + long lastLogId = getLastLogId(dir); + if (lastLogId > logId) { + logId = lastLogId; + } + } + createNewLog(); + } + + /** + * Maps entry log files to open channels. + */ + private ConcurrentHashMap channels = new ConcurrentHashMap(); + + /** + * Creates a new log file + */ + private void createNewLog() throws IOException { + List list = Arrays.asList(dirs); + Collections.shuffle(list); + if (logChannel != null) { + logChannel.flush(true); + } + + // It would better not to overwrite existing entry log files + File newLogFile = null; + do { + String logFileName = Long.toHexString(++logId) + ".log"; + for (File dir : list) { + newLogFile = new File(dir, logFileName); + if (newLogFile.exists()) { + LOG.warn("Found existed entry log " + newLogFile + + " when trying to create it as a new log."); + newLogFile = null; + break; + } + } + } while (newLogFile == null); + + logChannel = new BufferedChannel(new RandomAccessFile(newLogFile, "rw").getChannel(), 64*1024); + logChannel.write((ByteBuffer) LOGFILE_HEADER.clear()); + channels.put(logId, logChannel); + for(File f: dirs) { + setLastLogId(f, logId); + } + } + + /** + * Remove entry log. + * + * @param entryLogId + * Entry Log File Id + */ + protected boolean removeEntryLog(long entryLogId) { + BufferedChannel bc = channels.remove(entryLogId); + if (null != bc) { + // close its underlying file channel, so it could be deleted really + try { + bc.getFileChannel().close(); + } catch (IOException ie) { + LOG.warn("Exception while closing garbage collected entryLog file : ", ie); + } + } + File entryLogFile; + try { + entryLogFile = findFile(entryLogId); + } catch (FileNotFoundException e) { + LOG.error("Trying to delete an entryLog file that could not be found: " + + entryLogId + ".log"); + return false; + } + entryLogFile.delete(); + return true; + } + + /** + * writes the given id to the "lastId" file in the given directory. + */ + private void setLastLogId(File dir, long logId) throws IOException { + FileOutputStream fos; + fos = new FileOutputStream(new File(dir, "lastId")); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos)); + try { + bw.write(Long.toHexString(logId) + "\n"); + bw.flush(); + } finally { + try { + fos.close(); + } catch (IOException e) { + } + } + } + + private long getLastLogId(File dir) { + long id = readLastLogId(dir); + // read success + if (id > 0) { + return id; + } + // read failed, scan the ledger directories to find biggest log id + File[] logFiles = dir.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return file.getName().endsWith(".log"); + } + }); + List logs = new ArrayList(); + for (File lf : logFiles) { + String idString = lf.getName().split("\\.")[0]; + try { + long lid = Long.parseLong(idString, 16); + logs.add(lid); + } catch (NumberFormatException nfe) { + } + } + // no log file found in this directory + if (0 == logs.size()) { + return -1; + } + // order the collections + Collections.sort(logs); + return logs.get(logs.size() - 1); + } + + /** + * reads id from the "lastId" file in the given directory. + */ + private long readLastLogId(File f) { + FileInputStream fis; + try { + fis = new FileInputStream(new File(f, "lastId")); + } catch (FileNotFoundException e) { + return -1; + } + BufferedReader br = new BufferedReader(new InputStreamReader(fis)); + try { + String lastIdString = br.readLine(); + return Long.parseLong(lastIdString, 16); + } catch (IOException e) { + return -1; + } catch(NumberFormatException e) { + return -1; + } finally { + try { + fis.close(); + } catch (IOException e) { + } + } + } + + synchronized void flush() throws IOException { + if (logChannel != null) { + logChannel.flush(true); + } + } + synchronized long addEntry(long ledger, ByteBuffer entry) throws IOException { + if (logChannel.position() + entry.remaining() + 4 > logSizeLimit) { + createNewLog(); + } + ByteBuffer buff = ByteBuffer.allocate(4); + buff.putInt(entry.remaining()); + buff.flip(); + logChannel.write(buff); + long pos = logChannel.position(); + logChannel.write(entry); + //logChannel.flush(false); + + return (logId << 32L) | pos; + } + + byte[] readEntry(long ledgerId, long entryId, long location) throws IOException { + long entryLogId = location >> 32L; + long pos = location & 0xffffffffL; + ByteBuffer sizeBuff = ByteBuffer.allocate(4); + pos -= 4; // we want to get the ledgerId and length to check + BufferedChannel fc; + try { + fc = getChannelForLogId(entryLogId); + } catch (FileNotFoundException e) { + FileNotFoundException newe = new FileNotFoundException(e.getMessage() + " for " + ledgerId + " with location " + location); + newe.setStackTrace(e.getStackTrace()); + throw newe; + } + if (fc.read(sizeBuff, pos) != sizeBuff.capacity()) { + throw new IOException("Short read from entrylog " + entryLogId); + } + pos += 4; + sizeBuff.flip(); + int entrySize = sizeBuff.getInt(); + // entrySize does not include the ledgerId + if (entrySize > MB) { + LOG.error("Sanity check failed for entry size of " + entrySize + " at location " + pos + " in " + entryLogId); + + } + byte data[] = new byte[entrySize]; + ByteBuffer buff = ByteBuffer.wrap(data); + int rc = fc.read(buff, pos); + if ( rc != data.length) { + throw new IOException("Short read for " + ledgerId + "@" + entryId + " in " + entryLogId + "@" + pos + "("+rc+"!="+data.length+")"); + } + buff.flip(); + long thisLedgerId = buff.getLong(); + if (thisLedgerId != ledgerId) { + throw new IOException("problem found in " + entryLogId + "@" + entryId + " at position + " + pos + " entry belongs to " + thisLedgerId + " not " + ledgerId); + } + long thisEntryId = buff.getLong(); + if (thisEntryId != entryId) { + throw new IOException("problem found in " + entryLogId + "@" + entryId + " at position + " + pos + " entry is " + thisEntryId + " not " + entryId); + } + + return data; + } + + private BufferedChannel getChannelForLogId(long entryLogId) throws IOException { + BufferedChannel fc = channels.get(entryLogId); + if (fc != null) { + return fc; + } + File file = findFile(entryLogId); + // get channel is used to open an existing entry log file + // it would be better to open using read mode + FileChannel newFc = new RandomAccessFile(file, "r").getChannel(); + // If the file already exists before creating a BufferedChannel layer above it, + // set the FileChannel's position to the end so the write buffer knows where to start. + newFc.position(newFc.size()); + synchronized (channels) { + fc = channels.get(entryLogId); + if (fc != null) { + newFc.close(); + return fc; + } + fc = new BufferedChannel(newFc, 8192); + channels.put(entryLogId, fc); + return fc; + } + } + + private File findFile(long logId) throws FileNotFoundException { + for(File d: dirs) { + File f = new File(d, Long.toHexString(logId)+".log"); + if (f.exists()) { + return f; + } + } + throw new FileNotFoundException("No file for log " + Long.toHexString(logId)); + } + + /** + * Scan entry log + * + * @param entryLogId + * Entry Log Id + * @param scanner + * Entry Log Scanner + * @throws IOException + */ + protected void scanEntryLog(long entryLogId, EntryLogScanner scanner) throws IOException { + ByteBuffer sizeBuff = ByteBuffer.allocate(4); + ByteBuffer lidBuff = ByteBuffer.allocate(8); + BufferedChannel bc; + // Get the BufferedChannel for the current entry log file + try { + bc = getChannelForLogId(entryLogId); + } catch (IOException e) { + LOG.warn("Failed to get channel to scan entry log: " + entryLogId + ".log"); + throw e; + } + // Start the read position in the current entry log file to be after + // the header where all of the ledger entries are. + long pos = LOGFILE_HEADER_SIZE; + // Read through the entry log file and extract the ledger ID's. + while (true) { + // Check if we've finished reading the entry log file. + if (pos >= bc.size()) { + break; + } + if (bc.read(sizeBuff, pos) != sizeBuff.capacity()) { + throw new IOException("Short read for entry size from entrylog " + entryLogId); + } + pos += 4; + sizeBuff.flip(); + int entrySize = sizeBuff.getInt(); + if (entrySize > MB) { + LOG.warn("Found large size entry of " + entrySize + " at location " + pos + " in " + + entryLogId); + } + sizeBuff.clear(); + // try to read ledger id first + if (bc.read(lidBuff, pos) != lidBuff.capacity()) { + throw new IOException("Short read for ledger id from entrylog " + entryLogId); + } + lidBuff.flip(); + long lid = lidBuff.getLong(); + lidBuff.clear(); + if (!scanner.accept(lid)) { + // skip this entry + pos += entrySize; + continue; + } + // read the entry + byte data[] = new byte[entrySize]; + ByteBuffer buff = ByteBuffer.wrap(data); + int rc = bc.read(buff, pos); + if (rc != data.length) { + throw new IOException("Short read for ledger entry from entryLog " + entryLogId + + "@" + pos + "(" + rc + "!=" + data.length + ")"); + } + buff.flip(); + // process the entry + scanner.process(lid, buff); + // Advance position to the next entry + pos += entrySize; + } + } + + /** + * Shutdown method to gracefully stop entry logger. + */ + public void shutdown() { + // since logChannel is buffered channel, do flush when shutting down + try { + flush(); + logChannel.getFileChannel().close(); + } catch (IOException ie) { + // we have no idea how to avoid io exception during shutting down, so just ignore it + LOG.error("Error flush entry log during shutting down, which may cause entry log corrupted.", ie); + } finally { + if (logChannel.getFileChannel().isOpen()) { + IOUtils.close(LOG, logChannel.getFileChannel()); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedWriter` acquired to `bw` by call to `new()` at line 203 is not released after line 206. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void EntryLogger.setLastLogId(File,long) + +### Procedure Id: +org.apache.bookkeeper.bookie.EntryLogger.setLastLogId(java.io.File,long):void.44328c0381afde3e880469eea9b33e26 + +### File: +bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/EntryLogger.java + +### Key: +EntryLogger.java|setLastLogId|RESOURCE_LEAK + +### Node Key: +63248c5f7f52f9f8d01a88b987b758e2 + +### Hash: +b0c4d0b5d26ead82a7c007e25616bd5f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7129/instruction.md b/inferredbugs-7129/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0a591ba6a23b2ba7064648fbfd2928d58e8e75c --- /dev/null +++ b/inferredbugs-7129/instruction.md @@ -0,0 +1,1202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + Enumeration ls; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + // Synchronization + SyncObj sync; + Set syncObjs; + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + } + + @Test + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test + public void testReadWriteAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test + public void testReadWriteRangeAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) { + fail("Return code is not OK: " + rc); + } + + ls = seq; + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + /** + * Method for obtaining the available permits of a ledger handle + * using reflection to avoid adding a new public method to the + * class. + * + * @param lh + * @return + */ + @SuppressWarnings("unchecked") + int getAvailablePermits(LedgerHandle lh) throws + NoSuchFieldException, IllegalAccessException + { + Field field = LedgerHandle.class.getDeclaredField("opCounterSem"); + field.setAccessible(true); + return ((Semaphore)field.get(lh)).availablePermits(); + } + + @Test + public void testReadWriteAsyncSingleClientThrottle() throws + IOException, NoSuchFieldException, IllegalAccessException { + try { + + Integer throttle = 100; + ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); + // Create a ledger + bkc.getConf().setThrottleValue(throttle); + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + + numEntriesToWrite = 8000; + for (int i = 0; i < (numEntriesToWrite - 2000); i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + + for (int i = 0; i < 2000; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + sync.counter = 0; + for (int i = 0; i < numEntriesToWrite; i+=throttle) { + lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.info("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteAsyncLength() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + SyncObj x = (SyncObj) ctx; + + synchronized (x) { + x.counter++; + x.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + ls = seq; + + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + sync = new SyncObj(); // initialize the synchronization data structure + + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testSyncReadAsyncWriteStringsSingleClient` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.sync`. Potentially races with write in method `BookieReadWriteTest.setUp()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testSyncReadAsyncWriteStringsSingleClient() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testSyncReadAsyncWriteStringsSingleClient():void.6679f098748ca8245d03352878999fe6 + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testSyncReadAsyncWriteStringsSingleClient|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +5bbe564585e636c79edb2478e74da451 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7142/instruction.md b/inferredbugs-7142/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..06f50872f2722a7431501f54ba67357c3a269106 --- /dev/null +++ b/inferredbugs-7142/instruction.md @@ -0,0 +1,593 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 44 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package org.apache.bookkeeper.bookie; + +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.bookkeeper.bookie.EntryLogger.EntryLogScanner; +import org.apache.bookkeeper.bookie.GarbageCollector.GarbageCleaner; +import org.apache.bookkeeper.conf.ServerConfiguration; +import org.apache.bookkeeper.meta.LedgerManager; +import org.apache.bookkeeper.util.MathUtils; +import org.apache.bookkeeper.util.SnapshotMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This is the garbage collector thread that runs in the background to + * remove any entry log files that no longer contains any active ledger. + */ +public class GarbageCollectorThread extends Thread { + private static final Logger LOG = LoggerFactory.getLogger(GarbageCollectorThread.class); + + private static final int SECOND = 1000; + + // Maps entry log files to the set of ledgers that comprise the file and the size usage per ledger + private Map entryLogMetaMap = new ConcurrentHashMap(); + + // This is how often we want to run the Garbage Collector Thread (in milliseconds). + final long gcWaitTime; + + // Compaction parameters + boolean enableMinorCompaction = false; + final double minorCompactionThreshold; + final long minorCompactionInterval; + + boolean enableMajorCompaction = false; + final double majorCompactionThreshold; + final long majorCompactionInterval; + + long lastMinorCompactionTime; + long lastMajorCompactionTime; + + // Entry Logger Handle + final EntryLogger entryLogger; + final EntryLogScanner scanner; + + // Ledger Cache Handle + final LedgerCache ledgerCache; + final SnapshotMap activeLedgers; + + // flag to ensure gc thread will not be interrupted during compaction + // to reduce the risk getting entry log corrupted + final AtomicBoolean compacting = new AtomicBoolean(false); + + volatile boolean running = true; + + // track the last scanned successfully log id + long scannedLogId = 0; + + final GarbageCollector garbageCollector; + final GarbageCleaner garbageCleaner; + + /** + * A scanner wrapper to check whether a ledger is alive in an entry log file + */ + class CompactionScanner implements EntryLogScanner { + EntryLogMetadata meta; + + public CompactionScanner(EntryLogMetadata meta) { + this.meta = meta; + } + + @Override + public boolean accept(long ledgerId) { + return meta.containsLedger(ledgerId) && scanner.accept(ledgerId); + } + + @Override + public void process(long ledgerId, long offset, ByteBuffer entry) + throws IOException { + scanner.process(ledgerId, offset, entry); + } + } + + + /** + * Create a garbage collector thread. + * + * @param conf + * Server Configuration Object. + * @throws IOException + */ + public GarbageCollectorThread(ServerConfiguration conf, + final LedgerCache ledgerCache, + EntryLogger entryLogger, + SnapshotMap activeLedgers, + EntryLogScanner scanner, + LedgerManager ledgerManager) + throws IOException { + super("GarbageCollectorThread"); + + this.ledgerCache = ledgerCache; + this.entryLogger = entryLogger; + this.activeLedgers = activeLedgers; + this.scanner = scanner; + + this.gcWaitTime = conf.getGcWaitTime(); + + this.garbageCleaner = new GarbageCollector.GarbageCleaner() { + @Override + public void clean(long ledgerId) { + try { + if (LOG.isDebugEnabled()) { + LOG.debug("delete ledger : " + ledgerId); + } + ledgerCache.deleteLedger(ledgerId); + } catch (IOException e) { + LOG.error("Exception when deleting the ledger index file on the Bookie: ", e); + } + } + }; + + this.garbageCollector = new ScanAndCompareGarbageCollector(ledgerManager, activeLedgers); + + // compaction parameters + minorCompactionThreshold = conf.getMinorCompactionThreshold(); + minorCompactionInterval = conf.getMinorCompactionInterval() * SECOND; + majorCompactionThreshold = conf.getMajorCompactionThreshold(); + majorCompactionInterval = conf.getMajorCompactionInterval() * SECOND; + + if (minorCompactionInterval > 0 && minorCompactionThreshold > 0) { + if (minorCompactionThreshold > 1.0f) { + throw new IOException("Invalid minor compaction threshold " + + minorCompactionThreshold); + } + if (minorCompactionInterval <= gcWaitTime) { + throw new IOException("Too short minor compaction interval : " + + minorCompactionInterval); + } + enableMinorCompaction = true; + } + + if (majorCompactionInterval > 0 && majorCompactionThreshold > 0) { + if (majorCompactionThreshold > 1.0f) { + throw new IOException("Invalid major compaction threshold " + + majorCompactionThreshold); + } + if (majorCompactionInterval <= gcWaitTime) { + throw new IOException("Too short major compaction interval : " + + majorCompactionInterval); + } + enableMajorCompaction = true; + } + + if (enableMinorCompaction && enableMajorCompaction) { + if (minorCompactionInterval >= majorCompactionInterval || + minorCompactionThreshold >= majorCompactionThreshold) { + throw new IOException("Invalid minor/major compaction settings : minor (" + + minorCompactionThreshold + ", " + minorCompactionInterval + + "), major (" + majorCompactionThreshold + ", " + + majorCompactionInterval + ")"); + } + } + + LOG.info("Minor Compaction : enabled=" + enableMinorCompaction + ", threshold=" + + minorCompactionThreshold + ", interval=" + minorCompactionInterval); + LOG.info("Major Compaction : enabled=" + enableMajorCompaction + ", threshold=" + + majorCompactionThreshold + ", interval=" + majorCompactionInterval); + + lastMinorCompactionTime = lastMajorCompactionTime = MathUtils.now(); + } + + @Override + public void run() { + while (running) { + synchronized (this) { + try { + wait(gcWaitTime); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + continue; + } + } + + // Extract all of the ledger ID's that comprise all of the entry logs + // (except for the current new one which is still being written to). + entryLogMetaMap = extractMetaFromEntryLogs(entryLogMetaMap); + + // gc inactive/deleted ledgers + doGcLedgers(); + + // gc entry logs + doGcEntryLogs(); + + long curTime = MathUtils.now(); + if (enableMajorCompaction && + curTime - lastMajorCompactionTime > majorCompactionInterval) { + // enter major compaction + LOG.info("Enter major compaction"); + doCompactEntryLogs(majorCompactionThreshold); + lastMajorCompactionTime = MathUtils.now(); + // also move minor compaction time + lastMinorCompactionTime = lastMajorCompactionTime; + continue; + } + + if (enableMinorCompaction && + curTime - lastMinorCompactionTime > minorCompactionInterval) { + // enter minor compaction + LOG.info("Enter minor compaction"); + doCompactEntryLogs(minorCompactionThreshold); + lastMinorCompactionTime = MathUtils.now(); + } + } + } + + /** + * Do garbage collection ledger index files + */ + private void doGcLedgers() { + garbageCollector.gc(garbageCleaner); + } + + /** + * Garbage collect those entry loggers which are not associated with any active ledgers + */ + private void doGcEntryLogs() { + // Loop through all of the entry logs and remove the non-active ledgers. + for (Long entryLogId : entryLogMetaMap.keySet()) { + EntryLogMetadata meta = entryLogMetaMap.get(entryLogId); + for (Long entryLogLedger : meta.ledgersMap.keySet()) { + // Remove the entry log ledger from the set if it isn't active. + if (!activeLedgers.containsKey(entryLogLedger)) { + meta.removeLedger(entryLogLedger); + } + } + if (meta.isEmpty()) { + // This means the entry log is not associated with any active ledgers anymore. + // We can remove this entry log file now. + LOG.info("Deleting entryLogId " + entryLogId + " as it has no active ledgers!"); + removeEntryLog(entryLogId); + } + } + } + + /** + * Compact entry logs if necessary. + * + *

+ * Compaction will be executed from low unused space to high unused space. + * Those entry log files whose remaining size percentage is higher than threshold + * would not be compacted. + *

+ */ + private void doCompactEntryLogs(double threshold) { + LOG.info("Do compaction to compact those files lower than " + threshold); + // sort the ledger meta by occupied unused space + Comparator sizeComparator = new Comparator() { + @Override + public int compare(EntryLogMetadata m1, EntryLogMetadata m2) { + long unusedSize1 = m1.totalSize - m1.remainingSize; + long unusedSize2 = m2.totalSize - m2.remainingSize; + if (unusedSize1 > unusedSize2) { + return -1; + } else if (unusedSize1 < unusedSize2) { + return 1; + } else { + return 0; + } + } + }; + List logsToCompact = new ArrayList(); + logsToCompact.addAll(entryLogMetaMap.values()); + Collections.sort(logsToCompact, sizeComparator); + for (EntryLogMetadata meta : logsToCompact) { + if (meta.getUsage() >= threshold) { + break; + } + LOG.debug("Compacting entry log {} below threshold {}.", meta.entryLogId, threshold); + compactEntryLog(meta.entryLogId); + if (!running) { // if gc thread is not running, stop compaction + return; + } + } + } + + /** + * Shutdown the garbage collector thread. + * + * @throws InterruptedException if there is an exception stopping gc thread. + */ + public void shutdown() throws InterruptedException { + this.running = false; + if (compacting.compareAndSet(false, true)) { + // if setting compacting flag succeed, means gcThread is not compacting now + // it is safe to interrupt itself now + this.interrupt(); + } + this.join(); + } + + /** + * Remove entry log. + * + * @param entryLogId + * Entry Log File Id + */ + private void removeEntryLog(long entryLogId) { + // remove entry log file successfully + if (entryLogger.removeEntryLog(entryLogId)) { + entryLogMetaMap.remove(entryLogId); + } + } + + /** + * Compact an entry log. + * + * @param entryLogId + * Entry Log File Id + */ + protected void compactEntryLog(long entryLogId) { + EntryLogMetadata entryLogMeta = entryLogMetaMap.get(entryLogId); + if (null == entryLogMeta) { + LOG.warn("Can't get entry log meta when compacting entry log " + entryLogId + "."); + return; + } + + // Similar with Sync Thread + // try to mark compacting flag to make sure it would not be interrupted + // by shutdown during compaction. otherwise it will receive + // ClosedByInterruptException which may cause index file & entry logger + // closed and corrupted. + if (!compacting.compareAndSet(false, true)) { + // set compacting flag failed, means compacting is true now + // indicates another thread wants to interrupt gc thread to exit + return; + } + + LOG.info("Compacting entry log : " + entryLogId); + + try { + entryLogger.scanEntryLog(entryLogId, new CompactionScanner(entryLogMeta)); + // after moving entries to new entry log, remove this old one + removeEntryLog(entryLogId); + } catch (IOException e) { + LOG.info("Premature exception when compacting " + entryLogId, e); + } finally { + // clear compacting flag + compacting.set(false); + } + } + + /** + * Records the total size, remaining size and the set of ledgers that comprise a entry log. + */ + static class EntryLogMetadata { + long entryLogId; + long totalSize; + long remainingSize; + ConcurrentHashMap ledgersMap; + + public EntryLogMetadata(long logId) { + this.entryLogId = logId; + + totalSize = remainingSize = 0; + ledgersMap = new ConcurrentHashMap(); + } + + public void addLedgerSize(long ledgerId, long size) { + totalSize += size; + remainingSize += size; + Long ledgerSize = ledgersMap.get(ledgerId); + if (null == ledgerSize) { + ledgerSize = 0L; + } + ledgerSize += size; + ledgersMap.put(ledgerId, ledgerSize); + } + + public void removeLedger(long ledgerId) { + Long size = ledgersMap.remove(ledgerId); + if (null == size) { + return; + } + remainingSize -= size; + } + + public boolean containsLedger(long ledgerId) { + return ledgersMap.containsKey(ledgerId); + } + + public double getUsage() { + if (totalSize == 0L) { + return 0.0f; + } + return (double)remainingSize / totalSize; + } + + public boolean isEmpty() { + return ledgersMap.isEmpty(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("{ totalSize = ").append(totalSize).append(", remainingSize = ") + .append(remainingSize).append(", ledgersMap = ").append(ledgersMap).append(" }"); + return sb.toString(); + } + } + + /** + * A scanner used to extract entry log meta from entry log files. + */ + static class ExtractionScanner implements EntryLogScanner { + EntryLogMetadata meta; + + public ExtractionScanner(EntryLogMetadata meta) { + this.meta = meta; + } + + @Override + public boolean accept(long ledgerId) { + return true; + } + @Override + public void process(long ledgerId, long offset, ByteBuffer entry) { + // add new entry size of a ledger to entry log meta + meta.addLedgerSize(ledgerId, entry.limit() + 4); + } + } + + /** + * Method to read in all of the entry logs (those that we haven't done so yet), + * and find the set of ledger ID's that make up each entry log file. + * + * @param entryLogMetaMap + * Existing EntryLogs to Meta + * @throws IOException + */ + protected Map extractMetaFromEntryLogs(Map entryLogMetaMap) { + // Extract it for every entry log except for the current one. + // Entry Log ID's are just a long value that starts at 0 and increments + // by 1 when the log fills up and we roll to a new one. + long curLogId = entryLogger.getCurrentLogId(); + boolean hasExceptionWhenScan = false; + for (long entryLogId = scannedLogId; entryLogId < curLogId; entryLogId++) { + // Comb the current entry log file if it has not already been extracted. + if (entryLogMetaMap.containsKey(entryLogId)) { + continue; + } + + // check whether log file exists or not + // if it doesn't exist, this log file might have been garbage collected. + if (!entryLogger.logExists(entryLogId)) { + continue; + } + + LOG.info("Extracting entry log meta from entryLogId: " + entryLogId); + + try { + // Read through the entry log file and extract the entry log meta + EntryLogMetadata entryLogMeta = extractMetaFromEntryLog(entryLogger, entryLogId); + entryLogMetaMap.put(entryLogId, entryLogMeta); + } catch (IOException e) { + hasExceptionWhenScan = true; + LOG.warn("Premature exception when processing " + entryLogId + + " recovery will take care of the problem", e); + } + + // if scan failed on some entry log, we don't move 'scannedLogId' to next id + // if scan succeed, we don't need to scan it again during next gc run, + // we move 'scannedLogId' to next id + if (!hasExceptionWhenScan) { + ++scannedLogId; + } + } + return entryLogMetaMap; + } + + static EntryLogMetadata extractMetaFromEntryLog(EntryLogger entryLogger, long entryLogId) + throws IOException { + EntryLogMetadata entryLogMeta = new EntryLogMetadata(entryLogId); + ExtractionScanner scanner = new ExtractionScanner(entryLogMeta); + // Read through the entry log file and extract the entry log meta + entryLogger.scanEntryLog(entryLogId, scanner); + LOG.info("Retrieved entry log meta data entryLogId: " + + entryLogId + ", meta: " + entryLogMeta); + return entryLogMeta; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.bookie.GarbageCollectorThread.compactEntryLog` reads without synchronization from `this.org.apache.bookkeeper.bookie.GarbageCollectorThread.entryLogMetaMap`. Potentially races with write in method `GarbageCollectorThread.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GarbageCollectorThread.compactEntryLog(long) + +### Procedure Id: +org.apache.bookkeeper.bookie.GarbageCollectorThread.compactEntryLog(long):void.688c41624834d6128134c29b32660f6d + +### File: +bookkeeper-server/src/main/java/org/apache/bookkeeper/bookie/GarbageCollectorThread.java + +### Key: +GarbageCollectorThread.java|compactEntryLog|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +780cab8fbdb379721445909a9e8ef045 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7145/instruction.md b/inferredbugs-7145/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46cd9decd10c65ed852d7da5fbc57fdd6be5d9be --- /dev/null +++ b/inferredbugs-7145/instruction.md @@ -0,0 +1,1202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bookkeeper +**Bug ID:** 36 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.bookkeeper.test; + +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +import java.io.File; +import java.io.IOException; +import java.lang.NoSuchFieldException; +import java.lang.IllegalAccessException; +import java.lang.reflect.Field; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.Arrays; +import java.util.concurrent.Semaphore; + + +import org.apache.bookkeeper.client.AsyncCallback.AddCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadCallback; +import org.apache.bookkeeper.client.AsyncCallback.ReadLastConfirmedCallback; +import org.apache.bookkeeper.client.BKException; +import org.apache.bookkeeper.client.BookKeeper; +import org.apache.bookkeeper.client.LedgerEntry; +import org.apache.bookkeeper.client.LedgerHandle; +import org.apache.bookkeeper.client.BookKeeper.DigestType; +import org.apache.bookkeeper.streaming.LedgerInputStream; +import org.apache.bookkeeper.streaming.LedgerOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * This test tests read and write, synchronous and asynchronous, strings and + * integers for a BookKeeper client. The test deployment uses a ZooKeeper server + * and three BookKeepers. + * + */ + +public class BookieReadWriteTest extends MultiLedgerManagerMultiDigestTestCase + implements AddCallback, ReadCallback, ReadLastConfirmedCallback { + + // Depending on the taste, select the amount of logging + // by decommenting one of the two lines below + // static Logger LOG = Logger.getRootLogger(); + static Logger LOG = LoggerFactory.getLogger(BookieReadWriteTest.class); + + byte[] ledgerPassword = "aaa".getBytes(); + LedgerHandle lh, lh2; + long ledgerId; + Enumeration ls; + + // test related variables + int numEntriesToWrite = 200; + int maxInt = 2147483647; + Random rng; // Random Number Generator + ArrayList entries; // generated entries + ArrayList entriesSize; + + DigestType digestType; + + public BookieReadWriteTest(String ledgerManagerFactory, DigestType digestType) { + super(3); + this.digestType = digestType; + // set ledger manager + baseConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + baseClientConf.setLedgerManagerFactoryClassName(ledgerManagerFactory); + } + // Synchronization + SyncObj sync; + Set syncObjs; + + class SyncObj { + long lastConfirmed; + volatile int counter; + boolean value; + + public SyncObj() { + counter = 0; + lastConfirmed = LedgerHandle.INVALID_ENTRY_ID; + value = false; + } + } + + @Test + public void testOpenException() throws IOException, InterruptedException { + try { + lh = bkc.openLedger(0, digestType, ledgerPassword); + fail("Haven't thrown exception"); + } catch (BKException e) { + LOG.warn("Successfully thrown and caught exception:", e); + } + } + + /** + * test the streaming api for reading and writing + * + * @throws {@link IOException} + */ + @Test + public void testStreamingClients() throws IOException, BKException, InterruptedException { + lh = bkc.createLedger(digestType, ledgerPassword); + // write a string so that we cna + // create a buffer of a single bytes + // and check for corner cases + String toWrite = "we need to check for this string to match " + "and for the record mahadev is the best"; + LedgerOutputStream lout = new LedgerOutputStream(lh, 1); + byte[] b = toWrite.getBytes(); + lout.write(b); + lout.close(); + long lId = lh.getId(); + lh.close(); + // check for sanity + lh = bkc.openLedger(lId, digestType, ledgerPassword); + LedgerInputStream lin = new LedgerInputStream(lh, 1); + byte[] bread = new byte[b.length]; + int read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + + String newString = new String(bread); + assertTrue("these two should same", toWrite.equals(newString)); + lin.close(); + lh.close(); + // create another ledger to write one byte at a time + lh = bkc.createLedger(digestType, ledgerPassword); + lout = new LedgerOutputStream(lh); + for (int i = 0; i < b.length; i++) { + lout.write(b[i]); + } + lout.close(); + lId = lh.getId(); + lh.close(); + lh = bkc.openLedger(lId, digestType, ledgerPassword); + lin = new LedgerInputStream(lh); + bread = new byte[b.length]; + read = 0; + while (read < b.length) { + read = read + lin.read(bread, read, b.length); + } + newString = new String(bread); + assertTrue("these two should be same ", toWrite.equals(newString)); + lin.close(); + lh.close(); + } + + @Test + public void testReadWriteAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + lh.asyncReadEntries(0, numEntriesToWrite - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i)); + Integer origEntry = origbb.getInt(); + byte[] entry = ls.nextElement().getEntry(); + ByteBuffer result = ByteBuffer.wrap(entry); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + assertTrue("Checking entry " + i + " for size", entry.length == entriesSize.get(i).intValue()); + i++; + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + /** + * Check that the add api with offset and length work correctly. + * First try varying the offset. Then the length with a fixed non-zero + * offset. + */ + @Test + public void testReadWriteRangeAsyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + byte bytes[] = {'a','b','c','d','e','f','g','h','i'}; + + lh.asyncAddEntry(bytes, 0, bytes.length, this, sync); + lh.asyncAddEntry(bytes, 0, 4, this, sync); // abcd + lh.asyncAddEntry(bytes, 3, 4, this, sync); // defg + lh.asyncAddEntry(bytes, 3, (bytes.length-3), this, sync); // defghi + int numEntries = 4; + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntries) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + try { + lh.asyncAddEntry(bytes, -1, bytes.length, this, sync); + fail("Shouldn't be able to use negative offset"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 0, bytes.length+1, this, sync); + fail("Shouldn't be able to use that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -1, bytes.length+2, this, sync); + fail("Shouldn't be able to use negative offset " + + "with that much length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, 4, -3, this, sync); + fail("Shouldn't be able to use negative length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + try { + lh.asyncAddEntry(bytes, -4, -3, this, sync); + fail("Shouldn't be able to use negative offset & length"); + } catch (ArrayIndexOutOfBoundsException aiob) { + // expected + } + + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", + lh.getLastAddConfirmed() == (numEntries - 1)); + + // read entries + lh.asyncReadEntries(0, numEntries - 1, this, sync); + + synchronized (sync) { + while (sync.value == false) { + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] expected = null; + byte[] entry = ls.nextElement().getEntry(); + + switch (i) { + case 0: + expected = Arrays.copyOfRange(bytes, 0, bytes.length); + break; + case 1: + expected = Arrays.copyOfRange(bytes, 0, 4); + break; + case 2: + expected = Arrays.copyOfRange(bytes, 3, 3+4); + break; + case 3: + expected = Arrays.copyOfRange(bytes, 3, 3+(bytes.length-3)); + break; + } + assertNotNull("There are more checks than writes", expected); + + String message = "Checking entry " + i + " for equality [" + + new String(entry, "UTF-8") + "," + + new String(expected, "UTF-8") + "]"; + assertTrue(message, Arrays.equals(entry, expected)); + + i++; + } + assertTrue("Checking number of read entries", i == numEntries); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + class ThrottleTestCallback implements ReadCallback { + int throttle; + + ThrottleTestCallback(int threshold) { + this.throttle = threshold; + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) { + fail("Return code is not OK: " + rc); + } + + ls = seq; + synchronized(sync) { + sync.counter += throttle; + sync.notify(); + } + LOG.info("Current counter: " + sync.counter); + } + } + + /** + * Method for obtaining the available permits of a ledger handle + * using reflection to avoid adding a new public method to the + * class. + * + * @param lh + * @return + */ + @SuppressWarnings("unchecked") + int getAvailablePermits(LedgerHandle lh) throws + NoSuchFieldException, IllegalAccessException + { + Field field = LedgerHandle.class.getDeclaredField("opCounterSem"); + field.setAccessible(true); + return ((Semaphore)field.get(lh)).availablePermits(); + } + + @Test + public void testReadWriteAsyncSingleClientThrottle() throws + IOException, NoSuchFieldException, IllegalAccessException { + try { + + Integer throttle = 100; + ThrottleTestCallback tcb = new ThrottleTestCallback(throttle); + // Create a ledger + bkc.getConf().setThrottleValue(throttle); + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + + numEntriesToWrite = 8000; + for (int i = 0; i < (numEntriesToWrite - 2000); i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + + for (int i = 0; i < 2000; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + + /* + * Check that the difference is no larger than the throttling threshold + */ + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + sync.counter = 0; + for (int i = 0; i < numEntriesToWrite; i+=throttle) { + lh.asyncReadEntries(i, i + throttle - 1, tcb, sync); + int testValue = getAvailablePermits(lh); + assertTrue("Difference is incorrect : " + i + ", " + sync.counter + ", " + testValue, testValue <= throttle); + } + + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.info("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** READ COMPLETE ***"); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testSyncReadAsyncWriteStringsSingleClient() throws IOException { + LOG.info("TEST READ WRITE STRINGS MIXED SINGLE CLIENT"); + String charset = "utf-8"; + LOG.debug("Default charset: " + Charset.defaultCharset()); + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + int randomInt = rng.nextInt(maxInt); + byte[] entry = new String(Integer.toString(randomInt)).getBytes(charset); + entries.add(entry); + lh.asyncAddEntry(entry, this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + + LOG.debug("*** ASYNC WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETED // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + (lh.getLastAddConfirmed() + 1)); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + // read entries + ls = lh.readEntries(0, numEntriesToWrite - 1); + + LOG.debug("*** SYNC READ COMPLETE ***"); + + // at this point, Enumeration ls is filled with the returned + // values + int i = 0; + while (ls.hasMoreElements()) { + byte[] origEntryBytes = entries.get(i++); + byte[] retrEntryBytes = ls.nextElement().getEntry(); + + LOG.debug("Original byte entry size: " + origEntryBytes.length); + LOG.debug("Saved byte entry size: " + retrEntryBytes.length); + + String origEntry = new String(origEntryBytes, charset); + String retrEntry = new String(retrEntryBytes, charset); + + LOG.debug("Original entry: " + origEntry); + LOG.debug("Retrieved entry: " + retrEntry); + + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + assertTrue("Checking number of read entries", i == numEntriesToWrite); + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + + } + + @Test + public void testReadWriteSyncSingleClient() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + } + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer origbb = ByteBuffer.wrap(entries.get(i++)); + Integer origEntry = origbb.getInt(); + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + LOG.debug("Original entry: " + origEntry); + + Integer retrEntry = result.getInt(); + LOG.debug("Retrieved entry: " + retrEntry); + assertTrue("Checking entry " + i + " for equality", origEntry.equals(retrEntry)); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteZero() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + } + + /* + * Write a non-zero entry + */ + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + entries.add(entry.array()); + lh.addEntry(entry.array()); + + lh.close(); + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed()); + assertTrue("Verifying number of entries written", lh.getLastAddConfirmed() == numEntriesToWrite); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testMultiLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + lh2 = bkc.createLedger(digestType, ledgerPassword); + + long ledgerId = lh.getId(); + long ledgerId2 = lh2.getId(); + + // bkc.initMessageDigest("SHA1"); + LOG.info("Ledger ID 1: " + lh.getId() + ", Ledger ID 2: " + lh2.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + lh.addEntry(new byte[0]); + lh2.addEntry(new byte[0]); + } + + lh.close(); + lh2.close(); + + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + lh2 = bkc.openLedger(ledgerId2, digestType, ledgerPassword); + + LOG.debug("Number of entries written: " + lh.getLastAddConfirmed() + ", " + lh2.getLastAddConfirmed()); + assertTrue("Verifying number of entries written lh (" + lh.getLastAddConfirmed() + ")", lh + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + assertTrue("Verifying number of entries written lh2 (" + lh2.getLastAddConfirmed() + ")", lh2 + .getLastAddConfirmed() == (numEntriesToWrite - 1)); + + ls = lh.readEntries(0, numEntriesToWrite - 1); + int i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh.close(); + ls = lh2.readEntries(0, numEntriesToWrite - 1); + i = 0; + while (ls.hasMoreElements()) { + ByteBuffer result = ByteBuffer.wrap(ls.nextElement().getEntry()); + LOG.debug("Length of result: " + result.capacity()); + + assertTrue("Checking if entry " + i + " has zero bytes", result.capacity() == 0); + } + lh2.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadWriteAsyncLength() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.asyncAddEntry(entry.array(), this, sync); + } + + // wait for all entries to be acknowledged + synchronized (sync) { + while (sync.counter < numEntriesToWrite) { + LOG.debug("Entries counter = " + sync.counter); + sync.wait(); + } + } + long length = numEntriesToWrite * 4; + assertTrue("Ledger length before closing: " + lh.getLength(), lh.getLength() == length); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + + // *** WRITING PART COMPLETE // READ PART BEGINS *** + + // open ledger + lh = bkc.openLedger(ledgerId, digestType, ledgerPassword); + assertTrue("Ledger length after opening: " + lh.getLength(), lh.getLength() == length); + + + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedger() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if(i == numEntriesToWrite/2) { + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + // no recovery opened ledger 's last confirmed entry id is less than written + // and it just can read until (i-1) + int toRead = i - 1; + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + // close read only ledger should not change metadata + lhOpen.close(); + } + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == -1) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerOpenOnce() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + if (i == numEntriesToWrite / 2) { + // no recovery opened ledger 's last confirmed entry id is + // less than written + // and it just can read until (i-1) + int toRead = i - 1; + + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed != 0); + Enumeration readEntry = lhOpen.readEntries(toRead, toRead); + assertTrue("Enumeration of ledger entries has no element", readEntry.hasMoreElements() == true); + LedgerEntry e = readEntry.nextElement(); + assertEquals(toRead, e.getEntryId()); + Assert.assertArrayEquals(entries.get(toRead), e.getEntry()); + // should not written to a read only ledger + try { + lhOpen.addEntry(entry.array()); + fail("Should have thrown an exception here"); + } catch (BKException.BKIllegalOpException bkioe) { + // this is the correct response + } catch (Exception ex) { + LOG.error("Unexpected exception", ex); + fail("Unexpected exception"); + } + + } + } + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + @Test + public void testReadFromOpenLedgerZeroAndOne() throws Exception { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + LedgerHandle lhOpen = bkc.openLedgerNoRecovery(ledgerId, digestType, ledgerPassword); + + /* + * We haven't written anything, so it should be empty. + */ + LOG.debug("Checking that it is empty"); + long readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue("Last confirmed has the wrong value", + readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Writing one entry. + */ + LOG.debug("Going to write one entry"); + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + /* + * The hint should still indicate that there is no confirmed + * add. + */ + LOG.debug("Checking that it is still empty even after writing one entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == LedgerHandle.INVALID_ENTRY_ID); + + /* + * Adding one more, and this time we should expect to + * see one entry. + */ + entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + + LOG.info("Checking that it has an entry"); + readLastConfirmed = lhOpen.readLastConfirmed(); + assertTrue(readLastConfirmed == 0L); + + // close ledger + lh.close(); + // close read only ledger should not change metadata + lhOpen.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Test + public void testLastConfirmedAdd() throws IOException { + try { + // Create a ledger + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + long last = lh.readLastConfirmed(); + assertTrue("Last confirmed add: " + last, last == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + /* + * Asynchronous call to read last confirmed entry + */ + lh = bkc.createLedger(digestType, ledgerPassword); + // bkc.initMessageDigest("SHA1"); + ledgerId = lh.getId(); + LOG.info("Ledger ID: " + lh.getId()); + for (int i = 0; i < numEntriesToWrite; i++) { + ByteBuffer entry = ByteBuffer.allocate(4); + entry.putInt(rng.nextInt(maxInt)); + entry.position(0); + + entries.add(entry.array()); + entriesSize.add(entry.array().length); + lh.addEntry(entry.array()); + } + + + SyncObj sync = new SyncObj(); + lh.asyncReadLastConfirmed(this, sync); + + // Wait for for last confirmed + synchronized (sync) { + while (sync.lastConfirmed == LedgerHandle.INVALID_ENTRY_ID) { + LOG.debug("Counter = " + sync.lastConfirmed); + sync.wait(); + } + } + + assertTrue("Last confirmed add: " + sync.lastConfirmed, sync.lastConfirmed == (numEntriesToWrite - 2)); + + LOG.debug("*** WRITE COMPLETE ***"); + // close ledger + lh.close(); + } catch (BKException e) { + LOG.error("Test failed", e); + fail("Test failed due to BookKeeper exception"); + } catch (InterruptedException e) { + LOG.error("Test failed", e); + fail("Test failed due to interruption"); + } + } + + + @Override + public void addComplete(int rc, LedgerHandle lh, long entryId, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + SyncObj x = (SyncObj) ctx; + + synchronized (x) { + x.counter++; + x.notify(); + } + } + + @Override + public void readComplete(int rc, LedgerHandle lh, Enumeration seq, Object ctx) { + if(rc != BKException.Code.OK) fail("Return code is not OK: " + rc); + + ls = seq; + + synchronized (sync) { + sync.value = true; + sync.notify(); + } + } + + @Override + public void readLastConfirmedComplete(int rc, long lastConfirmed, Object ctx) { + SyncObj sync = (SyncObj) ctx; + + synchronized(sync) { + sync.lastConfirmed = lastConfirmed; + sync.notify(); + } + } + + @Override + @Before + public void setUp() throws Exception { + super.setUp(); + rng = new Random(System.currentTimeMillis()); // Initialize the Random + // Number Generator + entries = new ArrayList(); // initialize the entries list + entriesSize = new ArrayList(); + sync = new SyncObj(); // initialize the synchronization data structure + + } + + /* Clean up a directory recursively */ + protected boolean cleanUpDir(File dir) { + if (dir.isDirectory()) { + LOG.info("Cleaning up " + dir.getName()); + String[] children = dir.list(); + for (String string : children) { + boolean success = cleanUpDir(new File(dir, string)); + if (!success) + return false; + } + } + // The directory is now empty so delete it + return dir.delete(); + } + + /* User for testing purposes, void */ + class emptyWatcher implements Watcher { + @Override + public void process(WatchedEvent event) { + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.bookkeeper.test.BookieReadWriteTest.testReadWriteAsyncLength` reads without synchronization from `this.org.apache.bookkeeper.test.BookieReadWriteTest.sync`. Potentially races with write in method `BookieReadWriteTest.setUp()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BookieReadWriteTest.testReadWriteAsyncLength() + +### Procedure Id: +org.apache.bookkeeper.test.BookieReadWriteTest.testReadWriteAsyncLength():void.6c39830691886d6dec7e60341cf71a2d + +### File: +bookkeeper-server/src/test/java/org/apache/bookkeeper/test/BookieReadWriteTest.java + +### Key: +BookieReadWriteTest.java|testReadWriteAsyncLength|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +af41216f816ba0f538f5d034da127127 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7173/instruction.md b/inferredbugs-7173/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36be107f5910d0844b68e86e974b5790a0623b4d --- /dev/null +++ b/inferredbugs-7173/instruction.md @@ -0,0 +1,350 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 50 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.imixs.workflow.engine; + +import java.util.Calendar; +import java.util.Date; + +import org.imixs.workflow.ItemCollection; +import org.imixs.workflow.engine.WorkflowSchedulerService; +import org.imixs.workflow.exceptions.AccessDeniedException; +import org.imixs.workflow.exceptions.PluginException; +import org.imixs.workflow.exceptions.ProcessingErrorException; +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +/** + * Test class for WorkflowSchedulerService + * + * This test verifies if the inDue methods workItemInDue() and addWorkDays() + * + * @author rsoika + */ +public class TestWorkflowScheduler { + + @Before + public void setup() throws PluginException { + + } + + /** + * This test the date compare base on $lastProcessingDate in days + * + * @throws ProcessingErrorException + * @throws AccessDeniedException + * + */ + @Test + public void testDaysOnLastProcess() throws AccessDeniedException, ProcessingErrorException, PluginException { + + ItemCollection doc = new ItemCollection(); + ItemCollection activity = new ItemCollection(); + + // delay unit = days + activity.replaceItemValue("keyActivityDelayUnit", "3"); + // compare type = last process + activity.replaceItemValue("keyScheduledBaseObject", "1"); + // delay + activity.replaceItemValue("numActivityDelay", 10); + + Calendar workitemCal = Calendar.getInstance(); + workitemCal.setTime(new Date()); + // adjust -14 + workitemCal.add(Calendar.DAY_OF_MONTH, -14); + // prepare doc + doc.replaceItemValue("$lastProcessingDate", workitemCal.getTime()); + Assert.assertTrue(WorkflowSchedulerService.workItemInDue(doc, activity)); + + // delay + activity.replaceItemValue("numActivityDelay", 15); + workitemCal.setTime(new Date()); + // adjust -14 + workitemCal.add(Calendar.DAY_OF_MONTH, -14); + // prepare doc + doc.replaceItemValue("$lastProcessingDate", workitemCal.getTime()); + Assert.assertFalse(WorkflowSchedulerService.workItemInDue(doc, activity)); + + } + + + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Monday to Fiday + */ + @Test + public void testAddWorkdaysFromMonday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + System.out.println("Startdate=" + startDate.getTime()); + + + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + + + + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testAddWorkdaysFromFriday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testMinusWorkdaysFromFriday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK)); + // friday - 5 + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testMinusWorkdaysFromMonday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK)); + + } + + + + /** + * This method tests the addWorkDays function in a weekday movement from + * SATURDAY backwards + */ + @Test + public void testMinusWorkdaysFromSaturday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> THURSDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * SATURDAY forwards + */ + @Test + public void testAddWorkdaysFromSaturday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> TUESDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * SUNDAY backwards + */ + @Test + public void testMinusWorkdaysFromSunday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> THURSDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * SUNDAY forwards + */ + @Test + public void testAddWorkdaysFromSunday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> TUESDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `addWorkDays(startDate,1)` could be null and is dereferenced at line 265. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestWorkflowScheduler.testAddWorkdaysFromSunday() + +### Procedure Id: +org.imixs.workflow.engine.TestWorkflowScheduler.testAddWorkdaysFromSunday():void.900835c6e532cdd4c8e6ee3ff783f4bc + +### File: +imixs-workflow-engine/src/test/java/org/imixs/workflow/engine/TestWorkflowScheduler.java + +### Key: +TestWorkflowScheduler.java|testAddWorkdaysFromSunday|NULL_DEREFERENCE + +### Node Key: +15891b12c6ce50257e480adc810587ae + +### Hash: +a88a2f47b3fa29cb3af9e344553442f6 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7180/instruction.md b/inferredbugs-7180/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38853d408a6a0f12d5fcb3908526c2c2fa96f940 --- /dev/null +++ b/inferredbugs-7180/instruction.md @@ -0,0 +1,157 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 60 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.imixs.workflow.engine.solr; + +import java.util.List; +import java.util.logging.Logger; + +import org.imixs.workflow.ItemCollection; +import org.imixs.workflow.exceptions.ModelException; +import org.imixs.workflow.exceptions.PluginException; +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +/** + * Test the WorkflowService method parseJSONQueyResult from SolrSerachService + * + * @author rsoika + * + */ +public class TestParseSolrJSONResult { + + + @SuppressWarnings("unused") + private final static Logger logger = Logger.getLogger(TestParseSolrJSONResult.class.getName()); + + SolrSearchService solrSearchService=null; + + @Before + public void setUp() throws PluginException, ModelException { + solrSearchService=new SolrSearchService(); + } + + + /** + * Test + * + */ + @Test + public void testParseResult() { + List result=null; + String testString = "{\n" + + " \"responseHeader\":{\n" + + " \"status\":0,\n" + + " \"QTime\":4,\n" + + " \"params\":{\n" + + " \"q\":\"*:*\",\n" + + " \"_\":\"1567286252995\"}},\n" + + " \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" + + " {\n" + + " \"type\":[\"model\"],\n" + + " \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" + + " \"_modified\":[20190831211617],\n" + + " \"_created\":[20190831211617],\n" + + " \"_version_\":1643418672068296704},\n" + + " {\n" + + " \"type\":[\"adminp\"],\n" + + " \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" + + " \"_modified\":[20190831211618],\n" + + " \"_created\":[20190831211618],\n" + + " \"_version_\":1643418672172105728}]\n" + + " }}"; + + + + result=solrSearchService.parseQueryResult(testString); + Assert.assertEquals(2,result.size()); + + ItemCollection document=null; + + document=result.get(0); + Assert.assertEquals("model", document.getItemValueString("type")); + Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id")); + Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime()); + Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime()); + + document=result.get(1); + Assert.assertEquals("adminp", document.getItemValueString("type")); + Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id")); + Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime()); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `document.getItemValueDate("_created")` could be null and is dereferenced at line 79. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestParseSolrJSONResult.testParseResult() + +### Procedure Id: +org.imixs.workflow.engine.solr.TestParseSolrJSONResult.testParseResult():void.8bca95ae8d3576765b27ffb7c2dae7ea + +### File: +imixs-workflow-index-solr/src/test/java/org/imixs/workflow/engine/solr/TestParseSolrJSONResult.java + +### Key: +TestParseSolrJSONResult.java|testParseResult|NULL_DEREFERENCE + +### Node Key: +aa66545b443e053e1949db82c636558b + +### Hash: +3e0701326dca08fd3b27a3355297ca09 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7187/instruction.md b/inferredbugs-7187/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..139a9fe8676c290f8700c0d1328b76ed58798972 --- /dev/null +++ b/inferredbugs-7187/instruction.md @@ -0,0 +1,549 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Imixs Workflow + * Copyright (C) 2001, 2011 Imixs Software Solutions GmbH, + * http://www.imixs.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You can receive a copy of the GNU General Public + * License at http://www.gnu.org/licenses/gpl.html + * + * Project: + * http://www.imixs.org + * http://java.net/projects/imixs-workflow + * + * Contributors: + * Imixs Software Solutions GmbH - initial API and implementation + * Ralph Soika - Software Developer + *******************************************************************************/ + +package org.imixs.workflow.plugins; + +import java.io.IOException; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import org.imixs.workflow.ItemCollection; +import org.imixs.workflow.Plugin; +import org.imixs.workflow.exceptions.PluginException; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * This Plug-In evaluates the result message provided by the Activity property + * 'txtActivityResult'. The value will be parsed for the xml tag 'item' + * + * + * value + * + * + * The provided value will be assigend to the named property. The value can also + * be evaluated with the tag 'itemValue' + * + * + * namCreator + * + * + * + * The final result will be stored into the attribute + * "txtworkflowresultmessage". + * + * This field could be used by an application to display individual messages + * (e.g HTML Code) or return result Strings (e.g. JSF Action Results) + * + * @author Ralph Soika + * @version 1.0 + * @see org.imixs.workflow.WorkflowManager + * + */ +public class ResultPlugin extends AbstractPlugin { + + public static final String INVALID_FORMAT = "INVALID_FORMAT"; + + ItemCollection documentContext; + String sActivityResult; + private static Logger logger = Logger.getLogger(ResultPlugin.class.getName()); + + public int run(ItemCollection adocumentContext, ItemCollection adocumentActivity) throws PluginException { + documentContext = adocumentContext; + // evaluate new items.... + ItemCollection evalItemCollection = new ItemCollection(); + evalItemCollection=adocumentContext=evaluateWorkflowResult(adocumentActivity,documentContext); + // copy values + documentContext.replaceAllItems(evalItemCollection.getAllItems()); + return Plugin.PLUGIN_OK; + } + + public void close(int status) throws PluginException { + try { + // restore changes? + if (status < Plugin.PLUGIN_ERROR) { + documentContext.replaceItemValue("txtworkflowresultmessage", sActivityResult); + } + } catch (Exception e) { + System.out.println("[ResultPlugin] Error close(): " + e.toString()); + + } + } + + /** + * This method evaluates the given activityEntiy and returns a new + * ItemCollection containing all items defined by the activity property + * 'txtActivityResult'. + * + * @see method evaluate(String aString, ItemCollection documentContext) + * @throws PluginException + * + */ + @Deprecated + private static ItemCollection evaluate(ItemCollection activityEntity, ItemCollection documentContext) + throws PluginException { + + String sResult = activityEntity.getItemValueString("txtActivityResult"); + // replace dynamic values + sResult = new ResultPlugin().replaceDynamicValues(sResult, documentContext); + + ItemCollection evalItemCollection = new ItemCollection(); + ResultPlugin.evaluate(sResult, evalItemCollection); + + return evalItemCollection; + } + + /** + * This method parses a string for xml tag . Those tags will result in + * new workitem properties. + * + * + * new Title + * + * + * If an item with the same name exits multiple times the method creates a + * multivalue item + * + * Additional the attribute 'type' can be provided to specify a field type + * 'boolean', 'string', 'integer' + * + * The item will be added into the given documentContext. + * + * If the item name starts with $ it will be ignored! + * + * Also ' will be replaced with " in attribute name + * + * @throws PluginException + * + */ + @SuppressWarnings("unchecked") + @Deprecated + private static void evaluate(String aString, ItemCollection documentContext) throws PluginException { + + List mulitValueItemNames = new ArrayList(); + int iTagStartPos; + int iTagEndPos; + + int iContentStartPos; + int iContentEndPos; + + int iNameStartPos; + int iNameEndPos; + + int iTypeStartPos; + int iTypeEndPos; + + String sName = ""; + String sType = " "; + String sItemValue; + + if (aString == null) + return; + + // test if a tag exists... + while ((iTagStartPos = aString.toLowerCase().indexOf("", iTagStartPos); + + // if no end tag found return string unchanged... + if (iTagEndPos == -1) + throw new PluginException(ResultPlugin.class.getSimpleName(), INVALID_FORMAT, " expected!"); + + // reset pos vars + iContentStartPos = 0; + iContentEndPos = 0; + iNameStartPos = 0; + iNameEndPos = 0; + iTypeStartPos = 0; + iTypeEndPos = 0; + sName = ""; + sType = " "; + sItemValue = ""; + + // so we now search the beginning of the tag content + iContentEndPos = iTagEndPos; + // start pos is the last > before the iContentEndPos + String sTestString = aString.substring(0, iContentEndPos); + iContentStartPos = sTestString.indexOf('>') + 1; + + // if no end tag found return string unchanged... + if (iContentStartPos >= iContentEndPos) + return; + + iTagEndPos = iTagEndPos + "".length(); + + // now we have the start and end position of a tag and also the + // start and end pos of the value + + // next we check if the start tag contains a 'name' attribute + iNameStartPos = aString.toLowerCase().indexOf("name=", iTagStartPos); + // extract format string if available + // ' can be used instead of " chars! + // e.g.: name='txtName'> or name="txtName"> + if (iNameStartPos > -1 && iNameStartPos < iContentStartPos) { + // replace ' with " before content start pos + String sNamePart = aString.substring(0, iContentStartPos); + sNamePart = sNamePart.replace("'", "\""); + iNameStartPos = sNamePart.indexOf("\"", iNameStartPos) + 1; + iNameEndPos = sNamePart.indexOf("\"", iNameStartPos + 1); + sName = sNamePart.substring(iNameStartPos, iNameEndPos); + } + + // next we check if the start tag contains a 'type' + // attribute + iTypeStartPos = aString.toLowerCase().indexOf("type=", iTagStartPos); + // extract format string if available + if (iTypeStartPos > -1 && iTypeStartPos < iContentStartPos) { + String sTypePart = aString.substring(0, iContentStartPos); + sTypePart = sTypePart.replace("'", "\""); + + iTypeStartPos = sTypePart.indexOf("\"", iTypeStartPos) + 1; + iTypeEndPos = sTypePart.indexOf("\"", iTypeStartPos + 1); + sType = sTypePart.substring(iTypeStartPos, iTypeEndPos); + } + + // extract Item Value + sItemValue = aString.substring(iContentStartPos, iContentEndPos); + + // replace the item value + if (sName != null && !"".equals(sName)) { + // ignore case sensetive names + sName = sName.toLowerCase(); + + // if itemname starts with $ it will be ignored + if (sName.startsWith("$")) { + logger.warning("ResultPlugin - item '" + sName + "' update not allowed!"); + } else { + // convert to type... + Object oValue = sItemValue; + if ("boolean".equalsIgnoreCase(sType)) { + oValue = Boolean.valueOf(sItemValue); + } + if ("integer".equalsIgnoreCase(sType)) { + oValue = new Integer(sItemValue); + } + + // test if item was already computed before + + if (!mulitValueItemNames.contains(sName)) { + documentContext.replaceItemValue(sName, oValue); + mulitValueItemNames.add(sName); + } else { + // item was processed before so we add the value into a + // multivalue list + List values = documentContext.getItemValue(sName); + values.add(oValue); + documentContext.replaceItemValue(sName, values); + } + } + } + + // now cut the tag form the string + aString = aString.substring(0, iTagStartPos) + "" + aString.substring(iTagEndPos); + } + + } + + /** + * This method parses the xml content of a item element and returns a new + * ItemCollection containing all item values. Each tag is evaluated as the + * item name. + * + * MultiValues are currently not supported + * + * Example: + * + * + + 1.0.0 + 1000 + 10 + namTeam + + * + * + * @param evalItemCollection + * @throws PluginException + */ + public static ItemCollection parseItemStructure(String xmlContent) throws PluginException { + logger.fine("Evaluate Subprocess Item..."); + + ItemCollection result = new ItemCollection(); + if (xmlContent.length() > 0) { + // surround with a root element + xmlContent = "" + xmlContent.trim() + ""; + try { + + // parse item list... + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = documentBuilder.parse(new InputSource(new StringReader(xmlContent))); + Node node = doc.importNode(doc.getDocumentElement(), true); + DocumentFragment docfrag = doc.createDocumentFragment(); + while (node.hasChildNodes()) { + docfrag.appendChild(node.removeChild(node.getFirstChild())); + } + + // append all items into the evalItemCollection... + NodeList childs = docfrag.getChildNodes(); + int itemCount = childs.getLength(); + for (int i = 0; i < itemCount; i++) { + Node childNode = childs.item(i); + if (childNode instanceof Element && childNode.getFirstChild() != null) { + String name = childNode.getNodeName(); + String value = childNode.getFirstChild().getNodeValue(); + result.replaceItemValue(name, value); + logger.fine("[ResultPlugin] parsing item '" + name + "' value=" + value); + } + } + + } catch (ParserConfigurationException e) { + throw new PluginException(RulePlugin.class.getName(), INVALID_FORMAT, + "Parsing item content failed: " + e.getMessage()); + + } catch (SAXException e) { + throw new PluginException(RulePlugin.class.getName(), INVALID_FORMAT, + "Parsing item content failed: " + e.getMessage()); + + } catch (IOException e) { + throw new PluginException(RulePlugin.class.getName(), INVALID_FORMAT, + "Parsing item content failed: " + e.getMessage()); + + } + } + + return result; + } + + /** + * The method evaluates the WorkflowResult for a given activityEntity and + * returns a ItemColleciton containing all item definitions. Each item + * definition of a WorkflowResult contains a name and a optional list of + * additional attributes. The method generates a item for each content + * element and attribute value.
+ * e.g. text
+ * will result in the attributes 'comment' with value 'text' and + * 'comment.ignore' with the value 'true' + * + * + * @see http://ganeshtiwaridotcomdotnp.blogspot.de/2011/12/htmlxml-tag- + * parsing-using-regex-in-java.html + * @param activityEntity + * @param documentContext + * @return + * @throws PluginException + */ + public static ItemCollection evaluateWorkflowResult(ItemCollection activityEntity,ItemCollection documentContext) + throws PluginException { + + boolean invalidPattern = true; + + ItemCollection result = new ItemCollection(); + String workflowResult = activityEntity.getItemValueString("txtActivityResult"); + if (workflowResult.isEmpty()) { + return null; + } + // replace dynamic values + workflowResult = new ResultPlugin().replaceDynamicValues(workflowResult, documentContext); + + // extract all tags with attributes using regex (including empty + // item tags) + Pattern pattern = Pattern.compile("(.*?)|"); + Matcher matcher = pattern.matcher(workflowResult); + while (matcher.find()) { + invalidPattern = false; + // we expect up to 3 different result groups + + // group 0 contains complete item string + String attributes = matcher.group(1); + String content = matcher.group(2); + + // test if empty tag (group 1 and 2 empty) + if (attributes == null || content == null) { + attributes = matcher.group(3); + } + + if (content == null) { + content = ""; + } + + // now extract the attributes to verify the item name.. + if (attributes != null && !attributes.isEmpty()) { + // parse attributes... + String spattern = "(\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?"; + Pattern attributePattern = Pattern.compile(spattern); + Matcher attributeMatcher = attributePattern.matcher(attributes); + Map attrMap = new HashMap(); + while (attributeMatcher.find()) { + String attrName = attributeMatcher.group(1); // name + String attrValue = attributeMatcher.group(2); // value + attrMap.put(attrName, attrValue); + } + + String itemName = attrMap.get("name"); + if (itemName == null) { + throw new PluginException(ResultPlugin.class.getSimpleName(), INVALID_FORMAT, + " tag contains no name attribute."); + } + + if (itemName.startsWith("$")) { + throw new PluginException(ResultPlugin.class.getSimpleName(), INVALID_FORMAT, + " tag contains invalid name attribute '" + itemName + "'."); + } + + // now add optional attributes if available + for (String attrName : attrMap.keySet()) { + // we need to skip the 'name' attribute + if (!"name".equals(attrName)) { + result.appendItemValue(itemName + "." + attrName, attrMap.get(attrName)); + } + } + + // test if the type attribute was provided to convert content? + String sType = result.getItemValueString(itemName + ".type"); + if (!sType.isEmpty()) { + // convert content type + if ("boolean".equalsIgnoreCase(sType)) { + result.appendItemValue(itemName, Boolean.valueOf(content)); + } else if ("integer".equalsIgnoreCase(sType)) { + result.appendItemValue(itemName, new Integer(content)); + } else if ("double".equalsIgnoreCase(sType)) { + result.appendItemValue(itemName, new Double(content)); + } else + // no type conversion + result.appendItemValue(itemName, content); + } else { + // no type definition + result.appendItemValue(itemName, content); + } + + } else { + throw new PluginException(ResultPlugin.class.getSimpleName(), INVALID_FORMAT, + " tag contains no name attribute."); + + } + + } + + // test for general invalid format + if (invalidPattern) { + throw new PluginException(ResultPlugin.class.getSimpleName(), INVALID_FORMAT, + "invalid tag format - expected "); + } + + return result; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `evalItemCollection` last assigned on line 94 could be null and is dereferenced at line 96. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int ResultPlugin.run(ItemCollection,ItemCollection) + +### Procedure Id: +org.imixs.workflow.plugins.ResultPlugin.run(org.imixs.workflow.ItemCollection,org.imixs.workflow.Ite.606093ea37d8c6a8eb00747a20176c75 + +### File: +imixs-workflow-engine/src/main/java/org/imixs/workflow/plugins/ResultPlugin.java + +### Key: +ResultPlugin.java|run|NULL_DEREFERENCE + +### Node Key: +e9814c590e26c031348b9b6ea9d992af + +### Hash: +76832a1ae5238fdc25300a3099b84ed1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7189/instruction.md b/inferredbugs-7189/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eb3240a172d3a75b30c9b23f567b4a8fcb07c615 --- /dev/null +++ b/inferredbugs-7189/instruction.md @@ -0,0 +1,350 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.imixs.workflow.engine; + +import java.util.Calendar; +import java.util.Date; + +import org.imixs.workflow.ItemCollection; +import org.imixs.workflow.engine.WorkflowSchedulerService; +import org.imixs.workflow.exceptions.AccessDeniedException; +import org.imixs.workflow.exceptions.PluginException; +import org.imixs.workflow.exceptions.ProcessingErrorException; +import org.junit.Before; +import org.junit.Test; + +import junit.framework.Assert; + +/** + * Test class for WorkflowSchedulerService + * + * This test verifies if the inDue methods workItemInDue() and addWorkDays() + * + * @author rsoika + */ +public class TestWorkflowScheduler { + + @Before + public void setup() throws PluginException { + + } + + /** + * This test the date compare base on $lastProcessingDate in days + * + * @throws ProcessingErrorException + * @throws AccessDeniedException + * + */ + @Test + public void testDaysOnLastProcess() throws AccessDeniedException, ProcessingErrorException, PluginException { + + ItemCollection doc = new ItemCollection(); + ItemCollection activity = new ItemCollection(); + + // delay unit = days + activity.replaceItemValue("keyActivityDelayUnit", "3"); + // compare type = last process + activity.replaceItemValue("keyScheduledBaseObject", "1"); + // delay + activity.replaceItemValue("numActivityDelay", 10); + + Calendar workitemCal = Calendar.getInstance(); + workitemCal.setTime(new Date()); + // adjust -14 + workitemCal.add(Calendar.DAY_OF_MONTH, -14); + // prepare doc + doc.replaceItemValue("$lastProcessingDate", workitemCal.getTime()); + Assert.assertTrue(WorkflowSchedulerService.workItemInDue(doc, activity)); + + // delay + activity.replaceItemValue("numActivityDelay", 15); + workitemCal.setTime(new Date()); + // adjust -14 + workitemCal.add(Calendar.DAY_OF_MONTH, -14); + // prepare doc + doc.replaceItemValue("$lastProcessingDate", workitemCal.getTime()); + Assert.assertFalse(WorkflowSchedulerService.workItemInDue(doc, activity)); + + } + + + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Monday to Fiday + */ + @Test + public void testAddWorkdaysFromMonday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + System.out.println("Startdate=" + startDate.getTime()); + + + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + + + + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testAddWorkdaysFromFriday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testMinusWorkdaysFromFriday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.WEDNESDAY, + WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK)); + // friday - 5 + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * Friday back to Monday + */ + @Test + public void testMinusWorkdaysFromMonday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to FRIDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -3 Workdays -> THUSEDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK)); + + } + + + + /** + * This method tests the addWorkDays function in a weekday movement from + * SATURDAY backwards + */ + @Test + public void testMinusWorkdaysFromSaturday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> THURSDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + + } + + + /** + * This method tests the addWorkDays function in a weekday movement from + * SATURDAY forwards + */ + @Test + public void testAddWorkdaysFromSaturday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> TUESDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * SUNDAY backwards + */ + @Test + public void testMinusWorkdaysFromSunday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> THURSDAY + Assert.assertEquals(Calendar.THURSDAY, + WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK)); + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK)); + + } + + /** + * This method tests the addWorkDays function in a weekday movement from + * SUNDAY forwards + */ + @Test + public void testAddWorkdaysFromSunday() { + + Calendar startDate = Calendar.getInstance(); + // adjust to SATURDAY + startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); + System.out.println("Startdate=" + startDate.getTime()); + + // adjust -1 Workdays -> TUESDAY + Assert.assertEquals(Calendar.TUESDAY, + WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK)); + + Assert.assertEquals(Calendar.FRIDAY, + WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK)); + + + Assert.assertEquals(Calendar.MONDAY, + WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK)); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `addWorkDays(startDate,2)` could be null and is dereferenced at line 88. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestWorkflowScheduler.testAddWorkdaysFromMonday() + +### Procedure Id: +org.imixs.workflow.engine.TestWorkflowScheduler.testAddWorkdaysFromMonday():void.3b341ae0a16ef84212734955fa5d807d + +### File: +imixs-workflow-engine/src/test/java/org/imixs/workflow/engine/TestWorkflowScheduler.java + +### Key: +TestWorkflowScheduler.java|testAddWorkdaysFromMonday|NULL_DEREFERENCE + +### Node Key: +15891b12c6ce50257e480adc810587ae + +### Hash: +0cf9dccae58946dfed1eae455d70dd35 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7256/instruction.md b/inferredbugs-7256/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d12c558015116eeb093ab6e6c587fbba60959f3a --- /dev/null +++ b/inferredbugs-7256/instruction.md @@ -0,0 +1,151 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sonar-php +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * SonarQube PHP Plugin + * Copyright (C) 2010-2017 SonarSource SA + * mailto:info AT sonarsource DOT com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 3 of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +package org.sonar.php.checks; + +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.sonar.check.Rule; +import org.sonar.php.tree.impl.PHPTree; +import org.sonar.plugins.php.api.tree.Tree; +import org.sonar.plugins.php.api.tree.Tree.Kind; +import org.sonar.plugins.php.api.tree.declaration.VariableDeclarationTree; +import org.sonar.plugins.php.api.tree.expression.AssignmentExpressionTree; +import org.sonar.plugins.php.api.tree.expression.LiteralTree; +import org.sonar.plugins.php.api.tree.lexical.SyntaxToken; +import org.sonar.plugins.php.api.visitors.PHPVisitorCheck; + +@Rule(key = HardCodedCredentialsCheck.KEY) +public class HardCodedCredentialsCheck extends PHPVisitorCheck { + + public static final String KEY = "S2068"; + + private static final String MESSAGE = "Remove this hard-coded password."; + + private static final Pattern PASSWORD_LITERAL_PATTERN = Pattern.compile("password=..", Pattern.CASE_INSENSITIVE); + private static final Pattern PASSWORD_VARIABLE_PATTERN = Pattern.compile("password", Pattern.CASE_INSENSITIVE); + + @Override + public void visitLiteral(LiteralTree literal) { + if (literal.is(Kind.REGULAR_STRING_LITERAL) && PASSWORD_LITERAL_PATTERN.matcher(literal.token().text()).find()) { + addIssue(literal); + } + super.visitLiteral(literal); + } + + @Override + public void visitVariableDeclaration(VariableDeclarationTree declaration) { + String identifier = declaration.identifier().text(); + checkVariable(declaration.identifier(), identifier, declaration.initValue()); + super.visitVariableDeclaration(declaration); + } + + @Override + public void visitAssignmentExpression(AssignmentExpressionTree assignment) { + SyntaxToken lastToken = ((PHPTree) assignment.variable()).getLastToken(); + String variableName = lastToken.text(); + checkVariable(lastToken, variableName, assignment.value()); + super.visitAssignmentExpression(assignment); + } + + private void checkVariable(Tree tree, String identifier, @Nullable Tree value) { + if (value != null && value.is(Kind.REGULAR_STRING_LITERAL) && PASSWORD_VARIABLE_PATTERN.matcher(identifier).find()) { + addIssue(tree); + } + } + + private void addIssue(Tree tree) { + context().newIssue(this, tree, MESSAGE); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `lastToken` last assigned on line 61 could be null and is dereferenced at line 62. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HardCodedCredentialsCheck.visitAssignmentExpression(AssignmentExpressionTree) + +### Procedure Id: +org.sonar.php.checks.HardCodedCredentialsCheck.visitAssignmentExpression(org.sonar.plugins.php.api.t.76e64ddcc2f9ff76e17cde42af891538 + +### File: +php-checks/src/main/java/org/sonar/php/checks/HardCodedCredentialsCheck.java + +### Key: +HardCodedCredentialsCheck.java|visitAssignmentExpression|NULL_DEREFERENCE + +### Node Key: +d1bdf9e9f952f9146e298670995c382e + +### Hash: +6ff0ff8c84988201658cf069ca1fc9ef + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7294/instruction.md b/inferredbugs-7294/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..04fb60466a0426757aa72575251595c9b4ab4e1a --- /dev/null +++ b/inferredbugs-7294/instruction.md @@ -0,0 +1,248 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zookeeper +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.zookeeper.server.quorum; + +import java.util.ArrayList; +import java.util.LinkedList; + +import org.apache.log4j.Logger; + +import org.apache.zookeeper.ZooDefs.OpCode; +import org.apache.zookeeper.server.Request; +import org.apache.zookeeper.server.RequestProcessor; +import org.apache.zookeeper.server.ZooTrace; + +/** + * This RequestProcessor matches the incoming committed requests with the + * locally submitted requests. The trick is that locally submitted requests that + * change the state of the system will come back as incoming committed requests, + * so we need to match them up. + */ +public class CommitProcessor extends Thread implements RequestProcessor { + private static final Logger LOG = Logger.getLogger(CommitProcessor.class); + + /** + * Requests that we are holding until the commit comes in. + */ + LinkedList queuedRequests = new LinkedList(); + + /** + * Requests that have been committed. + */ + LinkedList committedRequests = new LinkedList(); + + RequestProcessor nextProcessor; + + public CommitProcessor(RequestProcessor nextProcessor) { + this.nextProcessor = nextProcessor; + start(); + } + + boolean finished = false; + + public void run() { + try { + Request nextPending = null; + ArrayList toProcess = new ArrayList(); + while (!finished) { + int len = toProcess.size(); + for (int i = 0; i < len; i++) { + nextProcessor.processRequest(toProcess.get(i)); + } + toProcess.clear(); + synchronized (this) { + if ((queuedRequests.size() == 0 || nextPending != null) + && committedRequests.size() == 0) { + wait(); + continue; + } + // First check and see if the commit came in for the pending + // request + if ((queuedRequests.size() == 0 || nextPending != null) + && committedRequests.size() > 0) { + Request r = committedRequests.remove(); + /* + * We match with nextPending so that we can move to the + * next request when it is committed. We also want to + * use nextPending because it has the cnxn member set + * properly. + */ + if (nextPending != null + && nextPending.sessionId == r.sessionId + && nextPending.cxid == r.cxid) { + // we want to send our version of the request. + // the pointer to the connection in the request + nextPending.hdr = r.hdr; + nextPending.txn = r.txn; + nextPending.zxid = r.zxid; + toProcess.add(nextPending); + nextPending = null; + } else { + // this request came from someone else so just + // send the commit packet + toProcess.add(r); + } + } + } + + // We haven't matched the pending requests, so go back to + // waiting + if (nextPending != null) { + continue; + } + + synchronized (this) { + // Process the next requests in the queuedRequests + while (nextPending == null && queuedRequests.size() > 0) { + Request request = queuedRequests.remove(); + switch (request.type) { + case OpCode.create: + case OpCode.delete: + case OpCode.setData: + case OpCode.setACL: + case OpCode.createSession: + case OpCode.closeSession: + nextPending = request; + break; + case OpCode.sync: + nextPending = request; + //pendingSyncs.add(request); + break; + default: + toProcess.add(request); + } + } + } + } + } catch (Exception e) { + LOG.error("FIXMSG",e); + } + ZooTrace.logTraceMessage(LOG, ZooTrace.getTextTraceLevel(), + "CommitProcessor exited loop!"); + } + + synchronized public void commit(Request request) { + if (!finished) { + if (request == null) { + LOG.warn("Committed a null!", + new Exception("committing a null! ")); + return; + } + LOG.debug("Committing" + request.cxid); + committedRequests.add(request); + notifyAll(); + } + } + + synchronized public void processRequest(Request request) { + // request.addRQRec(">commit"); + // LOG.info("Zoo processReq>>> cxid = " + request.cxid + " type = + // " + request.type + " id = " + request.sessionId + " cnxn " + + // request.cnxn); + if (!finished) { + queuedRequests.add(request); + notifyAll(); + } + } + + public void shutdown() { + finished = true; + queuedRequests.clear(); + synchronized (this) { + notifyAll(); + } + nextProcessor.shutdown(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.zookeeper.server.quorum.CommitProcessor.shutdown` writes to field `this.org.apache.zookeeper.server.quorum.CommitProcessor.finished` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CommitProcessor.shutdown() + +### Procedure Id: +org.apache.zookeeper.server.quorum.CommitProcessor.shutdown():void.b8c8e9b49f2afbd89abdb3deb5d47104 + +### File: +src/java/main/org/apache/zookeeper/server/quorum/CommitProcessor.java + +### Key: +CommitProcessor.java|shutdown|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +59256f8afa807bd7ee151422bb30af84 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7312/instruction.md b/inferredbugs-7312/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5574b9bbb8d91230e7b9b87d2923dc7af657a86b --- /dev/null +++ b/inferredbugs-7312/instruction.md @@ -0,0 +1,390 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ninja +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2012-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ninja.utils; + +import java.io.BufferedReader; +import java.io.File; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import ninja.NinjaTest; + +import org.apache.http.HttpResponse; +import org.apache.http.HttpVersion; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.cookie.Cookie; +import org.apache.http.entity.StringEntity; +import org.apache.http.entity.mime.HttpMultipartMode; +import org.apache.http.entity.mime.MultipartEntity; +import org.apache.http.entity.mime.content.FileBody; +import org.apache.http.impl.client.DefaultHttpClient; +import org.apache.http.message.BasicNameValuePair; +import org.apache.http.params.CoreProtocolPNames; +import org.apache.http.util.EntityUtils; +import org.codehaus.jackson.map.ObjectMapper; + +import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import com.google.common.collect.Maps; + +public class NinjaTestBrowser { + + private DefaultHttpClient httpClient; + + public NinjaTestBrowser() { + httpClient = new DefaultHttpClient(); + } + + /** + * The raw HttpClient. You can use it to fire your own requests. + * + * Note 1: This HttpClient will save the state by reusing cookies. You can + * do login / logout cycles using this class. + * + * Note 2: Will be shut down when calling the shutdown method. This is + * generally done by another test helper (like {@link NinjaTest}) that + * encapsulates this class. + * + * @return The HttpClient. Ready and there to be used. + */ + public HttpClient getHttpClient() { + + return this.httpClient; + + } + + /** + * @return all cookies saved by this TestBrowser. + */ + public List getCookies() { + return httpClient.getCookieStore().getCookies(); + } + + public Cookie getCookieWithName(String name) { + + List cookies = getCookies(); + + // skip through cookies and return cookie you want + for (Cookie cookie : cookies) { + if (cookie.getName().equals(name)) { + return cookie; + } + } + + return null; + } + + public HttpResponse makeRequestAndGetResponse(String url, + Map headers) { + + HttpResponse response = null; + + try { + + HttpGet getRequest = new HttpGet(url); + + // add all headers + for (Entry header : headers.entrySet()) { + getRequest.addHeader(header.getKey(), header.getValue()); + } + + response = httpClient.execute(getRequest); + getRequest.reset(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + + return response; + + } + + public String makeRequest(String url) { + return makeRequest(url, null); + } + + public String makeRequest(String url, Map headers) { + + StringBuffer sb = new StringBuffer(); + try { + + HttpGet getRequest = new HttpGet(url); + + if (headers != null) { + // add all headers + for (Entry header : headers.entrySet()) { + getRequest.addHeader(header.getKey(), header.getValue()); + } + } + + HttpResponse response; + + response = httpClient.execute(getRequest); + + BufferedReader br = new BufferedReader(new InputStreamReader( + response.getEntity().getContent(), "UTF-8")); + + String output; + while ((output = br.readLine()) != null) { + sb.append(output); + } + + getRequest.releaseConnection(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + + return sb.toString(); + + } + + public String makePostRequestWithFormParameters(String url, + Map headers, + Map formParameters) { + + StringBuffer sb = new StringBuffer(); + + try { + + HttpPost postRequest = new HttpPost(url); + + if (headers != null) { + // add all headers + for (Entry header : headers.entrySet()) { + postRequest.addHeader(header.getKey(), header.getValue()); + } + } + + // add form parameters: + List formparams = new ArrayList(); + if (formParameters != null) { + + for (Entry parameter : formParameters + .entrySet()) { + + formparams.add(new BasicNameValuePair(parameter.getKey(), + parameter.getValue())); + } + + } + + // encode form parameters and add + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams); + postRequest.setEntity(entity); + + HttpResponse response; + + response = httpClient.execute(postRequest); + + BufferedReader br = new BufferedReader(new InputStreamReader( + response.getEntity().getContent(), "UTF-8")); + + String output; + while ((output = br.readLine()) != null) { + sb.append(output); + } + + postRequest.releaseConnection(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + + return sb.toString(); + + } + + public String uploadFile(String url, String paramName, File fileToUpload) { + + String response = null; + + try { + + httpClient.getParams().setParameter( + CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); + + HttpPost post = new HttpPost(url); + + MultipartEntity entity = new MultipartEntity( + HttpMultipartMode.BROWSER_COMPATIBLE); + + // For File parameters + entity.addPart(paramName, new FileBody((File) fileToUpload)); + + post.setEntity(entity); + + // Here we go! + response = EntityUtils.toString(httpClient.execute(post) + .getEntity(), "UTF-8"); + post.releaseConnection(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + + return response; + + } + + public String makeJsonRequest(String url) { + + Map headers = Maps.newHashMap(); + headers.put("accept", "application/json; charset=utf-8"); + + return makeRequest(url, headers); + + } + + public String makeXmlRequest(String url) { + + Map headers = Maps.newHashMap(); + headers.put("accept", "application/xml; charset=utf-8"); + + return makeRequest(url, headers); + + } + + public String postJson(String url, Object object) { + + try { + httpClient.getParams().setParameter( + CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); + + HttpPost post = new HttpPost(url); + StringEntity entity = new StringEntity( + new ObjectMapper().writeValueAsString(object), "utf-8"); + entity.setContentType("application/json; charset=utf-8"); + post.setEntity(entity); + post.releaseConnection(); + + // Here we go! + return EntityUtils.toString(httpClient.execute(post).getEntity(), + "UTF-8"); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public String postXml(String url, Object object) { + + try { + httpClient.getParams().setParameter( + CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); + + HttpPost post = new HttpPost(url); + StringEntity entity = new StringEntity( + new XmlMapper().writeValueAsString(object), "utf-8"); + entity.setContentType("application/xml; charset=utf-8"); + post.setEntity(entity); + post.releaseConnection(); + + // Here we go! + return EntityUtils.toString(httpClient.execute(post).getEntity(), + "UTF-8"); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + public void shutdown() { + httpClient.getConnectionManager().shutdown(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `InputStreamReader(...)` at line 144 is not released after line 153. +**Note**: potential exception at line 147 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String NinjaTestBrowser.makeRequest(String,Map) + +### Procedure Id: +ninja.utils.NinjaTestBrowser.makeRequest(java.lang.String,java.util.Map):java.lang.String.458b33f3c269bf107ede6ae28eeccb74 + +### File: +ninja-test-utilities/src/main/java/ninja/utils/NinjaTestBrowser.java + +### Key: +NinjaTestBrowser.java|makeRequest|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +5430f5239ea2cbeb891bea330bce6da9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7313/instruction.md b/inferredbugs-7313/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..598839471cf759dcc766663cb3bb5bd207bd76a6 --- /dev/null +++ b/inferredbugs-7313/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ninja +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2012-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package ninja.jpa; + +import com.google.inject.Inject; +import com.google.inject.Provider; +import com.google.inject.persist.PersistService; +import com.google.inject.persist.UnitOfWork; +import javax.persistence.EntityManager; +import org.aopalliance.intercept.MethodInterceptor; +import org.aopalliance.intercept.MethodInvocation; + +/** + * See @UnitOfWork. + * + * This interceptor tracks and opens and closes your database connections. + * + * @author Raphael A. Bauer + */ +public class UnitOfWorkInterceptor implements MethodInterceptor { + + final Provider unitOfWorkProvider; + + // ThreadLocal tracks if the unit of work was begun + // implicitly by this thread. + // According to the docs we can start and end the UnitOfWork as often + // as we want. But this has to be balanced in some way. Otherwise we get: + // + // java.lang.IllegalStateException: Work already begun on this thread. Looks like you have called UnitOfWork.begin() twice without a balancing call to end() in between. + // at com.google.inject.internal.util.$Preconditions.checkState(Preconditions.java:142) ~[guice-3.0.jar:na] + // at com.google.inject.persist.jpa.JpaPersistService.begin(JpaPersistService.java:66) ~[guice-persist-3.0.jar:na] + // + // That way all begin() and end() calls are balanced + // because we only have one unit for this thread. + final ThreadLocal didWeStartWork = new ThreadLocal<>(); + + final Provider entityManagerProvider; + + @Inject + public UnitOfWorkInterceptor( + Provider unitOfWorkProvider, + Provider entityManagerProvider) { + this.unitOfWorkProvider = unitOfWorkProvider; + this.entityManagerProvider = entityManagerProvider; + } + + @Override + public Object invoke(MethodInvocation invocation) throws Throwable { + + final UnitOfWork unitOfWork; + + // Only start a new unit of work if the entitymanager is empty + // otherwise someone else has started the unit of work already + // and we do nothing + // Please compare to com.google.inject.persist.jpa.JpaLocalTxnInterceptor + // we just mimick that interceptor + // + // IMPORTANT: + // Nesting of begin() end() of unitOfWork is NOT allowed. Contrary to + // the documentation of Google Guice as of March 2014. + // Related Ninja issue: https://github.com/ninjaframework/ninja/issues/157 + if (entityManagerProvider.get() == null) { + + unitOfWork = unitOfWorkProvider.get(); + unitOfWork.begin(); + didWeStartWork.set(Boolean.TRUE); + + } else { + // If unit of work already started we don't do anything here... + // another UnitOfWorkInterceptor point point will take care... + // This happens if you are nesting your calls. + return invocation.proceed(); + } + + try { + + return invocation.proceed(); + + } finally { + + if (null != didWeStartWork.get()) { + + didWeStartWork.remove(); + unitOfWork.end(); + + } + + } + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `unitOfWork` last assigned on line 78 could be null and is dereferenced at line 79. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object UnitOfWorkInterceptor.invoke(MethodInvocation) + +### Procedure Id: +ninja.jpa.UnitOfWorkInterceptor.invoke(org.aopalliance.intercept.MethodInvocation):java.lang.Object.a773fda4dcd326446969708322b6e62a + +### File: +ninja-core/src/main/java/ninja/jpa/UnitOfWorkInterceptor.java + +### Key: +UnitOfWorkInterceptor.java|invoke|NULL_DEREFERENCE + +### Node Key: +25eec8bc2b565fcb7ecd79f1e598eda2 + +### Hash: +a7182800fb176974ed1834b9e38a3914 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7314/instruction.md b/inferredbugs-7314/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a60f364af61e1e4f229e87f1a3729e8ab79fd6af --- /dev/null +++ b/inferredbugs-7314/instruction.md @@ -0,0 +1,128 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ninja +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ninja; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import org.apache.http.HttpResponse; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; + +public class NinjaApiTestHelper { + + public static String makeJsonRequest(String url) { + + StringBuffer sb = new StringBuffer(); + try { + + DefaultHttpClient httpClient = new DefaultHttpClient(); + HttpGet getRequest = new HttpGet(url); + getRequest.addHeader("accept", "application/json"); + + HttpResponse response; + + response = httpClient.execute(getRequest); + + if (response.getStatusLine().getStatusCode() != 200) { + throw new RuntimeException("Failed : HTTP error code : " + + response.getStatusLine().getStatusCode()); + } + + BufferedReader br = new BufferedReader(new InputStreamReader( + (response.getEntity().getContent()))); + + String output; + while ((output = br.readLine()) != null) { + sb.append(output); + } + + httpClient.getConnectionManager().shutdown(); + } catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + return sb.toString(); + + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 33 is not released after line 41. +**Note**: potential exception at line 36 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String NinjaApiTestHelper.makeJsonRequest(String) + +### Procedure Id: +ninja.NinjaApiTestHelper.makeJsonRequest(java.lang.String):java.lang.String.517105b9f1f5035294b5c8ffc843b247 + +### File: +ninja-core-test/src/main/java/ninja/NinjaApiTestHelper.java + +### Key: +NinjaApiTestHelper.java|makeJsonRequest|RESOURCE_LEAK + +### Node Key: +f645aafdf4c7de4e5a37ff7e8f2268a3 + +### Hash: +8b540c603a3564db32e65e59d025b769 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7322/instruction.md b/inferredbugs-7322/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3371c39737a4e49a29a3030ef9c4c420d5a7578 --- /dev/null +++ b/inferredbugs-7322/instruction.md @@ -0,0 +1,905 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spring-lemon +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.naturalprogrammer.spring.lemon; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import javax.servlet.http.HttpServletResponse; +import javax.validation.Valid; +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.event.EventListener; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.core.oidc.StandardClaimNames; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.naturalprogrammer.spring.lemon.LemonProperties.Admin; +import com.naturalprogrammer.spring.lemon.domain.AbstractUser; +import com.naturalprogrammer.spring.lemon.domain.AbstractUser.Role; +import com.naturalprogrammer.spring.lemon.domain.AbstractUser.SignUpValidation; +import com.naturalprogrammer.spring.lemon.domain.AbstractUserRepository; +import com.naturalprogrammer.spring.lemon.domain.ChangePasswordForm; +import com.naturalprogrammer.spring.lemon.mail.LemonMailData; +import com.naturalprogrammer.spring.lemon.mail.MailSender; +import com.naturalprogrammer.spring.lemon.permissions.UserEditPermission; +import com.naturalprogrammer.spring.lemon.security.JwtService; +import com.naturalprogrammer.spring.lemon.security.LemonSecurityConfig; +import com.naturalprogrammer.spring.lemon.security.SpringUser; +import com.naturalprogrammer.spring.lemon.util.LemonUtils; +import com.naturalprogrammer.spring.lemon.validation.Password; +import com.nimbusds.jwt.JWTClaimsSet; + +/** + * The Lemon Service class + * + * @author Sanjay Patel + * + * @param The User class + * @param The Primary key type of User class + */ +@Validated +@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) +public abstract class LemonService + , ID extends Serializable> { + + private static final Log log = LogFactory.getLog(LemonService.class); + + private LemonProperties properties; + private PasswordEncoder passwordEncoder; + private MailSender mailSender; + private AbstractUserRepository userRepository; + private UserDetailsService userDetailsService; + private JwtService jwtService; + + @Autowired + public void createLemonService(LemonProperties properties, + PasswordEncoder passwordEncoder, + MailSender mailSender, + AbstractUserRepository userRepository, + UserDetailsService userDetailsService, + JwtService jwtService) { + + this.properties = properties; + this.passwordEncoder = passwordEncoder; + this.mailSender = mailSender; + this.userRepository = userRepository; + this.userDetailsService = userDetailsService; + this.jwtService = jwtService; + + log.info("Created"); + } + + + abstract public ID parseId(String id); + + + /** + * This method is called after the application is ready. + * Needs to be public - otherwise Spring screams. + * + * @param event + */ + @EventListener + public void afterApplicationReady(ApplicationReadyEvent event) { + + log.info("Starting up Spring Lemon ..."); + onStartup(); // delegate to onStartup() + log.info("Spring Lemon started"); + } + + + /** + * Creates the initial Admin user, if not found. + * Override this method if needed. + */ + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void onStartup() { + + try { + + // Check if the user already exists + userDetailsService + .loadUserByUsername(properties.getAdmin().getUsername()); + + } catch (UsernameNotFoundException e) { + + // Doesn't exist. So, create it. + U user = createAdminUser(); + userRepository.save(user); + } + } + + + /** + * Creates the initial Admin user. + * Override this if needed. + */ + protected U createAdminUser() { + + // fetch data about the user to be created + Admin initialAdmin = properties.getAdmin(); + + log.info("Creating the first admin user: " + initialAdmin.getUsername()); + + // create the user + U user = newUser(); + user.setEmail(initialAdmin.getUsername()); + user.setPassword(passwordEncoder.encode( + properties.getAdmin().getPassword())); + user.getRoles().add(Role.ADMIN); + + return user; + } + + + /** + * Creates a new user object. Must be overridden in the + * subclass, like this: + * + *
+	 * protected User newUser() {
+	 *    return new User();
+	 * }
+	 * 
+ */ + public abstract U newUser(); + + + /** + * Returns the context data to be sent to the client, + * i.e. reCaptchaSiteKey and all the properties + * prefixed with lemon.shared. + * + * To send custom properties, put those in your application + * properties in the format lemon.shared.fooBar. + * + * Override this method if needed. + * @param response + * @param expirationMillis + */ + public Map getContext(Optional expirationMillis, HttpServletResponse response) { + + log.debug("Getting context ..."); + + // make the context + Map sharedProperties = new HashMap(2); + sharedProperties.put("reCaptchaSiteKey", properties.getRecaptcha().getSitekey()); + sharedProperties.put("shared", properties.getShared()); + + SpringUser springUser = LemonUtils.getSpringUser(); + if (springUser != null) + jwtService.addAuthHeader(response, springUser.getUsername(), + expirationMillis.orElse(properties.getJwt().getExpirationMillis())); + + return LemonUtils.mapOf( + "context", sharedProperties, + "user", LemonUtils.getSpringUser()); + } + + + /** + * Signs up a user. + * + * @param user data fed by the user + */ + //@PreAuthorize("isAnonymous()") + @Validated(SignUpValidation.class) + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void signup(@Valid U user) { + + log.debug("Signing up user: " + user); + + initUser(user); // sets right all fields of the user + userRepository.save(user); + + // if successfully committed + LemonUtils.afterCommit(() -> { + + LemonUtils.login(user); // log the user in + log.debug("Signed up user: " + user); + }); + } + + + /** + * Initializes the user based on the input data + * + * @param user + */ + protected void initUser(U user) { + + log.debug("Initializing user: " + user); + + user.setPassword(passwordEncoder.encode(user.getPassword())); // encode the password + makeUnverified(user); // make the user unverified + } + + + /** + * Makes a user unverified + * @param user + */ + protected void makeUnverified(U user) { + + user.getRoles().add(Role.UNVERIFIED); + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + LemonUtils.afterCommit(() -> sendVerificationMail(user)); // send a verification mail to the user + } + +// /*** +// * Makes a user verified +// * @param user +// */ +// protected void makeVerified(U user) { +// user.getRoles().remove(Role.UNVERIFIED); +// user.setCredentialsUpdatedAt(new Date()); +// //user.setVerificationCode(null); +// } + + + /** + * Sends verification mail to a unverified user. + * + * @param user + */ + protected void sendVerificationMail(final U user) { + try { + + log.debug("Sending verification mail to: " + user); + + String verificationCode = jwtService.createToken(JwtService.VERIFY_AUDIENCE, + user.getId().toString(), properties.getJwt().getExpirationMillis(), + LemonUtils.mapOf("email", user.getEmail())); + + // make the link + String verifyLink = properties.getApplicationUrl() + + "/users/" + user.getId() + "/verification?code=" + verificationCode; + + // send the mail + sendVerificationMail(user, verifyLink); + + log.debug("Verification mail to " + user.getEmail() + " queued."); + + } catch (Throwable e) { + // In case of exception, just log the error and keep silent + log.error(ExceptionUtils.getStackTrace(e)); + } + } + + + /** + * Sends verification mail to a unverified user. + * Override this method if you're using a different MailData + */ + protected void sendVerificationMail(final U user, String verifyLink) { + + // send the mail + mailSender.send(LemonMailData.of(user.getEmail(), + LemonUtils.getMessage("com.naturalprogrammer.spring.verifySubject"), + LemonUtils.getMessage( + "com.naturalprogrammer.spring.verifyEmail", verifyLink))); + } + + + /** + * Resends verification mail to the user. + * + * @param user + */ + @UserEditPermission + public void resendVerificationMail(U user) { + + // The user must exist + LemonUtils.ensureFound(user); + + // must be unverified + LemonUtils.validate(user.getRoles().contains(Role.UNVERIFIED), + "com.naturalprogrammer.spring.alreadyVerified").go(); + + // send the verification mail + sendVerificationMail(user); + } + + + /** + * Fetches a user by email + * + * @param email + * @return the decorated user object + */ + public U fetchUserByEmail(@Valid @Email @NotBlank String email) { + + log.debug("Fetching user by email: " + email); + return processUser(userRepository.findByEmail(email).orElse(null)); + } + + + /** + * Returns a non-null, processed user for the client. + * + * @param user + * @return + */ + public U processUser(U user) { + + log.debug("Fetching user: " + user); + + // ensure that the user exists + LemonUtils.ensureFound(user); + + // hide confidential fields + user.hideConfidentialFields(); + + return user; + } + + + /** + * Verifies the email id of current-user + * + * @param verificationCode + */ + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void verifyUser(ID userId, String verificationCode) { + + log.debug("Verifying user ..."); + + U user = userRepository.findById(userId).orElseThrow(LemonUtils.notFoundSupplier()); + + // ensure that he is unverified + LemonUtils.validate(user.hasRole(Role.UNVERIFIED), + "com.naturalprogrammer.spring.alreadyVerified").go(); + + JWTClaimsSet claims = jwtService.parseToken(verificationCode, JwtService.VERIFY_AUDIENCE, user.getCredentialsUpdatedMillis()); + + LemonUtils.ensureAuthority( + claims.getSubject().equals(user.getId().toString()) && + claims.getClaim("email").equals(user.getEmail()), + "com.naturalprogrammer.spring.wrong.verificationCode"); + + user.getRoles().remove(Role.UNVERIFIED); // make him verified + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + userRepository.save(user); + + // after successful commit, + LemonUtils.afterCommit(() -> { + + // Re-login the user, so that the UNVERIFIED role is removed + LemonUtils.login(user); + log.debug("Re-logged-in the user for removing UNVERIFIED role."); + }); + + log.debug("Verified user: " + user); + } + + + /** + * Forgot password. + * + * @param email the email of the user who forgot his password + */ + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void forgotPassword(@Valid @Email @NotBlank String email) { + + log.debug("Processing forgot password for email: " + email); + + // fetch the user record from database + U user = userRepository.findByEmail(email) + .orElseThrow(LemonUtils.notFoundSupplier()); + + mailForgotPasswordLink(user); +// +// // set a forgot password code +// user.setForgotPasswordCode(LemonUtils.uid()); +// userRepository.save(user); +// +// // after successful commit, mail him a link to reset his password +// LemonUtils.afterCommit(() -> mailForgotPasswordLink(user)); + } + + +// /** +// * Forgot password. +// * +// * @param email the email of the user who forgot his password +// */ +// @Transactional(propagation=Propagation.REQUIRED, readOnly=false) +// public void forgotPassword(U user) { +// +// log.debug("Processing forgot password for user: " + user); +// +// // set a forgot password code +// user.setForgotPasswordCode(LemonUtils.uid()); +// userRepository.save(user); +// +// // after successful commit, mail him a link to reset his password +// LemonUtils.afterCommit(() -> mailForgotPasswordLink(user)); +// } +// +// + /** + * Mails the forgot password link. + * + * @param user + */ + public void mailForgotPasswordLink(U user) { + + log.debug("Mailing forgot password link to user: " + user); + + String forgotPasswordCode = jwtService.createToken(JwtService.FORGOT_PASSWORD_AUDIENCE, + user.getEmail(), properties.getJwt().getExpirationMillis()); + + // make the link + String forgotPasswordLink = properties.getApplicationUrl() + + "/reset-password?code=" + forgotPasswordCode; + + mailForgotPasswordLink(user, forgotPasswordLink); + + log.debug("Forgot password link mail queued."); + } + + + /** + * Mails the forgot password link. + * + * Override this method if you're using a different MailData + */ + public void mailForgotPasswordLink(U user, String forgotPasswordLink) { + + // send the mail + mailSender.send(LemonMailData.of(user.getEmail(), + LemonUtils.getMessage("com.naturalprogrammer.spring.forgotPasswordSubject"), + LemonUtils.getMessage("com.naturalprogrammer.spring.forgotPasswordEmail", + forgotPasswordLink))); + } + + /** + * Resets the password. + * + * @param forgotPasswordCode + * @param newPassword + */ + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void resetPassword( + @Valid @NotBlank String forgotPasswordCode, + @Valid @Password String newPassword) { + + log.debug("Resetting password ..."); + + JWTClaimsSet claims = jwtService.parseToken(forgotPasswordCode, + JwtService.FORGOT_PASSWORD_AUDIENCE); + + String email = claims.getSubject(); + + // fetch the user + U user = userRepository.findByEmail(email).orElseThrow(LemonUtils.notFoundSupplier()); + LemonUtils.ensureCredentialsUpToDate(claims, user); + + // sets the password + user.setPassword(passwordEncoder.encode(newPassword)); + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + //user.setForgotPasswordCode(null); + + userRepository.save(user); + + // after successful commit, + LemonUtils.afterCommit(() -> { + + // Login the user + LemonUtils.login(user); + }); + + log.debug("Password reset."); + } + + + /** + * Updates a user with the given data. + * + * @param user + * @param updatedUser + */ + @UserEditPermission + @Validated(AbstractUser.UpdateValidation.class) + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public SpringUser updateUser(U user, @Valid U updatedUser) { + + log.debug("Updating user: " + user); + + // checks + LemonUtils.ensureCorrectVersion(user, updatedUser); + + // delegates to updateUserFields + updateUserFields(user, updatedUser, LemonUtils.getSpringUser()); + userRepository.save(user); + + log.debug("Updated user: " + user); + + SpringUser springUser = user.toSpringUser(); + springUser.setPassword(null); + return springUser; + } + + + /** + * Changes the password. + * + * @param user + * @param changePasswordForm + */ + @UserEditPermission + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) { + + log.debug("Changing password for user: " + user); + + // Get the old password of the logged in user (logged in user may be an ADMIN) + SpringUser springUser = LemonUtils.getSpringUser(); + U loggedIn = userRepository.findById(springUser.getId()).get(); + String oldPassword = loggedIn.getPassword(); + + // checks + LemonUtils.ensureFound(user); + LemonUtils.validate("changePasswordForm.oldPassword", + passwordEncoder.matches(changePasswordForm.getOldPassword(), + oldPassword), + "com.naturalprogrammer.spring.wrong.password").go(); + + // sets the password + user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword())); + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + userRepository.save(user); + +// // after successful commit +// LemonUtils.afterCommit(() -> { +// +// SpringUser currentUser = LemonUtils.getSpringUser(); +// +//// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed, +//// +//// log.debug("Logging out ..."); +//// LemonUtils.logOut(); // log him out +//// } +// }); +// + log.debug("Changed password for user: " + user); + return user.toSpringUser().getUsername(); + } + + + /** + * Updates the fields of the users. Override this if you have more fields. + * + * @param user + * @param updatedUser + * @param currentUser + */ + protected void updateUserFields(U user, U updatedUser, SpringUser currentUser) { + + log.debug("Updating user fields for user: " + user); + + // User is already decorated while checking the 'edit' permission + // So, user.isRolesEditable() below would work + + // Another good admin must be logged in to edit roles + if (currentUser.isGoodAdmin() && + !currentUser.getId().equals(user.getId())) { + + log.debug("Updating roles for user: " + user); + + // update the roles + + if (user.getRoles().equals(updatedUser.getRoles())) // roles are same + return; + + if (updatedUser.hasRole(Role.UNVERIFIED)) { + + if (!user.hasRole(Role.UNVERIFIED)) { + + makeUnverified(user); // make user unverified + } + } else { + + if (user.hasRole(Role.UNVERIFIED)) + user.getRoles().remove(Role.UNVERIFIED); // make user verified + } + + user.setRoles(updatedUser.getRoles()); + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + } + } + + + /** + * Requests for email change. + * + * @param user + * @param updatedUser + */ + @UserEditPermission + @Validated(AbstractUser.ChangeEmailValidation.class) + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void requestEmailChange(U user, @Valid U updatedUser) { + + log.debug("Requesting email change: " + user); + + // checks + LemonUtils.ensureFound(user); + LemonUtils.validate("updatedUser.password", + passwordEncoder.matches(updatedUser.getPassword(), + user.getPassword()), + "com.naturalprogrammer.spring.wrong.password").go(); + + // preserves the new email id + user.setNewEmail(updatedUser.getNewEmail()); + //user.setChangeEmailCode(LemonUtils.uid()); + userRepository.save(user); + + // after successful commit, mails a link to the user + LemonUtils.afterCommit(() -> mailChangeEmailLink(user)); + + log.debug("Requested email change: " + user); + } + + + /** + * Mails the change-email verification link to the user. + */ + protected void mailChangeEmailLink(U user) { + + String changeEmailCode = jwtService.createToken(JwtService.CHANGE_EMAIL_AUDIENCE, + user.getId().toString(), properties.getJwt().getExpirationMillis(), + LemonUtils.mapOf("newEmail", user.getNewEmail())); + + try { + + log.debug("Mailing change email link to user: " + user); + + // make the link + String changeEmailLink = properties.getApplicationUrl() + + "/users/" + user.getId() + + "/change-email?code=" + changeEmailCode; + + // mail it + mailChangeEmailLink(user, changeEmailLink); + + log.debug("Change email link mail queued."); + + } catch (Throwable e) { + // In case of exception, just log the error and keep silent + log.error(ExceptionUtils.getStackTrace(e)); + } + } + + + /** + * Mails the change-email verification link to the user. + * + * Override this method if you're using a different MailData + */ + protected void mailChangeEmailLink(U user, String changeEmailLink) { + + mailSender.send(LemonMailData.of(user.getNewEmail(), + LemonUtils.getMessage( + "com.naturalprogrammer.spring.changeEmailSubject"), + LemonUtils.getMessage( + "com.naturalprogrammer.spring.changeEmailEmail", + changeEmailLink))); + } + + + /** + * Change the email. + * + * @param changeEmailCode + */ + @PreAuthorize("isAuthenticated()") + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void changeEmail(ID userId, @Valid @NotBlank String changeEmailCode) { + + log.debug("Changing email of current user ..."); + + // fetch the current-user + SpringUser currentUser = LemonUtils.getSpringUser(); + + LemonUtils.validate(userId.equals(currentUser.getId()), + "com.naturalprogrammer.spring.wrong.login").go(); + + U user = userRepository.findById(userId).orElseThrow(LemonUtils.notFoundSupplier()); + + LemonUtils.validate(StringUtils.isNotBlank(user.getNewEmail()), + "com.naturalprogrammer.spring.blank.newEmail").go(); + + JWTClaimsSet claims = jwtService.parseToken(changeEmailCode, + JwtService.CHANGE_EMAIL_AUDIENCE, + user.getCredentialsUpdatedMillis()); + + LemonUtils.ensureAuthority( + claims.getSubject().equals(user.getId().toString()) && + claims.getClaim("newEmail").equals(user.getNewEmail()), + "com.naturalprogrammer.spring.wrong.changeEmailCode"); + + // Ensure that the email would be unique + LemonUtils.validate( + !userRepository.findByEmail(user.getNewEmail()).isPresent(), + "com.naturalprogrammer.spring.duplicate.email").go(); + + // update the fields + user.setEmail(user.getNewEmail()); + user.setNewEmail(null); + //user.setChangeEmailCode(null); + user.setCredentialsUpdatedMillis(System.currentTimeMillis()); + + // make the user verified if he is not + if (user.hasRole(Role.UNVERIFIED)) + user.getRoles().remove(Role.UNVERIFIED); + + userRepository.save(user); + + // after successful commit, + LemonUtils.afterCommit(() -> { + + // Login the user + LemonUtils.login(user); + }); + // logout after successful commit + //LemonUtils.afterCommit(LemonUtils::logOut); + + log.debug("Changed email of user: " + user); + } + + + public String getOAuth2Email(String registrationId, Map attributes) { + + return (String) attributes.get(StandardClaimNames.EMAIL); + } + + public void fillAdditionalFields(String clientId, U user, Map attributes) { + + } + + public boolean getOAuth2AccountVerified(String registrationId, Map attributes) { + + Object verified = attributes.get(StandardClaimNames.EMAIL_VERIFIED); + if (verified == null) + verified = attributes.get("verified"); + + return (boolean) verified; + } + +// @Transactional(propagation=Propagation.REQUIRED, readOnly=false) +// public void loginWithNonce(@Valid NonceForm nonce, HttpServletResponse response) { +// +// U user = userRepository.findById(nonce.getUserId()) +// .orElseThrow(LemonUtils.notFoundSupplier()); +// +// LemonUtils.ensureCredentials(nonce.getNonce().equals(user.getNonce()), +// "com.naturalprogrammer.spring.invalidNonce"); +// +// user.setNonce(null); +// userRepository.save(user); +// LemonUtils.login(user); +// } + +// @Transactional(propagation=Propagation.REQUIRED, readOnly=false) +// public String addNonce(U user) { +// +// String nonce = LemonUtils.uid(); +// user.setNonce(nonce); +// userRepository.save(user); +// +// return nonce; +// } +// + /** + * Fetches a new token - for session scrolling etc. + * @return + */ + @PreAuthorize("isAuthenticated()") + public String fetchNewToken(Optional expirationMillis, + Optional optionalUsername) { + + SpringUser springUser = LemonUtils.getSpringUser(); + String username = optionalUsername.orElse(springUser.getUsername()); + + LemonUtils.ensureAuthority(springUser.getUsername().equals(username) || + springUser.isGoodAdmin(), "com.naturalprogrammer.spring.notGoodAdminOrSameUser"); + + return LemonSecurityConfig.TOKEN_PREFIX + + jwtService.createToken(JwtService.AUTH_AUDIENCE, username, + expirationMillis.orElse(properties.getJwt().getExpirationMillis())); + } + + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void save(U user) { + + userRepository.save(user); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `springUser` last assigned on line 550 could be null and is dereferenced at line 551. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String LemonService.changePassword(AbstractUser,ChangePasswordForm) + +### Procedure Id: +com.naturalprogrammer.spring.lemon.LemonService.changePassword(com.naturalprogrammer.spring.lemon.do.86e1d5bc5daabfcadc229e87309f7bd7 + +### File: +src/main/java/com/naturalprogrammer/spring/lemon/LemonService.java + +### Key: +LemonService.java|changePassword|NULL_DEREFERENCE + +### Node Key: +a8e5ea4c3fb7e7356fb4a16694fe8325 + +### Hash: +23c4c24a72464a4e3523048c3e5e63c3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7323/instruction.md b/inferredbugs-7323/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c73a62fd8773edc48acd37037b2fd507ac343ce --- /dev/null +++ b/inferredbugs-7323/instruction.md @@ -0,0 +1,525 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spring-lemon +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.naturalprogrammer.spring.lemon; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import javax.mail.MessagingException; +import javax.validation.Valid; + +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.NotBlank; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.validation.annotation.Validated; + +import com.naturalprogrammer.spring.lemon.domain.AbstractUser; +import com.naturalprogrammer.spring.lemon.domain.AbstractUser.Role; +import com.naturalprogrammer.spring.lemon.domain.AbstractUser.SignUpValidation; +import com.naturalprogrammer.spring.lemon.domain.AbstractUserRepository; +import com.naturalprogrammer.spring.lemon.domain.ChangePasswordForm; +import com.naturalprogrammer.spring.lemon.mail.MailSender; +import com.naturalprogrammer.spring.lemon.util.LemonUtil; +import com.naturalprogrammer.spring.lemon.validation.Password; + +@Validated +@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) +public abstract class LemonService + , ID extends Serializable> { + + private static final Log log = LogFactory.getLog(LemonService.class); + + @Autowired + private LemonProperties properties; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private MailSender mailSender; + + @Autowired + private AbstractUserRepository userRepository; + + @Autowired + private UserDetailsService userDetailsService; + + /** + * This method needs to be public; otherwise Spring screams + * + * @param event + */ + @EventListener + public void afterContextRefreshed(ContextRefreshedEvent event) { + + log.info("Starting up Spring Lemon ..."); + onStartup(); + log.info("Spring Lemon started"); + + } + + /** + * Creates a new ADMIN user, if not found. + * Override if needed. + */ + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void onStartup() { + + try { + userDetailsService + .loadUserByUsername(properties.getAdmin().getLogin()); + } catch (UsernameNotFoundException e) { + U user = createAdminUser(); + userRepository.save(user); + } + } + + + /** + * Override this if you have more fields to set, + * or if the email field if not your loginId + */ + protected U createAdminUser() { + + String adminEmail = properties.getAdmin().getLogin(); + + log.info("Creating the first admin user: " + adminEmail); + + U user = newUser(); + user.setEmail(adminEmail); + user.setPassword(passwordEncoder.encode( + properties.getAdmin().getPassword())); + user.getRoles().add(Role.ADMIN); + + return user; + + } + + abstract protected U newUser(); + + @Autowired + private LemonProperties lemonProperties; + + /** + * Returns the context data to be sent to the client, + * i.e. reCaptchaSiteKey and all the properties + * prefixed with lemon.shared. + * + * To send custom properties, put those in your application + * properties in the format lemon.shared.fooBar. + * + * You can also override this method. + */ + public Map getContext() { + + Map context = new HashMap(2); + context.put("reCaptchaSiteKey", properties.getRecaptcha().getSitekey()); + context.put("shared", properties.getShared()); + + log.debug("Returning context: " + context); + + return context; + } + + @PreAuthorize("isAnonymous()") + @Validated(SignUpValidation.class) + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void signup(@Valid U user) { + + log.debug("Signing up user: " + user); + + initUser(user); + userRepository.save(user); + + LemonUtil.afterCommit(() -> { + + LemonUtil.logInUser(user); + sendVerificationMail(user); + log.debug("Signed up user: " + user); + }); + } + + protected U initUser(U user) { + + log.debug("Initializing user: " + user); + + user.setPassword(passwordEncoder.encode(user.getPassword())); + makeUnverified(user); + + return user; + } + + protected void makeUnverified(U user) { + user.getRoles().add(Role.UNVERIFIED); + user.setVerificationCode(UUID.randomUUID().toString()); + } + + protected void makeVerified(U user) { + user.getRoles().remove(Role.UNVERIFIED); + user.setVerificationCode(null); + } + + protected void sendVerificationMail(final U user) { + try { + + log.debug("Sending verification mail to: " + user); + + String verifyLink = properties.getApplicationUrl() + + "/users/" + user.getVerificationCode() + "/verify"; + + mailSender.send(user.getEmail(), + LemonUtil.getMessage("com.naturalprogrammer.spring.verifySubject"), + LemonUtil.getMessage( + "com.naturalprogrammer.spring.verifyEmail", verifyLink)); + + log.debug("Verification mail to " + user.getEmail() + " queued."); + + } catch (MessagingException e) { + log.error(ExceptionUtils.getStackTrace(e)); + } + } + + /** + * Resends verification mail to user + * See here for details + * @param user + */ + @PreAuthorize("hasPermission(#user, 'edit')") + public void resendVerificationMail(U user) { + + LemonUtil.check("id", user != null, + "com.naturalprogrammer.spring.userNotFound").go(); + + LemonUtil.check(user.getRoles().contains(Role.UNVERIFIED), + "com.naturalprogrammer.spring.alreadyVerified").go(); + + sendVerificationMail(user); + } + + public U fetchUser(@Valid @Email @NotBlank String email) { + + log.debug("Fetching user by email: " + email); + + U user = userRepository.findByEmail(email); + LemonUtil.check("email", user != null, + "com.naturalprogrammer.spring.userNotFound").go(); + + user.decorate().hideConfidentialFields(); + + log.debug("Returning user: " + user); + + return user; + } + + + public U fetchUser(U user) { + + log.debug("Fetching user: " + user); + + LemonUtil.check("id", user != null, + "com.naturalprogrammer.spring.userNotFound").go(); + + user.decorate().hideConfidentialFields(); + + return user; + } + + @PreAuthorize("isAuthenticated()") + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void verifyUser(@Valid @NotBlank String verificationCode) { + + log.debug("Verifying user ..."); + + U currentUser = LemonUtil.getUser(); + + U user = userRepository.findOne(currentUser.getId()); + + LemonUtil.check(user.getRoles().contains(Role.UNVERIFIED), + "com.naturalprogrammer.spring.alreadyVerified").go(); + + LemonUtil.check(verificationCode.equals(user.getVerificationCode()), + "com.naturalprogrammer.spring.wrong.verificationCode").go(); + + makeVerified(user); + userRepository.save(user); + + LemonUtil.afterCommit(() -> { + + currentUser.getRoles().remove(Role.UNVERIFIED); + currentUser.decorate(currentUser); + log.debug("Removed UNVERIFIED role from current user."); + }); + + log.debug("Verified user: " + user); + } + + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void forgotPassword(@Valid @Email @NotBlank String email) { + + log.debug("Processing forgot password for email: " + email); + final U user = userRepository.findByEmail(email); + + LemonUtil.check(user != null, "com.naturalprogrammer.spring.userNotFound").go(); + + user.setForgotPasswordCode(UUID.randomUUID().toString()); + userRepository.save(user); + + LemonUtil.afterCommit(() -> { + mailForgotPasswordLink(user); + }); + + } + + private void mailForgotPasswordLink(U user) { + + try { + + log.debug("Mailing forgot password link to user: " + user); + + String forgotPasswordLink = + properties.getApplicationUrl() + "/reset-password/" + + user.getForgotPasswordCode(); + mailSender.send(user.getEmail(), + LemonUtil.getMessage("com.naturalprogrammer.spring.forgotPasswordSubject"), + LemonUtil.getMessage("com.naturalprogrammer.spring.forgotPasswordEmail", forgotPasswordLink)); + + log.debug("Forgot password link mail queued."); + + } catch (MessagingException e) { + log.error(ExceptionUtils.getStackTrace(e)); + } + + } + + + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void resetPassword(String forgotPasswordCode, @Valid @Password String newPassword) { + + log.debug("Resetting password ..."); + + U user = userRepository.findByForgotPasswordCode(forgotPasswordCode); + LemonUtil.check(user != null, "com.naturalprogrammer.spring.invalidLink").go(); + + user.setPassword(passwordEncoder.encode(newPassword)); + user.setForgotPasswordCode(null); + + userRepository.save(user); + + log.debug("Password reset."); + + } + + @PreAuthorize("hasPermission(#user, 'edit')") + @Validated(AbstractUser.UpdateValidation.class) + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void updateUser(U user, @Valid U updatedUser) { + + log.debug("Updating user: " + user); + + LemonUtil.check("id", user != null, "com.naturalprogrammer.spring.userNotFound").go(); + LemonUtil.validateVersion(user, updatedUser); + + U currentUser = LemonUtil.getUser(); + + updateUserFields(user, updatedUser, currentUser); + + userRepository.save(user); + + log.debug("Updated user: " + user); + } + + @PreAuthorize("hasPermission(#user, 'edit')") + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void changePassword(U user, @Valid ChangePasswordForm changePasswordForm) { + + log.debug("Changing password for user: " + user); + + LemonUtil.check("id", user != null, "com.naturalprogrammer.spring.userNotFound").go(); + LemonUtil.check("changePasswordForm.oldPassword", + passwordEncoder.matches(changePasswordForm.getOldPassword(), user.getPassword()), + "com.naturalprogrammer.spring.wrong.password").go(); + + user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword())); + userRepository.save(user); + + LemonUtil.afterCommit(() -> { + + U currentUser = LemonUtil.getUser(); + + if (currentUser.equals(user)) { + + log.debug("Setting password for logged in user."); + currentUser.setPassword(user.getPassword()); + } + }); + + log.debug("Changed password for user: " + user); + } + + + /** + * Override this if you have more fields + * + * @param user + * @param updatedUser + * @param currentUser + */ + protected void updateUserFields(U user, U updatedUser, U currentUser) { + + log.debug("Updating user fields for user: " + user); + + if (user.isRolesEditable()) { + + log.debug("Updating roles for user: " + user); + + Set roles = user.getRoles(); + + if (updatedUser.isUnverified()) { + + if (!user.hasRole(Role.UNVERIFIED)) { + makeUnverified(user); // make user unverified + LemonUtil.afterCommit(() -> { + sendVerificationMail(user); // send a verification mail to the user + }); + } + } else { + + if (user.hasRole(Role.UNVERIFIED)) + makeVerified(user); // make user verified + } + + if (updatedUser.isAdmin()) + roles.add(Role.ADMIN); + else + roles.remove(Role.ADMIN); + + if (updatedUser.isBlocked()) + roles.add(Role.BLOCKED); + else + roles.remove(Role.BLOCKED); + } + +// This is not needed, because the logged in user can't update his own role +// LemonUtil.afterCommit(() -> { +// if (currentUser.equals(user)) { +// +// log.debug("Setting roles for logged in user."); +// currentUser.setRoles(user.getRoles()); +// } +// }); + + } + + public U userForClient() { + return userForClient(LemonUtil.getUser()); + } + + + /** + * Override this if you have more fields + * + * @param currentUser + */ + protected U userForClient(U currentUser) { + + if (currentUser == null) + return null; + + U user = newUser(); + user.setIdForClient(currentUser.getId()); + user.setEmail(currentUser.getEmail()); + user.setRoles(currentUser.getRoles()); + user.decorate(currentUser); + + log.debug("Returning user for client: " + user); + + return user; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `user` last assigned on line 215 could be null and is dereferenced at line 219. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AbstractUser LemonService.fetchUser(String) + +### Procedure Id: +com.naturalprogrammer.spring.lemon.LemonService.fetchUser(java.lang.String):com.naturalprogrammer.sp.52b89ca1fd64feae7f4b394ab1eea744 + +### File: +src/main/java/com/naturalprogrammer/spring/lemon/LemonService.java + +### Key: +LemonService.java|fetchUser|NULL_DEREFERENCE + +### Node Key: +913f39c549db9d899ffc72b5138ab2e6 + +### Hash: +0dd2239fce66aa7409013073ff4c3f98 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7325/instruction.md b/inferredbugs-7325/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..095c5c1e627e067307eea0c2cf6765c8ca043b3a --- /dev/null +++ b/inferredbugs-7325/instruction.md @@ -0,0 +1,240 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spring-lemon +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.naturalprogrammer.spring.boot; + +import javax.mail.MessagingException; +import javax.validation.ConstraintViolationException; +import javax.validation.Valid; +import javax.validation.constraints.NotNull; + +import org.apache.commons.lang3.RandomStringUtils; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.validator.constraints.Email; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.transaction.support.TransactionSynchronizationAdapter; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.validation.annotation.Validated; + +import com.naturalprogrammer.spring.boot.SaUser.Role; +import com.naturalprogrammer.spring.boot.mail.MailSender; +import com.naturalprogrammer.spring.boot.security.UserDto; + +@Validated +@Transactional(propagation=Propagation.SUPPORTS, readOnly=true) +public abstract class SaService { + + private final Log log = LogFactory.getLog(getClass()); + + @Value(SaUtil.APPLICATION_URL) + private String applicationUrl; + + @Value(SaUtil.RECAPTCHA_SITE_KEY) + private String reCaptchaSiteKey; + + @Value("${admin.email}") + private String adminEmail; + + @Value("${admin.password}") + private String adminPassword; + + @Autowired + private PasswordEncoder passwordEncoder; + + @Autowired + private MailSender mailSender; + + @Autowired + private SaUserRepository userRepository; + + + /** + * This method needs to be public; otherwise Spring screams + * + * @param event + */ + @EventListener + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public void afterContextRefreshed(ContextRefreshedEvent event) { + + onStartup(); + + } + + /** + * Override this if needed + */ + protected void onStartup() { + U user = userRepository.findByEmail(adminEmail); + if (user == null) { + user = createAdminUser(); + userRepository.save(user); + } + } + + + /** + * Override this if you have more fields to set + */ + protected U createAdminUser() { + + final U user = (U) SaUtil.getBean(SaUser.class); + + user.setEmail(adminEmail); + user.setName("Administrator"); + user.setPassword(passwordEncoder.encode(adminPassword)); + user.getRoles().add(Role.ADMIN); + + return user; + + } + + + public ContextDto getContext() { + ContextDto contextDto = new ContextDto(); + contextDto.setReCaptchaSiteKey(reCaptchaSiteKey); + contextDto.setUserDto(SaUtil.getUserDto()); + return contextDto; + } + + @PreAuthorize("isAnonymous()") + @Transactional(propagation=Propagation.REQUIRED, readOnly=false) + public UserDto signup(@Valid S signupForm) { + + U user = createUser(signupForm); + userRepository.save(user); + sendVerificationMail(user); + SaUtil.logInUser(user); + return user.getUserDto(); + } + + protected U createUser(S signupForm) { + + final U user = (U) SaUtil.getBean(SaUser.class); + + user.setEmail(signupForm.getEmail()); + user.setName(signupForm.getName()); + user.setPassword(passwordEncoder.encode(signupForm.getPassword())); + user.getRoles().add(Role.UNVERIFIED); + user.setVerificationCode(RandomStringUtils.randomAlphanumeric(16)); + + return user; + + } + + protected void sendVerificationMail(final U user) { + TransactionSynchronizationManager.registerSynchronization( + new TransactionSynchronizationAdapter() { + @Override + public void afterCommit() { + try { + String verifyLink = applicationUrl + "/users/" + user.getVerificationCode() + "/verify"; + mailSender.send(user.getEmail(), SaUtil.getMessage("verifySubject"), SaUtil.getMessage("verifyEmail", verifyLink)); + log.info("Verification mail to " + user.getEmail() + " queued."); + } catch (MessagingException e) { + log.error(ExceptionUtils.getStackTrace(e)); + } + } + }); + + } + + public U fetchUser(@Valid @Email @NotNull String email) { + + SaUser loggedIn = SaUtil.getSessionUser(); + + U user = userRepository.findByEmail(email); + + if (user == null) { + ////////////////// throw SaFormException + } + + user.setPassword(null); + + if (loggedIn == null || loggedIn.getId() != user.getId() && !loggedIn.isAdmin()) + user.setEmail("Confidential"); + + return user; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `user` last assigned on line 152 could be null and is dereferenced at line 158. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SaUser SaService.fetchUser(String) + +### Procedure Id: +com.naturalprogrammer.spring.boot.SaService.fetchUser(java.lang.String):com.naturalprogrammer.spring.e283d17f5fd1ccff09fa22020cf685e0 + +### File: +src/main/java/com/naturalprogrammer/spring/boot/SaService.java + +### Key: +SaService.java|fetchUser|NULL_DEREFERENCE + +### Node Key: +f097a339c449f77f32c35350634f5e98 + +### Hash: +8e5d703808e5d5fc0388ce90ebb93bfb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7341/instruction.md b/inferredbugs-7341/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f1ff1cf60c4ff93f82847e6762420c663c7d1f8 --- /dev/null +++ b/inferredbugs-7341/instruction.md @@ -0,0 +1,160 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** wro4j +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ro.isdc.wro.http.support; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ro.isdc.wro.WroRuntimeException; +import ro.isdc.wro.config.Context; +import ro.isdc.wro.http.WroFilter; +import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; + +/** + * Allows configuration of a list of processors to be applied on the + * + * @author Alex Objelean + * @since 1.4.5 + * @created 17 Mar 2012 + */ +public abstract class AbstractProcessorFilter + implements Filter { + private static final Logger LOG = LoggerFactory.getLogger(WroFilter.class); + private FilterConfig filterConfig; + /** + * {@inheritDoc} + */ + public final void init(final FilterConfig config) + throws ServletException { + this.filterConfig = config; + } + + /** + * {@inheritDoc} + */ + public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) + throws IOException, ServletException { + final HttpServletRequest request = (HttpServletRequest) req; + final HttpServletResponse response = (HttpServletResponse) res; + try { + // add request, response & servletContext to thread local + Context.set(Context.webContext(request, response, filterConfig)); + chain.doFilter(req, res); + } catch (final RuntimeException e) { + onRuntimeException(e, response, chain); + } finally { + Context.unset(); + } + } + + /** + * Invoked when a {@link RuntimeException} is thrown. Allows custom exception handling. The default implementation + * redirects to 404 for a specific {@link WroRuntimeException} exception when in DEPLOYMENT mode. + * + * @param e {@link RuntimeException} thrown during request processing. + */ + protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, + final FilterChain chain) { + LOG.debug("RuntimeException occured", e); + try { + LOG.debug("Cannot process. Proceeding with chain execution."); + final OutputStream os = new ByteArrayOutputStream(); + HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); + chain.doFilter(Context.get().getRequest(), wrappedResponse); + } catch (final Exception ex) { + // should never happen + LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); + } + } + + /** + * @return a list of processors to apply for this filter. + */ + protected abstract List processorsList(); +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `ro.isdc.wro.http.support.DelegatingServletOutputStream` acquired by call to `RedirectedStreamServletResponseWrapper(...)` at line 74 is not released after line 75. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractProcessorFilter.onRuntimeException(RuntimeException,HttpServletResponse,FilterChain) + +### Procedure Id: +ro.isdc.wro.http.support.AbstractProcessorFilter.onRuntimeException(java.lang.RuntimeException,javax.b9f8e2e8297d6483c81c6fe315223308 + +### File: +wro4j-core/src/main/java/ro/isdc/wro/http/support/AbstractProcessorFilter.java + +### Key: +AbstractProcessorFilter.java|onRuntimeException|RESOURCE_LEAK + +### Node Key: +5d242acb1076468218a9cfd70cc4ceda + +### Hash: +d01021825048eb62e17028bca544771a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7346/instruction.md b/inferredbugs-7346/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cfa6199973d56329d84a8bee924b79ea20c7dfda --- /dev/null +++ b/inferredbugs-7346/instruction.md @@ -0,0 +1,161 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** wro4j +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ro.isdc.wro.http.support; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.List; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ro.isdc.wro.WroRuntimeException; +import ro.isdc.wro.config.Context; +import ro.isdc.wro.http.WroFilter; +import ro.isdc.wro.model.resource.processor.ResourcePreProcessor; + +/** + * Allows configuration of a list of processors to be applied on the + * + * @author Alex Objelean + * @since 1.4.5 + * @created 17 Mar 2012 + */ +public abstract class AbstractProcessorFilter + implements Filter { + private static final Logger LOG = LoggerFactory.getLogger(WroFilter.class); + private FilterConfig filterConfig; + /** + * {@inheritDoc} + */ + public final void init(final FilterConfig config) + throws ServletException { + this.filterConfig = config; + } + + /** + * {@inheritDoc} + */ + public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) + throws IOException, ServletException { + final HttpServletRequest request = (HttpServletRequest) req; + final HttpServletResponse response = (HttpServletResponse) res; + try { + // add request, response & servletContext to thread local + Context.set(Context.webContext(request, response, filterConfig)); + chain.doFilter(req, res); + } catch (final RuntimeException e) { + onRuntimeException(e, response, chain); + } finally { + Context.unset(); + } + } + + /** + * Invoked when a {@link RuntimeException} is thrown. Allows custom exception handling. The default implementation + * redirects to 404 for a specific {@link WroRuntimeException} exception when in DEPLOYMENT mode. + * + * @param e {@link RuntimeException} thrown during request processing. + */ + protected void onRuntimeException(final RuntimeException e, final HttpServletResponse response, + final FilterChain chain) { + LOG.debug("RuntimeException occured", e); + try { + LOG.debug("Cannot process. Proceeding with chain execution."); + final OutputStream os = new ByteArrayOutputStream(); + HttpServletResponse wrappedResponse = new RedirectedStreamServletResponseWrapper(os, response); + chain.doFilter(Context.get().getRequest(), wrappedResponse); + } catch (final Exception ex) { + // should never happen + LOG.error("Error while chaining the request: " + HttpServletResponse.SC_NOT_FOUND); + } + } + + /** + * @return a list of processors to apply for this filter. + */ + protected abstract List processorsList(); +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `ro.isdc.wro.http.support.DelegatingServletOutputStream` acquired by call to `RedirectedStreamServletResponseWrapper(...)` at line 74 is not released after line 76. +**Note**: potential exception at line 75 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractProcessorFilter.onRuntimeException(RuntimeException,HttpServletResponse,FilterChain) + +### Procedure Id: +ro.isdc.wro.http.support.AbstractProcessorFilter.onRuntimeException(java.lang.RuntimeException,javax.b9f8e2e8297d6483c81c6fe315223308 + +### File: +wro4j-core/src/main/java/ro/isdc/wro/http/support/AbstractProcessorFilter.java + +### Key: +AbstractProcessorFilter.java|onRuntimeException|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +5f2c664fd3cdbb707a6743e1efdeccaa + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7348/instruction.md b/inferredbugs-7348/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4013d5ef40740a6a174de520ecbcb57c4248819e --- /dev/null +++ b/inferredbugs-7348/instruction.md @@ -0,0 +1,197 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** wro4j +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2008. All rights reserved. + */ +package ro.isdc.wro.manager; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import ro.isdc.wro.AbstractWroTest; +import ro.isdc.wro.config.ConfigurationContext; +import ro.isdc.wro.config.Context; +import ro.isdc.wro.config.jmx.WroConfiguration; +import ro.isdc.wro.http.DelegatingServletOutputStream; +import ro.isdc.wro.manager.factory.ServletContextAwareWroManagerFactory; +import ro.isdc.wro.model.factory.XmlModelFactory; +import ro.isdc.wro.test.util.WroTestUtils; + + +/** + * TestWroManager.java. + * + * @author Alex Objelean + * @created Created on Nov 3, 2008 + */ +public class TestWroManager extends AbstractWroTest { + private WroManager manager; + + + @Before + public void setUp() { + initConfigWithUpdatePeriodValue(0); + final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); + manager = factory.getInstance(); + Context.set(Mockito.mock(Context.class, Mockito.RETURNS_DEEP_STUBS)); + } + + + @Test + public void testNoProcessorWroManagerFactory() throws IOException { + final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); + manager = factory.getInstance(); + manager.setModelFactory(getValidModelFactory()); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final OutputStream os = System.out; + final HttpServletResponse response = Context.get().getResponse(); + + final InputStream actualStream = WroTestUtils.convertToInputStream(os); + Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(os)); + Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); + manager.process(request, response); + WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), actualStream); + } + + + @Test + public void processValidModel() throws IOException { + manager.setModelFactory(getValidModelFactory()); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpServletResponse response = Context.get().getResponse(); + Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); + manager.process(request, response); + } + + + /** + * @return a {@link XmlModelFactory} pointing to a valid config resource. + */ + private XmlModelFactory getValidModelFactory() { + return new XmlModelFactory() { + @Override + protected InputStream getConfigResourceAsStream() { + return getResourceAsStream(TestWroManager.class.getPackage().getName().replace(".", "/") + "/wro.xml"); + } + }; + } + + + /** + * Test how manager behaves when the update period value is greater than zero and the scheduler starts. + * + * @throws Exception + */ + @Test + public void testManagerWhenSchedulerIsStarted() throws Exception { + manager.setModelFactory(getValidModelFactory()); + initConfigWithUpdatePeriodValue(1); + final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + final HttpServletResponse response = Context.get().getResponse(); + Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); + manager.process(request, response); + // allow thread to do their job + Thread.sleep(2000); + } + + + /** + * Initialize {@link WroConfiguration} object with cacheUpdatePeriod & modelUpdatePeriod equal with provided argument. + */ + private void initConfigWithUpdatePeriodValue(final long periodValue) { + final WroConfiguration config = new WroConfiguration(); + config.setCacheUpdatePeriod(periodValue); + config.setModelUpdatePeriod(periodValue); + + ConfigurationContext.get().setConfig(config); + } + + + @After + public void tearDown() { + manager.destroy(); + Context.unset(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PipedInputStream` acquired by call to `convertToInputStream(...)` at line 56 is not released after line 61. +**Note**: potential exception at line 57 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestWroManager.testNoProcessorWroManagerFactory() + +### Procedure Id: +ro.isdc.wro.manager.TestWroManager.testNoProcessorWroManagerFactory():void.85d168d543f867f7970115b0a95f7273 + +### File: +wro4j-core/src/test/java/ro/isdc/wro/manager/TestWroManager.java + +### Key: +TestWroManager.java|testNoProcessorWroManagerFactory|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +b3b0a56f520628a49b629d449c2a3739 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7370/instruction.md b/inferredbugs-7370/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3992185dc51a670bdb630fa9a2a656e61f19c420 --- /dev/null +++ b/inferredbugs-7370/instruction.md @@ -0,0 +1,710 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ghprb-plugin +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jenkinsci.plugins.ghprb; + +import com.google.common.base.Joiner; + +import hudson.model.AbstractBuild; + +import org.apache.commons.lang.StringUtils; +import org.kohsuke.github.GHCommitPointer; +import org.kohsuke.github.GHIssue; +import org.kohsuke.github.GHIssueComment; +import org.kohsuke.github.GHPullRequest; +import org.kohsuke.github.GHPullRequestCommitDetail; +import org.kohsuke.github.GHUser; +import org.kohsuke.github.GitUser; + +import java.io.IOException; +import java.net.URL; +import java.util.Date; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Maintains state about a Pull Request for a particular Jenkins job. This is what understands the current state of a PR + * for a particular job. + * + * @author Honza Brázdil + */ +public class GhprbPullRequest { + + private static final Logger logger = Logger.getLogger(GhprbPullRequest.class.getName()); + + @Deprecated + @SuppressWarnings("unused") + private transient GHUser author; + @Deprecated + @SuppressWarnings("unused") + private transient String title; + @Deprecated + @SuppressWarnings("unused") + private transient String reponame; + @Deprecated + @SuppressWarnings("unused") + private transient URL url; + @Deprecated + @SuppressWarnings("unused") + private transient String description; + @Deprecated + @SuppressWarnings("unused") + private transient String target; + @Deprecated + @SuppressWarnings("unused") + private transient String source; + @Deprecated + @SuppressWarnings("unused") + private transient String authorRepoGitUrl; + @Deprecated + @SuppressWarnings("unused") + private transient Boolean changed = true; + + private transient String authorEmail; + private transient Ghprb helper; // will be refreshed each time GhprbRepository.init() is called + private transient GhprbRepository repo; // will be refreshed each time GhprbRepository.init() is called + + private transient GHPullRequest pr; + + private transient GHUser triggerSender; // Only needed for a single build + private transient GitUser commitAuthor; // Only needed for a single build + private transient String commentBody; + + private transient boolean shouldRun = false; // Declares if we should run the build this time. + private transient boolean triggered = false; // Only lets us know if the trigger phrase was used for this run + private transient boolean mergeable = false; // Only works as an easy way to pass the value around for the start of + // this build + + private final int id; + private Date updated; // Needed to track when the PR was updated + private String head; + private String base; + private boolean accepted = false; // Needed to see if the PR has been added to the accepted list + private String lastBuildId; + + private void setUpdated(Date lastUpdateTime) { + updated = lastUpdateTime; + } + + private void setHead(String newHead) { + this.head = StringUtils.isEmpty(newHead) ? head : newHead; + } + + private void setBase(String newBase) { + this.base = StringUtils.isEmpty(newBase) ? base : newBase; + } + + private void setAccepted(boolean shouldRun) { + accepted = true; + this.shouldRun = shouldRun; + } + + public GhprbPullRequest(GHPullRequest pr, + Ghprb ghprb, + GhprbRepository repo, + boolean isNew) { + + id = pr.getNumber(); + setPullRequest(pr); + + this.helper = ghprb; + + this.repo = repo; + + GHUser author = pr.getUser(); + String reponame = repo.getName(); + + try { + if (ghprb.isWhitelisted(getPullRequestAuthor())) { + setAccepted(true); + } else { + logger.log(Level.INFO, + "Author of #{0} {1} on {2} not in whitelist!", + new Object[] { id, author.getLogin(), reponame }); + repo.addComment(id, GhprbTrigger.getDscp().getRequestForTestingPhrase()); + } + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to get pull request author", e); + } + + logger.log(Level.INFO, + "Created Pull Request #{0} on {1} by {2} ({3}) updated at: {4} SHA: {5}", + new Object[] { id, reponame, author.getLogin(), getAuthorEmail(), updated, this.head }); + } + + public void init(Ghprb helper, + GhprbRepository repo) { + this.helper = helper; + this.repo = repo; + } + + /** + * Checks this Pull Request representation against a GitHub version of the Pull Request, and triggers a build if + * necessary. + * + * @param ghpr + */ + public void check(GHPullRequest ghpr) { + setPullRequest(ghpr); + if (helper.isProjectDisabled()) { + logger.log(Level.FINE, "Project is disabled, ignoring pull request"); + return; + } + + try { + getPullRequest(false); + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); + return; + } + + updatePR(pr, pr.getUser()); + + checkSkipBuild(pr); + tryBuild(); + } + + private void checkSkipBuild(GHIssue issue) { + String skipBuildPhrase = helper.checkSkipBuild(issue); + if (!StringUtils.isEmpty(skipBuildPhrase)) { + logger.log(Level.INFO, + "Pull request commented with {0} skipBuildPhrase. Hence skipping the build.", + skipBuildPhrase); + shouldRun = false; + } + } + + public void check(GHIssueComment comment) { + if (helper.isProjectDisabled()) { + logger.log(Level.FINE, "Project is disabled, ignoring comment"); + return; + } + + synchronized (this) { + try { + checkComment(comment); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); + return; + } + + try { + GHUser user = null; + try { + user = comment.getUser(); + } catch (IOException e) { + logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); + } + updatePR(getPullRequest(true), user); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); + } + + checkSkipBuild(comment.getParent()); + tryBuild(); + } + } + + private void updatePR(GHPullRequest pr, + GHUser user) { + setPullRequest(pr); + + synchronized (this) { + Date lastUpdateTime = updated; + if (isUpdated(pr)) { + logger.log(Level.INFO, + "Pull request #{0} was updated on {1} at {2} by {3}", + new Object[] { id, repo.getName(), updated, user }); + + // the author of the PR could have been whitelisted since its creation + if (!accepted && helper.isWhitelisted(pr.getUser())) { + logger.log(Level.INFO, "Pull request #{0}'s author has been whitelisted", new Object[] { id }); + setAccepted(false); + } + + int commentsChecked = checkComments(pr, lastUpdateTime); + boolean newCommit = checkCommit(pr); + + if (!newCommit && commentsChecked == 0) { + logger.log(Level.INFO, + "Pull request #{0} was updated on repo {1} but there aren''t any new comments nor commits; " + + "that may mean that commit status was updated.", + new Object[] { id, repo.getName() }); + } + } + } + } + + public boolean isWhiteListedTargetBranch() { + List branches = helper.getWhiteListTargetBranches(); + if (branches.isEmpty() || (branches.size() == 1 && branches.get(0).getBranch().equals(""))) { + // no branches in white list means we should test all + return true; + } + + String target = getTarget(); + for (GhprbBranch b : branches) { + if (b.matches(target)) { + // the target branch is in the whitelist! + return true; + } + } + logger.log(Level.FINEST, + "PR #{0} target branch: {1} isn''t in our whitelist of target branches: {2}", + new Object[] { id, target, Joiner.on(',').skipNulls().join(branches) }); + return false; + } + + private boolean isUpdated(GHPullRequest pr) { + synchronized (this) { + Date lastUpdated = new Date(); + boolean ret = false; + try { + lastUpdated = pr.getUpdatedAt(); + ret = updated.compareTo(lastUpdated) < 0; + setUpdated(lastUpdated); + } catch (Exception e) { + logger.log(Level.WARNING, "Unable to update last updated date", e); + } + GHCommitPointer pointer = pr.getHead(); + String pointerSha = pointer.getSha(); + ret |= !pointerSha.equals(head); + + pointer = pr.getBase(); + pointerSha = pointer.getSha(); + ret |= !pointerSha.equals(base); + + return ret; + } + } + + private void tryBuild() { + if (helper.isProjectDisabled()) { + logger.log(Level.FINEST, "Project is disabled, not trying to build"); + shouldRun = false; + triggered = false; + } + if (helper.ifOnlyTriggerPhrase() && !triggered) { + logger.log(Level.FINEST, "Trigger only phrase but we are not triggered"); + shouldRun = false; + } + triggered = false; // Once we have decided that we are triggered then the flag should be set to false. + + if (!isWhiteListedTargetBranch()) { + logger.log(Level.FINEST, "Branch is not whitelisted, skipping the build"); + return; + } + if (shouldRun) { + shouldRun = false; // Change the shouldRun flag as soon as we decide to build. + logger.log(Level.FINEST, "Running the build"); + + if (pr != null) { + logger.log(Level.FINEST, "PR is not null, checking if mergable"); + checkMergeable(); + try { + for (GHPullRequestCommitDetail commitDetails : pr.listCommits()) { + if (commitDetails.getSha().equals(getHead())) { + commitAuthor = commitDetails.getCommit().getCommitter(); + break; + } + } + } catch (Exception ex) { + logger.log(Level.INFO, "Unable to get PR commits: ", ex); + } + + } + + logger.log(Level.FINEST, "Running build..."); + build(); + } + } + + private void build() { + GhprbBuilds builder = helper.getBuilds(); + builder.build(this, triggerSender, commentBody); + } + + // returns false if no new commit + private boolean checkCommit(GHPullRequest pr) { + GHCommitPointer head = pr.getHead(); + GHCommitPointer base = pr.getBase(); + + String headSha = head.getSha(); + String baseSha = base.getSha(); + + if (StringUtils.equals(headSha, this.head) && StringUtils.equals(baseSha, this.base)) { + return false; + } + + logger.log(Level.FINE, + "New commit. Sha: Head[{0} => {1}] Base[{2} => {3}]", + new Object[] { this.head, headSha, this.base, baseSha }); + + setHead(headSha); + setBase(baseSha); + + if (accepted) { + shouldRun = true; + } + return true; + } + + private void checkComment(GHIssueComment comment) throws IOException { + GHUser sender = comment.getUser(); + String body = comment.getBody(); + + logger.log(Level.FINEST, "[{0}] Added comment: {1}", new Object[] { sender.getName(), body }); + + // Disabled until more advanced configs get set up + // ignore comments from bot user, this fixes an issue where the bot would auto-whitelist + // a user or trigger a build when the 'request for testing' phrase contains the + // whitelist/trigger phrase and the bot is a member of a whitelisted organisation + // if (helper.isBotUser(sender)) { + // logger.log(Level.INFO, "Comment from bot user {0} ignored.", sender); + // return; + // } + + if (helper.isWhitelistPhrase(body) && helper.isAdmin(sender)) { // add to whitelist + GHIssue parent = comment.getParent(); + GHUser author = parent.getUser(); + if (!helper.isWhitelisted(author)) { + logger.log(Level.FINEST, "Author {0} not whitelisted, adding to whitelist.", author); + helper.addWhitelist(author.getLogin()); + } + setAccepted(true); + } else if (helper.isOktotestPhrase(body) && helper.isAdmin(sender)) { // ok to test + logger.log(Level.FINEST, "Admin {0} gave OK to test", sender); + setAccepted(true); + } else if (helper.isRetestPhrase(body)) { // test this please + logger.log(Level.FINEST, "Retest phrase"); + if (helper.isAdmin(sender)) { + logger.log(Level.FINEST, "Admin {0} gave retest phrase", sender); + shouldRun = true; + } else if (accepted && helper.isWhitelisted(sender)) { + logger.log(Level.FINEST, "Retest accepted and user {0} is whitelisted", sender); + shouldRun = true; + } + } else if (helper.isTriggerPhrase(body)) { // trigger phrase + logger.log(Level.FINEST, "Trigger phrase"); + if (helper.isAdmin(sender)) { + logger.log(Level.FINEST, "Admin {0} ran trigger phrase", sender); + shouldRun = true; + triggered = true; + } else if (accepted && helper.isWhitelisted(sender)) { + logger.log(Level.FINEST, "Trigger accepted and user {0} is whitelisted", sender); + shouldRun = true; + triggered = true; + } + } + + if (shouldRun) { + triggerSender = sender; + commentBody = body; + } + } + + private int checkComments(GHPullRequest ghpr, + Date lastUpdatedTime) { + int count = 0; + logger.log(Level.FINEST, "Checking for comments after: {0}", lastUpdatedTime); + try { + for (GHIssueComment comment : ghpr.getComments()) { + logger.log(Level.FINEST, "Comment was made at: {0}", comment.getUpdatedAt()); + if (lastUpdatedTime.compareTo(comment.getUpdatedAt()) < 0) { + logger.log(Level.FINEST, "Comment was made after last update time, {0}", comment.getBody()); + count++; + try { + checkComment(comment); + } catch (IOException ex) { + logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); + } + } + } + } catch (IOException e) { + logger.log(Level.SEVERE, "Couldn't obtain comments.", e); + } + return count; + } + + public boolean checkMergeable() { + try { + getPullRequest(false); + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to get a copy of the PR from github", e); + return mergeable; + } + try { + int r = 5; + Boolean isMergeable = pr.getMergeable(); + while (isMergeable == null && r-- > 0) { + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + break; + } + isMergeable = pr.getMergeable(); + } + mergeable = isMergeable != null && isMergeable; + } catch (IOException e) { + logger.log(Level.SEVERE, "Couldn't obtain mergeable status.", e); + } + return mergeable; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof GhprbPullRequest)) { + return false; + } + GhprbPullRequest o = (GhprbPullRequest) obj; + return o.id == id; + } + + @Override + public int hashCode() { + int hash = 7; + hash = 89 * hash + this.id; + return hash; + } + + public int getId() { + return id; + } + + public String getHead() { + return head; + } + + public String getAuthorRepoGitUrl() { + GHCommitPointer prHead = pr.getHead(); + String authorRepoGitUrl = ""; + + if (prHead != null && prHead.getRepository() != null) { + authorRepoGitUrl = prHead.getRepository().gitHttpTransportUrl(); + } + return authorRepoGitUrl; + } + + public boolean isMergeable() { + return mergeable; + } + + /** + * Base and Ref are part of the PullRequest object + * + * @return + */ + public String getTarget() { + try { + return getPullRequest(false).getBase().getRef(); + } catch (IOException e) { + return "UNKNOWN"; + } + } + + /** + * Head and Ref are part of the PullRequest object + * + * @return + */ + public String getSource() { + try { + return getPullRequest(false).getHead().getRef(); + } catch (IOException e) { + return "UNKNOWN"; + } + } + + /** + * Title is part of the PullRequest object + * + * @return + */ + public String getTitle() { + try { + return getPullRequest(false).getTitle(); + } catch (IOException e) { + return "UNKNOWN"; + } + } + + /** + * Returns the URL to the Github Pull Request. + * This URL is part of the pull request object + * + * @return the Github Pull Request URL + */ + public URL getUrl() throws IOException { + return getPullRequest(false).getHtmlUrl(); + } + + /** + * The description body is part of the PullRequest object + * + * @return + */ + public String getDescription() { + try { + return getPullRequest(false).getBody(); + } catch (IOException e) { + return "UNKNOWN"; + } + } + + public GitUser getCommitAuthor() { + return commitAuthor; + } + + /** + * Author is part of the PullRequest Object + * + * @return + * @throws IOException + */ + public GHUser getPullRequestAuthor() throws IOException { + return getPullRequest(false).getUser(); + } + + /** + * Get the PullRequest object for this PR + * + * @param force - forces the code to go get the PullRequest from GitHub now + * @return + * @throws IOException + */ + public GHPullRequest getPullRequest(boolean force) throws IOException { + if (this.pr == null || force) { + setPullRequest(repo.getActualPullRequest(this.id)); + } + return pr; + } + + private void setPullRequest(GHPullRequest pr) { + if (pr == null) { + return; + } + synchronized (this) { + this.pr = pr; + + try { + if (updated == null) { + setUpdated(pr.getCreatedAt()); + } + } catch (IOException e) { + logger.log(Level.WARNING, "Unable to get date for new PR", e); + setUpdated(new Date()); + } + + if (StringUtils.isEmpty(this.head)) { + GHCommitPointer prHead = pr.getHead(); + setHead(prHead.getSha()); + } + + if (StringUtils.isEmpty(this.base)) { + GHCommitPointer prBase = pr.getBase(); + setBase(prBase.getSha()); + } + } + } + + /** + * Email address is collected from GitHub as extra information, so lets cache it. + * + * @return + */ + public String getAuthorEmail() { + if (StringUtils.isEmpty(authorEmail)) { + try { + GHUser user = getPullRequestAuthor(); + authorEmail = user.getEmail(); + } catch (IOException e) { + logger.log(Level.SEVERE, "Unable to fetch author info for " + id); + } + } + authorEmail = StringUtils.isEmpty(authorEmail) ? "" : authorEmail; + return authorEmail; + } + + public void setBuild(AbstractBuild build) { + lastBuildId = build.getId(); + } + + public String getLastBuildId() { + return lastBuildId; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.jenkinsci.plugins.ghprb.GhprbPullRequest.check` indirectly reads with synchronization from `n$4.org.jenkinsci.plugins.ghprb.GhprbTrigger$DescriptorImpl.githubAuth`. Potentially races with unsynchronized write in method `GhprbPullRequest.check(...)`. + Reporting because this access may occur on a background thread. + +Note that the prefix path n$4 has been contaminated during the execution, so the reported race on n$4.org.jenkinsci.plugins.ghprb.GhprbTrigger$DescriptorImpl.githubAuth might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GhprbPullRequest.check(GHIssueComment) + +### Procedure Id: +org.jenkinsci.plugins.ghprb.GhprbPullRequest.check(org.kohsuke.github.GHIssueComment):void.a4bde69b29781ee9c8f07e0b8f0757d6 + +### File: +src/main/java/org/jenkinsci/plugins/ghprb/GhprbPullRequest.java + +### Key: +GhprbPullRequest.java|check|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +3cfb6358b5d1089e9c0f5d36e4745433 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7383/instruction.md b/inferredbugs-7383/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17009fc8e7f6ddd9bde78e8ce55ec989da95e64c --- /dev/null +++ b/inferredbugs-7383/instruction.md @@ -0,0 +1,142 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** goodsKill +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.seckill.service.impl; + +import org.seckill.dao.GoodsDao; +import org.seckill.entity.Goods; +import org.seckill.exception.HengException; +import org.seckill.service.GoodsService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; + +/** + * Created by heng on 2017/1/7. + */ +@SuppressWarnings("ALL") +@Service +public class GoodsServiceImpl implements GoodsService { + @Autowired + private GoodsDao goodsDao; + + @Override + public void uploadGoodsPhoto(CommonsMultipartFile file, long goodsId) { + String path = uploadGoodsPhoto(file); + goodsDao.updatePhotoUrl(goodsId, path); + } + + @Override + public String getPhotoUrl(int goodsId) { + Goods good = goodsDao.selectById(goodsId); + return good.getPhotoUrl(); + } + + @Override + public void addGoods(Goods goods,CommonsMultipartFile file) { + String path = uploadGoodsPhoto(file); + goods.setPhotoUrl(path); + goodsDao.insert(goods); + } + + private String uploadGoodsPhoto(CommonsMultipartFile file) { + final String s = "/Users/heng/java学习/"; + String path = s + file.getOriginalFilename(); + try { + String filePath = s; + File file_tmp = new File(filePath); + if (!file_tmp.exists() && !file_tmp.mkdirs()) { + throw new HengException("dir create error!"); + } + FileOutputStream fos = new FileOutputStream(path); + InputStream is = file.getInputStream(); + int b = 0; + while ((b = is.read()) != -1) { + fos.write(b); + } + fos.flush(); + fos.close(); + is.close(); + } catch (IOException e) { + throw new HengException("上传文件异常"); + } + return path; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `fos` by call to `FileOutputStream(...)` at line 53 is not released after line 62. +**Note**: potential exception at line 56 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String GoodsServiceImpl.uploadGoodsPhoto(CommonsMultipartFile) + +### Procedure Id: +org.seckill.service.impl.GoodsServiceImpl.uploadGoodsPhoto(org.springframework.web.multipart.commons.aa74775cf4bcf534cca529054d25ac47 + +### File: +src/main/java/org/seckill/service/impl/GoodsServiceImpl.java + +### Key: +GoodsServiceImpl.java|uploadGoodsPhoto|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +9874d5f5f6c6a316255869a34e26cb18 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7384/instruction.md b/inferredbugs-7384/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..193c72a5357ec0bd2c1ce609cacb6b0fa776f309 --- /dev/null +++ b/inferredbugs-7384/instruction.md @@ -0,0 +1,97 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** goodsKill +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.seckill.service; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.context.support.AbstractApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +/** + * 服务启动类 + * Created by techa03 on 2017/2/3. + */ +@Slf4j +public class GoodsKillRpcServiceApplication { + + public static void main(String[] args) { + log.info(">>>>> goodsKill-rpc-service 正在启动 <<<<<"); + AbstractApplicationContext context= new ClassPathXmlApplicationContext( + "classpath*:META-INF/spring/spring-*.xml"); + // 程序退出前优雅关闭JVM + context.registerShutdownHook(); + context.start(); + log.info(">>>>> goodsKill-rpc-service 启动完成 <<<<<"); + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.springframework.context.support.ClassPathXmlApplicationContext` acquired by call to `new()` at line 16 is not released after line 20. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GoodsKillRpcServiceApplication.main(java.lang.String[]) + +### Procedure Id: +org.seckill.service.GoodsKillRpcServiceApplication.main(java.lang.String[]):void.e3228a6a5076940abb2c0feadf3d37f1 + +### File: +goodsKill-service/src/main/java/org/seckill/service/GoodsKillRpcServiceApplication.java + +### Key: +GoodsKillRpcServiceApplication.java|main|RESOURCE_LEAK + +### Node Key: +dd04d0a305ee9eb51297bdf6972eaa70 + +### Hash: +309626bd4165e8743dd01ed92037f9a2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7409/instruction.md b/inferredbugs-7409/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1edc730c70f9c066cccde34c9d3f0f07325abf51 --- /dev/null +++ b/inferredbugs-7409/instruction.md @@ -0,0 +1,182 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** greenmail +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.icegreen.greenmail.test.commands; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintStream; +import java.net.Socket; + +import javax.mail.MessagingException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; + +import com.icegreen.greenmail.junit.GreenMailRule; +import com.icegreen.greenmail.pop3.commands.AuthCommand; +import com.icegreen.greenmail.user.UserException; +import com.icegreen.greenmail.util.ServerSetupTest; + +public class POP3CommandTest { + private static final String CRLF = "\r\n"; + + @Rule + public final GreenMailRule greenMail = new GreenMailRule(ServerSetupTest.POP3); + + private int port; + private String hostAddress; + + @Before + public void setUp() { + hostAddress = greenMail.getPop3().getBindTo(); + port = greenMail.getPop3().getPort(); + } + + @Test + public void authPlain() throws IOException, MessagingException, UserException { + try (Socket socket = new Socket(hostAddress, port)) { + assertThat(socket.isConnected()).isTrue(); + PrintStream printStream = new PrintStream(socket.getOutputStream()); + final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + + // No such user + assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v"); + printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / testpass */); + assertThat(reader.readLine()).isEqualTo("-ERR Authentication failed: User doesn't exist"); + + greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass"); + + // Invalid pwd + printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwY" + CRLF /* test / test / */); + assertThat(reader.readLine()).isEqualTo( + "-ERR Authentication failed, expected base64 encoding : Last unit does not have enough valid bits"); + + // Successful auth + printStream.print("AUTH PLAIN dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / */); + assertThat(reader.readLine()).isEqualTo("+OK"); + } + } + + @Test + public void authPlainWithContinuation() throws IOException, UserException { + try (Socket socket = new Socket(hostAddress, port)) { + assertThat(socket.isConnected()).isTrue(); + PrintStream printStream = new PrintStream(socket.getOutputStream()); + final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + greenMail.getManagers().getUserManager().createUser("test@localhost", "test", "testpass"); + + assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v"); + printStream.print("AUTH PLAIN" + CRLF /* test / test / testpass */); + assertThat(reader.readLine()).isEqualTo(AuthCommand.CONTINUATION); + printStream.print("dGVzdAB0ZXN0AHRlc3RwYXNz" + CRLF /* test / test / */); + assertThat(reader.readLine()).isEqualTo("+OK"); + } + } + + @Test + public void authDisabled() throws IOException, UserException { + try (Socket socket = new Socket(hostAddress, port)) { + assertThat(socket.isConnected()).isTrue(); + PrintStream printStream = new PrintStream(socket.getOutputStream()); + final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + + greenMail.getManagers().getUserManager().setAuthRequired(false); + + assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v"); + printStream.print("USER blar@blar.com" + CRLF); + assertThat(reader.readLine()).isEqualTo("+OK"); + } + } + + @Test + public void authEnabled() throws IOException, UserException { + try (Socket socket = new Socket(hostAddress, port)) { + assertThat(socket.isConnected()).isTrue(); + PrintStream printStream = new PrintStream(socket.getOutputStream()); + final BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); + + greenMail.getManagers().getUserManager().setAuthRequired(true); + + assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v"); + printStream.print("USER blar@blar.com" + CRLF); + assertThat(reader.readLine()).isNotEqualTo("+OK"); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 67 is not released after line 74. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void POP3CommandTest.authPlainWithContinuation() + +### Procedure Id: +com.icegreen.greenmail.test.commands.POP3CommandTest.authPlainWithContinuation():void.62d274c2b8e98064f3182a1de032a38e + +### File: +greenmail-core/src/test/java/com/icegreen/greenmail/test/commands/POP3CommandTest.java + +### Key: +POP3CommandTest.java|authPlainWithContinuation|RESOURCE_LEAK + +### Node Key: +cae3982ec48ebc2e71a637f9430f461a + +### Hash: +2903d69eb5692f2a49119b8d25e310cc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7510/instruction.md b/inferredbugs-7510/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60f906d8e00b84db376f8a849d894d9dd6a44cd2 --- /dev/null +++ b/inferredbugs-7510/instruction.md @@ -0,0 +1,154 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + * + */ +package org.neo4j.ogm.session.delegates; + +import java.util.Map; + +import org.apache.commons.lang.StringUtils; +import org.neo4j.ogm.cypher.query.RowModelQueryWithStatistics; +import org.neo4j.ogm.session.Capability; +import org.neo4j.ogm.session.Neo4jSession; +import org.neo4j.ogm.session.Utils; +import org.neo4j.ogm.session.response.Neo4jResponse; +import org.neo4j.ogm.session.result.QueryStatistics; +import org.neo4j.ogm.session.result.RowQueryStatisticsResult; + +/** + * @author Vince Bickers + * @author Luanne Misquitta + */ +public class ExecuteStatementsDelegate implements Capability.ExecuteStatements { + + private final Neo4jSession session; + + public ExecuteStatementsDelegate(Neo4jSession neo4jSession) { + this.session = neo4jSession; + } + + @Override + public QueryStatistics execute(String cypher, Map parameters) { + if (StringUtils.isEmpty(cypher)) { + throw new RuntimeException("Supplied cypher statement must not be null or empty."); + } + + if (parameters == null) { + throw new RuntimeException("Supplied Parameters cannot be null."); + } + assertNothingReturned(cypher); + String url = session.ensureTransaction().url(); + // NOTE: No need to check if domain objects are parameters and flatten them to json as this is done + // for us using the existing execute() method. + RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); + try (Neo4jResponse response = session.requestHandler().execute(parameterisedStatement, url)) { + RowQueryStatisticsResult result = response.next(); + return result == null ? null : result.getStats(); + } + } + + @Override + public QueryStatistics execute(String statement) { + if (StringUtils.isEmpty(statement)) { + throw new RuntimeException("Supplied cypher statement must not be null or empty."); + } + assertNothingReturned(statement); + RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(statement, Utils.map()); + String url = session.ensureTransaction().url(); + try (Neo4jResponse response = session.requestHandler().execute(parameterisedStatement, url)) { + RowQueryStatisticsResult result = response.next(); + return result == null ? null : result.getStats(); + } + } + + + private void assertNothingReturned(String cypher) { + if (cypher.toUpperCase().contains(" RETURN ")) { + throw new RuntimeException("execute() must not return data. Use query() instead."); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.neo4j.ogm.session.transaction.SimpleTransaction` acquired by call to `ensureTransaction()` at line 49 is not released after line 49. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +QueryStatistics ExecuteStatementsDelegate.execute(String,Map) + +### Procedure Id: +org.neo4j.ogm.session.delegates.ExecuteStatementsDelegate.execute(java.lang.String,java.util.Map):or.dcdbe904ea4f8f1a3f29d9d1587ac6c4 + +### File: +src/main/java/org/neo4j/ogm/session/delegates/ExecuteStatementsDelegate.java + +### Key: +ExecuteStatementsDelegate.java|execute|RESOURCE_LEAK + +### Node Key: +029cc97151e2d4d8a49f2551c8f2c484 + +### Hash: +eb9d81d9a6ec45cc4008de2cb065f106 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7517/instruction.md b/inferredbugs-7517/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..51d1fbbb798d74bb741cf16b669a08855b60f107 --- /dev/null +++ b/inferredbugs-7517/instruction.md @@ -0,0 +1,1042 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 54 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2017 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + */ + +package org.neo4j.ogm.metadata; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +import org.neo4j.ogm.annotation.*; +import org.neo4j.ogm.exception.MappingException; +import org.neo4j.ogm.exception.MetadataException; +import org.neo4j.ogm.id.IdStrategy; +import org.neo4j.ogm.id.InternalIdStrategy; +import org.neo4j.ogm.id.UuidStrategy; +import org.neo4j.ogm.session.Neo4jException; +import org.neo4j.ogm.utils.ClassUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Maintains object to graph mapping details at the class (type) level + * The ClassInfo object is used to maintain mappings from Java Types->Neo4j Labels + * thereby allowing the correct labels to be applied to new nodes when they + * are persisted. + * The ClassInfo object also maintains a map of FieldInfo and MethodInfo objects + * that maintain the appropriate information for mapping Java class attributes to Neo4j + * node properties / paths (node)-[:relationship]->(node), via field or method + * accessors respectively. + * Given a type hierarchy, the ClassInfo object guarantees that for any type in that + * hierarchy, the labels associated with that type will include the labels for + * all its superclass and interface types as well. This is to avoid the need to iterate + * through the ClassInfo hierarchy to recover label information. + * + * @author Vince Bickers + * @author Luanne Misquitta + * @author Mark Angrish + */ +public class ClassInfo { + + private static final Logger LOGGER = LoggerFactory.getLogger(ClassInfo.class); + + private final List directSubclasses = new ArrayList<>(); + private final List directInterfaces = new ArrayList<>(); + private final List directImplementingClasses = new ArrayList<>(); + private String className; + private String directSuperclassName; + private String neo4jName; + private boolean isInterface; + private boolean isAbstract; + private boolean isEnum; + private boolean hydrated; + private FieldsInfo fieldsInfo; + private MethodsInfo methodsInfo; + private AnnotationsInfo annotationsInfo; + private InterfacesInfo interfacesInfo; + private ClassInfo directSuperclass; + private Map> iterableFieldsForType = new HashMap<>(); + private Map fieldInfoFields = new ConcurrentHashMap<>(); + private volatile Set fieldInfos; + private volatile Map propertyFields; + private volatile Map indexFields; + private volatile LazyInstance identityField; + private volatile FieldInfo primaryIndexField = null; + private volatile FieldInfo labelField = null; + private volatile boolean labelFieldMapped = false; + private volatile boolean isPostLoadMethodMapped = false; + private volatile MethodInfo postLoadMethod; + private boolean primaryIndexFieldChecked = false; + private Class cls; + private Class idStrategyClass; + private IdStrategy idStrategy; + + /** + * This class was referenced as a superclass of the given subclass. + * + * @param name the name of the class + * @param subclass {@link ClassInfo} of the subclass + */ + ClassInfo(String name, ClassInfo subclass) { + this.className = name; + this.hydrated = false; + this.fieldsInfo = new FieldsInfo(); + this.methodsInfo = new MethodsInfo(); + this.annotationsInfo = new AnnotationsInfo(); + this.interfacesInfo = new InterfacesInfo(); + addSubclass(subclass); + } + + public ClassInfo(Class cls) { + this.cls = cls; + final int modifiers = cls.getModifiers(); + this.isInterface = Modifier.isInterface(modifiers); + this.isAbstract = Modifier.isAbstract(modifiers); + this.isEnum = cls.isEnum(); + this.className = cls.getName(); + + if (cls.getSuperclass() != null) { + this.directSuperclassName = cls.getSuperclass().getName(); + } + this.interfacesInfo = new InterfacesInfo(cls); + this.fieldsInfo = new FieldsInfo(this, cls); + this.methodsInfo = new MethodsInfo(cls); + this.annotationsInfo = new AnnotationsInfo(cls); + + if (isRelationshipEntity() && labelFieldOrNull() != null) { + throw new MappingException(String.format("'%s' is a relationship entity. The @Labels annotation can't be applied to " + + "relationship entities.", name())); + } + + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.hasAnnotation(Property.class) && fieldInfo.hasCompositeConverter()) { + throw new MappingException(String.format("'%s' has both @Convert and @Property annotations applied to the field '%s'", + name(), fieldInfo.getName())); + } + } + } + + /** + * A class that was previously only seen as a temp superclass of another class can now be fully hydrated. + * + * @param classInfoDetails ClassInfo details + */ + void hydrate(ClassInfo classInfoDetails) { + + if (!this.hydrated) { + this.hydrated = true; + + this.isAbstract = classInfoDetails.isAbstract; + this.isInterface = classInfoDetails.isInterface; + this.isEnum = classInfoDetails.isEnum; + this.directSuperclassName = classInfoDetails.directSuperclassName; + this.cls = classInfoDetails.cls; + + //this.interfaces.addAll(classInfoDetails.interfaces()); + + this.interfacesInfo.append(classInfoDetails.interfacesInfo()); + + this.annotationsInfo.append(classInfoDetails.annotationsInfo()); + this.fieldsInfo.append(classInfoDetails.fieldsInfo()); + this.methodsInfo.append(classInfoDetails.methodsInfo()); + } + } + + void extend(ClassInfo classInfo) { + this.interfacesInfo.append(classInfo.interfacesInfo()); + this.fieldsInfo.append(classInfo.fieldsInfo()); + this.methodsInfo.append(classInfo.methodsInfo()); + } + + /** + * Connect this class to a subclass. + * + * @param subclass the subclass + */ + void addSubclass(ClassInfo subclass) { + if (subclass.directSuperclass != null && subclass.directSuperclass != this) { + throw new RuntimeException(subclass.className + " has two superclasses: " + subclass.directSuperclass.className + ", " + this.className); + } + subclass.directSuperclass = this; + this.directSubclasses.add(subclass); + } + + boolean hydrated() { + return hydrated; + } + + public String name() { + return className; + } + + String simpleName() { + return className.substring(className.lastIndexOf('.') + 1); + } + + public ClassInfo directSuperclass() { + return directSuperclass; + } + + /** + *

+ * Retrieves the static labels that are applied to nodes in the database. If the class' instances are persisted by + * a relationship instead of a node then this method returns an empty collection. + *

+ *

+ * Note that this method returns only the static labels. A node entity instance may declare additional labels + * manged at runtime by using the @Labels annotation on a collection field, therefore the full set of labels to be + * mapped to a node will be the static labels, in addition to any labels declared by the backing field of an + * {@link Labels} annotation. + *

+ * + * @return A {@link Collection} of all the static labels that apply to the node or an empty list if there aren't + * any, never null + */ + public Collection staticLabels() { + return collectLabels(new ArrayList<>()); + } + + public String neo4jName() { + if (neo4jName == null) { + AnnotationInfo annotationInfo = annotationsInfo.get(NodeEntity.class); + if (annotationInfo != null) { + neo4jName = annotationInfo.get(NodeEntity.LABEL, simpleName()); + return neo4jName; + } + annotationInfo = annotationsInfo.get(RelationshipEntity.class); + if (annotationInfo != null) { + neo4jName = annotationInfo.get(RelationshipEntity.TYPE, simpleName().toUpperCase()); + return neo4jName; + } + neo4jName = simpleName(); + } + return neo4jName; + } + + private Collection collectLabels(Collection labelNames) { + if (!isAbstract || annotationsInfo.get(NodeEntity.class) != null) { + labelNames.add(neo4jName()); + } + if (directSuperclass != null && !"java.lang.Object".equals(directSuperclass.className)) { + directSuperclass.collectLabels(labelNames); + } + for (ClassInfo interfaceInfo : directInterfaces()) { + interfaceInfo.collectLabels(labelNames); + } + return labelNames; + } + + List directSubclasses() { + return directSubclasses; + } + + List directImplementingClasses() { + return directImplementingClasses; + } + + List directInterfaces() { + return directInterfaces; + } + + InterfacesInfo interfacesInfo() { + return interfacesInfo; + } + + public Collection annotations() { + return annotationsInfo.list(); + } + + public boolean isInterface() { + return isInterface; + } + + public boolean isEnum() { + return isEnum; + } + + public AnnotationsInfo annotationsInfo() { + return annotationsInfo; + } + + String superclassName() { + return directSuperclassName; + } + + public FieldsInfo fieldsInfo() { + return fieldsInfo; + } + + MethodsInfo methodsInfo() { + return methodsInfo; + } + + + public FieldInfo identityFieldOrNull() { + initIdentityField(); + return identityField.get(); + } + + /** + * The identity field is a field annotated with @NodeId, or if none exists, a field + * of type Long called 'id' + * + * @return A {@link FieldInfo} object representing the identity field never null + * @throws MappingException if no identity field can be found + */ + public FieldInfo identityField() { + initIdentityField(); + FieldInfo field = identityField.get(); + if (field == null) { + throw new MetadataException("No internal identity field found for class: " + this.className); + } + return field; + } + + private void initIdentityField() { + if (identityField == null) { + identityField = new LazyInstance<>(() -> { + Collection identityFields = getFieldInfos(this::isInternalIdentity); + if (identityFields.size() == 1) { + return identityFields.iterator().next(); + } + if (identityFields.size() > 1) { + throw new MetadataException("Expected exactly one internal identity field (@GraphId or @Id with " + + "InternalIdStrategy), found " + identityFields.size() + " " + identityFields); + } + FieldInfo fieldInfo = fieldsInfo().get("id"); + if (fieldInfo != null) { + if (fieldInfo.getTypeDescriptor().equals("java.lang.Long")) { + return fieldInfo; + } + } + return null; + }); + } + } + + public boolean hasIdentityField() { + initIdentityField(); + return identityField.exists(); + } + + // Identity field + private boolean isInternalIdentity(FieldInfo fieldInfo) { + return fieldInfo.getAnnotations().has(GraphId.class) || + (fieldInfo.getAnnotations().has(Id.class) && + fieldInfo.getAnnotations().has(GeneratedValue.class) && + ((GeneratedValue) fieldInfo.getAnnotations().get(GeneratedValue.class).getAnnotation()) + .strategy().equals(InternalIdStrategy.class) + ); + } + + Collection getFieldInfos(Predicate predicate) { + return fieldsInfo().fields().stream() + .filter(predicate) + .collect(Collectors.toSet()); + } + + /** + * The label field is an optional field annotated with @Labels. + * + * @return A {@link FieldInfo} object representing the label field. Optionally null + */ + public FieldInfo labelFieldOrNull() { + if (labelFieldMapped) { + return labelField; + } + if (!labelFieldMapped) { + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.isLabelField()) { + if (!fieldInfo.isIterable()) { + throw new MappingException(String.format( + "Field '%s' in class '%s' includes the @Labels annotation, however this field is not a " + + "type of collection.", fieldInfo.getName(), this.name())); + } + labelFieldMapped = true; + labelField = fieldInfo; + return labelField; + } + } + labelFieldMapped = true; + } + return null; + } + + public boolean isRelationshipEntity() { + for (AnnotationInfo info : annotations()) { + if (info.getName().equals(RelationshipEntity.class.getName())) { + return true; + } + } + return false; + } + + /** + * A property field is any field annotated with @Property, or any field that can be mapped to a + * node property. The identity field is not a property field. + * + * @return A Collection of FieldInfo objects describing the classInfo's property fields + */ + public Collection propertyFields() { + if (fieldInfos == null) { + if (fieldInfos == null) { + FieldInfo identityField = identityFieldOrNull(); + fieldInfos = new HashSet<>(); + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo != identityField && !fieldInfo.isLabelField() + && !fieldInfo.hasAnnotation(StartNode.class) + && !fieldInfo.hasAnnotation(EndNode.class)) { + AnnotationInfo annotationInfo = fieldInfo.getAnnotations().get(Property.class); + if (annotationInfo == null) { + if (fieldInfo.persistableAsProperty()) { + fieldInfos.add(fieldInfo); + } + } else { + fieldInfos.add(fieldInfo); + } + } + } + } + } + return fieldInfos; + } + + /** + * Finds the property field with a specific property name from the ClassInfo's property fields + * Note that this method does not allow for property names with differing case. //TODO + * + * @param propertyName the propertyName of the field to find + * @return A FieldInfo object describing the required property field, or null if it doesn't exist. + */ + public FieldInfo propertyField(String propertyName) { + if (propertyFields == null) { + + if (propertyFields == null) { + Collection fieldInfos = propertyFields(); + propertyFields = new HashMap<>(fieldInfos.size()); + for (FieldInfo fieldInfo : fieldInfos) { + + propertyFields.put(fieldInfo.property().toLowerCase(), fieldInfo); + } + } + } + return propertyFields.get(propertyName.toLowerCase()); + } + + + /** + * Finds the property field with a specific field name from the ClassInfo's property fields + * + * @param propertyName the propertyName of the field to find + * @return A FieldInfo object describing the required property field, or null if it doesn't exist. + */ + public FieldInfo propertyFieldByName(String propertyName) { + for (FieldInfo fieldInfo : propertyFields()) { + if (fieldInfo.getName().equalsIgnoreCase(propertyName)) { + return fieldInfo; + } + } + return null; + } + + /** + * A relationship field is any field annotated with @Relationship, or any field that cannot be mapped to a + * node property. The identity field is not a relationship field. + * + * @return A Collection of FieldInfo objects describing the classInfo's relationship fields + */ + public Collection relationshipFields() { + FieldInfo identityField = identityFieldOrNull(); + Set fieldInfos = new HashSet<>(); + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo != identityField) { + AnnotationInfo annotationInfo = fieldInfo.getAnnotations().get(Relationship.class); + if (annotationInfo == null) { + if (!fieldInfo.persistableAsProperty()) { + fieldInfos.add(fieldInfo); + } + } else { + fieldInfos.add(fieldInfo); + } + } + } + return fieldInfos; + } + + /** + * Finds the relationship field with a specific name from the ClassInfo's relationship fields + * + * @param relationshipName the relationshipName of the field to find + * @return A FieldInfo object describing the required relationship field, or null if it doesn't exist. + */ + public FieldInfo relationshipField(String relationshipName) { + for (FieldInfo fieldInfo : relationshipFields()) { + if (fieldInfo.relationship().equalsIgnoreCase(relationshipName)) { + return fieldInfo; + } + } + return null; + } + + /** + * Finds the relationship field with a specific name and direction from the ClassInfo's relationship fields + * + * @param relationshipName the relationshipName of the field to find + * @param relationshipDirection the direction of the relationship + * @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo + * @return A FieldInfo object describing the required relationship field, or null if it doesn't exist. + */ + public FieldInfo relationshipField(String relationshipName, String relationshipDirection, boolean strict) { + for (FieldInfo fieldInfo : relationshipFields()) { + String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship(); + if (relationshipName.equalsIgnoreCase(relationship)) { + if (((fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING) || fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.UNDIRECTED)) && (relationshipDirection.equals(Relationship.INCOMING))) + || (relationshipDirection.equals(Relationship.OUTGOING) && !(fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING)))) { + return fieldInfo; + } + } + } + return null; + } + + /** + * Finds all relationship fields with a specific name and direction from the ClassInfo's relationship fields + * + * @param relationshipName the relationshipName of the field to find + * @param relationshipDirection the direction of the relationship + * @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo + * @return Set of FieldInfo objects describing the required relationship field, or empty set if it doesn't exist. + */ + public Set candidateRelationshipFields(String relationshipName, String relationshipDirection, boolean strict) { + Set candidateFields = new HashSet<>(); + for (FieldInfo fieldInfo : relationshipFields()) { + String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship(); + if (relationshipName.equalsIgnoreCase(relationship)) { + if (((fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING) || fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.UNDIRECTED)) && (relationshipDirection.equals(Relationship.INCOMING))) + || (relationshipDirection.equals(Relationship.OUTGOING) && !(fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING)))) { + candidateFields.add(fieldInfo); + } + } + } + return candidateFields; + } + + /** + * Finds the relationship field with a specific property name from the ClassInfo's relationship fields + * + * @param fieldName the name of the field + * @return A FieldInfo object describing the required relationship field, or null if it doesn't exist. + */ + public FieldInfo relationshipFieldByName(String fieldName) { + for (FieldInfo fieldInfo : relationshipFields()) { + if (fieldInfo.getName().equalsIgnoreCase(fieldName)) { + return fieldInfo; + } + } + return null; + } + + public Field getField(FieldInfo fieldInfo) { + Field field = fieldInfoFields.get(fieldInfo); + if (field != null) { + return field; + } + try { + field = cls.getDeclaredField(fieldInfo.getName()); + fieldInfoFields.put(fieldInfo, field); + return field; + } catch (NoSuchFieldException e) { + if (directSuperclass() != null) { + field = directSuperclass().getField(fieldInfo); + fieldInfoFields.put(fieldInfo, field); + return field; + } else { + throw new RuntimeException("Field " + fieldInfo.getName() + " not found in class " + name() + " or any of its superclasses"); + } + } + } + + /** + * Returns the Method corresponding to the supplied MethodInfo as declared by the class represented by this ClassInfo + * + * @param methodInfo the MethodInfo used to obtain the Method + * @return a Method + */ + public Method getMethod(MethodInfo methodInfo) { + return methodInfo.getMethod(); + } + + /** + * Find all FieldInfos for the specified ClassInfo whose type matches the supplied fieldType + * + * @param fieldType The field type to look for + * @return A {@link List} of {@link FieldInfo} objects that are of the given type, never null + */ + public List findFields(Class fieldType) { + String fieldSignature = fieldType.getName(); + List fieldInfos = new ArrayList<>(); + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.getTypeDescriptor().equals(fieldSignature)) { + fieldInfos.add(fieldInfo); + } + } + return fieldInfos; + } + + /** + * Find all FieldInfos for the specified ClassInfo which have the specified annotation + * + * @param annotation The annotation + * @return A {@link List} of {@link FieldInfo} objects that are of the given type, never null + */ + public List findFields(String annotation) { + List fieldInfos = new ArrayList<>(); + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.hasAnnotation(annotation)) { + fieldInfos.add(fieldInfo); + } + } + return fieldInfos; + } + + /** + * Retrieves a {@link List} of {@link FieldInfo} representing all of the fields that can be iterated over + * using a "foreach" loop. + * + * @return {@link List} of {@link FieldInfo} + */ + public List findIterableFields() { + List fieldInfos = new ArrayList<>(); + try { + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + Class type = getField(fieldInfo).getType(); + if (type.isArray() || Iterable.class.isAssignableFrom(type)) { + fieldInfos.add(fieldInfo); + } + } + return fieldInfos; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X> + * where X is the generic parameter type of the Array or Iterable + * + * @param iteratedType the type of iterable + * @return {@link List} of {@link MethodInfo}, never null + */ + public List findIterableFields(Class iteratedType) { + if (iterableFieldsForType.containsKey(iteratedType)) { + return iterableFieldsForType.get(iteratedType); + } + List fieldInfos = new ArrayList<>(); + String typeSignature = iteratedType.getName(); + String arrayOfTypeSignature = typeSignature + "[]"; + try { + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + String fieldType = fieldInfo.getTypeDescriptor(); + if (fieldInfo.isArray() && (fieldType.equals(arrayOfTypeSignature) || fieldInfo.isParameterisedTypeOf(iteratedType))) { + fieldInfos.add(fieldInfo); + } else if (fieldInfo.isIterable() && (fieldType.equals(typeSignature) || fieldInfo.isParameterisedTypeOf(iteratedType))) { + fieldInfos.add(fieldInfo); + } + } + iterableFieldsForType.put(iteratedType, fieldInfos); + return fieldInfos; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + /** + * Finds all fields whose type is equivalent to Array<X> or assignable from Iterable<X> + * where X is the generic parameter type of the Array or Iterable and the relationship type backing this iterable is "relationshipType" + * + * @param iteratedType the type of iterable + * @param relationshipType the relationship type + * @param relationshipDirection the relationship direction + * @param strict if true, does not infer relationship type but looks for it in the @Relationship annotation. Null if missing. If false, infers relationship type from FieldInfo + * @return {@link List} of {@link MethodInfo}, never null + */ + public List findIterableFields(Class iteratedType, String relationshipType, String relationshipDirection, boolean strict) { + List fieldInfos = new ArrayList<>(); + for (FieldInfo fieldInfo : findIterableFields(iteratedType)) { + String relationship = strict ? fieldInfo.relationshipTypeAnnotation() : fieldInfo.relationship(); + if (relationshipType.equals(relationship)) { + if (((fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING) || fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.UNDIRECTED)) && relationshipDirection.equals(Relationship.INCOMING)) + || (relationshipDirection.equals(Relationship.OUTGOING) && !(fieldInfo.relationshipDirection(Relationship.OUTGOING).equals(Relationship.INCOMING)))) { + fieldInfos.add(fieldInfo); + } + } + } + return fieldInfos; + } + + public boolean isTransient() { + return annotationsInfo.get(Transient.class) != null; + } + + public boolean isAbstract() { + return isAbstract; + } + + /** + * Returns true if this classInfo is in the subclass hierarchy of b, or if this classInfo is the same as b, false otherwise + * + * @param classInfo the classInfo at the toplevel of a type hierarchy to search through + * @return true if this classInfo is in the subclass hierarchy of classInfo, false otherwise + */ + boolean isSubclassOf(ClassInfo classInfo) { + + if (this == classInfo) { + return true; + } + + boolean found = false; + + for (ClassInfo subclass : classInfo.directSubclasses()) { + found = isSubclassOf(subclass); + if (found) { + break; + } + } + + return found; + } + + /** + * Get the underlying class represented by this ClassInfo + * + * @return the underlying class or null if it cannot be determined + */ + public Class getUnderlyingClass() { + return cls; + } + + /** + * Gets the class of the type parameter description of the entity related to this. + * The match is done based on the following- + * 2. Look for a field explicitly annotated with @Relationship for a type and implied direction + * 4. Look for a field with name derived from the relationship type for the given direction + * + * @param relationshipType the relationship type + * @param relationshipDirection the relationship direction + * @return class of the type parameter descriptor or null if it could not be determined + */ + Class getTypeParameterDescriptorForRelationship(String relationshipType, String relationshipDirection) { + final boolean STRICT_MODE = true; //strict mode for matching methods and fields, will only look for explicit annotations + final boolean INFERRED_MODE = false; //inferred mode for matching methods and fields, will infer the relationship type from the getter/setter/property + + try { + FieldInfo fieldInfo = relationshipField(relationshipType, relationshipDirection, STRICT_MODE); + if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { + return ClassUtils.getType(fieldInfo.getTypeDescriptor()); + } + + if (!relationshipDirection.equals(Relationship.INCOMING)) { //we always expect an annotation for INCOMING + fieldInfo = relationshipField(relationshipType, relationshipDirection, INFERRED_MODE); + if (fieldInfo != null && fieldInfo.getTypeDescriptor() != null) { + return ClassUtils.getType(fieldInfo.getTypeDescriptor()); + } + } + } catch (RuntimeException e) { + LOGGER.debug("Could not get {} class type for relationshipType {} and relationshipDirection {} ", className, relationshipType, relationshipDirection); + } + return null; + } + + /** + * @return If this class contains any fields/properties annotated with @Index. + */ + public boolean containsIndexes() { + return !getIndexFields().isEmpty(); + } + + /** + * @return The FieldInfos representing the Indexed fields in this class. + */ + public Collection getIndexFields() { + if (indexFields == null) { + indexFields = addIndexes(); + } + return indexFields.values(); + } + + private Map addIndexes() { + Map indexes = new HashMap<>(); + + // No way to get declared fields from current byte code impl. Using reflection instead. + Field[] declaredFields; + try { + declaredFields = Class.forName(className, false, Thread.currentThread().getContextClassLoader()).getDeclaredFields(); + } catch (ClassNotFoundException e) { + throw new RuntimeException("Could not reflectively read declared fields", e); + } + + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (isDeclaredField(declaredFields, fieldInfo.getName()) && + (fieldInfo.hasAnnotation(Index.class) || fieldInfo.hasAnnotation(Id.class))) { + + String propertyValue = fieldInfo.property(); + if (fieldInfo.hasAnnotation(Property.class.getName())) { + propertyValue = fieldInfo.property(); + } + indexes.put(propertyValue, fieldInfo); + } + } + return indexes; + } + + private static boolean isDeclaredField(Field[] declaredFields, String name) { + + for (Field field : declaredFields) { + if (field.getName().equals(name)) { + return true; + } + } + return false; + } + + + public FieldInfo primaryIndexField() { + if (!primaryIndexFieldChecked && primaryIndexField == null) { + + Collection primaryIndexFields = getFieldInfos(this::isPrimaryIndexField); + if (primaryIndexFields.size() > 1) { + throw new MetadataException("Only one @Id / @Index(primary=true, unique=true) annotation is allowed in a class hierarchy. Please check annotations in the class " + name() + " or its parents"); + } else if (primaryIndexFields.size() == 1) { + primaryIndexField = primaryIndexFields.iterator().next(); + AnnotationInfo generatedValueAnnotation = primaryIndexField.getAnnotations().get(GeneratedValue.class); + if (generatedValueAnnotation != null) { + GeneratedValue value = (GeneratedValue) generatedValueAnnotation.getAnnotation(); + idStrategyClass = value.strategy(); + instantiateIdStrategy(); + } + } + validateIdGenerationConfig(); + primaryIndexFieldChecked = true; + } + + return primaryIndexField; + } + + public boolean hasPrimaryIndexField() { + if (!primaryIndexFieldChecked) { + primaryIndexField(); + } + return primaryIndexField != null; + } + + private boolean isPrimaryIndexField(FieldInfo fieldInfo) { + // primary index field is either + // field with @Id or @Id @GeneratedValue(strategy=..) where strategy != InternalIdStrategy + return (fieldInfo.getAnnotations().has(Id.class) && + !(fieldInfo.getAnnotations().has(GeneratedValue.class) && + ((GeneratedValue) fieldInfo.getAnnotations().get(GeneratedValue.class).getAnnotation()).strategy().equals(InternalIdStrategy.class) + + )) || + // or @Index(primary=true) - backward compatibility + fieldInfo.getAnnotations().has(Index.class) && + ((Index) fieldInfo.getAnnotations().get(Index.class).getAnnotation()).primary(); + } + + private void instantiateIdStrategy() { + try { + idStrategy = idStrategyClass.newInstance(); + } catch (InstantiationException | IllegalAccessException e) { + LOGGER.debug("Could not instantiate {}. Expecting this to be registered manually.", idStrategyClass); + } + } + + private void validateIdGenerationConfig() { + fieldsInfo().fields().forEach(info -> { + if (info.hasAnnotation(GeneratedValue.class) && !info.hasAnnotation(Id.class)) { + throw new MetadataException("The type of @Generated field in class " + className + " must be also annotated with @Id."); + } + }); + if (UuidStrategy.class.equals(idStrategyClass) + && !primaryIndexField.isTypeOf(UUID.class) + && !primaryIndexField.isTypeOf(String.class)) { + throw new MetadataException("The type of " + primaryIndexField.getName() + " in class " + className + " must be of type java.lang.UUID or java.lang.String because it has an UUID generation strategy."); + } + } + + public IdStrategy idStrategy() { + if (!primaryIndexFieldChecked) { + primaryIndexField(); // force init + } + return idStrategy; + } + + public Class idStrategyClass() { + return idStrategyClass; + } + + public void registerIdGenerationStrategy(IdStrategy strategy) { + if (strategy.getClass().equals(idStrategyClass)) { + idStrategy = strategy; + } else { + throw new IllegalArgumentException("Strategy " + strategy + + " is not an instance of " + idStrategyClass); + } + } + + public MethodInfo postLoadMethodOrNull() { + if (isPostLoadMethodMapped) { + return postLoadMethod; + } + if (!isPostLoadMethodMapped) { + for (MethodInfo methodInfo : methodsInfo().methods()) { + if (methodInfo.hasAnnotation(PostLoad.class.getName())) { + isPostLoadMethodMapped = true; + postLoadMethod = methodInfo; + return postLoadMethod; + } + } + isPostLoadMethodMapped = true; + } + return null; + } + + public FieldInfo getFieldInfo(String propertyName) { + + // fall back to the field if method cannot be found + FieldInfo labelField = labelFieldOrNull(); + if (labelField != null && labelField.getName().equals(propertyName)) { + return labelField; + } + FieldInfo propertyField = propertyField(propertyName); + if (propertyField != null) { + return propertyField; + } + return null; + } + + /** + * Return a FieldInfo for the EndNode of a RelationshipEntity + * + * @return a FieldInfo for the field annotated as the EndNode, or none if not found + */ + public FieldInfo getEndNodeReader() { + if (isRelationshipEntity()) { + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.getAnnotations().get(EndNode.class) != null) { + return fieldInfo; + } + } + LOGGER.warn("Failed to find an @EndNode on {}", name()); + } + + return null; + } + + /** + * Return a FieldInfo for the StartNode of a RelationshipEntity + * + * @return a FieldInfo for the field annotated as the StartNode, or none if not found + */ + public FieldInfo getStartNodeReader() { + if (isRelationshipEntity()) { + + for (FieldInfo fieldInfo : fieldsInfo().fields()) { + if (fieldInfo.getAnnotations().get(StartNode.class) != null) { + return fieldInfo; + } + } + LOGGER.warn("Failed to find an @StartNode on {}", name()); + } + return null; + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `fieldInfo.property()` could be null and is dereferenced at line 433. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +FieldInfo ClassInfo.propertyField(String) + +### Procedure Id: +org.neo4j.ogm.metadata.ClassInfo.propertyField(java.lang.String):org.neo4j.ogm.metadata.FieldInfo.24248e42846acf777721593dc61cdb1b + +### File: +core/src/main/java/org/neo4j/ogm/metadata/ClassInfo.java + +### Key: +ClassInfo.java|propertyField|NULL_DEREFERENCE + +### Node Key: +3673c4de52f870dfd662aca72d369e76 + +### Hash: +cc98bb2a925d87d4487dd0dc711f08bc + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7519/instruction.md b/inferredbugs-7519/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..357fd165b76ada54fd8ad7c1b3dff21d712ff493 --- /dev/null +++ b/inferredbugs-7519/instruction.md @@ -0,0 +1,187 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2016 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + */ + +package org.neo4j.ogm.drivers.http.response; + +import static junit.framework.Assert.assertEquals; +import static junit.framework.TestCase.assertNotNull; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.Map; + +import org.junit.Test; +import org.neo4j.ogm.response.Response; +import org.neo4j.ogm.response.model.DefaultRestModel; +import org.neo4j.ogm.result.ResultRestModel; + +/** + * @author Luanne Misquitta + */ +public class JsonRestResponseTest { + + @Test + public void shouldParseColumnsInRowResponseCorrectly() { + try (Response rsp = new TestRestHttpResponse((rowResultsAndNoErrors()))) { + assertEquals(3, rsp.columns().length); + assertEquals("count",rsp.columns()[0]); + } + } + + @Test + public void shouldParseColumnsInRowResponseWithNoColumnsCorrectly() { + try (Response rsp = new TestRestHttpResponse((noRowResultsAndNoErrors()))) { + assertEquals(3, rsp.columns().length); + assertEquals("director",rsp.columns()[1]); + + } + } + + @Test + public void shouldParseDataInRowResponseCorrectly() { + try (Response rsp = new TestRestHttpResponse((rowResultsAndNoErrors()))) { + DefaultRestModel restModel = rsp.next(); + assertNotNull(restModel); + Object[] rows = restModel.getValues(); + assertEquals(3,rows.length); + assertEquals(1, rows[0]); + Map data = (Map) rows[1]; + assertEquals(1931,((Map)data.get("data")).get("born")); + data = (Map) rows[2]; + assertEquals("The Birdcage", ((Map)data.get("data")).get("title")); + assertEquals(395, ((Map)data.get("metadata")).get("id")); + + restModel = rsp.next(); + rows = restModel.getValues(); + assertEquals(3,rows.length); + assertEquals(1, rows[0]); + data = (Map) rows[1]; + assertEquals(1931,((Map)data.get("data")).get("born")); + data = (Map) rows[2]; + assertEquals(2007, ((Map)data.get("data")).get("released")); + } + } + + private InputStream rowResultsAndNoErrors() { + + final String s= "{\"results\":[{\"columns\":[\"count\",\"director\",\"movie\"],\"data\":[{\"rest\":[1,{\"outgoing_relationships\":\"http://localhost:7474/db/data/node/396/relationships/out\",\"labels\":\"http://localhost:7474/db/data/node/396/labels\",\"all_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/all/{-list|&|types}\",\"traverse\":\"http://localhost:7474/db/data/node/396/traverse/{returnType}\",\"self\":\"http://localhost:7474/db/data/node/396\",\"property\":\"http://localhost:7474/db/data/node/396/properties/{key}\",\"outgoing_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/out/{-list|&|types}\",\"properties\":\"http://localhost:7474/db/data/node/396/properties\",\"incoming_relationships\":\"http://localhost:7474/db/data/node/396/relationships/in\",\"create_relationship\":\"http://localhost:7474/db/data/node/396/relationships\",\"paged_traverse\":\"http://localhost:7474/db/data/node/396/paged/traverse/{returnType}{?pageSize,leaseTime}\",\"all_relationships\":\"http://localhost:7474/db/data/node/396/relationships/all\",\"incoming_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/in/{-list|&|types}\",\"metadata\":{\"id\":396,\"labels\":[\"Person\"]},\"data\":{\"born\":1931,\"name\":\"Mike Nichols\"}},{\"outgoing_relationships\":\"http://localhost:7474/db/data/node/395/relationships/out\",\"labels\":\"http://localhost:7474/db/data/node/395/labels\",\"all_typed_relationships\":\"http://localhost:7474/db/data/node/395/relationships/all/{-list|&|types}\",\"traverse\":\"http://localhost:7474/db/data/node/395/traverse/{returnType}\",\"self\":\"http://localhost:7474/db/data/node/395\",\"property\":\"http://localhost:7474/db/data/node/395/properties/{key}\",\"outgoing_typed_relationships\":\"http://localhost:7474/db/data/node/395/relationships/out/{-list|&|types}\",\"properties\":\"http://localhost:7474/db/data/node/395/properties\",\"incoming_relationships\":\"http://localhost:7474/db/data/node/395/relationships/in\",\"create_relationship\":\"http://localhost:7474/db/data/node/395/relationships\",\"paged_traverse\":\"http://localhost:7474/db/data/node/395/paged/traverse/{returnType}{?pageSize,leaseTime}\",\"all_relationships\":\"http://localhost:7474/db/data/node/395/relationships/all\",\"incoming_typed_relationships\":\"http://localhost:7474/db/data/node/395/relationships/in/{-list|&|types}\",\"metadata\":{\"id\":395,\"labels\":[\"Movie\"]},\"data\":{\"released\":1996,\"title\":\"The Birdcage\",\"tagline\":\"Come as you are\"}}]},{\"rest\":[1,{\"outgoing_relationships\":\"http://localhost:7474/db/data/node/396/relationships/out\",\"labels\":\"http://localhost:7474/db/data/node/396/labels\",\"all_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/all/{-list|&|types}\",\"traverse\":\"http://localhost:7474/db/data/node/396/traverse/{returnType}\",\"self\":\"http://localhost:7474/db/data/node/396\",\"property\":\"http://localhost:7474/db/data/node/396/properties/{key}\",\"outgoing_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/out/{-list|&|types}\",\"properties\":\"http://localhost:7474/db/data/node/396/properties\",\"incoming_relationships\":\"http://localhost:7474/db/data/node/396/relationships/in\",\"create_relationship\":\"http://localhost:7474/db/data/node/396/relationships\",\"paged_traverse\":\"http://localhost:7474/db/data/node/396/paged/traverse/{returnType}{?pageSize,leaseTime}\",\"all_relationships\":\"http://localhost:7474/db/data/node/396/relationships/all\",\"incoming_typed_relationships\":\"http://localhost:7474/db/data/node/396/relationships/in/{-list|&|types}\",\"metadata\":{\"id\":396,\"labels\":[\"Person\"]},\"data\":{\"born\":1931,\"name\":\"Mike Nichols\"}},{\"outgoing_relationships\":\"http://localhost:7474/db/data/node/457/relationships/out\",\"labels\":\"http://localhost:7474/db/data/node/457/labels\",\"all_typed_relationships\":\"http://localhost:7474/db/data/node/457/relationships/all/{-list|&|types}\",\"traverse\":\"http://localhost:7474/db/data/node/457/traverse/{returnType}\",\"self\":\"http://localhost:7474/db/data/node/457\",\"property\":\"http://localhost:7474/db/data/node/457/properties/{key}\",\"outgoing_typed_relationships\":\"http://localhost:7474/db/data/node/457/relationships/out/{-list|&|types}\",\"properties\":\"http://localhost:7474/db/data/node/457/properties\",\"incoming_relationships\":\"http://localhost:7474/db/data/node/457/relationships/in\",\"create_relationship\":\"http://localhost:7474/db/data/node/457/relationships\",\"paged_traverse\":\"http://localhost:7474/db/data/node/457/paged/traverse/{returnType}{?pageSize,leaseTime}\",\"all_relationships\":\"http://localhost:7474/db/data/node/457/relationships/all\",\"incoming_typed_relationships\":\"http://localhost:7474/db/data/node/457/relationships/in/{-list|&|types}\",\"metadata\":{\"id\":457,\"labels\":[\"Movie\"]},\"data\":{\"released\":2007,\"title\":\"Charlie Wilson's War\",\"tagline\":\"A stiff drink. A little mascara. A lot of nerve. Who said they couldn't bring down the Soviet empire.\"}}]}]}],\"errors\":[]}"; + + return new ByteArrayInputStream(s.getBytes()); + } + + private InputStream noRowResultsAndNoErrors() { + + final String s = "{\"results\":[{\"columns\":[\"count\",\"director\",\"movie\"],\"data\":[]}],\"errors\":[]}"; + + return new ByteArrayInputStream(s.getBytes()); + } + + + + static class TestRestHttpResponse extends AbstractHttpResponse implements Response { + + public TestRestHttpResponse(InputStream inputStream) { + super(inputStream, ResultRestModel.class); + } + + @Override + public DefaultRestModel next() { + ResultRestModel restModel = nextDataRecord("rest"); + + if (restModel != null) { + return new DefaultRestModel(restModel.queryResults()); + } + return null; + } + + @Override + public void close() { + //Nothing to do, the response has been closed already + } + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `restModel` last assigned on line 53 could be null and is dereferenced at line 55. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JsonRestResponseTest.shouldParseDataInRowResponseCorrectly() + +### Procedure Id: +org.neo4j.ogm.drivers.http.response.JsonRestResponseTest.shouldParseDataInRowResponseCorrectly():voi.80b05d89066fed4423b59c2d1b4d1b36 + +### File: +drivers/src/test/java/org/neo4j/ogm/drivers/http/response/JsonRestResponseTest.java + +### Key: +JsonRestResponseTest.java|shouldParseDataInRowResponseCorrectly|NULL_DEREFERENCE + +### Node Key: +187abbcb57254a2b1a780352ad623c0b + +### Hash: +474cde65860a912c68d410e86a1c1ae1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7521/instruction.md b/inferredbugs-7521/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1197f94010a59d622fc2b2dea8ac2c3f1356678a --- /dev/null +++ b/inferredbugs-7521/instruction.md @@ -0,0 +1,297 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 39 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2016 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + */ + +package org.neo4j.ogm.drivers.http.driver; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.client.HttpResponseException; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.apache.http.ssl.TrustStrategy; +import org.apache.http.util.EntityUtils; +import org.neo4j.ogm.driver.AbstractConfigurableDriver; +import org.neo4j.ogm.drivers.http.request.HttpRequest; +import org.neo4j.ogm.drivers.http.transaction.HttpTransaction; +import org.neo4j.ogm.exception.ResultErrorsException; +import org.neo4j.ogm.exception.ResultProcessingException; +import org.neo4j.ogm.request.Request; +import org.neo4j.ogm.transaction.Transaction; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import java.security.cert.X509Certificate; + +/** + * @author vince + */ + +public final class HttpDriver extends AbstractConfigurableDriver +{ + private static final Logger LOGGER = LoggerFactory.getLogger(HttpDriver.class); + + private CloseableHttpClient httpClient; + + public HttpDriver() {} + + public HttpDriver( CloseableHttpClient httpClient ) { + this.httpClient = httpClient; + } + + @Override + public synchronized void close() { + try { + LOGGER.info("Shutting down Http driver {} ", this); + if (httpClient != null) { + httpClient.close(); + } + } catch (Exception e) { + LOGGER.warn( "Unexpected Exception when closing http client httpClient: ", e ); + } + } + + @Override + public Request request() { + String url = requestUrl(); + return new HttpRequest(httpClient(), url, driverConfig.getCredentials()); + } + + @Override + public Transaction newTransaction() { + + String url = newTransactionUrl(); + return new HttpTransaction(transactionManager, this, url); + } + + public CloseableHttpResponse executeHttpRequest(HttpRequestBase request) { + + try { + try(CloseableHttpResponse response = HttpRequest.execute(httpClient(), request, driverConfig.getCredentials())) { + HttpEntity responseEntity = response.getEntity(); + if (responseEntity != null) { + String responseText = EntityUtils.toString(responseEntity); + LOGGER.debug("Thread {}: {}", Thread.currentThread().getId(), responseText ); + EntityUtils.consume(responseEntity); + if (responseText.contains("\"errors\":[{") || responseText.contains("\"errors\": [{")) { + throw new ResultErrorsException(responseText); + } + } + return response; + } + } + + catch (HttpResponseException hre) { + if (hre.getStatusCode() == 404) { + Transaction tx = transactionManager.getCurrentTransaction(); + if (tx != null) { + transactionManager.rollback(tx); + } + } + throw new ResultProcessingException("HttpResponse exception: Not Found", hre); + } + + catch (Exception e) { + throw new ResultProcessingException("Failed to execute request: ", e); + } + + finally { + request.releaseConnection(); + LOGGER.debug( "Thread {}: Connection released", Thread.currentThread().getId() ); + } + } + + private String newTransactionUrl() { + + String url = transactionEndpoint(driverConfig.getURI()); + LOGGER.debug( "Thread {}: POST {}", Thread.currentThread().getId(), url ); + + try (CloseableHttpResponse response = executeHttpRequest(new HttpPost(url))) { + Header location = response.getHeaders("Location")[0]; + response.close(); + return location.getValue(); + } catch (Exception e) { + throw new ResultProcessingException("Could not obtain new Transaction: ", e); + } + } + + private String autoCommitUrl() { + return transactionEndpoint(driverConfig.getURI()).concat("/commit"); + } + + private String transactionEndpoint(String server) { + if (server == null) { + return null; + } + String url = server; + + if (!server.endsWith("/")) { + url += "/"; + } + return url + "db/data/transaction"; + } + + private String requestUrl() { + if (transactionManager != null) { + Transaction tx = transactionManager.getCurrentTransaction(); + if (tx != null) { + LOGGER.debug("Thread {}: request url {}", Thread.currentThread().getId(), ((HttpTransaction) tx).url()); + return ((HttpTransaction) tx).url(); + } else { + LOGGER.debug( "Thread {}: No current transaction, using auto-commit", Thread.currentThread().getId() ); + } + } else { + LOGGER.debug( "Thread {}: No transaction manager available, using auto-commit", Thread.currentThread().getId() ); + } + LOGGER.debug( "Thread {}: request url {}", Thread.currentThread().getId(), autoCommitUrl() ); + return autoCommitUrl(); + } + + private synchronized CloseableHttpClient httpClient() { + + if (httpClient == null) { // most of the time this will be false, branch-prediction will be very fast and the lock released immediately + + try { + HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); + + SSLContext sslContext = SSLContext.getDefault(); + + if (driverConfig.getTrustStrategy() != null) { + + if (driverConfig.getTrustStrategy().equals("ACCEPT_UNSIGNED")) { + sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { + public boolean isTrusted(X509Certificate[] arg0, String arg1) { + return true; + } + }).build(); + + LOGGER.warn("Certificate validation has been disabled"); + } + } + + // setup the default or custom ssl context + httpClientBuilder.setSSLContext(sslContext); + + HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); + + SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); + Registry socketFactoryRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslSocketFactory) + .build(); + + // allows multi-threaded use + PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); + + Integer connectionPoolSize = driverConfig.getConnectionPoolSize(); + + connectionManager.setMaxTotal(connectionPoolSize); + connectionManager.setDefaultMaxPerRoute(connectionPoolSize); + + httpClientBuilder.setConnectionManager(connectionManager); + + httpClient = httpClientBuilder.build(); + + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + return httpClient; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `response` last assigned on line 130 could be null and is dereferenced at line 131. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String HttpDriver.newTransactionUrl() + +### Procedure Id: +org.neo4j.ogm.drivers.http.driver.HttpDriver.newTransactionUrl():java.lang.String.e28db02f03fe305e22f76fc2c7e6a376 + +### File: +http-driver/src/main/java/org/neo4j/ogm/drivers/http/driver/HttpDriver.java + +### Key: +HttpDriver.java|newTransactionUrl|NULL_DEREFERENCE + +### Node Key: +33a23cce47ae73762338530d2e74790f + +### Hash: +15ceb1a2e19ac456fef878be4ec027d2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7526/instruction.md b/inferredbugs-7526/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0340f8771de52797fd7473b56a348841b50ea321 --- /dev/null +++ b/inferredbugs-7526/instruction.md @@ -0,0 +1,730 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 48 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2017 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + */ + +package org.neo4j.ogm.context; + + +import static org.neo4j.ogm.annotation.Relationship.*; +import static org.neo4j.ogm.metadata.reflect.EntityAccessManager.*; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.*; + +import org.neo4j.ogm.annotation.EndNode; +import org.neo4j.ogm.annotation.Relationship; +import org.neo4j.ogm.annotation.StartNode; +import org.neo4j.ogm.exception.BaseClassNotFoundException; +import org.neo4j.ogm.exception.MappingException; +import org.neo4j.ogm.metadata.ClassInfo; +import org.neo4j.ogm.metadata.FieldInfo; +import org.neo4j.ogm.metadata.MetaData; +import org.neo4j.ogm.metadata.MethodInfo; +import org.neo4j.ogm.metadata.reflect.EntityAccessManager; +import org.neo4j.ogm.metadata.reflect.EntityFactory; +import org.neo4j.ogm.model.Edge; +import org.neo4j.ogm.model.GraphModel; +import org.neo4j.ogm.model.Node; +import org.neo4j.ogm.model.Property; +import org.neo4j.ogm.response.Response; +import org.neo4j.ogm.response.model.PropertyModel; +import org.neo4j.ogm.typeconversion.CompositeAttributeConverter; +import org.neo4j.ogm.utils.ClassUtils; +import org.neo4j.ogm.utils.EntityUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author Vince Bickers + * @author Luanne Misquitta + */ +public class GraphEntityMapper implements ResponseMapper { + + private static final Logger logger = LoggerFactory.getLogger(GraphEntityMapper.class); + + private static Map toMap(List> propertyList) { + + Map map = new HashMap<>(); + + for (Property property : propertyList) { + map.put(property.getKey(), property.getValue()); + } + + return map; + } + + private final MappingContext mappingContext; + private final EntityFactory entityFactory; + private final MetaData metadata; + + public GraphEntityMapper(MetaData metaData, MappingContext mappingContext) { + this.metadata = metaData; + this.entityFactory = new EntityFactory(metadata); + this.mappingContext = mappingContext; + } + + @Override + public Iterable map(Class type, Response model) { + + List objects = new ArrayList<>(); + Set objectIds = new HashSet<>(); + /* + * these two lists will contain the node ids and edge ids from the response, in the order + * they were presented to us. + */ + Set nodeIds = new LinkedHashSet<>(); + Set edgeIds = new LinkedHashSet<>(); + + GraphModel graphModel; + while ((graphModel = model.next()) != null) { + List mappedEntities = map(type, graphModel, nodeIds, edgeIds); + for (T entity : mappedEntities) { + Long identity = EntityUtils.identity(entity, metadata); + if (!objectIds.contains(identity)) { + objects.add(entity); + objectIds.add(identity); + } + } + } + + model.close(); + return objects; + } + + Map mapRelationships(GraphModel model) { + Map results = new HashMap<>(); + Set edgeIds = new LinkedHashSet<>(); + mapRelationships(model, edgeIds); + for (Long id : edgeIds) { + Object o = mappingContext.getRelationshipEntity(id); + if (o != null) { + results.put(id, o); + } + } + return results; + } + + public List map(Class type, GraphModel graphModel) { + Set nodeIds = new LinkedHashSet<>(); + Set edgeIds = new LinkedHashSet<>(); + return map(type, graphModel, nodeIds, edgeIds); + } + + public List map(Class type, GraphModel graphModel, Set nodeIds, Set edgeIds) { + + mapEntities(type, graphModel, nodeIds, edgeIds); + List results = new ArrayList<>(); + Set seenNodeIds = new HashSet<>(); + Set seenEdgeIds = new HashSet<>(); + + for (Long id : nodeIds) { + Object o = mappingContext.getNodeEntity(id); + + if (!seenNodeIds.contains(id)) { + executePostLoad(o); + seenNodeIds.add(id); + } + + if (o != null && type.isAssignableFrom(o.getClass())) { + results.add(type.cast(o)); + } + } + + // only look for REs if no node entities were found + if (results.isEmpty()) { + for (Long id : edgeIds) { + Object o = mappingContext.getRelationshipEntity(id); + + if (!seenEdgeIds.contains(id)) { + if (o != null) { + executePostLoad(o); + } + seenEdgeIds.add(id); + } + + if (o != null && type.isAssignableFrom(o.getClass())) { + results.add(type.cast(o)); + } + } + } + + return results; + } + + private void mapEntities(Class type, GraphModel graphModel, Set nodeIds, Set edgeIds) { + try { + mapNodes(graphModel, nodeIds); + mapRelationships(graphModel, edgeIds); + } catch (Exception e) { + throw new MappingException("Error mapping GraphModel to instance of " + type.getName(), e); + } + } + + private void mapNodes(GraphModel graphModel, Set nodeIds) { + + for (Node node : graphModel.getNodes()) { + if (!nodeIds.contains(node.getId())) { + Object entity = mappingContext.getNodeEntity(node.getId()); + try { + if (entity == null) { + entity = entityFactory.newObject(node); + setIdentity(entity, node.getId()); + setProperties(node.getPropertyList(), entity); + setLabels(node, entity); + mappingContext.addNodeEntity(entity, node.getId()); + } + nodeIds.add(node.getId()); + } catch (BaseClassNotFoundException e) { + logger.debug(e.getMessage()); + } + } + } + } + + private void executePostLoad(Object instance) { + ClassInfo classInfo = metadata.classInfo(instance); + MethodInfo postLoadMethod = classInfo.postLoadMethodOrNull(); + if (postLoadMethod != null) { + final Method method = classInfo.getMethod(postLoadMethod); + try { + method.invoke(instance); + } catch (IllegalAccessException | InvocationTargetException e) { + logger.error("Failed to execute post load method", e); + } + } + } + + private void setIdentity(Object instance, Long id) { + ClassInfo classInfo = metadata.classInfo(instance); + FieldInfo fieldInfo = classInfo.identityField(); + FieldInfo.write(classInfo.getField(fieldInfo), instance, id); + } + + private void setProperties(List> propertyList, Object instance) { + ClassInfo classInfo = metadata.classInfo(instance); + + Collection compositeFields = classInfo.fieldsInfo().compositeFields(); + if (compositeFields.size() > 0) { + Map propertyMap = toMap(propertyList); + for (FieldInfo field : compositeFields) { + CompositeAttributeConverter converter = field.getCompositeConverter(); + Object value = converter.toEntityAttribute(propertyMap); + FieldInfo writer = classInfo.getFieldInfo(field.getName()); + writer.write(instance, value); + } + } + + for (Property property : propertyList) { + writeProperty(classInfo, instance, property); + } + } + + private void setLabels(Node nodeModel, Object instance) { + ClassInfo classInfo = metadata.classInfo(instance); + FieldInfo labelFieldInfo = classInfo.labelFieldOrNull(); + if (labelFieldInfo != null) { + Collection staticLabels = classInfo.staticLabels(); + Set dynamicLabels = new HashSet<>(); + for (String label : nodeModel.getLabels()) { + if (!staticLabels.contains(label)) { + dynamicLabels.add(label); + } + } + writeProperty(classInfo, instance, PropertyModel.with(labelFieldInfo.getName(), dynamicLabels)); + } + } + + private void writeProperty(ClassInfo classInfo, Object instance, Property property) { + + FieldInfo writer = classInfo.getFieldInfo(property.getKey().toString()); + + if (writer == null) { + logger.debug("Unable to find property: {} on class: {} for writing", property.getKey(), classInfo.name()); + } else { + Object value = property.getValue(); + // merge iterable / arrays and co-erce to the correct attribute type + if (writer.type().isArray() || Iterable.class.isAssignableFrom(writer.type())) { + FieldInfo reader = classInfo.getFieldInfo(property.getKey().toString()); + if (reader != null) { + Object currentValue = reader.readProperty(instance); + Class paramType = writer.type(); + Class elementType = underlyingElementType(classInfo, property.getKey().toString()); + if (paramType.isArray()) { + value = EntityAccessManager.merge(paramType, value, (Object[]) currentValue, elementType); + } else { + value = EntityAccessManager.merge(paramType, value, (Collection) currentValue, elementType); + } + } + } + writer.write(instance, value); + } + } + + private boolean tryMappingAsSingleton(Object source, Object parameter, Edge edge, String relationshipDirection) { + + String edgeLabel = edge.getType(); + ClassInfo sourceInfo = metadata.classInfo(source); + + FieldInfo writer = getRelationalWriter(sourceInfo, edgeLabel, relationshipDirection, parameter); + if (writer != null && writer.forScalar()) { + writer.write(source, parameter); + return true; + } + + return false; + } + + private void mapRelationships(GraphModel graphModel, Set edgeIds) { + + final List oneToMany = new ArrayList<>(); + + for (Edge edge : graphModel.getRelationships()) { + if (!edgeIds.contains(edge.getId())) { + Object source = mappingContext.getNodeEntity(edge.getStartNode()); + Object target = mappingContext.getNodeEntity(edge.getEndNode()); + + edgeIds.add(edge.getId()); + + if (source != null && target != null) { + // check whether this edge should in fact be handled as a relationship entity + ClassInfo relationshipEntityClassInfo = getRelationshipEntity(edge); + + if (relationshipEntityClassInfo != null) { + mapRelationshipEntity(oneToMany, edge, source, target, relationshipEntityClassInfo); + } else { + mapRelationship(oneToMany, edge, source, target); + } + } else { + logger.debug("Relationship {} cannot be hydrated because one or more required node types are not mapped to entity classes", edge); + } + } + } + if (oneToMany.size() > 0) { + mapOneToMany(oneToMany); + } + } + + private void mapRelationship(List oneToMany, Edge edge, Object source, Object target) { + boolean oneToOne; + //Since source=start node, end=end node, the direction from source->target has to be outgoing, try mapping it + oneToOne = tryMappingAsSingleton(source, target, edge, OUTGOING); + + //Try mapping the incoming relation on the end node, target + oneToOne &= tryMappingAsSingleton(target, source, edge, Relationship.INCOMING); + + // if its not one->one on BOTH sides, we'll try a one->many | many->one | many->many mapping later. + if (!oneToOne) { + oneToMany.add(edge); + } else { + FieldInfo writer = getRelationalWriter(metadata.classInfo(source), edge.getType(), OUTGOING, target); + mappingContext.addRelationship(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), source.getClass(), ClassUtils.getType(writer.typeParameterDescriptor()))); + } + } + + private void mapRelationshipEntity(List oneToMany, Edge edge, Object source, Object target, ClassInfo relationshipEntityClassInfo) { + logger.debug("Found relationship type: {} to map to RelationshipEntity: {}", edge.getType(), relationshipEntityClassInfo.name()); + + // look to see if this relationship already exists in the mapping context. + Object relationshipEntity = mappingContext.getRelationshipEntity(edge.getId()); + + // do we know about it? + if (relationshipEntity == null) { // no, create a new relationship entity + relationshipEntity = createRelationshipEntity(edge, source, target); + } + + // If the source has a writer for an outgoing relationship for the rel entity, then write the rel entity on the source if it's a scalar writer + ClassInfo sourceInfo = metadata.classInfo(source); + FieldInfo writer = getRelationalWriter(sourceInfo, edge.getType(), OUTGOING, relationshipEntity); + if (writer == null) { + logger.debug("No writer for {}", target); + } else { + if (writer.forScalar()) { + writer.write(source, relationshipEntity); + mappingContext.addRelationship(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), source.getClass(), ClassUtils.getType(writer.typeParameterDescriptor()))); + } else { + oneToMany.add(edge); + } + } + + //If the target has a writer for an incoming relationship for the rel entity, then write the rel entity on the target if it's a scalar writer + ClassInfo targetInfo = metadata.classInfo(target); + writer = getRelationalWriter(targetInfo, edge.getType(), Relationship.INCOMING, relationshipEntity); + + if (writer == null) { + logger.debug("No writer for {}", target); + } else { + if (writer.forScalar()) { + writer.write(target, relationshipEntity); + } else { + oneToMany.add(edge); + } + } + } + + private Object createRelationshipEntity(Edge edge, Object startEntity, Object endEntity) { + + // create and hydrate the new RE + Object relationshipEntity = entityFactory.newObject(getRelationshipEntity(edge)); + setIdentity(relationshipEntity, edge.getId()); + + // REs also have properties + setProperties(edge.getPropertyList(), relationshipEntity); + + // register it in the mapping context + mappingContext.addRelationshipEntity(relationshipEntity, edge.getId()); + + // set the start and end entities + ClassInfo relEntityInfo = metadata.classInfo(relationshipEntity); + + FieldInfo startNodeWriter = relEntityInfo.getStartNodeReader(); + if (startNodeWriter != null) { + startNodeWriter.write(relationshipEntity, startEntity); + } else { + throw new RuntimeException("Cannot find a writer for the StartNode of relational entity " + relEntityInfo.name()); + } + + FieldInfo endNodeWriter = relEntityInfo.getEndNodeReader(); + if (endNodeWriter != null) { + endNodeWriter.write(relationshipEntity, endEntity); + } else { + throw new RuntimeException("Cannot find a writer for the EndNode of relational entity " + relEntityInfo.name()); + } + + return relationshipEntity; + } + + private void mapOneToMany(Collection oneToManyRelationships) { + + EntityCollector entityCollector = new EntityCollector(); + List relationshipsToRegister = new ArrayList<>(); + Set registeredEdges = new HashSet<>(); + + // first, build the full set of related entities of each type and direction for each source entity in the relationship + for (Edge edge : oneToManyRelationships) { + + Object instance = mappingContext.getNodeEntity(edge.getStartNode()); + Object parameter = mappingContext.getNodeEntity(edge.getEndNode()); + + // is this a relationship entity we're trying to map? + Object relationshipEntity = mappingContext.getRelationshipEntity(edge.getId()); + if (relationshipEntity != null) { + // establish a relationship between + FieldInfo outgoingWriter = findIterableWriter(instance, relationshipEntity, edge.getType(), OUTGOING); + if (outgoingWriter != null) { + entityCollector.recordTypeRelationship(edge.getStartNode(), relationshipEntity, edge.getType(), OUTGOING); + relationshipsToRegister.add(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), instance.getClass(), ClassUtils.getType(outgoingWriter.typeParameterDescriptor()))); + } + FieldInfo incomingWriter = findIterableWriter(parameter, relationshipEntity, edge.getType(), Relationship.INCOMING); + if (incomingWriter != null) { + entityCollector.recordTypeRelationship(edge.getEndNode(), relationshipEntity, edge.getType(), Relationship.INCOMING); + relationshipsToRegister.add(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), instance.getClass(), ClassUtils.getType(incomingWriter.typeParameterDescriptor()))); + } + if (incomingWriter != null || outgoingWriter != null) { + registeredEdges.add(edge); + } + } else { + FieldInfo outgoingWriter = findIterableWriter(instance, parameter, edge.getType(), OUTGOING); + if (outgoingWriter != null) { + entityCollector.recordTypeRelationship(edge.getStartNode(), parameter, edge.getType(), OUTGOING); + relationshipsToRegister.add(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), instance.getClass(), ClassUtils.getType(outgoingWriter.typeParameterDescriptor()))); + } + FieldInfo incomingWriter = findIterableWriter(parameter, instance, edge.getType(), Relationship.INCOMING); + if (incomingWriter != null) { + entityCollector.recordTypeRelationship(edge.getEndNode(), instance, edge.getType(), Relationship.INCOMING); + relationshipsToRegister.add(new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), instance.getClass(), ClassUtils.getType(incomingWriter.typeParameterDescriptor()))); + } + if (incomingWriter != null || outgoingWriter != null) { + registeredEdges.add(edge); + } + } + } + + // then set the entire collection at the same time for each owning type + for (Long instanceId : entityCollector.getOwningTypes()) { + //get all relationship types for which we're trying to set collections of instances + for (String relationshipType : entityCollector.getOwningRelationshipTypes(instanceId)) { + //for each relationship type, get all the directions for which we're trying to set collections of instances + for (String relationshipDirection : entityCollector.getRelationshipDirectionsForOwningTypeAndRelationshipType(instanceId, relationshipType)) { + //for each direction, get all the entity types for which we're trying to set collections of instances + for (Class entityClass : entityCollector.getEntityClassesForOwningTypeAndRelationshipTypeAndRelationshipDirection(instanceId, relationshipType, relationshipDirection)) { + Collection entities = entityCollector.getCollectiblesForOwnerAndRelationship(instanceId, relationshipType, relationshipDirection, entityClass); + //Class entityType = entityCollector.getCollectibleTypeForOwnerAndRelationship(instanceId, relationshipType, relationshipDirection); + mapOneToMany(mappingContext.getNodeEntity(instanceId), entityClass, entities, relationshipType, relationshipDirection); + } + } + } + } + + // now register all the relationships we've mapped as iterable types into the mapping context + for (MappedRelationship mappedRelationship : relationshipsToRegister) { + mappingContext.addRelationship(mappedRelationship); + } + // finally, register anything left over. These will be singleton relationships that + // were not mapped during one->one mapping, or one->many mapping. + for (Edge edge : oneToManyRelationships) { + if (!registeredEdges.contains(edge)) { + Object source = mappingContext.getNodeEntity(edge.getStartNode()); + Object target = mappingContext.getNodeEntity(edge.getEndNode()); + FieldInfo writer = getRelationalWriter(metadata.classInfo(source), edge.getType(), OUTGOING, target); + if (writer == null) { + writer = getRelationalWriter(metadata.classInfo(target), edge.getType(), INCOMING, source); + } + // ensures its tracked in the domain + if (writer != null) { + MappedRelationship mappedRelationship = new MappedRelationship(edge.getStartNode(), edge.getType(), edge.getEndNode(), edge.getId(), source.getClass(), ClassUtils.getType(writer.typeParameterDescriptor())); + if (!mappingContext.containsRelationship(mappedRelationship)) { + mappingContext.addRelationship(mappedRelationship); + } + } + } + } + } + + /** + * Return an iterable writer to map a relationship onto an entity for the given relationshipType and relationshipDirection + * + * @param instance the instance onto which the relationship is to be mapped + * @param parameter the value to be mapped + * @param relationshipType the relationship type + * @param relationshipDirection the relationship direction + * @return FieldWriter or null if none exists + */ + private FieldInfo findIterableWriter(Object instance, Object parameter, String relationshipType, String relationshipDirection) { + ClassInfo classInfo = metadata.classInfo(instance); + return EntityAccessManager.getIterableField(classInfo, parameter.getClass(), relationshipType, relationshipDirection); + } + + + /** + * Map many values to an instance based on the relationship type. + * See DATAGRAPH-637 + * + * @param instance the instance to map values onto + * @param valueType the type of each value + * @param values the values to map + * @param relationshipType the relationship type associated with these values + */ + private void mapOneToMany(Object instance, Class valueType, Object values, String relationshipType, String relationshipDirection) { + + ClassInfo classInfo = metadata.classInfo(instance); + + FieldInfo writer = EntityAccessManager.getIterableField(classInfo, valueType, relationshipType, relationshipDirection); + if (writer != null) { + if (writer.type().isArray() || Iterable.class.isAssignableFrom(writer.type())) { + FieldInfo reader = EntityAccessManager.getIterableField(classInfo, valueType, relationshipType, relationshipDirection); + Object currentValues; + if (reader != null) { + currentValues = reader.read(instance); + if (writer.type().isArray()) { + values = EntityAccessManager.merge(writer.type(), values, (Object[]) currentValues, valueType); + } else { + values = EntityAccessManager.merge(writer.type(), values, (Collection) currentValues, valueType); + } + } + } + writer.write(instance, values); + return; + } + // this is not necessarily an error. but we can't tell. + logger.debug("Unable to map iterable of type: {} onto property of {}", valueType, classInfo.name()); + } + + // Find the correct RE associated with the edge. The edge type may be polymorphic, so we need to do a bit of work + // to identify the correct RE to bind to. We must not cache the value when found, because the correct determination + // depends on the runtime values of the edge in the mapping context, which may vary for the same edge pattern. + private ClassInfo getRelationshipEntity(Edge edge) { + + Object source = mappingContext.getNodeEntity(edge.getStartNode()); + Object target = mappingContext.getNodeEntity(edge.getEndNode()); + + Set classInfos = metadata.classInfoByLabelOrType(edge.getType()); + + for (ClassInfo classInfo : classInfos) { + + // both source and target must be declared as START and END nodes respectively + if (!nodeTypeMatches(classInfo, source, StartNode.class)) { + continue; + } + + if (!nodeTypeMatches(classInfo, target, EndNode.class)) { + continue; + } + + // if the source OR the target (or one of their superclasses) declares the relationship + // back to the relationshipEntityClass, we've found a match + Class relationshipEntityClass = classInfo.getUnderlyingClass(); + if (declaresRelationshipTo(relationshipEntityClass, source.getClass(), edge.getType(), OUTGOING)) { + return classInfo; + } + + if (declaresRelationshipTo(relationshipEntityClass, target.getClass(), edge.getType(), INCOMING)) { + return classInfo; + } + } + // we've made our best efforts to find the correct RE. If we've failed it means + // that either a matching RE doesn't exist, or its start and end nodes don't declare a reference + // to the RE. If we can find a single properly-formed matching RE for this edge we'll assume it is + // the right one, otherwise ... give up + if (classInfos.size() == 1) { + ClassInfo classInfo = classInfos.iterator().next(); + if (nodeTypeMatches(classInfo, source, StartNode.class) && nodeTypeMatches(classInfo, target, EndNode.class)) { + return classInfo; + } + } else { + if (classInfos.size() == 0) { + // not necessarily a problem, we mey be fetching edges we don't want to hydrate + if (logger.isDebugEnabled()) { + logger.debug("Unable to find a matching @RelationshipEntity for {}", edge.toString()); + } + } else { + // almost definitely a user bug + logger.error("Found more than one matching @RelationshipEntity for {} but cannot tell which one to use", edge.toString()); + } + } + return null; + } + + /** + * Determines if a class hierarchy that possibly declares a given relationship declares it on a specific class. + * This method is used to resolve polymorphic relationship entity relationship types. In this case, 'to' is + * a concrete subclass of a relationship entity whose relationship type is declared on a superclass. In other words, + * the relationship type is polymorphic. The class 'by' is a class that is either a start node or end node of that + * polymorphic type, but which does not necessarily refer to the relationship entity subtype referenced by 'to'. + * See #298 + * Logic: + * Given a class 'to', a class 'by' and a relationship 'r': + * if the class 'by' (or one of its superclasses) declares a setter or field 'x', annotated with relationship 'r': + * if the class of 'x' is the same as 'to': + * <-- true + * Otherwise: <-- false. + * + * @param to the Class which the named relationship must refer to + * @param by a Class the named relationship is declared by + * @param relationshipName the name of the relationship + * @param relationshipDirection the direction of the relationship + * @return true if 'by' declares the specified relationship on 'to', false otherwise + */ + private boolean declaresRelationshipTo(Class to, Class by, String relationshipName, String relationshipDirection) { + return EntityAccessManager.getRelationalWriter(metadata.classInfo(by.getName()), relationshipName, relationshipDirection, to) != null; + } + + /** + * Checks that the class of the node matches the class defined in the class info for a given annotation + * + * @param classInfo the ClassInfo + * @param node the node object + * @param annotationClass the annotation to match + * @return true if the class of the node matches field annotated + */ + private boolean nodeTypeMatches(ClassInfo classInfo, Object node, Class annotationClass) { + List fields = classInfo.findFields(annotationClass.getName()); + if (fields.size() == 1) { + FieldInfo field = fields.get(0); + if (field.isTypeOf(node.getClass())) { + return true; + } + } + return false; + } + + private Class underlyingElementType(ClassInfo classInfo, String propertyName) { + FieldInfo fieldInfo = fieldInfoForPropertyName(propertyName, classInfo); + Class clazz = null; + if (fieldInfo != null) { + clazz = ClassUtils.getType(fieldInfo.getTypeDescriptor()); + } + return clazz; + } + + private FieldInfo fieldInfoForPropertyName(String propertyName, ClassInfo classInfo) { + FieldInfo labelField = classInfo.labelFieldOrNull(); + if (labelField != null && labelField.getName().toLowerCase().equals(propertyName.toLowerCase())) { + return labelField; + } + return classInfo.propertyField(propertyName); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `parameter` last assigned on line 416 could be null and is dereferenced by call to `findIterableWriter(...)` at line 436. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GraphEntityMapper.mapOneToMany(ArrayList) + +### Procedure Id: +org.neo4j.ogm.context.GraphEntityMapper.mapOneToMany(java.util.ArrayList):void.1946ecc5b3c6d8a405eb74d64a6bdfb0 + +### File: +core/src/main/java/org/neo4j/ogm/context/GraphEntityMapper.java + +### Key: +GraphEntityMapper.java|mapOneToMany|NULL_DEREFERENCE + +### Node Key: +8e77d472cdb83d73c8e7e76a5a5748c4 + +### Hash: +32f4278c03f773273a67f1c3cc8de9e1 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7528/instruction.md b/inferredbugs-7528/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8f4277c9320653ef45c73622a5611fc1e5d800b7 --- /dev/null +++ b/inferredbugs-7528/instruction.md @@ -0,0 +1,124 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + * + */ +package org.neo4j.ogm.session.delegates; + +import org.neo4j.ogm.cypher.query.Query; +import org.neo4j.ogm.model.GraphModel; +import org.neo4j.ogm.session.Capability; +import org.neo4j.ogm.session.Neo4jSession; +import org.neo4j.ogm.session.request.strategy.QueryStatements; +import org.neo4j.ogm.session.response.Neo4jResponse; + +/** + * @author Vince Bickers + */ +public class LoadOneDelegate implements Capability.LoadOne { + + private Neo4jSession session; + + public LoadOneDelegate(Neo4jSession session) { + this.session = session; + } + + @Override + public T load(Class type, Long id) { + return load(type, id, 1); + } + + @Override + public T load(Class type, Long id, int depth) { + String url = session.ensureTransaction().url(); + QueryStatements queryStatements = session.queryStatementsFor(type); + Query qry = queryStatements.findOne(id,depth); + try (Neo4jResponse response = session.requestHandler().execute(qry, url)) { + return session.responseHandler().loadById(type, response, id); + } + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.neo4j.ogm.session.transaction.SimpleTransaction` acquired by call to `ensureTransaction()` at line 41 is not released after line 41. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object LoadOneDelegate.load(Class,Long,int) + +### Procedure Id: +org.neo4j.ogm.session.delegates.LoadOneDelegate.load(java.lang.Class,java.lang.Long,int):java.lang.O.71be2a21fa562d3cb1772589d5b670ee + +### File: +src/main/java/org/neo4j/ogm/session/delegates/LoadOneDelegate.java + +### Key: +LoadOneDelegate.java|load|RESOURCE_LEAK + +### Node Key: +acaec5e305bcc4bb44d93c058ea68ab1 + +### Hash: +fc7c6a0206cad0dc6d549aa4401fc043 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7529/instruction.md b/inferredbugs-7529/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7f3f0bd8e2ccb0673cb25b9c4b03c9550dea7db --- /dev/null +++ b/inferredbugs-7529/instruction.md @@ -0,0 +1,183 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** neo4j-ogm +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2002-2015 "Neo Technology," + * Network Engine for Objects in Lund AB [http://neotechnology.com] + * + * This product is licensed to you under the Apache License, Version 2.0 (the "License"). + * You may not use this product except in compliance with the License. + * + * This product may include a number of subcomponents with + * separate copyright notices and license terms. Your use of the source + * code for these subcomponents is subject to the terms and + * conditions of the subcomponent's license, as noted in the LICENSE file. + * + */ +package org.neo4j.ogm.session.delegates; + +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.List; + +import org.neo4j.ogm.cypher.statement.ParameterisedStatement; +import org.neo4j.ogm.entityaccess.FieldWriter; +import org.neo4j.ogm.metadata.info.ClassInfo; +import org.neo4j.ogm.session.Capability; +import org.neo4j.ogm.session.Neo4jSession; +import org.neo4j.ogm.session.request.strategy.DeleteNodeStatements; +import org.neo4j.ogm.session.request.strategy.DeleteRelationshipStatements; +import org.neo4j.ogm.session.request.strategy.DeleteStatements; +import org.neo4j.ogm.session.response.Neo4jResponse; + +/** + * @author Vince Bickers + */ +public class DeleteDelegate implements Capability.Delete { + + private final Neo4jSession session; + + public DeleteDelegate(Neo4jSession neo4jSession) { + this.session = neo4jSession; + } + + private DeleteStatements getDeleteStatementsBasedOnType(Class type) { + if (session.metaData().isRelationshipEntity(type.getName())) { + return new DeleteRelationshipStatements(); + } + return new DeleteNodeStatements(); + } + + + private void deleteAll(T object) { + List list; + if (object.getClass().isArray()) { + list = Arrays.asList(object); + } else { + list = (List) object; + } + for (T element : list) { + delete(element); + } + } + + @Override + public void delete(T object) { + if (object.getClass().isArray() || Iterable.class.isAssignableFrom(object.getClass())) { + deleteAll(object); + } else { + ClassInfo classInfo = session.metaData().classInfo(object); + if (classInfo != null) { + Field identityField = classInfo.getField(classInfo.identityField()); + Long identity = (Long) FieldWriter.read(identityField, object); + if (identity != null) { + String url = session.ensureTransaction().url(); + ParameterisedStatement request = getDeleteStatementsBasedOnType(object.getClass()).delete(identity); + try (Neo4jResponse response = session.requestHandler().execute(request, url)) { + session.context().clear(object); + } + } + } else { + session.info(object.getClass().getName() + " is not an instance of a persistable class"); + } + } + } + + @Override + public void deleteAll(Class type) { + ClassInfo classInfo = session.metaData().classInfo(type.getName()); + if (classInfo != null) { + String url = session.ensureTransaction().url(); + ParameterisedStatement request = getDeleteStatementsBasedOnType(type).deleteByType(session.entityType(classInfo.name())); + try (Neo4jResponse response = session.requestHandler().execute(request, url)) { + session.context().clear(type); + } + } else { + session.info(type.getName() + " is not a persistable class"); + } + } + + + @Override + public void purgeDatabase() { + String url = session.ensureTransaction().url(); + session.requestHandler().execute(new DeleteNodeStatements().purge(), url).close(); + session.context().clear(); + } + + @Override + public void clear() { + session.context().clear(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.neo4j.ogm.session.transaction.SimpleTransaction` acquired by call to `ensureTransaction()` at line 100 is not released after line 100. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DeleteDelegate.purgeDatabase() + +### Procedure Id: +org.neo4j.ogm.session.delegates.DeleteDelegate.purgeDatabase():void.1c8d0c910ee3d8e2e97ecc10517259bb + +### File: +src/main/java/org/neo4j/ogm/session/delegates/DeleteDelegate.java + +### Key: +DeleteDelegate.java|purgeDatabase|RESOURCE_LEAK + +### Node Key: +555eb4653f57a9c18c7378b53476017b + +### Hash: +610979d7aa8920494cc4c57c55c39b7a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7542/instruction.md b/inferredbugs-7542/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89f68ee4a2a04239772f533c1e3bb330cceaea60 --- /dev/null +++ b/inferredbugs-7542/instruction.md @@ -0,0 +1,164 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nCoAP +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uniluebeck.itm.spitfire.nCoap.communication.utils; + +import de.uniluebeck.itm.spitfire.nCoap.application.client.CoapClientApplication; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapResponse; +import org.apache.log4j.Logger; + +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +//import de.uniluebeck.itm.spitfire.nCoap.communication.core.CoapExecutorService; + + +/** + * A CoapClientApplication for testing purposes. + * To send a request use the inherited writeCoapRequest() method. + * Received responses are stored and can be accessed using getReceivedResponses(). + * + * @author Oliver Kleine, Stefan Hueske + */ +public class CoapTestClient extends CoapClientApplication { + + //private static CoapTestClient instance = new CoapTestClient(); + + private Logger log = Logger.getLogger(this.getClass().getName()); + + private SortedMap receivedResponses = new TreeMap(); + private SortedSet emptyAckNotificationTimes = new TreeSet(); + private SortedSet timeoutNotificationTimes = new TreeSet(); + + private boolean receiveEnabled = true; + +// public static CoapTestClient getInstance(){ +// return instance; +// } +// +// private CoapTestClient(){} + + @Override + public void receiveResponse(CoapResponse coapResponse) { + if (receiveEnabled) { + receivedResponses.put(System.currentTimeMillis(), coapResponse); + } + } + + @Override + public void receiveEmptyACK(){ + if(receiveEnabled && !emptyAckNotificationTimes.add(System.currentTimeMillis())){ + log.error("Could not add notification time for empty ACK."); + } + } + + @Override + public void handleRetransmissionTimout() { + if(receiveEnabled && !timeoutNotificationTimes.add(System.currentTimeMillis())){ + log.error("Could not add notification time for retransmission timeout."); + } + } + + public SortedSet getEmptyAckNotificationTimes() { + return emptyAckNotificationTimes; + } + + public SortedSet getTimeoutNotificationTimes() { + return timeoutNotificationTimes; + } + + public SortedMap getReceivedResponses() { + return receivedResponses; + } + +// public void reset() { +// receivedResponses.clear(); +// setReceiveEnabled(true); +// +// //CoapExecutorService.cancelAll(); +// +// datagramChannel.close().awaitUninterruptibly(); +//// datagramChannel.getFactory().releaseExternalResources(); +// CoapClientDatagramChannelFactory.resetInstance(); +// datagramChannel = CoapClientDatagramChannelFactory.getInstance().getChannel(); +// +// } + + public synchronized void setReceiveEnabled(boolean receiveEnabled) { + this.receiveEnabled = receiveEnabled; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.receiveResponse` reads without synchronization from `this.de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.receiveEnabled`. Potentially races with write in method `CoapTestClient.setReceiveEnabled(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CoapTestClient.receiveResponse(CoapResponse) + +### Procedure Id: +de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.receiveResponse(de.uniluebeck.it.2ef54042876abe03df9136c5f4e48db0 + +### File: +src/test/java/de/uniluebeck/itm/spitfire/nCoap/communication/utils/CoapTestClient.java + +### Key: +CoapTestClient.java|receiveResponse|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +696f6209c951240cef7430bb209fc512 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7543/instruction.md b/inferredbugs-7543/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a19c241d7f12052795e722afc53eaa4d3988389 --- /dev/null +++ b/inferredbugs-7543/instruction.md @@ -0,0 +1,164 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nCoAP +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uniluebeck.itm.spitfire.nCoap.communication.utils; + +import de.uniluebeck.itm.spitfire.nCoap.application.client.CoapClientApplication; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapResponse; +import org.apache.log4j.Logger; + +import java.util.SortedMap; +import java.util.SortedSet; +import java.util.TreeMap; +import java.util.TreeSet; + +//import de.uniluebeck.itm.spitfire.nCoap.communication.core.CoapExecutorService; + + +/** + * A CoapClientApplication for testing purposes. + * To send a request use the inherited writeCoapRequest() method. + * Received responses are stored and can be accessed using getReceivedResponses(). + * + * @author Oliver Kleine, Stefan Hueske + */ +public class CoapTestClient extends CoapClientApplication { + + //private static CoapTestClient instance = new CoapTestClient(); + + private Logger log = Logger.getLogger(this.getClass().getName()); + + private SortedMap receivedResponses = new TreeMap(); + private SortedSet emptyAckNotificationTimes = new TreeSet(); + private SortedSet timeoutNotificationTimes = new TreeSet(); + + private boolean receiveEnabled = true; + +// public static CoapTestClient getInstance(){ +// return instance; +// } +// +// private CoapTestClient(){} + + @Override + public void receiveResponse(CoapResponse coapResponse) { + if (receiveEnabled) { + receivedResponses.put(System.currentTimeMillis(), coapResponse); + } + } + + @Override + public void receiveEmptyACK(){ + if(receiveEnabled && !emptyAckNotificationTimes.add(System.currentTimeMillis())){ + log.error("Could not add notification time for empty ACK."); + } + } + + @Override + public void handleRetransmissionTimout() { + if(receiveEnabled && !timeoutNotificationTimes.add(System.currentTimeMillis())){ + log.error("Could not add notification time for retransmission timeout."); + } + } + + public SortedSet getEmptyAckNotificationTimes() { + return emptyAckNotificationTimes; + } + + public SortedSet getTimeoutNotificationTimes() { + return timeoutNotificationTimes; + } + + public SortedMap getReceivedResponses() { + return receivedResponses; + } + +// public void reset() { +// receivedResponses.clear(); +// setReceiveEnabled(true); +// +// //CoapExecutorService.cancelAll(); +// +// datagramChannel.close().awaitUninterruptibly(); +//// datagramChannel.getFactory().releaseExternalResources(); +// CoapClientDatagramChannelFactory.resetInstance(); +// datagramChannel = CoapClientDatagramChannelFactory.getInstance().getChannel(); +// +// } + + public synchronized void setReceiveEnabled(boolean receiveEnabled) { + this.receiveEnabled = receiveEnabled; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.handleRetransmissionTimout` reads without synchronization from `this.de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.receiveEnabled`. Potentially races with write in method `CoapTestClient.setReceiveEnabled(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CoapTestClient.handleRetransmissionTimout() + +### Procedure Id: +de.uniluebeck.itm.spitfire.nCoap.communication.utils.CoapTestClient.handleRetransmissionTimout():voi.67ef9c9e010c054b1e948d23add73cfc + +### File: +src/test/java/de/uniluebeck/itm/spitfire/nCoap/communication/utils/CoapTestClient.java + +### Key: +CoapTestClient.java|handleRetransmissionTimout|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +2ccf5d1934a790467b51ca67f19586ec + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7544/instruction.md b/inferredbugs-7544/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..279df51d10543f5d79e9c939c79b5a51cc1dec5d --- /dev/null +++ b/inferredbugs-7544/instruction.md @@ -0,0 +1,334 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nCoAP +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uniluebeck.itm.spitfire.nCoap.communication.blockwise; + +import de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapRequest; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapResponse; +import de.uniluebeck.itm.spitfire.nCoap.message.MessageDoesNotAllowPayloadException; +import de.uniluebeck.itm.spitfire.nCoap.message.header.InvalidHeaderException; +import de.uniluebeck.itm.spitfire.nCoap.message.header.MsgType; +import de.uniluebeck.itm.spitfire.nCoap.message.options.InvalidOptionException; +import de.uniluebeck.itm.spitfire.nCoap.message.options.ToManyOptionsException; +import de.uniluebeck.itm.spitfire.nCoap.toolbox.ByteArrayWrapper; +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; + +import static de.uniluebeck.itm.spitfire.nCoap.message.options.OptionRegistry.OptionName.BLOCK_2; + +/** + * Created with IntelliJ IDEA. + * User: olli + * Date: 12.09.12 + * Time: 17:50 + * To change this template use File | Settings | File Templates. + */ +public class BlockwiseTransferHandler extends SimpleChannelHandler{ + + private static Logger log = LoggerFactory.getLogger(BlockwiseTransferHandler.class.getName()); + + private Object incompleteResponseMonitor = new Object(); + private Object incompleteRequestMonitor = new Object(); + + private HashMap incompleteResponsePayload = + new HashMap(); + + private HashMap incompleteRequestPayload = + new HashMap(); + + private static BlockwiseTransferHandler instance = new BlockwiseTransferHandler(); + + private BlockwiseTransferHandler(){ + + } + + public static BlockwiseTransferHandler getInstance(){ + return instance; + } + + @Override + public void writeRequested(ChannelHandlerContext ctx, MessageEvent me){ + if(!(me.getMessage() instanceof CoapMessage)){ + ctx.sendDownstream(me); + return; + } + + if(me.getMessage() instanceof CoapRequest){ + CoapRequest request = (CoapRequest) me.getMessage(); + byte[] token = request.getToken(); + + //There was no ResponseCallback attached to the response and thus there is no token + if(token.length == 0){ + ctx.sendDownstream(me); + return; + } + + BlockwiseTransfer transfer = + new BlockwiseTransfer(request, ChannelBuffers.dynamicBuffer()); + + synchronized (incompleteResponseMonitor){ + incompleteResponsePayload.put(new ByteArrayWrapper(token), transfer); + } + + ctx.sendDownstream(me); + + //TODO handle blockwise transfer for outgoing requests with payload + + } + else{ + //TODO handle blockwise transfer for outgoing responses with payload + ctx.sendDownstream(me); + } + + + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){ + if(!(me.getMessage() instanceof CoapMessage)){ + ctx.sendUpstream(me); + return; + } + + CoapMessage coapMessage = (CoapMessage) me.getMessage(); + if(coapMessage.getCode().isError() || coapMessage.getMessageType().equals(MsgType.RST)){ + errorMessageReceived(ctx, me); + return; + } + + if(me.getMessage() instanceof CoapResponse){ + CoapResponse response = (CoapResponse) me.getMessage(); + + final byte[] token = response.getToken(); + + BlockwiseTransfer transfer; + //Add latest received payload to already received payload + synchronized (incompleteResponseMonitor){ + transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token)); + if(transfer != null){ + try { + if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){ + log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) + + " , Block: " + response.getBlockNumber(BLOCK_2) + "), "); + + if (log.isDebugEnabled()){ + //Copy Payload + ChannelBuffer payloadCopy = ChannelBuffers.copiedBuffer(response.getPayload()); + byte[] bytes = new byte[payloadCopy.readableBytes()]; + payloadCopy.getBytes(0, bytes); + log.debug("Payload Hex: " + new ByteArrayWrapper(bytes).toHexString()); + } + + transfer.getPartialPayload() + .writeBytes(response.getPayload(), 0, response.getPayload().readableBytes()); + transfer.setNextBlockNumber(transfer.getNextBlockNumber() + 1); + } + else{ + log.debug("Received unexpected response (Token: " + (new ByteArrayWrapper(token).toHexString()) + + " , Block: " + response.getBlockNumber(BLOCK_2) + "). IGNORE!"); + me.getFuture().setSuccess(); + return; + } + } + catch (InvalidOptionException e) { + log.error("This should never happen!", e); + } + } + } + + //Check whether payload of the response is complete + if(transfer != null){ + try { + if(response.isLastBlock(BLOCK_2)){ + + //Send response with complete payload to application + log.debug("Block " + response.getBlockNumber(BLOCK_2) + " for response with token " + + new ByteArrayWrapper(token).toHexString() + + " received. Payload complete. Forward to client application."); + + response.getOptionList().removeAllOptions(BLOCK_2); + + response.setPayload(transfer.getPartialPayload()); + MessageEvent event = new UpstreamMessageEvent(me.getChannel(), response, me.getRemoteAddress()); + ctx.sendUpstream(event); + + synchronized (incompleteResponseMonitor){ + if(incompleteResponsePayload.remove(new ByteArrayWrapper(token)) == null){ + log.error("This should never happen! No incomplete payload found for token " + + new ByteArrayWrapper(token).toHexString()); + } + else{ + log.debug("Deleted not anymore incomplete payload for token " + + new ByteArrayWrapper(token).toHexString() + " from list"); + } + } + return; + + } + else{ + final long receivedBlockNumber = response.getBlockNumber(BLOCK_2); + + log.debug("Block " + receivedBlockNumber + " for response with token " + + new ByteArrayWrapper(token).toHexString() + + " received. Payload (still) incomplete."); + + CoapRequest nextCoapRequest = (CoapRequest) transfer.getCoapMessage(); + nextCoapRequest.setMessageID(-1); + nextCoapRequest.setBlockOption(BLOCK_2, receivedBlockNumber + 1, + false, response.getMaxBlocksizeForResponse()); + + + ChannelFuture future = Channels.future(me.getChannel()); + + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + log.debug("Request for block " + (receivedBlockNumber + 1) + " for token " + + new ByteArrayWrapper(token).toHexString() + " sent succesfully."); + + } + }); + MessageEvent event = new DownstreamMessageEvent(me.getChannel(), + future, nextCoapRequest, me.getRemoteAddress()); + + log.debug("Send request for block " + (receivedBlockNumber + 1) + " for token " + + new ByteArrayWrapper(token).toHexString() + "."); + + ctx.sendDownstream(event); + return; + } + } + catch (InvalidOptionException e) { + log.error("This should never happen!", e); + } + catch (MessageDoesNotAllowPayloadException e) { + log.error("This should never happen!", e); + } + catch (ToManyOptionsException e){ + log.error("This should never happen!", e); + } + catch (InvalidHeaderException e) { + log.error("This should never happen!", e); + } + } + } + + ctx.sendUpstream(me); + } + + private void errorMessageReceived(ChannelHandlerContext ctx, MessageEvent me){ + CoapMessage coapMessage = (CoapMessage) me.getMessage(); + synchronized (incompleteResponseMonitor){ + incompleteResponsePayload.remove(coapMessage.getToken()); + } + ctx.sendUpstream(me); + } + + private class BlockwiseTransfer { + + private CoapMessage coapMessage; + private ChannelBuffer partialPayload; + private int nextBlockNumber = 0; + + public BlockwiseTransfer(CoapMessage coapMessage, ChannelBuffer partialPayload){ + this.coapMessage = coapMessage; + this.partialPayload = partialPayload; + } + + public CoapMessage getCoapMessage() throws InvalidHeaderException { + return coapMessage; + } + + public ChannelBuffer getPartialPayload() { + return partialPayload; + } + + public void setNextBlockNumber(int nextBlockNumber){ + this.nextBlockNumber = nextBlockNumber; + } + + public int getNextBlockNumber(){ + return this.nextBlockNumber; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `de.uniluebeck.itm.spitfire.nCoap.communication.blockwise.BlockwiseTransferHandler.messageReceived` indirectly writes to field `response.de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage.payload` outside of synchronization. + Reporting because this access may occur on a background thread. + +Note that the prefix path response has been contaminated during the execution, so the reported race on response.de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage.payload might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockwiseTransferHandler.messageReceived(ChannelHandlerContext,MessageEvent) + +### Procedure Id: +de.uniluebeck.itm.spitfire.nCoap.communication.blockwise.BlockwiseTransferHandler.messageReceived(or.34a7450d3fa81d4a967b1800e6cae7ad + +### File: +src/main/java/de/uniluebeck/itm/spitfire/nCoap/communication/blockwise/BlockwiseTransferHandler.java + +### Key: +BlockwiseTransferHandler.java|messageReceived|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c725632ad8d8f5635f236a5e0316dc6c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7545/instruction.md b/inferredbugs-7545/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b92d01d3e58ed6f63051478068075728bb6d03cb --- /dev/null +++ b/inferredbugs-7545/instruction.md @@ -0,0 +1,334 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nCoAP +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.uniluebeck.itm.spitfire.nCoap.communication.blockwise; + +import de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapRequest; +import de.uniluebeck.itm.spitfire.nCoap.message.CoapResponse; +import de.uniluebeck.itm.spitfire.nCoap.message.MessageDoesNotAllowPayloadException; +import de.uniluebeck.itm.spitfire.nCoap.message.header.InvalidHeaderException; +import de.uniluebeck.itm.spitfire.nCoap.message.header.MsgType; +import de.uniluebeck.itm.spitfire.nCoap.message.options.InvalidOptionException; +import de.uniluebeck.itm.spitfire.nCoap.message.options.ToManyOptionsException; +import de.uniluebeck.itm.spitfire.nCoap.toolbox.ByteArrayWrapper; +import org.jboss.netty.buffer.ChannelBuffer; +import org.jboss.netty.buffer.ChannelBuffers; +import org.jboss.netty.channel.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; + +import static de.uniluebeck.itm.spitfire.nCoap.message.options.OptionRegistry.OptionName.BLOCK_2; + +/** + * Created with IntelliJ IDEA. + * User: olli + * Date: 12.09.12 + * Time: 17:50 + * To change this template use File | Settings | File Templates. + */ +public class BlockwiseTransferHandler extends SimpleChannelHandler{ + + private static Logger log = LoggerFactory.getLogger(BlockwiseTransferHandler.class.getName()); + + private Object incompleteResponseMonitor = new Object(); + private Object incompleteRequestMonitor = new Object(); + + private HashMap incompleteResponsePayload = + new HashMap(); + + private HashMap incompleteRequestPayload = + new HashMap(); + + private static BlockwiseTransferHandler instance = new BlockwiseTransferHandler(); + + private BlockwiseTransferHandler(){ + + } + + public static BlockwiseTransferHandler getInstance(){ + return instance; + } + + @Override + public void writeRequested(ChannelHandlerContext ctx, MessageEvent me){ + if(!(me.getMessage() instanceof CoapMessage)){ + ctx.sendDownstream(me); + return; + } + + if(me.getMessage() instanceof CoapRequest){ + CoapRequest request = (CoapRequest) me.getMessage(); + byte[] token = request.getToken(); + + //There was no ResponseCallback attached to the response and thus there is no token + if(token.length == 0){ + ctx.sendDownstream(me); + return; + } + + BlockwiseTransfer transfer = + new BlockwiseTransfer(request, ChannelBuffers.dynamicBuffer()); + + synchronized (incompleteResponseMonitor){ + incompleteResponsePayload.put(new ByteArrayWrapper(token), transfer); + } + + ctx.sendDownstream(me); + + //TODO handle blockwise transfer for outgoing requests with payload + + } + else{ + //TODO handle blockwise transfer for outgoing responses with payload + ctx.sendDownstream(me); + } + + + } + + @Override + public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){ + if(!(me.getMessage() instanceof CoapMessage)){ + ctx.sendUpstream(me); + return; + } + + CoapMessage coapMessage = (CoapMessage) me.getMessage(); + if(coapMessage.getCode().isError() || coapMessage.getMessageType().equals(MsgType.RST)){ + errorMessageReceived(ctx, me); + return; + } + + if(me.getMessage() instanceof CoapResponse){ + CoapResponse response = (CoapResponse) me.getMessage(); + + final byte[] token = response.getToken(); + + BlockwiseTransfer transfer; + //Add latest received payload to already received payload + synchronized (incompleteResponseMonitor){ + transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token)); + if(transfer != null){ + try { + if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){ + log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) + + " , Block: " + response.getBlockNumber(BLOCK_2) + "), "); + + if (log.isDebugEnabled()){ + //Copy Payload + ChannelBuffer payloadCopy = ChannelBuffers.copiedBuffer(response.getPayload()); + byte[] bytes = new byte[payloadCopy.readableBytes()]; + payloadCopy.getBytes(0, bytes); + log.debug("Payload Hex: " + new ByteArrayWrapper(bytes).toHexString()); + } + + transfer.getPartialPayload() + .writeBytes(response.getPayload(), 0, response.getPayload().readableBytes()); + transfer.setNextBlockNumber(transfer.getNextBlockNumber() + 1); + } + else{ + log.debug("Received unexpected response (Token: " + (new ByteArrayWrapper(token).toHexString()) + + " , Block: " + response.getBlockNumber(BLOCK_2) + "). IGNORE!"); + me.getFuture().setSuccess(); + return; + } + } + catch (InvalidOptionException e) { + log.error("This should never happen!", e); + } + } + } + + //Check whether payload of the response is complete + if(transfer != null){ + try { + if(response.isLastBlock(BLOCK_2)){ + + //Send response with complete payload to application + log.debug("Block " + response.getBlockNumber(BLOCK_2) + " for response with token " + + new ByteArrayWrapper(token).toHexString() + + " received. Payload complete. Forward to client application."); + + response.getOptionList().removeAllOptions(BLOCK_2); + + response.setPayload(transfer.getPartialPayload()); + MessageEvent event = new UpstreamMessageEvent(me.getChannel(), response, me.getRemoteAddress()); + ctx.sendUpstream(event); + + synchronized (incompleteResponseMonitor){ + if(incompleteResponsePayload.remove(new ByteArrayWrapper(token)) == null){ + log.error("This should never happen! No incomplete payload found for token " + + new ByteArrayWrapper(token).toHexString()); + } + else{ + log.debug("Deleted not anymore incomplete payload for token " + + new ByteArrayWrapper(token).toHexString() + " from list"); + } + } + return; + + } + else{ + final long receivedBlockNumber = response.getBlockNumber(BLOCK_2); + + log.debug("Block " + receivedBlockNumber + " for response with token " + + new ByteArrayWrapper(token).toHexString() + + " received. Payload (still) incomplete."); + + CoapRequest nextCoapRequest = (CoapRequest) transfer.getCoapMessage(); + nextCoapRequest.setMessageID(-1); + nextCoapRequest.setBlockOption(BLOCK_2, receivedBlockNumber + 1, + false, response.getMaxBlocksizeForResponse()); + + + ChannelFuture future = Channels.future(me.getChannel()); + + future.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + log.debug("Request for block " + (receivedBlockNumber + 1) + " for token " + + new ByteArrayWrapper(token).toHexString() + " sent succesfully."); + + } + }); + MessageEvent event = new DownstreamMessageEvent(me.getChannel(), + future, nextCoapRequest, me.getRemoteAddress()); + + log.debug("Send request for block " + (receivedBlockNumber + 1) + " for token " + + new ByteArrayWrapper(token).toHexString() + "."); + + ctx.sendDownstream(event); + return; + } + } + catch (InvalidOptionException e) { + log.error("This should never happen!", e); + } + catch (MessageDoesNotAllowPayloadException e) { + log.error("This should never happen!", e); + } + catch (ToManyOptionsException e){ + log.error("This should never happen!", e); + } + catch (InvalidHeaderException e) { + log.error("This should never happen!", e); + } + } + } + + ctx.sendUpstream(me); + } + + private void errorMessageReceived(ChannelHandlerContext ctx, MessageEvent me){ + CoapMessage coapMessage = (CoapMessage) me.getMessage(); + synchronized (incompleteResponseMonitor){ + incompleteResponsePayload.remove(coapMessage.getToken()); + } + ctx.sendUpstream(me); + } + + private class BlockwiseTransfer { + + private CoapMessage coapMessage; + private ChannelBuffer partialPayload; + private int nextBlockNumber = 0; + + public BlockwiseTransfer(CoapMessage coapMessage, ChannelBuffer partialPayload){ + this.coapMessage = coapMessage; + this.partialPayload = partialPayload; + } + + public CoapMessage getCoapMessage() throws InvalidHeaderException { + return coapMessage; + } + + public ChannelBuffer getPartialPayload() { + return partialPayload; + } + + public void setNextBlockNumber(int nextBlockNumber){ + this.nextBlockNumber = nextBlockNumber; + } + + public int getNextBlockNumber(){ + return this.nextBlockNumber; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `de.uniluebeck.itm.spitfire.nCoap.communication.blockwise.BlockwiseTransferHandler.messageReceived` indirectly reads with synchronization from `response.de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage.payload`. Potentially races with unsynchronized write in method `BlockwiseTransferHandler.messageReceived(...)`. + Reporting because this access may occur on a background thread. + +Note that the prefix path response has been contaminated during the execution, so the reported race on response.de.uniluebeck.itm.spitfire.nCoap.message.CoapMessage.payload might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockwiseTransferHandler.messageReceived(ChannelHandlerContext,MessageEvent) + +### Procedure Id: +de.uniluebeck.itm.spitfire.nCoap.communication.blockwise.BlockwiseTransferHandler.messageReceived(or.34a7450d3fa81d4a967b1800e6cae7ad + +### File: +src/main/java/de/uniluebeck/itm/spitfire/nCoap/communication/blockwise/BlockwiseTransferHandler.java + +### Key: +BlockwiseTransferHandler.java|messageReceived|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +194d30cbec765ce984ce867e789ce682 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7572/instruction.md b/inferredbugs-7572/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7b32202025a41e9afd5f8d1768b6b63eb150b7e --- /dev/null +++ b/inferredbugs-7572/instruction.md @@ -0,0 +1,233 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cassandra-lucene-index +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Stratio. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.stratio.cassandra.lucene.service; + +import com.google.common.collect.Sets; +import com.stratio.cassandra.lucene.IndexConfig; +import org.apache.lucene.analysis.standard.StandardAnalyzer; +import org.apache.lucene.document.Document; +import org.apache.lucene.document.Field; +import org.apache.lucene.document.SortedDocValuesField; +import org.apache.lucene.document.StringField; +import org.apache.lucene.index.Term; +import org.apache.lucene.search.IndexSearcher; +import org.apache.lucene.search.Query; +import org.apache.lucene.search.ScoreDoc; +import org.apache.lucene.search.SearcherManager; +import org.apache.lucene.search.Sort; +import org.apache.lucene.search.SortField; +import org.apache.lucene.search.TermQuery; +import org.apache.lucene.search.WildcardQuery; +import org.apache.lucene.util.BytesRef; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import static junit.framework.Assert.assertEquals; + +/** + * @author Andres de la Pena {@literal } + */ +public class LuceneIndexTest { + + private static final Double REFRESH_SECONDS = 0.1D; + private static final int REFRESH_MILLISECONDS = (int) (REFRESH_SECONDS * 1000); + private static final int WAIT_MILLISECONDS = REFRESH_MILLISECONDS * 2; + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + @Test + public void testCRUD() throws IOException, InterruptedException { + + Path path = Paths.get(folder.newFolder("directory" + UUID.randomUUID()).getPath()); + LuceneIndex index = new LuceneIndex("ks", + "cf", + "idx", + path, + IndexConfig.DEFAULT_RAM_BUFFER_MB, + IndexConfig.DEFAULT_MAX_MERGE_MB, + IndexConfig.DEFAULT_MAX_CACHED_MB, + new StandardAnalyzer(), + REFRESH_SECONDS, + null); + Sort sort = new Sort(new SortField("field", SortField.Type.STRING)); + index.init(sort); + assertEquals(0, index.getNumDocs()); + + Term term1 = new Term("field", "value1"); + Document document1 = new Document(); + document1.add(new StringField("field", "value1", Field.Store.NO)); + document1.add(new SortedDocValuesField("field", new BytesRef("value1"))); + index.upsert(term1, document1); + + Term term2 = new Term("field", "value2"); + Document document2 = new Document(); + document2.add(new StringField("field", "value2", Field.Store.NO)); + document2.add(new SortedDocValuesField("field", new BytesRef("value2"))); + index.upsert(term2, document2); + + index.commit(); + Thread.sleep(REFRESH_MILLISECONDS); + assertEquals(2, index.getNumDocs()); + + Query query = new WildcardQuery(new Term("field", "value*")); + Set fields = Sets.newHashSet("field"); + Map results; + + // Search + SearcherManager searcherManager = index.getSearcherManager(); + IndexSearcher searcher = searcherManager.acquire(); + + try { + results = index.search(searcher, query, null, null, 1, fields, true); + assertEquals(1, results.size()); + ScoreDoc last1 = results.values().iterator().next(); + results = index.search(searcher, query, null, last1, 1, fields, true); + assertEquals(1, results.size()); + + results = index.search(searcher, query, null, null, 1, fields, false); + assertEquals(1, results.size()); + ScoreDoc last2 = results.values().iterator().next(); + results = index.search(searcher, query, null, last2, 1, fields, false); + assertEquals(1, results.size()); + + results = index.search(searcher, query, sort, null, 1, fields, false); + assertEquals(1, results.size()); + ScoreDoc last3 = results.values().iterator().next(); + results = index.search(searcher, query, sort, last3, 1, fields, false); + assertEquals(1, results.size()); + } finally { + searcherManager.release(searcher); + } + + // Delete by term + index.delete(term1); + index.commit(); + Thread.sleep(WAIT_MILLISECONDS); + assertEquals(1, index.getNumDocs()); + + // Delete by query + index.upsert(term1, document1); + index.commit(); + Thread.sleep(WAIT_MILLISECONDS); + assertEquals(2, index.getNumDocs()); + index.delete(new TermQuery(term1)); + Thread.sleep(WAIT_MILLISECONDS); + assertEquals(1, index.getNumDocs()); + + // Upsert + index.upsert(term1, document1); + index.upsert(term2, document2); + index.upsert(term2, document2); + index.commit(); + Thread.sleep(WAIT_MILLISECONDS); + assertEquals(2, index.getNumDocs()); + + // Truncate + index.truncate(); + index.commit(); + Thread.sleep(WAIT_MILLISECONDS); + assertEquals(0, index.getNumDocs()); + + // Delete + index.delete(); + + // Cleanup + folder.delete(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.lucene.search.ControlledRealTimeReopenThread` acquired by call to `init(...)` at line 75 is not released after line 154. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LuceneIndexTest.testCRUD() + +### Procedure Id: +com.stratio.cassandra.lucene.service.LuceneIndexTest.testCRUD():void.1bbcb2907f29e6698142797f4ed9a5bb + +### File: +plugin/src/test/java/com/stratio/cassandra/lucene/service/LuceneIndexTest.java + +### Key: +LuceneIndexTest.java|testCRUD|RESOURCE_LEAK + +### Node Key: +51cbdc235541c090ef1fc6256c2c0426 + +### Hash: +49e41ce0af557820b53912b147735553 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7573/instruction.md b/inferredbugs-7573/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce6b0d1782a77d1b05352ada56a736c558dca9ba --- /dev/null +++ b/inferredbugs-7573/instruction.md @@ -0,0 +1,381 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cassandra-lucene-index +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Stratio. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.stratio.cassandra.lucene.schema; + +import com.stratio.cassandra.lucene.schema.analysis.PreBuiltAnalyzers; +import com.stratio.cassandra.lucene.schema.mapping.ColumnMapper; +import com.stratio.cassandra.lucene.schema.mapping.ColumnMapperInteger; +import com.stratio.cassandra.lucene.schema.mapping.ColumnMapperText; +import com.stratio.cassandra.lucene.schema.mapping.builder.ColumnMapperBuilder; +import com.stratio.cassandra.lucene.schema.mapping.builder.ColumnMapperIntegerBuilder; +import com.stratio.cassandra.lucene.schema.mapping.builder.ColumnMapperStringBuilder; +import com.stratio.cassandra.lucene.util.JsonSerializer; +import org.apache.cassandra.config.CFMetaData; +import org.apache.cassandra.db.marshal.AsciiType; +import org.apache.cassandra.db.marshal.IntegerType; +import org.apache.cassandra.db.marshal.LongType; +import org.apache.cassandra.db.marshal.UTF8Type; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.cassandra.exceptions.InvalidRequestException; +import org.apache.cassandra.thrift.CfDef; +import org.apache.cassandra.thrift.ColumnDef; +import org.apache.cassandra.thrift.IndexType; +import org.apache.cassandra.utils.ByteBufferUtil; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.en.EnglishAnalyzer; +import org.apache.lucene.analysis.es.SpanishAnalyzer; +import org.apache.lucene.document.Document; +import org.codehaus.jackson.map.JsonMappingException; +import org.junit.Test; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.*; + +/** + * @author Andres de la Pena + */ +public class SchemaTest { + + @Test + public void testGetDefaultAnalyzer() { + Map columnMappers = new HashMap<>(); + Schema schema = new Schema(columnMappers, null, "English"); + Analyzer analyzer = schema.getDefaultAnalyzer(); + assertEquals(EnglishAnalyzer.class, analyzer.getClass()); + schema.close(); + } + + @Test + public void testGetDefaultAnalyzerNotSpecified() { + Map columnMappers = new HashMap<>(); + Schema schema = new Schema(columnMappers, null, null); + Analyzer analyzer = schema.getDefaultAnalyzer(); + assertEquals(PreBuiltAnalyzers.DEFAULT.get(), analyzer); + schema.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetAnalyzerNotExistent() { + Map columnMappers = new HashMap<>(); + Schema schema = new Schema(columnMappers, null, "English"); + schema.getAnalyzer("custom"); + schema.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetAnalyzerNull() { + Map columnMappers = new HashMap<>(); + Schema schema = new Schema(columnMappers, null, "English"); + schema.getAnalyzer(null); + schema.close(); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetAnalyzerEmpty() { + Map columnMappers = new HashMap<>(); + Schema schema = new Schema(columnMappers, null, "English"); + schema.getAnalyzer(" \t"); + schema.close(); + } + + @Test + public void testParseJSON() throws IOException { + + String json = "{" + + " analyzers:{" + + " spanish_analyzer : {type:\"classpath\", " + + " class:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_analyzer : {type:\"snowball\", " + + " language:\"Spanish\", " + + " stopwords : \"el,la,lo,loas,las,a,ante,bajo,cabe,con,contra\"}" + + " }," + + " default_analyzer : \"spanish_analyzer\"," + + " fields : {" + + " id : {type : \"integer\"}," + + " spanish_text : {type:\"text\", analyzer:\"spanish_analyzer\"}," + + " snowball_text : {type:\"text\", analyzer:\"snowball_analyzer\"}" + + " }" + + " }'"; + + Schema schema = JsonSerializer.fromString(json, Schema.class); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertTrue(defaultAnalyzer instanceof SpanishAnalyzer); + + Analyzer spanishAnalyzer = schema.getAnalyzer("spanish_analyzer"); + assertTrue(spanishAnalyzer instanceof SpanishAnalyzer); + + ColumnMapper idMapper = schema.getMapper("id"); + assertTrue(idMapper instanceof ColumnMapperInteger); + + ColumnMapper spanishMapper = schema.getMapper("spanish_text"); + assertTrue(spanishMapper instanceof ColumnMapperText); + assertEquals("spanish_analyzer", spanishMapper.getAnalyzer()); + + ColumnMapper snowballMapper = schema.getMapper("snowball_text"); + assertTrue(snowballMapper instanceof ColumnMapperText); + assertEquals("snowball_analyzer", snowballMapper.getAnalyzer()); + + schema.close(); + } + + @Test + public void testParseJSONWithNullAnalyzers() throws IOException { + + String json = "{" + + " default_analyzer : \"org.apache.lucene.analysis.en.EnglishAnalyzer\"," + + " fields : {" + + " id : {type : \"integer\"}," + + " spanish_text : {" + + " type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_text : {" + + " type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}" + + " }" + + " }'"; + + Schema schema = JsonSerializer.fromString(json, Schema.class); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertTrue(defaultAnalyzer instanceof EnglishAnalyzer); + + ColumnMapper idMapper = schema.getMapper("id"); + assertTrue(idMapper instanceof ColumnMapperInteger); + + ColumnMapper spanishMapper = schema.getMapper("spanish_text"); + assertTrue(spanishMapper instanceof ColumnMapperText); + assertEquals(SpanishAnalyzer.class.getName(), spanishMapper.getAnalyzer()); + + ColumnMapper snowballMapper = schema.getMapper("snowball_text"); + assertTrue(snowballMapper instanceof ColumnMapperText); + assertEquals(EnglishAnalyzer.class.getName(), snowballMapper.getAnalyzer()); + + schema.close(); + } + + @Test + public void testParseJSONWithEmptyAnalyzers() throws IOException { + + String json = "{" + + " analyzers:{}, " + + " default_analyzer : \"org.apache.lucene.analysis.en.EnglishAnalyzer\"," + + " fields : {" + + " id : {type : \"integer\"}," + + " spanish_text : {type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_text : {type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}" + + " }" + + " }'"; + + Schema schema = JsonSerializer.fromString(json, Schema.class); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertTrue(defaultAnalyzer instanceof EnglishAnalyzer); + + ColumnMapper idMapper = schema.getMapper("id"); + assertEquals(ColumnMapperInteger.class, idMapper.getClass()); + + ColumnMapper spanishMapper = schema.getMapper("spanish_text"); + assertTrue(spanishMapper instanceof ColumnMapperText); + assertEquals(SpanishAnalyzer.class.getName(), spanishMapper.getAnalyzer()); + + ColumnMapper snowballMapper = schema.getMapper("snowball_text"); + assertTrue(snowballMapper instanceof ColumnMapperText); + assertEquals(EnglishAnalyzer.class.getName(), snowballMapper.getAnalyzer()); + + schema.close(); + } + + @Test + public void testParseJSONWithNullDefaultAnalyzer() throws IOException { + + String json = "{" + + " analyzers:{" + + " spanish_analyzer : {" + + " type:\"classpath\", " + + " class:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_analyzer : {" + + " type:\"snowball\", " + + " language:\"Spanish\", " + + " stopwords : \"el,la,lo,lo,as,las,a,ante,con,contra\"}" + + " }," + + " fields : { id : {type : \"integer\"} }" + + " }'"; + + Schema schema = JsonSerializer.fromString(json, Schema.class); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertEquals(PreBuiltAnalyzers.DEFAULT.get(), defaultAnalyzer); + + Analyzer spanishAnalyzer = schema.getAnalyzer("spanish_analyzer"); + assertTrue(spanishAnalyzer instanceof SpanishAnalyzer); + + schema.close(); + } + + @Test(expected = JsonMappingException.class) + public void testParseJSONWithFailingDefaultAnalyzer() throws IOException { + String json = "{default_analyzer : \"xyz\", fields : { id : {type : \"integer\"} } }'"; + JsonSerializer.fromString(json, Schema.class); + } + + @Test + public void testAddColumns() { + + ColumnMapperBuilder columnMapper1 = new ColumnMapperStringBuilder(); + ColumnMapperBuilder columnMapper2 = new ColumnMapperIntegerBuilder(); + + Map columnMappers = new HashMap<>(); + columnMappers.put("field1", columnMapper1); + columnMappers.put("field2", columnMapper2); + + Schema schema = new Schema(columnMappers, null, null); + + Columns columns = new Columns().add(Column.fromComposed("field1", "value", UTF8Type.instance, false)) + .add(Column.fromComposed("field2", 1L, LongType.instance, false)); + + Document document = new Document(); + schema.addFields(document, columns); + assertEquals(4, document.getFields().size()); + assertEquals(2, document.getFields("field1").length); + assertEquals(2, document.getFields("field2").length); + + schema.close(); + } + + @Test + public void testValidate() throws InvalidRequestException, ConfigurationException { + + List columnDefinitions = new ArrayList<>(); + columnDefinitions.add(new ColumnDef(ByteBufferUtil.bytes("field1"), + UTF8Type.class.getCanonicalName()).setIndex_name("field1") + .setIndex_type(IndexType.KEYS)); + + columnDefinitions.add(new ColumnDef(ByteBufferUtil.bytes("field2"), + IntegerType.class.getCanonicalName()).setIndex_name("field2") + .setIndex_type(IndexType.KEYS)); + CfDef cfDef = new CfDef().setDefault_validation_class(AsciiType.class.getCanonicalName()) + .setColumn_metadata(columnDefinitions) + .setKeyspace("Keyspace1") + .setName("Standard1"); + CFMetaData metadata = CFMetaData.fromThrift(cfDef); + + ColumnMapperBuilder columnMapper1 = new ColumnMapperStringBuilder(); + ColumnMapperBuilder columnMapper2 = new ColumnMapperIntegerBuilder(); + + Map columnMappers = new HashMap<>(); + columnMappers.put("field1", columnMapper1); + columnMappers.put("field2", columnMapper2); + + Schema schema = new Schema(columnMappers, null, null); + schema.validate(metadata); + } + + @Test + public void testToString() { + + ColumnMapperBuilder columnMapper1 = new ColumnMapperStringBuilder(); + ColumnMapperBuilder columnMapper2 = new ColumnMapperIntegerBuilder(); + + Map columnMappers = new HashMap<>(); + columnMappers.put("field1", columnMapper1); + columnMappers.put("field2", columnMapper2); + + Schema schema = new Schema(columnMappers, null, null); + assertNotNull(schema.toString()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper` acquired by call to `Schema(...)` at line 304 is not released after line 305. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SchemaTest.testToString() + +### Procedure Id: +com.stratio.cassandra.lucene.schema.SchemaTest.testToString():void.7aab73bb822f2b30ed85bf87d52b3402 + +### File: +src/test/java/com/stratio/cassandra/lucene/schema/SchemaTest.java + +### Key: +SchemaTest.java|testToString|RESOURCE_LEAK + +### Node Key: +42ab969312eb9d1b9b64961488901c68 + +### Hash: +dd602430ad39a31b575710a9d2bef19d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7574/instruction.md b/inferredbugs-7574/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9308b6a9228e937155aaa0096d0c4de452cbbe38 --- /dev/null +++ b/inferredbugs-7574/instruction.md @@ -0,0 +1,354 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** cassandra-lucene-index +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015, Stratio. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.stratio.cassandra.lucene.schema; + +import com.stratio.cassandra.lucene.IndexException; +import com.stratio.cassandra.lucene.schema.analysis.PreBuiltAnalyzers; +import com.stratio.cassandra.lucene.schema.analysis.SnowballAnalyzerBuilder.SnowballAnalyzer; +import com.stratio.cassandra.lucene.schema.mapping.*; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.en.EnglishAnalyzer; +import org.apache.lucene.analysis.es.SpanishAnalyzer; +import org.junit.Test; + +import java.io.IOException; + +import static com.stratio.cassandra.lucene.schema.SchemaBuilders.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * @author Andres de la Pena {@literal } + */ +public class SchemaBuilderTest { + + @Test + public void testBuild() throws Exception { + Schema schema = schema().defaultAnalyzer("custom") + .analyzer("custom", classpathAnalyzer("org.apache.lucene.analysis.en.EnglishAnalyzer")) + .analyzer("snowball", snowballAnalyzer("English", "the,at")) + .mapper("big_int", bigIntegerMapper().digits(10)) + .mapper("big_dec", bigDecimalMapper().indexed(false).sorted(true)) + .mapper("bitemporal", bitemporalMapper("vt_from", "vt_to", "tt_from", "tt_to")) + .mapper("blob", blobMapper()) + .mapper("bool", booleanMapper()) + .mapper("date", dateMapper()) + .mapper("date_range", dateRangeMapper("from", "to")) + .mapper("double", doubleMapper()) + .mapper("float", floatMapper()) + .mapper("geo", geoPointMapper("lat", "lon")) + .mapper("inet", inetMapper()) + .mapper("int", integerMapper().boost(0.3f)) + .mapper("long", longMapper()) + .mapper("string", stringMapper()) + .mapper("text", textMapper()) + .mapper("uuid", uuidMapper()) + .build(); + assertEquals("Failed schema building", EnglishAnalyzer.class, schema.getDefaultAnalyzer().getClass()); + assertEquals("Failed schema building", EnglishAnalyzer.class, schema.getAnalyzer("custom").getClass()); + assertEquals("Failed schema building", SnowballAnalyzer.class, schema.getAnalyzer("snowball").getClass()); + assertEquals("Failed schema building", BigIntegerMapper.class, schema.getMapper("big_int").getClass()); + assertEquals("Failed schema building", BigDecimalMapper.class, schema.getMapper("big_dec").getClass()); + assertEquals("Failed schema building", BitemporalMapper.class, schema.getMapper("bitemporal").getClass()); + assertEquals("Failed schema building", BlobMapper.class, schema.getMapper("blob").getClass()); + assertEquals("Failed schema building", BooleanMapper.class, schema.getMapper("bool").getClass()); + assertEquals("Failed schema building", DateMapper.class, schema.getMapper("date").getClass()); + assertEquals("Failed schema building", DateRangeMapper.class, schema.getMapper("date_range").getClass()); + assertEquals("Failed schema building", DoubleMapper.class, schema.getMapper("double").getClass()); + assertEquals("Failed schema building", FloatMapper.class, schema.getMapper("float").getClass()); + assertEquals("Failed schema building", GeoPointMapper.class, schema.getMapper("geo").getClass()); + assertEquals("Failed schema building", InetMapper.class, schema.getMapper("inet").getClass()); + assertEquals("Failed schema building", IntegerMapper.class, schema.getMapper("int").getClass()); + assertEquals("Failed schema building", LongMapper.class, schema.getMapper("long").getClass()); + assertEquals("Failed schema building", StringMapper.class, schema.getMapper("string").getClass()); + assertEquals("Failed schema building", TextMapper.class, schema.getMapper("text").getClass()); + assertEquals("Failed schema building", UUIDMapper.class, schema.getMapper("uuid").getClass()); + } + + @Test + public void testToJson() throws IOException { + String json = schema().defaultAnalyzer("custom") + .analyzer("custom", classpathAnalyzer("org.apache.lucene.analysis.en.EnglishAnalyzer")) + .analyzer("snowball", snowballAnalyzer("English", "the,at")) + .mapper("big_int", bigIntegerMapper().digits(10)) + .mapper("big_dec", bigDecimalMapper().indexed(false).sorted(true)) + .mapper("bitemporal", bitemporalMapper("vtFrom", "vtTo", "ttFrom", "ttTo")) + .mapper("blob", blobMapper()) + .mapper("bool", booleanMapper()) + .mapper("date", dateMapper()) + .mapper("date_range", dateRangeMapper("from", "to")) + .mapper("double", doubleMapper()) + .mapper("float", floatMapper()) + .mapper("geo", geoPointMapper("lat", "lon")) + .mapper("inet", inetMapper()) + .mapper("int", integerMapper().boost(0.3f)) + .mapper("long", longMapper()) + .mapper("string", stringMapper()) + .mapper("text", textMapper()) + .mapper("uuid", uuidMapper()) + .toJson(); + String expectedJson = "{default_analyzer:\"custom\"," + + "analyzers:{" + + "custom:{type:\"classpath\",class:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}," + + "snowball:{type:\"snowball\",language:\"English\",stopwords:\"the,at\"}}," + + "fields:" + + "{big_int:{type:\"bigint\",digits:10}," + + "big_dec:{type:\"bigdec\",indexed:false,sorted:true}," + + "bitemporal:{type:\"bitemporal\"," + + "vt_from:\"vtFrom\",vt_to:\"vtTo\",tt_from:\"ttFrom\",tt_to:\"ttTo\"}," + + "blob:{type:\"bytes\"}," + + "bool:{type:\"boolean\"}," + + "date:{type:\"date\"}," + + "date_range:{type:\"date_range\",from:\"from\",to:\"to\"}," + + "double:{type:\"double\"}," + + "float:{type:\"float\"}," + + "geo:{type:\"geo_point\",latitude:\"lat\",longitude:\"lon\"}," + + "inet:{type:\"inet\"}," + + "int:{type:\"integer\",boost:0.3}," + + "long:{type:\"long\"}," + + "string:{type:\"string\"}," + + "text:{type:\"text\"}," + + "uuid:{type:\"uuid\"}}}"; + assertEquals("Failed schema JSON serialization", expectedJson, json); + } + + @Test + public void testFromJson() throws IOException { + String json = "{analyzers:{" + + "custom:{type:\"classpath\",class:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}," + + "snowball:{type:\"snowball\",language:\"English\",stopwords:\"the,at\"}}," + + "default_analyzer:\"custom\"," + + "fields:" + + "{big_int:{type:\"bigint\",digits:10}," + + "big_dec:{type:\"bigdec\",indexed:false,sorted:true}," + + "bitemporal:{type:\"bitemporal\",vt_from:\"vtFrom\",vt_to:\"vtTo\",tt_from:\"ttFrom\",tt_to:\"ttTo\"}," + + "blob:{type:\"bytes\"}," + + "bool:{type:\"boolean\"}," + + "date:{type:\"date\"}," + + "date_range:{type:\"date_range\",from:\"from\",to:\"to\"}," + + "double:{type:\"double\"}," + + "float:{type:\"float\"}," + + "geo:{type:\"geo_point\",latitude:\"lat\",longitude:\"lon\"}," + + "inet:{type:\"inet\"}," + + "int:{type:\"integer\",boost:0.3}," + + "long:{type:\"long\"}," + + "string:{type:\"string\"}," + + "text:{type:\"text\"}," + + "uuid:{type:\"uuid\"}}}"; + Schema schema = SchemaBuilder.fromJson(json).build(); + assertEquals("Failed schema JSON parsing", EnglishAnalyzer.class, schema.getDefaultAnalyzer().getClass()); + assertEquals("Failed schema JSON parsing", EnglishAnalyzer.class, schema.getAnalyzer("custom").getClass()); + assertEquals("Failed schema JSON parsing", SnowballAnalyzer.class, schema.getAnalyzer("snowball").getClass()); + assertEquals("Failed schema JSON parsing", BigIntegerMapper.class, schema.getMapper("big_int").getClass()); + assertEquals("Failed schema JSON parsing", BigDecimalMapper.class, schema.getMapper("big_dec").getClass()); + assertEquals("Failed schema JSON parsing", BitemporalMapper.class, schema.getMapper("bitemporal").getClass()); + assertEquals("Failed schema JSON parsing", BlobMapper.class, schema.getMapper("blob").getClass()); + assertEquals("Failed schema JSON parsing", BooleanMapper.class, schema.getMapper("bool").getClass()); + assertEquals("Failed schema JSON parsing", DateMapper.class, schema.getMapper("date").getClass()); + assertEquals("Failed schema JSON parsing", DateRangeMapper.class, schema.getMapper("date_range").getClass()); + assertEquals("Failed schema JSON parsing", DoubleMapper.class, schema.getMapper("double").getClass()); + assertEquals("Failed schema JSON parsing", FloatMapper.class, schema.getMapper("float").getClass()); + assertEquals("Failed schema JSON parsing", GeoPointMapper.class, schema.getMapper("geo").getClass()); + assertEquals("Failed schema JSON parsing", InetMapper.class, schema.getMapper("inet").getClass()); + assertEquals("Failed schema JSON parsing", IntegerMapper.class, schema.getMapper("int").getClass()); + assertEquals("Failed schema JSON parsing", LongMapper.class, schema.getMapper("long").getClass()); + assertEquals("Failed schema JSON parsing", StringMapper.class, schema.getMapper("string").getClass()); + assertEquals("Failed schema JSON parsing", TextMapper.class, schema.getMapper("text").getClass()); + assertEquals("Failed schema JSON parsing", UUIDMapper.class, schema.getMapper("uuid").getClass()); + } + + @Test + public void testFromJSONWithNullAnalyzers() throws IOException { + + String json = "{" + + " default_analyzer : \"org.apache.lucene.analysis.en.EnglishAnalyzer\"," + + " fields : {" + + " id : {type : \"integer\"}," + + " spanish_text : {" + + " type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_text : {" + + " type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}," + + " default_text : { type:\"text\"}" + + " }" + + " }'"; + + Schema schema = SchemaBuilder.fromJson(json).build(); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertTrue("Expected english analyzer", defaultAnalyzer instanceof EnglishAnalyzer); + + Mapper idMapper = schema.getMapper("id"); + assertTrue("Expected IntegerMapper", idMapper instanceof IntegerMapper); + + Mapper spanishMapper = schema.getMapper("spanish_text"); + assertTrue("Expected TextMapper", spanishMapper instanceof TextMapper); + assertEquals("Expected spanish analyzer", SpanishAnalyzer.class.getName(), spanishMapper.analyzer); + + Mapper snowballMapper = schema.getMapper("snowball_text"); + assertTrue("Expected TextMapper", snowballMapper instanceof TextMapper); + assertEquals("Expected english analyzer", EnglishAnalyzer.class.getName(), snowballMapper.analyzer); + + Mapper defaultMapper = schema.getMapper("default_text"); + assertTrue("Expected TextMapper", defaultMapper instanceof TextMapper); + assertEquals("Expected english analyzer", EnglishAnalyzer.class.getName(), snowballMapper.analyzer); + + schema.close(); + } + + @Test + public void testFromJSONWithEmptyAnalyzers() throws IOException { + + String json = "{" + + " analyzers:{}, " + + " default_analyzer : \"org.apache.lucene.analysis.en.EnglishAnalyzer\"," + + " fields : {" + + " id : {type : \"integer\"}," + + " spanish_text : {type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_text : {type:\"text\", " + + " analyzer:\"org.apache.lucene.analysis.en.EnglishAnalyzer\"}" + + " }" + + " }'"; + Schema schema = SchemaBuilder.fromJson(json).build(); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertTrue("Expected EnglishAnalyzer", defaultAnalyzer instanceof EnglishAnalyzer); + + Mapper idMapper = schema.getMapper("id"); + assertEquals("Expected IntegerMapper", IntegerMapper.class, idMapper.getClass()); + + Mapper spanishMapper = schema.getMapper("spanish_text"); + assertTrue(spanishMapper instanceof TextMapper); + assertEquals("Expected SpanishAnalyzer", SpanishAnalyzer.class.getName(), spanishMapper.analyzer); + + Mapper snowballMapper = schema.getMapper("snowball_text"); + assertTrue(snowballMapper instanceof TextMapper); + assertEquals("Expected EnglishAnalyzer", EnglishAnalyzer.class.getName(), snowballMapper.analyzer); + + schema.close(); + } + + @Test + public void testParseJSONWithNullDefaultAnalyzer() throws IOException { + + String json = "{" + + " analyzers:{" + + " spanish_analyzer : {" + + " type:\"classpath\", " + + " class:\"org.apache.lucene.analysis.es.SpanishAnalyzer\"}," + + " snowball_analyzer : {" + + " type:\"snowball\", " + + " language:\"Spanish\", " + + " stopwords : \"el,la,lo,lo,as,las,a,ante,con,contra\"}" + + " }," + + " fields : { id : {type : \"integer\"} }" + + " }'"; + Schema schema = SchemaBuilder.fromJson(json).build(); + + Analyzer defaultAnalyzer = schema.getDefaultAnalyzer(); + assertEquals("Expected default analyzer", + PreBuiltAnalyzers.DEFAULT.get().getClass(), + defaultAnalyzer.getClass()); + + Analyzer spanishAnalyzer = schema.getAnalyzer("spanish_analyzer"); + assertTrue("Expected SpanishAnalyzer", spanishAnalyzer instanceof SpanishAnalyzer); + + schema.close(); + } + + @Test(expected = IndexException.class) + public void testParseJSONWithFailingDefaultAnalyzer() throws IOException { + String json = "{default_analyzer : \"xyz\", fields : { id : {type : \"integer\"} } }'"; + SchemaBuilder.fromJson(json).build(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `schema.getDefaultAnalyzer()` could be null and is dereferenced at line 153. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SchemaBuilderTest.testFromJson() + +### Procedure Id: +com.stratio.cassandra.lucene.schema.SchemaBuilderTest.testFromJson():void.eb6acb956016852d73345f0284821863 + +### File: +plugin/src/test/java/com/stratio/cassandra/lucene/schema/SchemaBuilderTest.java + +### Key: +SchemaBuilderTest.java|testFromJson|NULL_DEREFERENCE + +### Node Key: +aa66545b443e053e1949db82c636558b + +### Hash: +0922092f66cd773c5f00935e4902dba0 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7580/instruction.md b/inferredbugs-7580/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b388911a1795c2a270f9afc89bd6807e3c96c4bf --- /dev/null +++ b/inferredbugs-7580/instruction.md @@ -0,0 +1,291 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0 + */ +package de.rub.nds.tlsattacker.tls.protocol.handshake; + +import de.rub.nds.tlsattacker.tls.constants.HandshakeByteLength; +import de.rub.nds.tlsattacker.tls.constants.CipherSuite; +import de.rub.nds.tlsattacker.tls.constants.HandshakeMessageType; +import de.rub.nds.tlsattacker.tls.constants.ProtocolVersion; +import de.rub.nds.tlsattacker.tls.exceptions.InvalidMessageTypeException; +import de.rub.nds.tlsattacker.tls.constants.ExtensionByteLength; +import de.rub.nds.tlsattacker.tls.constants.ExtensionType; +import de.rub.nds.tlsattacker.tls.protocol.extension.ExtensionHandler; +import de.rub.nds.tlsattacker.tls.constants.CompressionMethod; +import de.rub.nds.tlsattacker.tls.constants.RecordByteLength; +import de.rub.nds.tlsattacker.tls.exceptions.UnknownCiphersuiteException; +import de.rub.nds.tlsattacker.tls.exceptions.WorkflowExecutionException; +import de.rub.nds.tlsattacker.tls.protocol.extension.ExtensionMessage; +import de.rub.nds.tlsattacker.tls.workflow.TlsContext; +import de.rub.nds.tlsattacker.util.ArrayConverter; +import de.rub.nds.tlsattacker.util.RandomHelper; +import de.rub.nds.tlsattacker.util.Time; +import java.util.Arrays; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * @author Juraj Somorovsky + * @author Philip Riese + */ +public class ServerHelloHandler extends HandshakeMessageHandler { + + private static final Logger LOGGER = LogManager.getLogger(ServerHelloMessage.class); + + public ServerHelloHandler(TlsContext tlsContext) { + super(tlsContext); + this.correctProtocolMessageClass = ServerHelloMessage.class; + } + + /** + * @param message + * @param pointer + * @return + */ + @Override + public int parseMessageAction(byte[] message, int pointer) { + if (message[pointer] != HandshakeMessageType.SERVER_HELLO.getValue()) { + throw new InvalidMessageTypeException("This is not a server hello message"); + } + protocolMessage.setType(message[pointer]); + + int currentPointer = pointer + HandshakeByteLength.MESSAGE_TYPE; + int nextPointer = currentPointer + HandshakeByteLength.MESSAGE_TYPE_LENGTH; + int length = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setLength(length); + + currentPointer = nextPointer; + nextPointer = currentPointer + RecordByteLength.PROTOCOL_VERSION; + ProtocolVersion serverProtocolVersion = ProtocolVersion.getProtocolVersion(Arrays.copyOfRange(message, + currentPointer, nextPointer)); + protocolMessage.setProtocolVersion(serverProtocolVersion.getValue()); + + currentPointer = nextPointer; + nextPointer = currentPointer + HandshakeByteLength.UNIX_TIME; + byte[] serverUnixTime = Arrays.copyOfRange(message, currentPointer, nextPointer); + protocolMessage.setUnixTime(serverUnixTime); + // System.out.println(new + // Date(ArrayConverter.bytesToLong(serverUnixTime) * 1000)); + + currentPointer = nextPointer; + nextPointer = currentPointer + HandshakeByteLength.RANDOM; + byte[] serverRandom = Arrays.copyOfRange(message, currentPointer, nextPointer); + protocolMessage.setRandom(serverRandom); + + tlsContext.setServerRandom(ArrayConverter.concatenate(protocolMessage.getUnixTime().getValue(), protocolMessage + .getRandom().getValue())); + + currentPointer = nextPointer; + int sessionIdLength = message[currentPointer] & 0xFF; + currentPointer = currentPointer + HandshakeByteLength.SESSION_ID_LENGTH; + nextPointer = currentPointer + sessionIdLength; + byte[] sessionId = Arrays.copyOfRange(message, currentPointer, nextPointer); + protocolMessage.setSessionId(sessionId); + + // handle unknown SessionID during Session resumption + if (tlsContext.isSessionResumption() + && !(Arrays.equals(tlsContext.getSessionID(), protocolMessage.getSessionId().getValue()))) { + throw new WorkflowExecutionException("Session ID is unknown to the Client"); + } + + tlsContext.setSessionID(sessionId); + + currentPointer = nextPointer; + nextPointer = currentPointer + HandshakeByteLength.CIPHER_SUITE; + CipherSuite selectedCipher; + try { + selectedCipher = CipherSuite.getCipherSuite(Arrays.copyOfRange(message, currentPointer, nextPointer)); + } catch (UnknownCiphersuiteException ex) { + LOGGER.error(ex.getLocalizedMessage()); + LOGGER.debug(ex.getLocalizedMessage(), ex); + selectedCipher = CipherSuite.TLS_UNKNOWN_CIPHER; + } + // System.out.println(selectedCipher); + protocolMessage.setSelectedCipherSuite(selectedCipher.getByteValue()); + + tlsContext.setSelectedCipherSuite(CipherSuite.getCipherSuite(protocolMessage.getSelectedCipherSuite() + .getValue())); + tlsContext.setProtocolVersion(serverProtocolVersion); + tlsContext.initiliazeTlsMessageDigest(); + + currentPointer = nextPointer; + byte compression = message[currentPointer]; + currentPointer += HandshakeByteLength.COMPRESSION; + protocolMessage.setSelectedCompressionMethod(compression); + + tlsContext.setCompressionMethod(CompressionMethod.getCompressionMethod(protocolMessage + .getSelectedCompressionMethod().getValue())); + + if ((currentPointer - pointer) < length) { + currentPointer += ExtensionByteLength.EXTENSIONS; + while ((currentPointer - pointer) < length) { + nextPointer = currentPointer + ExtensionByteLength.TYPE; + byte[] extensionType = Arrays.copyOfRange(message, currentPointer, nextPointer); + // Not implemented/unknown extensions will generate an Exception + // ... + try { + ExtensionHandler eh = ExtensionType.getExtensionType(extensionType).getExtensionHandler(); + currentPointer = eh.parseExtension(message, currentPointer); + protocolMessage.addExtension(eh.getExtensionMessage()); + } // ... which we catch, then disregard that extension and carry + // on. + catch (Exception ex) { + currentPointer = nextPointer; + nextPointer += 2; + currentPointer += ArrayConverter.bytesToInt(Arrays + .copyOfRange(message, currentPointer, nextPointer)); + nextPointer += 2; + currentPointer += 2; + } + } + } + + protocolMessage.setCompleteResultingMessage(Arrays.copyOfRange(message, pointer, currentPointer)); + + return currentPointer; + } + + @Override + public byte[] prepareMessageAction() { + protocolMessage.setProtocolVersion(tlsContext.getProtocolVersion().getValue()); + + // supporting Session Resumption with Session IDs + if (tlsContext.isSessionResumption()) { + protocolMessage.setSessionId(tlsContext.getSessionID()); + } else { + // since the server cannot handle more than one Client at once a + // static Session-ID is set + protocolMessage.setSessionId(ArrayConverter + .hexStringToByteArray("f727d526b178ecf3218027ccf8bb125d572068220000ba8c0f774ba7de9f5cdb")); + tlsContext.setSessionID(protocolMessage.getSessionId().getValue()); + } + int length = protocolMessage.getSessionId().getValue().length; + protocolMessage.setSessionIdLength(length); + + // random handling + final long unixTime = Time.getUnixTime(); + protocolMessage.setUnixTime(ArrayConverter.longToUint32Bytes(unixTime)); + + byte[] random = new byte[HandshakeByteLength.RANDOM]; + RandomHelper.getRandom().nextBytes(random); + protocolMessage.setRandom(random); + + tlsContext.setServerRandom(ArrayConverter.concatenate(protocolMessage.getUnixTime().getValue(), protocolMessage + .getRandom().getValue())); + + CipherSuite selectedCipherSuite = tlsContext.getSelectedCipherSuite(); + protocolMessage.setSelectedCipherSuite(selectedCipherSuite.getByteValue()); + tlsContext.initiliazeTlsMessageDigest(); + + CompressionMethod selectedCompressionMethod = tlsContext.getCompressionMethod(); + protocolMessage.setSelectedCompressionMethod(selectedCompressionMethod.getValue()); + + byte[] result = ArrayConverter.concatenate(protocolMessage.getProtocolVersion().getValue(), protocolMessage + .getUnixTime().getValue(), protocolMessage.getRandom().getValue(), ArrayConverter.intToBytes( + protocolMessage.getSessionIdLength().getValue(), 1), protocolMessage.getSessionId().getValue(), + protocolMessage.getSelectedCipherSuite().getValue(), new byte[] { protocolMessage + .getSelectedCompressionMethod().getValue() }); + + // extensions have to be added to the protocol message before the + // workflow trace is generated + byte[] extensionBytes = null; + for (ExtensionMessage extension : protocolMessage.getExtensions()) { + ExtensionHandler handler = extension.getExtensionHandler(); + handler.initializeClientHelloExtension(extension); + extensionBytes = ArrayConverter.concatenate(extensionBytes, extension.getExtensionBytes().getValue()); + } + + if (extensionBytes != null && extensionBytes.length != 0) { + byte[] extensionLength = ArrayConverter.intToBytes(extensionBytes.length, ExtensionByteLength.EXTENSIONS); + + result = ArrayConverter.concatenate(result, extensionLength, extensionBytes); + } + + protocolMessage.setLength(result.length); + + long header = (HandshakeMessageType.SERVER_HELLO.getValue() << 24) + protocolMessage.getLength().getValue(); + + protocolMessage.setCompleteResultingMessage(ArrayConverter.concatenate( + ArrayConverter.longToUint32Bytes(header), result)); + + return protocolMessage.getCompleteResultingMessage().getValue(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `serverProtocolVersion` last assigned on line 63 could be null and is dereferenced at line 65. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int ServerHelloHandler.parseMessageAction(byte[],int) + +### Procedure Id: +de.rub.nds.tlsattacker.tls.protocol.handshake.ServerHelloHandler.parseMessageAction(byte[],int):int.0efae2b55e7c81558ac3380a3152b89f + +### File: +TLS/src/main/java/de/rub/nds/tlsattacker/tls/protocol/handshake/ServerHelloHandler.java + +### Key: +ServerHelloHandler.java|parseMessageAction|NULL_DEREFERENCE + +### Node Key: +2ad2c69f89cd458ad84f96f60007b771 + +### Hash: +8d11f2cd07cf0a421d0aa9d783cede13 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7581/instruction.md b/inferredbugs-7581/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16851285aa1dd0bf148a620a89889ed1ac44df07 --- /dev/null +++ b/inferredbugs-7581/instruction.md @@ -0,0 +1,252 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package de.rub.nds.tlsattacker.attacks.impl; + +import de.rub.nds.tlsattacker.attacks.config.Cve20162107CommandConfig; +import de.rub.nds.tlsattacker.tls.Attacker; +import de.rub.nds.tlsattacker.modifiablevariable.VariableModification; +import de.rub.nds.tlsattacker.modifiablevariable.bytearray.ByteArrayModificationFactory; +import de.rub.nds.tlsattacker.modifiablevariable.bytearray.ModifiableByteArray; +import de.rub.nds.tlsattacker.tls.config.ConfigHandler; +import de.rub.nds.tlsattacker.tls.constants.AlertDescription; +import de.rub.nds.tlsattacker.tls.constants.AlertLevel; +import de.rub.nds.tlsattacker.tls.constants.CipherSuite; +import de.rub.nds.tlsattacker.transport.ConnectionEnd; +import de.rub.nds.tlsattacker.tls.constants.HandshakeMessageType; +import de.rub.nds.tlsattacker.tls.constants.ProtocolMessageType; +import de.rub.nds.tlsattacker.tls.constants.ProtocolVersion; +import de.rub.nds.tlsattacker.tls.exceptions.WorkflowExecutionException; +import de.rub.nds.tlsattacker.tls.protocol.ProtocolMessage; +import de.rub.nds.tlsattacker.tls.protocol.alert.AlertMessage; +import de.rub.nds.tlsattacker.tls.protocol.handshake.FinishedMessage; +import de.rub.nds.tlsattacker.tls.record.Record; +import de.rub.nds.tlsattacker.tls.util.LogLevel; +import de.rub.nds.tlsattacker.tls.workflow.TlsConfig; +import de.rub.nds.tlsattacker.tls.workflow.TlsContext; +import de.rub.nds.tlsattacker.tls.workflow.WorkflowExecutor; +import de.rub.nds.tlsattacker.tls.workflow.WorkflowTrace; +import de.rub.nds.tlsattacker.tls.workflow.action.ReceiveAction; +import de.rub.nds.tlsattacker.transport.TransportHandler; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * Tests for the availability of the OpenSSL padding oracle (CVE-2016-2107). + * + * @author Juraj Somorovsky (juraj.somorovsky@rub.de) + */ +public class Cve20162107 extends Attacker { + + private static final Logger LOGGER = LogManager.getLogger(Cve20162107.class); + + private final List lastMessages; + + public Cve20162107(Cve20162107CommandConfig config) { + super(config); + lastMessages = new LinkedList<>(); + } + + @Override + public void executeAttack(ConfigHandler configHandler) { + ProtocolVersion[] versions; + TlsConfig tlsConfig = configHandler.initialize(config); + + if (tlsConfig.getHighestProtocolVersion() == null) { + versions = new ProtocolVersion[] { ProtocolVersion.TLS10, ProtocolVersion.TLS11, ProtocolVersion.TLS12 }; + } else { + versions = new ProtocolVersion[] { tlsConfig.getHighestProtocolVersion() };// TODO + // Initialisation + // should + // be + // done + // in + // config + } + List ciphers = new LinkedList<>(); + if (tlsConfig.getSupportedCiphersuites().isEmpty()) { + for (CipherSuite cs : CipherSuite.getImplemented()) { + if (cs.isCBC()) { + ciphers.add(cs); + } + } + } else { + ciphers = tlsConfig.getSupportedCiphersuites(); + } + + for (ProtocolVersion pv : versions) { + for (CipherSuite cs : ciphers) { + tlsConfig.setHighestProtocolVersion(pv); + tlsConfig.setSupportedCiphersuites(Collections.singletonList(cs)); // TODO + // what + executeAttackRound(configHandler); + } + } + + if (vulnerable) { + LOGGER.log(LogLevel.CONSOLE_OUTPUT, "VULNERABLE"); + } else { + LOGGER.log(LogLevel.CONSOLE_OUTPUT, "NOT VULNERABLE"); + } + + LOGGER.debug("All the attack runs executed. The following messages arrived at the ends of the connections"); + for (ProtocolMessage pm : lastMessages) { + LOGGER.debug("----- NEXT TLS CONNECTION WITH MODIFIED APPLICATION DATA RECORD -----"); + LOGGER.debug("Last protocol message in the protocol flow"); + LOGGER.debug(pm.toString()); + } + } + + private void executeAttackRound(ConfigHandler configHandler) { + TlsConfig tlsConfig = configHandler.initialize(config); + LOGGER.info("Testing {}, {}", tlsConfig.getHighestProtocolVersion(), tlsConfig.getSupportedCiphersuites().get(0)); + + TransportHandler transportHandler = configHandler.initializeTransportHandler(tlsConfig); + TlsContext tlsContext = configHandler.initializeTlsContext(tlsConfig); + WorkflowExecutor workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); + + WorkflowTrace trace = tlsContext.getWorkflowTrace(); + + FinishedMessage finishedMessage = (FinishedMessage) trace + .getFirstConfiguredSendMessageOfType(HandshakeMessageType.FINISHED); + Record record = createRecordWithBadPadding(); + finishedMessage.addRecord(record); + + // Remove last two server messages (CCS and Finished). Instead of them, + // an alert will be sent. + AlertMessage alertMessage = new AlertMessage(tlsConfig); + + ReceiveAction action = (ReceiveAction) (trace.getLastMessageAction()); + List messages = new LinkedList<>(); + messages.add(alertMessage); + action.setConfiguredMessages(lastMessages); + try { + workflowExecutor.executeWorkflow(); + } catch (WorkflowExecutionException ex) { + LOGGER.info("Not possible to finalize the defined workflow: {}", ex.getLocalizedMessage()); + } + + ProtocolMessage lm = trace.getLastConfiguredReceiveMesssage(); + lastMessages.add(lm); + tlsContexts.add(tlsContext); + + if (lm.getProtocolMessageType() == ProtocolMessageType.ALERT) { + AlertMessage am = ((AlertMessage) lm); + LOGGER.info(" Last protocol message: Alert ({},{}) [{},{}]", AlertLevel.getAlertLevel(am.getLevel() + .getValue()), AlertDescription.getAlertDescription(am.getDescription().getValue()), am.getLevel() + .getValue(), am.getDescription().getValue()); + } else { + LOGGER.info(" Last protocol message: {}", lm.getProtocolMessageType()); + } + + if (lm.getProtocolMessageType() == ProtocolMessageType.ALERT + && ((AlertMessage) lm).getDescription().getValue() == 22) { + LOGGER.info(" Vulnerable"); + vulnerable = true; + } else { + LOGGER.info(" Not Vulnerable / Not supported"); + } + + transportHandler.closeConnection(); + } + + private Record createRecordWithBadPadding() { + byte[] plain = new byte[] { (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, (byte) 255, + (byte) 255 }; + Record r = new Record(); + ModifiableByteArray plainData = new ModifiableByteArray(); + VariableModification modifier = ByteArrayModificationFactory.explicitValue(plain); + plainData.setModification(modifier); + r.setPlainRecordBytes(plainData); + return r; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `trace` last assigned on line 117 could be null and is dereferenced at line 120. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Cve20162107.executeAttackRound(ConfigHandler) + +### Procedure Id: +de.rub.nds.tlsattacker.attacks.impl.Cve20162107.executeAttackRound(de.rub.nds.tlsattacker.tls.config.4a1826783ea5b8e7c4668d0458614bd2 + +### File: +Attacks/src/main/java/de/rub/nds/tlsattacker/attacks/impl/Cve20162107.java + +### Key: +Cve20162107.java|executeAttackRound|NULL_DEREFERENCE + +### Node Key: +03f78c8e698e098c7d7421c6d3e394e4 + +### Hash: +9b3cd559ae56e6ff628865e193b09e62 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7586/instruction.md b/inferredbugs-7586/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76353c9e3fba517544030ece76046dc5cd45d79c --- /dev/null +++ b/inferredbugs-7586/instruction.md @@ -0,0 +1,309 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package de.rub.nds.tlsattacker.tls.protocol.handshake.handler; + +import de.rub.nds.tlsattacker.dtls.protocol.handshake.ClientHelloDtlsMessage; +import de.rub.nds.tlsattacker.tls.constants.CipherSuite; +import de.rub.nds.tlsattacker.tls.constants.CompressionMethod; +import de.rub.nds.tlsattacker.tls.constants.ExtensionByteLength; +import de.rub.nds.tlsattacker.tls.constants.ExtensionType; +import de.rub.nds.tlsattacker.tls.constants.HandshakeByteLength; +import de.rub.nds.tlsattacker.tls.constants.HandshakeMessageType; +import de.rub.nds.tlsattacker.tls.constants.ProtocolVersion; +import de.rub.nds.tlsattacker.tls.constants.RecordByteLength; +import de.rub.nds.tlsattacker.tls.exceptions.InvalidMessageTypeException; +import de.rub.nds.tlsattacker.tls.exceptions.WorkflowExecutionException; +import de.rub.nds.tlsattacker.tls.protocol.extension.ExtensionHandler; +import de.rub.nds.tlsattacker.tls.protocol.extension.ExtensionMessage; +import de.rub.nds.tlsattacker.tls.protocol.handshake.ClientHelloMessage; +import de.rub.nds.tlsattacker.tls.workflow.TlsContext; +import de.rub.nds.tlsattacker.util.ArrayConverter; +import de.rub.nds.tlsattacker.util.RandomHelper; +import de.rub.nds.tlsattacker.util.Time; +import java.util.Arrays; + +/** + * @author Juraj Somorovsky + * @author Philip Riese + * @param + */ +public class ClientHelloHandler extends HandshakeMessageHandler { + + @SuppressWarnings("unchecked") + public ClientHelloHandler(TlsContext tlsContext) { + super(tlsContext); + this.correctProtocolMessageClass = (Class) ClientHelloMessage.class; + } + + @Override + public byte[] prepareMessageAction() { + protocolMessage.setProtocolVersion(tlsContext.getConfig().getHighestProtocolVersion().getValue()); + protocolMessage.setSessionId(tlsContext.getConfig().getSessionId()); + int length = protocolMessage.getSessionId().getValue().length; + protocolMessage.setSessionIdLength(length); + final long unixTime = Time.getUnixTime(); + protocolMessage.setUnixTime(ArrayConverter.longToUint32Bytes(unixTime)); + byte[] random = new byte[HandshakeByteLength.RANDOM]; + RandomHelper.getRandom().nextBytes(random); + protocolMessage.setRandom(random); + tlsContext.setClientRandom(ArrayConverter.concatenate(protocolMessage.getUnixTime().getValue(), protocolMessage + .getRandom().getValue())); + byte[] cookieArray = new byte[0]; + // Ugly but more secure + if (protocolMessage instanceof ClientHelloDtlsMessage) { + ClientHelloDtlsMessage dtlsClientHello = (de.rub.nds.tlsattacker.dtls.protocol.handshake.ClientHelloDtlsMessage) protocolMessage; + dtlsClientHello.setCookie(tlsContext.getDtlsHandshakeCookie()); + dtlsClientHello.setCookieLength((byte) tlsContext.getDtlsHandshakeCookie().length); + cookieArray = ArrayConverter.concatenate(new byte[] { dtlsClientHello.getCookieLength().getValue() }, + dtlsClientHello.getCookie().getValue()); + } + + byte[] cipherSuites = new byte[0]; + for (CipherSuite cs : tlsContext.getConfig().getSupportedCiphersuites()) { + cipherSuites = ArrayConverter.concatenate(cipherSuites, cs.getByteValue()); + } + protocolMessage.setCipherSuites(cipherSuites); + int cipherSuiteLength = 0; + cipherSuiteLength = protocolMessage.getCipherSuites().getValue().length; + protocolMessage.setCipherSuiteLength(cipherSuiteLength); + + byte[] compressionMethods = new byte[0]; + for (CompressionMethod cm : tlsContext.getConfig().getSupportedCompressionMethods()) { + compressionMethods = ArrayConverter.concatenate(compressionMethods, cm.getArrayValue()); + } + protocolMessage.setCompressions(compressionMethods); + + int compressionMethodLength = protocolMessage.getCompressions().getValue().length; + protocolMessage.setCompressionLength(compressionMethodLength); + + byte[] result = ArrayConverter.concatenate(protocolMessage.getProtocolVersion().getValue(), protocolMessage + .getUnixTime().getValue(), protocolMessage.getRandom().getValue(), ArrayConverter.intToBytes( + protocolMessage.getSessionIdLength().getValue(), 1), protocolMessage.getSessionId().getValue(), + cookieArray, ArrayConverter.intToBytes(protocolMessage.getCipherSuiteLength().getValue(), + HandshakeByteLength.CIPHER_SUITE), protocolMessage.getCipherSuites().getValue(), + ArrayConverter.intToBytes(protocolMessage.getCompressionLength().getValue(), + HandshakeByteLength.COMPRESSION), protocolMessage.getCompressions().getValue()); + + byte[] extensionBytes = null; + + if (tlsContext.getConfig().isMitm()) { + extensionBytes = protocolMessage.getExtensionBytes(); + result = ArrayConverter.concatenate(result, extensionBytes); + } else { + for (ExtensionMessage extension : protocolMessage.getExtensions()) { + ExtensionHandler handler = extension.getExtensionHandler(); + handler.setExtensionMessage(extension); + handler.prepareExtension(tlsContext); + extensionBytes = ArrayConverter.concatenate(extensionBytes, extension.getExtensionBytes().getValue()); + } + + if (extensionBytes != null && extensionBytes.length != 0) { + byte[] extensionLength = ArrayConverter.intToBytes(extensionBytes.length, + ExtensionByteLength.EXTENSIONS); + + result = ArrayConverter.concatenate(result, extensionLength, extensionBytes); + } + } + + protocolMessage.setLength(result.length); + + long header = (HandshakeMessageType.CLIENT_HELLO.getValue() << 24) + protocolMessage.getLength().getValue(); + + protocolMessage.setCompleteResultingMessage(ArrayConverter.concatenate( + ArrayConverter.longToUint32Bytes(header), result)); + + return protocolMessage.getCompleteResultingMessage().getValue(); + } + + @Override + public int parseMessageAction(byte[] message, int pointer) { + if (message[pointer] != HandshakeMessageType.CLIENT_HELLO.getValue()) { + throw new InvalidMessageTypeException("This is not a client hello message"); + } + protocolMessage.setType(message[pointer]); + + int currentPointer = pointer + HandshakeByteLength.MESSAGE_TYPE; + int nextPointer = currentPointer + HandshakeByteLength.MESSAGE_TYPE_LENGTH; + int length = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setLength(length); + + currentPointer = nextPointer; + nextPointer = currentPointer + RecordByteLength.PROTOCOL_VERSION; + ProtocolVersion serverProtocolVersion = ProtocolVersion.getProtocolVersion(Arrays.copyOfRange(message, + currentPointer, nextPointer)); + protocolMessage.setProtocolVersion(serverProtocolVersion.getValue()); + currentPointer = nextPointer; + nextPointer = currentPointer + HandshakeByteLength.UNIX_TIME; + protocolMessage.setUnixTime(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + currentPointer = nextPointer; + nextPointer = currentPointer + HandshakeByteLength.RANDOM; + protocolMessage.setRandom(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + tlsContext.setClientRandom(ArrayConverter.concatenate(protocolMessage.getUnixTime().getValue(), protocolMessage + .getRandom().getValue())); + + currentPointer = nextPointer; + nextPointer += HandshakeByteLength.SESSION_ID_LENGTH; + int sessionIdLength = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setSessionIdLength(sessionIdLength); + + currentPointer = nextPointer; + nextPointer += sessionIdLength; + protocolMessage.setSessionId(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + // handle unknown SessionID during Session resumption + if (tlsContext.getConfig().isSessionResumption() + && !(Arrays.equals(tlsContext.getSessionID(), protocolMessage.getSessionId().getValue()))) { + throw new WorkflowExecutionException("Session ID is unknown to the Server"); + } + // TODO !!! + if (tlsContext.getConfig().getHighestProtocolVersion() == ProtocolVersion.DTLS12 + || tlsContext.getConfig().getHighestProtocolVersion() == ProtocolVersion.DTLS10) { + de.rub.nds.tlsattacker.dtls.protocol.handshake.ClientHelloDtlsMessage dtlsClientHello = (de.rub.nds.tlsattacker.dtls.protocol.handshake.ClientHelloDtlsMessage) protocolMessage; + currentPointer = nextPointer; + nextPointer += HandshakeByteLength.DTLS_HANDSHAKE_COOKIE_LENGTH; + byte cookieLength = message[currentPointer]; + dtlsClientHello.setCookieLength(cookieLength); + + currentPointer = nextPointer; + nextPointer += cookieLength; + dtlsClientHello.setCookie(Arrays.copyOfRange(message, currentPointer, nextPointer)); + } + + currentPointer = nextPointer; + nextPointer += HandshakeByteLength.CIPHER_SUITE; + int cipherSuitesLength = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setCipherSuiteLength(cipherSuitesLength); + + currentPointer = nextPointer; + nextPointer += cipherSuitesLength; + protocolMessage.setCipherSuites(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + tlsContext.setClientSupportedCiphersuites(CipherSuite.getCiphersuites(protocolMessage.getCipherSuites() + .getValue())); + currentPointer = nextPointer; + nextPointer += HandshakeByteLength.COMPRESSION; + int compressionsLength = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setCompressionLength(compressionsLength); + + currentPointer = nextPointer; + nextPointer += compressionsLength; + protocolMessage.setCompressions(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + byte[] compression = protocolMessage.getCompressions().getValue(); + tlsContext.setCompressionMethod(CompressionMethod.getCompressionMethod(compression[0])); + + currentPointer = nextPointer; + if ((currentPointer - pointer) < length) { + currentPointer += ExtensionByteLength.EXTENSIONS; + + while ((currentPointer - pointer) < length) { + nextPointer = currentPointer + ExtensionByteLength.TYPE; + byte[] extensionType = Arrays.copyOfRange(message, currentPointer, nextPointer); + // Not implemented/unknown extensions will generate an Exception + // ... + try { + ExtensionHandler eh = ExtensionType.getExtensionType(extensionType) + .getExtensionHandler(); + currentPointer = eh.parseExtension(message, currentPointer); + protocolMessage.addExtension(eh.getExtensionMessage()); + } + // ... which we catch, then disregard that extension and carry + // on. + catch (Exception ex) { + currentPointer = nextPointer; + nextPointer += 2; + currentPointer += ArrayConverter.bytesToInt(Arrays + .copyOfRange(message, currentPointer, nextPointer)); + nextPointer += 2; + currentPointer += 2; + } + } + } + + protocolMessage.setCompleteResultingMessage(Arrays.copyOfRange(message, pointer, currentPointer)); + + return (currentPointer - pointer); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `serverProtocolVersion` last assigned on line 138 could be null and is dereferenced at line 140. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int ClientHelloHandler.parseMessageAction(byte[],int) + +### Procedure Id: +de.rub.nds.tlsattacker.tls.protocol.handshake.handler.ClientHelloHandler.parseMessageAction(byte[],i.efd344123ffd19bf71dcbb2a83b42793 + +### File: +TLS-Core/src/main/java/de/rub/nds/tlsattacker/tls/protocol/handshake/handler/ClientHelloHandler.java + +### Key: +ClientHelloHandler.java|parseMessageAction|NULL_DEREFERENCE + +### Node Key: +2ad2c69f89cd458ad84f96f60007b771 + +### Hash: +fb01245a5410da5a145d7372421fa858 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7587/instruction.md b/inferredbugs-7587/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8286bdf87997dffb277d3e2cf3de43928c29e16e --- /dev/null +++ b/inferredbugs-7587/instruction.md @@ -0,0 +1,173 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package de.rub.nds.tlsattacker.main; + +import com.beust.jcommander.JCommander; +import de.rub.nds.tlsattacker.tls.client.ClientCommandConfig; +import de.rub.nds.tlsattacker.tls.config.delegate.GeneralDelegate; +import de.rub.nds.tlsattacker.tls.exceptions.ConfigurationException; +import de.rub.nds.tlsattacker.tls.exceptions.WorkflowExecutionException; +import de.rub.nds.tlsattacker.tls.util.LogLevel; +import de.rub.nds.tlsattacker.tls.util.WorkflowTraceSerializer; +import de.rub.nds.tlsattacker.tls.workflow.TlsConfig; +import de.rub.nds.tlsattacker.tls.workflow.TlsContext; +import de.rub.nds.tlsattacker.tls.workflow.WorkflowExecutor; +import de.rub.nds.tlsattacker.tls.workflow.WorkflowExecutorFactory; +import de.rub.nds.tlsattacker.transport.TransportHandler; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.logging.Level; +import javax.xml.bind.JAXBException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * A TLS-TLSClient implementation that supports custom Workflows + * + * @author Robert Merget - robert.merget@rub.de + */ +public class TLSClient { + + private static final Logger LOGGER = LogManager.getLogger("Client"); + + public static void main(String args[]) { + ClientCommandConfig config = new ClientCommandConfig(new GeneralDelegate()); + JCommander commander = new JCommander(config); + Exception ex = null; + try { + commander.parse(args); + } catch (Exception E) { + LOGGER.info("Could not parse provided parameters"); + LOGGER.debug(E); + commander.usage(); + ex = E; + } + if (ex == null) { + // Cmd was parsable + TlsConfig tlsConfig = null; + try { + tlsConfig = config.createConfig(); + TLSClient client = new TLSClient(); + client.startTlsClient(tlsConfig); + } catch (ConfigurationException E) { + LOGGER.info("Encountered a ConfigurationException aborting."); + LOGGER.debug(E); + } + + } + } + + public void startTlsClient(TlsConfig config) { + TlsContext tlsContext = new TlsContext(config); + WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.createWorkflowExecutor(config.getExecutorType(), + tlsContext); + + try { + workflowExecutor.executeWorkflow(); + } catch (WorkflowExecutionException ex) { + LOGGER.info("The TLS protocol flow was not executed completely, follow the debug messages for more information."); + LOGGER.debug(ex.getLocalizedMessage(), ex); + } + + if (config.getWorkflowOutput() != null && !config.getWorkflowOutput().isEmpty()) { + FileOutputStream fos = null; + try { + fos = new FileOutputStream(config.getWorkflowOutput()); + WorkflowTraceSerializer.write(fos, tlsContext.getWorkflowTrace()); + } catch (FileNotFoundException ex) { + java.util.logging.Logger.getLogger(TLSClient.class.getName()).log(Level.SEVERE, null, ex); + } catch (JAXBException | IOException ex) { + LOGGER.info("Could not serialize WorkflowTrace."); + LOGGER.debug(ex); + } finally { + try { + fos.close(); + } catch (IOException ex) { + LOGGER.debug(ex); + } + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `fos` last assigned on line 80 could be null and is dereferenced at line 91. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TLSClient.startTlsClient(TlsConfig) + +### Procedure Id: +de.rub.nds.tlsattacker.main.TLSClient.startTlsClient(de.rub.nds.tlsattacker.tls.workflow.TlsConfig):.ff15217b61a242deaf3d97db948251a9 + +### File: +TLS-Client/src/main/java/de/rub/nds/tlsattacker/main/TLSClient.java + +### Key: +TLSClient.java|startTlsClient|NULL_DEREFERENCE + +### Node Key: +befc1e6da835838381fc1bcb984dfebd + +### Hash: +c4a697a5612da9374735bd54e1dc8255 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7588/instruction.md b/inferredbugs-7588/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8dff615cba1060f5d5bbb5fe062fc694bf29c945 --- /dev/null +++ b/inferredbugs-7588/instruction.md @@ -0,0 +1,151 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0 + */ +package tlsattacker.fuzzer.analyzer; + +import tlsattacker.fuzzer.config.analyzer.RuleConfig; +import tlsattacker.fuzzer.config.EvolutionaryFuzzerConfig; +import tlsattacker.fuzzer.result.Result; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.xml.bind.JAXB; + +/** + * + * @author Robert Merget - robert.merget@rub.de + */ +public abstract class Rule { + + protected File ruleFolder; + protected final String configFileName; + protected EvolutionaryFuzzerConfig evoConfig; + private boolean isActive = true; + + protected Rule(EvolutionaryFuzzerConfig evoConfig, String configFileName) { + this.configFileName = configFileName; + this.evoConfig = evoConfig; + } + + public File getRuleFolder() { + return ruleFolder; + } + + public boolean isActive() { + return isActive; + } + + public abstract RuleConfig getConfig(); + + public abstract boolean applys(Result result); + + public abstract void onApply(Result result); + + public abstract void onDecline(Result result); + + public abstract String report(); + + protected void writeConfig(RuleConfig c) { + File f = new File(evoConfig.getAnalyzerConfigFolder() + configFileName); + if (f.exists()) { + LOG.log(Level.SEVERE, "Config File already exists, not writing new Config:" + configFileName); + } else { + JAXB.marshal(c, f); + } + } + + protected void prepareConfigOutputFolder() { + File f = new File(evoConfig.getOutputFolder() + this.getConfig().getOutputFolder()); + if (evoConfig.isCleanStart()) { + if (f.exists()) { + for (File tempFile : f.listFiles()) { + tempFile.delete(); + } + } + } + f.mkdirs(); + } + + private static final Logger LOG = Logger.getLogger(Rule.class.getName()); + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `f.listFiles()` could be null and is dereferenced at line 67. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Rule.prepareConfigOutputFolder() + +### Procedure Id: +tlsattacker.fuzzer.analyzer.Rule.prepareConfigOutputFolder():void.247042f0fe0ba78a6bfa316434a19ac2 + +### File: +EvolutionaryFuzzer/src/main/java/tlsattacker/fuzzer/analyzer/Rule.java + +### Key: +Rule.java|prepareConfigOutputFolder|NULL_DEREFERENCE + +### Node Key: +24ee14a57e8a90ab88fc833015223ecd + +### Hash: +8fccf8bd2dd0e99503b9991834766dea + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7589/instruction.md b/inferredbugs-7589/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67c0192d3fc8671e5c5f826a911732b3d6b74089 --- /dev/null +++ b/inferredbugs-7589/instruction.md @@ -0,0 +1,283 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** TLS-Attacker +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * TLS-Attacker - A Modular Penetration Testing Framework for TLS + * + * Copyright 2014-2016 Ruhr University Bochum / Hackmanit GmbH + * + * Licensed under Apache License 2.0 + * http://www.apache.org/licenses/LICENSE-2.0 + */ +package de.rub.nds.tlsattacker.tls.protocol.handshake.handler; + +import de.rub.nds.tlsattacker.tls.constants.AlgorithmResolver; +import de.rub.nds.tlsattacker.tls.constants.HandshakeByteLength; +import de.rub.nds.tlsattacker.tls.constants.KeyExchangeAlgorithm; +import de.rub.nds.tlsattacker.tls.constants.PRFAlgorithm; +import de.rub.nds.tlsattacker.tls.crypto.PseudoRandomFunction; +import de.rub.nds.tlsattacker.tls.exceptions.ConfigurationException; +import de.rub.nds.tlsattacker.tls.exceptions.WorkflowExecutionException; +import de.rub.nds.tlsattacker.tls.protocol.handshake.RSAClientKeyExchangeMessage; +import de.rub.nds.tlsattacker.tls.workflow.TlsContext; +import de.rub.nds.tlsattacker.util.ArrayConverter; +import de.rub.nds.tlsattacker.util.RandomHelper; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyPairGenerator; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.UnrecoverableKeyException; +import java.security.interfaces.RSAPrivateCrtKey; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +/** + * @author Juraj Somorovsky + * @author Philip Riese + */ +public class RSAClientKeyExchangeHandler extends ClientKeyExchangeHandler { + + private static final Logger LOGGER = LogManager.getLogger(RSAClientKeyExchangeHandler.class); + private static RSAPublicKey bufferedKey = null; + + public RSAClientKeyExchangeHandler(TlsContext tlsContext) { + super(tlsContext); + this.correctProtocolMessageClass = RSAClientKeyExchangeMessage.class; + this.keyExchangeAlgorithm = KeyExchangeAlgorithm.RSA; + } + + @Override + byte[] prepareKeyExchangeMessage() { + RSAPublicKey publicKey = null; + if (!tlsContext.getX509ServerCertificateObject().getPublicKey().getAlgorithm().equals("RSA")) { + + if (tlsContext.getConfig().isFuzzingMode()) { + if (bufferedKey == null) { + KeyPairGenerator keyGen = null; + try { + keyGen = KeyPairGenerator.getInstance("RSA", "BC"); + } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { + LOGGER.error(ex.getLocalizedMessage(), ex); + } + bufferedKey = (RSAPublicKey) keyGen.genKeyPair().getPublic(); + } + publicKey = bufferedKey;// TODO not multithreadable + } + } else { + publicKey = (RSAPublicKey) tlsContext.getX509ServerCertificateObject().getPublicKey(); + + } + int keyByteLength = publicKey.getModulus().bitLength() / 8; + // the number of random bytes in the pkcs1 message + int randomByteLength = keyByteLength - HandshakeByteLength.PREMASTER_SECRET - 3; + byte[] padding = new byte[randomByteLength]; + RandomHelper.getRandom().nextBytes(padding); + ArrayConverter.makeArrayNonZero(padding); + + byte[] premasterSecret = new byte[HandshakeByteLength.PREMASTER_SECRET]; + + RandomHelper.getRandom().nextBytes(premasterSecret); + premasterSecret[0] = tlsContext.getSelectedProtocolVersion().getMajor(); + premasterSecret[1] = tlsContext.getSelectedProtocolVersion().getMinor(); + protocolMessage.setPremasterSecret(premasterSecret); + + LOGGER.debug("Computed PreMaster Secret: {}", + ArrayConverter.bytesToHexString(protocolMessage.getPremasterSecret().getValue())); + + protocolMessage.setPlainPaddedPremasterSecret(ArrayConverter.concatenate(new byte[] { 0x00, 0x02 }, padding, + new byte[] { 0x00 }, protocolMessage.getPremasterSecret().getValue())); + + byte[] paddedPremasterSecret = protocolMessage.getPlainPaddedPremasterSecret().getValue(); + + byte[] random = tlsContext.getClientServerRandom(); + + PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getSelectedProtocolVersion(), + tlsContext.getSelectedCipherSuite()); + byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm, protocolMessage.getPremasterSecret() + .getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random, HandshakeByteLength.MASTER_SECRET); + protocolMessage.setMasterSecret(masterSecret); + LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret)); + + tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue()); + + try { + Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC"); + cipher.init(Cipher.ENCRYPT_MODE, publicKey); + LOGGER.debug("Encrypting the following padded premaster secret: {}", + ArrayConverter.bytesToHexString(paddedPremasterSecret)); + // TODO can throw a tooMuchData for RSA Block exception + if (paddedPremasterSecret.length == 0) { + paddedPremasterSecret = new byte[] { 0 }; + } + if (new BigInteger(paddedPremasterSecret).compareTo(publicKey.getModulus()) == 1) { + if (tlsContext.getConfig().isFuzzingMode()) { + paddedPremasterSecret = masterSecret; + } else { + throw new IllegalStateException("Trying to encrypt more data then modulus size!"); + } + } + byte[] encrypted = null; + try { + encrypted = cipher.doFinal(paddedPremasterSecret); + } catch (org.bouncycastle.crypto.DataLengthException | ArrayIndexOutOfBoundsException E) { + // too much data for RSA block + throw new UnsupportedOperationException(E); + } + protocolMessage.setEncryptedPremasterSecret(encrypted); + protocolMessage + .setEncryptedPremasterSecretLength(protocolMessage.getEncryptedPremasterSecret().getValue().length); + return ArrayConverter.concatenate(ArrayConverter.intToBytes(protocolMessage + .getEncryptedPremasterSecretLength().getValue(), + HandshakeByteLength.ENCRYPTED_PREMASTER_SECRET_LENGTH), protocolMessage + .getEncryptedPremasterSecret().getValue()); + } catch (BadPaddingException | IllegalBlockSizeException | NoSuchProviderException | InvalidKeyException + | NoSuchAlgorithmException | NoSuchPaddingException ex) { + LOGGER.info(ex); + throw new WorkflowExecutionException(ex.getLocalizedMessage()); + } + + } + + @Override + int parseKeyExchangeMessage(byte[] message, int currentPointer) { + int nextPointer = currentPointer + HandshakeByteLength.ENCRYPTED_PREMASTER_SECRET_LENGTH; + int length = ArrayConverter.bytesToInt(Arrays.copyOfRange(message, currentPointer, nextPointer)); + protocolMessage.setEncryptedPremasterSecretLength(length); + currentPointer = nextPointer; + + nextPointer = currentPointer + length; + protocolMessage.setEncryptedPremasterSecret(Arrays.copyOfRange(message, currentPointer, nextPointer)); + + byte[] encryptedPremasterSecret = protocolMessage.getEncryptedPremasterSecret().getValue(); + + KeyStore ks = tlsContext.getConfig().getKeyStore(); + + try { + Key key = ks.getKey(tlsContext.getConfig().getAlias(), tlsContext.getConfig().getPassword().toCharArray()); + RSAPrivateCrtKey rsaKey = (RSAPrivateCrtKey) key; + + Cipher cipher = Cipher.getInstance("RSA/None/NoPadding", "BC"); + cipher.init(Cipher.DECRYPT_MODE, rsaKey); + LOGGER.debug("Decrypting the following encrypted premaster secret: {}", + ArrayConverter.bytesToHexString(encryptedPremasterSecret)); + byte[] decrypted = cipher.doFinal(encryptedPremasterSecret); + + protocolMessage.setPlainPaddedPremasterSecret(decrypted); + + } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException | InvalidKeyException + | NoSuchProviderException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) { + throw new ConfigurationException( + "Something went wrong loading key from Keystore or decrypting Premastersecret", ex); + } + + byte[] plainPaddedPremasterSecret = protocolMessage.getPlainPaddedPremasterSecret().getValue(); + + int plainPaddedPremasterSecretLength = plainPaddedPremasterSecret.length; + + int plainPaddedPremasterSecretoffset = plainPaddedPremasterSecretLength - 48; + + byte[] premasterSecret = Arrays.copyOfRange(plainPaddedPremasterSecret, plainPaddedPremasterSecretoffset, + plainPaddedPremasterSecretLength); + + LOGGER.debug("Resulting premaster secret: {}", ArrayConverter.bytesToHexString(premasterSecret)); + + protocolMessage.setPremasterSecret(premasterSecret); + tlsContext.setPreMasterSecret(premasterSecret); + + byte[] random = tlsContext.getClientServerRandom(); + + PRFAlgorithm prfAlgorithm = AlgorithmResolver.getPRFAlgorithm(tlsContext.getSelectedProtocolVersion(), + tlsContext.getSelectedCipherSuite()); + byte[] masterSecret = PseudoRandomFunction.compute(prfAlgorithm, protocolMessage.getPremasterSecret() + .getValue(), PseudoRandomFunction.MASTER_SECRET_LABEL, random, HandshakeByteLength.MASTER_SECRET); + protocolMessage.setMasterSecret(masterSecret); + LOGGER.debug("Computed Master Secret: {}", ArrayConverter.bytesToHexString(masterSecret)); + + tlsContext.setMasterSecret(protocolMessage.getMasterSecret().getValue()); + + currentPointer = nextPointer; + + return currentPointer; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `publicKey` last assigned on line 58 could be null and is dereferenced at line 77. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] RSAClientKeyExchangeHandler.prepareKeyExchangeMessage() + +### Procedure Id: +de.rub.nds.tlsattacker.tls.protocol.handshake.handler.RSAClientKeyExchangeHandler.prepareKeyExchange.e9fae13b36fc43c784c6e994f4094944 + +### File: +TLS-Core/src/main/java/de/rub/nds/tlsattacker/tls/protocol/handshake/handler/RSAClientKeyExchangeHandler.java + +### Key: +RSAClientKeyExchangeHandler.java|prepareKeyExchangeMessage|NULL_DEREFERENCE + +### Node Key: +89164183295eb6345138e0406223c3df + +### Hash: +f324646ebe6ac8f24d0b0614b4c92064 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7604/instruction.md b/inferredbugs-7604/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7200584202e7754af85e0e2a6ea0324ac7c18670 --- /dev/null +++ b/inferredbugs-7604/instruction.md @@ -0,0 +1,107 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** CFLint +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.cflint; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +public class Version { + + public static String getVersion() { + final InputStream is = Version.class + .getResourceAsStream("/META-INF/maven/com.github.cflint/CFLint/pom.properties"); + try { + final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); + String line = reader.readLine(); + while (line != null && !line.startsWith("version=")) { + line = reader.readLine(); + } + if (line != null) { + return line.replaceAll("version=", ""); + } + } catch (final Exception e) { + try { + if (is != null) { + is.close(); + } + } catch (final IOException e1) { + e1.printStackTrace(); + } + } + return ""; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 14 is not released after line 20. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String Version.getVersion() + +### Procedure Id: +com.cflint.Version.getVersion():java.lang.String.e1bb4ce91af4edb5c295c87c6635ceef + +### File: +src/main/java/com/cflint/Version.java + +### Key: +Version.java|getVersion|RESOURCE_LEAK + +### Node Key: +403b923eb008d1cc6b180a4b1bc6a1bb + +### Hash: +f35bebc4a47ebef4b8417dd37c3ab537 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7713/instruction.md b/inferredbugs-7713/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e20564dbb2fb18bc2421727a4efad94e1acbda42 --- /dev/null +++ b/inferredbugs-7713/instruction.md @@ -0,0 +1,306 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ez-vcard +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ezvcard.types; + +import java.util.List; +import java.util.Set; + +import org.w3c.dom.Element; + +import ezvcard.VCard; +import ezvcard.VCardException; +import ezvcard.VCardSubTypes; +import ezvcard.VCardVersion; +import ezvcard.io.CompatibilityMode; +import ezvcard.parameters.TelephoneTypeParameter; +import ezvcard.parameters.ValueParameter; +import ezvcard.util.VCardStringUtils; +import ezvcard.util.XCardUtils; + +/* + Copyright (c) 2012, Michael Angstadt + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + The views and conclusions contained in the software and documentation are those + of the authors and should not be interpreted as representing official policies, + either expressed or implied, of the FreeBSD Project. + */ + +/** + * A telephone number. + * + *
+ * VCard vcard = new VCard();
+ * TelephoneType tel = new TelephoneType("+1 123-555-6789");
+ * tel.addType(TelephoneTypeParameter.HOME);
+ * tel.setPref(2); //the second-most preferred
+ * vcard.addTelephoneNumber(tel);
+ * tel = new TelephoneType("+1 800-555-9876;ext=111");
+ * tel.addType(TelephoneTypeParameter.WORK);
+ * tel.setPref(1); //the most preferred
+ * vcard.addTelephoneNumber(tel);
+ * 
+ * + *

+ * vCard property name: TEL + *

+ *

+ * vCard versions: 2.1, 3.0, 4.0 + *

+ * @author Michael Angstadt + */ +public class TelephoneType extends MultiValuedTypeParameterType { + public static final String NAME = "TEL"; + + private String value; + + public TelephoneType() { + this(null); + } + + /** + * @param telNumber the telephone number + */ + public TelephoneType(String telNumber) { + super(NAME); + this.value = telNumber; + } + + /** + * Gets the telephone number. + * @return the telephone number + */ + public String getValue() { + return value; + } + + /** + * Sets the telephone number. + * @param value the telephone number + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Gets all PID parameter values. + *

+ * vCard versions: 4.0 + *

+ * @return the PID values or empty set if there are none + * @see VCardSubTypes#getPids + */ + public Set getPids() { + return subTypes.getPids(); + } + + /** + * Adds a PID value. + *

+ * vCard versions: 4.0 + *

+ * @param localId the local ID + * @param clientPidMapRef the ID used to reference the property's globally + * unique identifier in the CLIENTPIDMAP property. + * @see VCardSubTypes#addPid(int, int) + */ + public void addPid(int localId, int clientPidMapRef) { + subTypes.addPid(localId, clientPidMapRef); + } + + /** + * Removes all PID values. + *

+ * vCard versions: 4.0 + *

+ * @see VCardSubTypes#removePids + */ + public void removePids() { + subTypes.removePids(); + } + + /** + * Gets the preference value. + *

+ * vCard versions: 4.0 + *

+ * @return the preference value or null if it doesn't exist + * @see VCardSubTypes#getPref + */ + public Integer getPref() { + return subTypes.getPref(); + } + + /** + * Sets the preference value. + *

+ * vCard versions: 4.0 + *

+ * @param pref the preference value or null to remove + * @see VCardSubTypes#setPref + */ + public void setPref(Integer pref) { + subTypes.setPref(pref); + } + + /** + * Gets the ALTID. + *

+ * vCard versions: 4.0 + *

+ * @return the ALTID or null if it doesn't exist + * @see VCardSubTypes#getAltId + */ + public String getAltId() { + return subTypes.getAltId(); + } + + /** + * Sets the ALTID. + *

+ * vCard versions: 4.0 + *

+ * @param altId the ALTID or null to remove + * @see VCardSubTypes#setAltId + */ + public void setAltId(String altId) { + subTypes.setAltId(altId); + } + + @Override + protected TelephoneTypeParameter buildTypeObj(String type) { + TelephoneTypeParameter param = TelephoneTypeParameter.valueOf(type); + if (param == null) { + param = new TelephoneTypeParameter(type); + } + return param; + } + + @Override + protected void doMarshalSubTypes(VCardSubTypes copy, VCardVersion version, List warnings, CompatibilityMode compatibilityMode, VCard vcard) { + if (version == VCardVersion.V4_0) { + copy.setValue(ValueParameter.URI); + } else { + copy.setValue(null); + } + } + + @Override + protected void doMarshalValue(StringBuilder sb, VCardVersion version, List warnings, CompatibilityMode compatibilityMode) { + sb.append(VCardStringUtils.escapeText(this.value)); + if (version == VCardVersion.V4_0) { + sb.insert(0, "tel:"); + } + } + + @Override + protected void doUnmarshalValue(String value, VCardVersion version, List warnings, CompatibilityMode compatibilityMode) { + if (value.matches("(?i)tel:.*")) { + //remove "tel:" + value = (value.length() > 4) ? value.substring(4) : ""; + } + this.value = VCardStringUtils.unescape(value.trim()); + } + + @Override + protected void doUnmarshalValue(Element element, VCardVersion version, List warnings, CompatibilityMode compatibilityMode) throws VCardException { + Element ele = XCardUtils.getFirstElement(element.getChildNodes()); + value = ele.getTextContent(); + if (value.matches("(?i)tel:.*")) { + //remove "tel:" + value = (value.length() > 4) ? value.substring(4) : ""; + } + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `ele` last assigned on line 225 could be null and is dereferenced at line 226. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TelephoneType.doUnmarshalValue(Element,VCardVersion,List,CompatibilityMode) + +### Procedure Id: +ezvcard.types.TelephoneType.doUnmarshalValue(org.w3c.dom.Element,ezvcard.VCardVersion,java.util.List.7996cfac4e4819b34003101893ced4a6 + +### File: +src/main/java/ezvcard/types/TelephoneType.java + +### Key: +TelephoneType.java|doUnmarshalValue|NULL_DEREFERENCE + +### Node Key: +fdb1f2fbea286a7be2bdab2f2dfd8b72 + +### Hash: +2fcc4a30e7b646352bb154bfdac5a05c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7722/instruction.md b/inferredbugs-7722/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81cecbcb4e060c9b2b3678640265a804bd7b1e1f --- /dev/null +++ b/inferredbugs-7722/instruction.md @@ -0,0 +1,249 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ez-vcard +**Bug ID:** 38 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ezvcard.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +/* + Copyright (c) 2013, Michael Angstadt + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * Manages objects that are like enums in that they are constant, but unlike + * enums in that new instances can be created during runtime. This class ensures + * that all instances of a class are unique, so they can be safely compared + * using "==" (provided their constructors are private). It mimics the + * "case class" feature in Scala. + * @author Michael Angstadt + * + * @param the class + * @param the value that the class holds (e.g. String) + */ +public abstract class CaseClasses { + protected final Class clazz; + protected Collection preDefined = null; + protected Collection runtimeDefined = null; + + /** + * Creates a new case class collection. + * @param clazz the case class + */ + public CaseClasses(Class clazz) { + this.clazz = clazz; + } + + /** + * Creates a new instance of the case class. + * @param value the value to give the instance + * @return the new instance + */ + protected abstract T create(V value); + + /** + * Determines if a value is associated with a case object. + * @param object the object + * @param value the value + * @return true if it matches, false if not + */ + protected abstract boolean matches(T object, V value); + + /** + * Searches for a case object by value, only looking at the case class' + * static constants (does not include runtime-defined objects). + * @param value the value + * @return the object or null if one wasn't found + */ + public T find(V value) { + return find(value, false, false); + } + + /** + * Searches for a case object by value, creating a new object if one cannot + * be found. + * @param value the value + * @return the object + */ + public T get(V value) { + return find(value, true, true); + } + + /** + * Searches for a case object by value. + * @param value the value + * @param createIfNotFound true to create a new instance of the object if it + * can't be found, false to return "null" if not found + * @param searchRuntimeDefined true to include the runtime-defined objects + * in the search, false not to + * @return the object + */ + protected T find(V value, boolean createIfNotFound, boolean searchRuntimeDefined) { + checkInit(); + + for (T obj : preDefined) { + if (matches(obj, value)) { + return obj; + } + } + + if (searchRuntimeDefined) { + synchronized (this) { + for (T obj : runtimeDefined) { + if (matches(obj, value)) { + return obj; + } + } + if (createIfNotFound) { + T created = create(value); + runtimeDefined.add(created); + return created; + } + } + } + return null; + } + + /** + * Gets all the static constants of the case class. + * @return all static constants + */ + public Collection all() { + checkInit(); + return preDefined; + } + + private void checkInit() { + if (preDefined == null) { + synchronized (this) { + if (preDefined == null) { //duplicate if condition needed for concurrency purposes + init(); + } + } + } + } + + private void init() { + Collection preDefined = new ArrayList(); + for (Field field : clazz.getFields()) { + int modifiers = field.getModifiers(); + //@formatter:off + if (Modifier.isStatic(modifiers) && + Modifier.isPublic(modifiers) && + field.getDeclaringClass() == clazz && + field.getType() == clazz) { + //@formatter:on + try { + Object obj = field.get(null); + if (obj != null) { + T c = clazz.cast(obj); + preDefined.add(c); + } + } catch (Exception ex) { + //reflection error + //should never be thrown because we check for "public static" and the correct type + throw new RuntimeException(ex); + } + } + } + + runtimeDefined = new ArrayList(0); + this.preDefined = Collections.unmodifiableCollection(preDefined); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `ezvcard.util.CaseClasses.get` indirectly reads without synchronization from `this.ezvcard.util.CaseClasses.preDefined`. Potentially races with write in method `CaseClasses.find(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object CaseClasses.get(Object) + +### Procedure Id: +ezvcard.util.CaseClasses.get(java.lang.Object):java.lang.Object.0c9828541d13e758c5566d8178ee5666 + +### File: +src/main/java/ezvcard/util/CaseClasses.java + +### Key: +CaseClasses.java|get|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +ff9424910a919cc9d97e0cbb14780a27 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7725/instruction.md b/inferredbugs-7725/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9be0e51cd75488f936fd2b9d5364ac61a9ee006f --- /dev/null +++ b/inferredbugs-7725/instruction.md @@ -0,0 +1,2946 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ez-vcard +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package ezvcard.io; + +import static ezvcard.util.TestUtils.assertIntEquals; +import static ezvcard.util.VCardStringUtils.NEWLINE; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.TimeZone; + +import org.junit.Test; + +import ezvcard.VCard; +import ezvcard.VCardVersion; +import ezvcard.parameters.AddressTypeParameter; +import ezvcard.parameters.EmailTypeParameter; +import ezvcard.parameters.ImageTypeParameter; +import ezvcard.parameters.KeyTypeParameter; +import ezvcard.parameters.TelephoneTypeParameter; +import ezvcard.types.AddressType; +import ezvcard.types.BirthdayType; +import ezvcard.types.CategoriesType; +import ezvcard.types.ClassificationType; +import ezvcard.types.EmailType; +import ezvcard.types.FbUrlType; +import ezvcard.types.FormattedNameType; +import ezvcard.types.GeoType; +import ezvcard.types.KeyType; +import ezvcard.types.LabelType; +import ezvcard.types.MailerType; +import ezvcard.types.NicknameType; +import ezvcard.types.NoteType; +import ezvcard.types.OrganizationType; +import ezvcard.types.PhotoType; +import ezvcard.types.ProdIdType; +import ezvcard.types.ProfileType; +import ezvcard.types.RawType; +import ezvcard.types.RevisionType; +import ezvcard.types.RoleType; +import ezvcard.types.SortStringType; +import ezvcard.types.SourceDisplayTextType; +import ezvcard.types.SourceType; +import ezvcard.types.StructuredNameType; +import ezvcard.types.TelephoneType; +import ezvcard.types.TimezoneType; +import ezvcard.types.TitleType; +import ezvcard.types.UidType; +import ezvcard.types.UrlType; + +/* + Copyright (c) 2013, Michael Angstadt + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR + ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + The views and conclusions contained in the software and documentation are those + of the authors and should not be interpreted as representing official policies, + either expressed or implied, of the FreeBSD Project. + */ + +/** + * @author Michael Angstadt + */ +public class VCardReaderTest { + /** + * Tests to make sure it can read sub types properly + */ + @Test + public void getSubTypes() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "NOTE;x-size=8:The note\r\n" + + "ADR;HOME;WORK:;;;;\r\n" + //nameless parameters + "LABEL;type=dOm;TyPE=parcel:\r\n" + //repeated parameter name + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + NoteType note = vcard.getNotes().get(0); + assertEquals(1, note.getSubTypes().size()); + assertEquals("8", note.getSubTypes().first("X-SIZE")); + assertEquals("8", note.getSubTypes().first("x-size")); + assertNull(note.getSubTypes().first("non-existant")); + + AddressType adr = vcard.getAddresses().get(0); + assertEquals(2, adr.getSubTypes().size()); + assertEquals(2, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + + LabelType label = vcard.getOrphanedLabels().get(0); + assertEquals(2, label.getSubTypes().size()); + assertEquals(2, label.getTypes().size()); + assertTrue(label.getTypes().contains(AddressTypeParameter.DOM)); + assertTrue(label.getTypes().contains(AddressTypeParameter.PARCEL)); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void type_parameter_enclosed_in_double_quotes() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:4.0\r\n" + + "ADR;TYPE=\"dom,home,work\":;;;;\r\n" + + "ADR;TYPE=\"dom\",\"home\",\"work\":;;;;\r\n" + + "ADR;TYPE=\"dom\",home,work:;;;;\r\n" + + "ADR;TYPE=dom,home,work:;;;;\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + AddressType adr = vcard.getAddresses().get(0); + assertEquals(3, adr.getSubTypes().size()); + assertEquals(3, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.DOM)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + + adr = vcard.getAddresses().get(1); + assertEquals(3, adr.getSubTypes().size()); + assertEquals(3, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.DOM)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + + adr = vcard.getAddresses().get(2); + assertEquals(3, adr.getSubTypes().size()); + assertEquals(3, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.DOM)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + + adr = vcard.getAddresses().get(3); + assertEquals(3, adr.getSubTypes().size()); + assertEquals(3, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.DOM)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * All "quoted-printable" values should be decoded by the VCardReader. + */ + @Test + public void decodeQuotedPrintable() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "LABEL;HOME;ENCODING=QUOTED-PRINTABLE:123 Main St.=0D=0A\r\n" + + " Austin, TX 91827=0D=0A\r\n" + + " USA\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + LabelType label = vcard.getOrphanedLabels().get(0); + assertEquals("123 Main St.\r\nAustin, TX 91827\r\nUSA", label.getValue()); + assertNull(label.getSubTypes().getEncoding()); //ENCODING sub type should be removed + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * Tests to make sure it can unfold folded lines. + */ + @Test + public void unfold() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "NOTE:The vCard MIME Directory Profile also provides support for represent\r\n" + + " ing other important information about the person associated with the dire\r\n" + + " ctory entry. For instance, the date of birth of the person\\; an audio clip \r\n" + + " describing the pronunciation of the name associated with the directory en\r\n" + + " try, or some other application of the digital sound\\; longitude and latitu\r\n" + + " de geo-positioning information related to the person associated with the \r\n" + + " directory entry\\; date and time that the directory information was last up\r\n" + + " dated\\; annotations often written on a business card\\; Uniform Resource Loc\r\n" + + " ators (URL) for a website\\; public key information.\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + String expected = "The vCard MIME Directory Profile also provides support for representing other important information about the person associated with the directory entry. For instance, the date of birth of the person; an audio clip describing the pronunciation of the name associated with the directory entry, or some other application of the digital sound; longitude and latitude geo-positioning information related to the person associated with the directory entry; date and time that the directory information was last updated; annotations often written on a business card; Uniform Resource Locators (URL) for a website; public key information."; + String actual = vcard.getNotes().get(0).getValue(); + assertEquals(expected, actual); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * Tests to make sure it can read extended types. + */ + @Test + public void readExtendedType() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "X-LUCKY-NUM:24\r\n" + + "X-GENDER:ma\\,le\r\n" + + "X-LUCKY-NUM:22\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + reader.registerExtendedType(LuckyNumType.class); + VCard vcard = reader.readNext(); + + //read a type that has a type class + List luckyNumTypes = vcard.getProperties(LuckyNumType.class); + assertEquals(2, luckyNumTypes.size()); + assertEquals(24, luckyNumTypes.get(0).luckyNum); + assertEquals(22, luckyNumTypes.get(1).luckyNum); + assertTrue(vcard.getExtendedProperties("X-LUCKY-NUM").isEmpty()); + + //read a type without a type class + List genderTypes = vcard.getExtendedProperties("X-GENDER"); + assertEquals(1, genderTypes.size()); + assertEquals("ma\\,le", genderTypes.get(0).getValue()); //raw type values are not unescaped + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test(expected = RuntimeException.class) + public void registerExtendedType_no_default_constructor() throws Exception { + VCardReader reader = new VCardReader(""); + reader.registerExtendedType(BadType.class); + } + + /** + * Tests to make sure it can read multiple vCards from the same stream. + */ + @Test + public void readMultiple() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "FN:John Doe\r\n" + + "END:VCARD\r\n" + + "BEGIN:VCARD\r\n" + + "VERSION:3.0\r\n" + + "FN:Jane Doe\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard; + + vcard = reader.readNext(); + assertEquals(VCardVersion.V2_1, vcard.getVersion()); + assertEquals("John Doe", vcard.getFormattedName().getValue()); + assertEquals(0, reader.getWarnings().size()); + + vcard = reader.readNext(); + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + assertEquals("Jane Doe", vcard.getFormattedName().getValue()); + assertEquals(0, reader.getWarnings().size()); + + assertNull(reader.readNext()); + } + + /** + * Tests types with nested vCards (i.e AGENT type) in version 2.1. + */ + @Test + public void nestedVCard() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "AGENT:\r\n" + + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "FN:Agent 007\r\n" + + "AGENT:\r\n" + + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "FN:Agent 009\r\n" + + "END:VCARD\r\n" + + "END:VCARD\r\n" + + "FN:John Doe\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + + VCard vcard = reader.readNext(); + assertEquals("John Doe", vcard.getFormattedName().getValue()); + VCard agent1 = vcard.getAgent().getVCard(); + assertEquals("Agent 007", agent1.getFormattedName().getValue()); + VCard agent2 = agent1.getAgent().getVCard(); + assertEquals("Agent 009", agent2.getFormattedName().getValue()); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void nestedVCard_missing_vcard() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "AGENT:\r\n" + + "FN:John Doe\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + + VCard vcard = reader.readNext(); + assertEquals("John Doe", vcard.getFormattedName().getValue()); + assertNull(vcard.getAgent().getVCard()); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * Tests types with embedded vCards (i.e. AGENT type) in version 3.0. + */ + @Test + public void embeddedVCard() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:3.0\r\n" + + "AGENT:" + + "BEGIN:VCARD\\n" + + "VERSION:3.0\\n" + + "FN:Agent 007\\n" + + "AGENT:" + + "BEGIN:VCARD\\\\n" + + "VERSION:3.0\\\\n" + + "FN:Agent 009\\\\n" + + "END:VCARD\\\\n" + + "END:VCARD\r\n" + + "FN:John Doe\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + assertEquals("John Doe", vcard.getFormattedName().getValue()); + VCard agent1 = vcard.getAgent().getVCard(); + assertEquals("Agent 007", agent1.getFormattedName().getValue()); + VCard agent2 = agent1.getAgent().getVCard(); + assertEquals("Agent 009", agent2.getFormattedName().getValue()); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * LABEL types should be assigned to an ADR and stored in the + * "AddressType.getLabel()" field. LABELs that could not be assigned to an + * ADR should go in "VCard.getOrphanedLabels()". + */ + @Test + public void readLabel() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:3.0\r\n" + + "ADR;TYPE=home:;;123 Main St.;Austin;TX;91827;USA\r\n" + + "LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 91827\\nUSA\r\n" + + "ADR;TYPE=work,parcel:;;200 Broadway;New York;NY;12345;USA\r\n" + + "LABEL;TYPE=work:200 Broadway\\nNew York\\, NY 12345\\nUSA\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + + assertEquals(2, vcard.getAddresses().size()); + + AddressType adr = vcard.getAddresses().get(0); + assertEquals(1, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.HOME)); + assertEquals("123 Main St." + NEWLINE + "Austin, TX 91827" + NEWLINE + "USA", adr.getLabel()); + + adr = vcard.getAddresses().get(1); + assertEquals(2, adr.getTypes().size()); + assertTrue(adr.getTypes().contains(AddressTypeParameter.WORK)); + assertTrue(adr.getTypes().contains(AddressTypeParameter.PARCEL)); + assertNull(adr.getLabel()); + + assertEquals(1, vcard.getOrphanedLabels().size()); + LabelType label = vcard.getOrphanedLabels().get(0); + assertEquals("200 Broadway" + NEWLINE + "New York, NY 12345" + NEWLINE + "USA", label.getValue()); + assertEquals(1, label.getTypes().size()); + assertTrue(label.getTypes().contains(AddressTypeParameter.WORK)); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + /** + * If the type's unmarshal method throws a {@link SkipMeException}, then a + * warning should be added to the warnings list and the type object should + * NOT be added to the {@link VCard} object. + */ + @Test + public void skipMeException() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:3.0\r\n" + + "X-LUCKY-NUM:24\r\n" + + "X-LUCKY-NUM:13\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + reader.registerExtendedType(LuckyNumType.class); + VCard vcard = reader.readNext(); + + List luckyNumTypes = vcard.getProperties(LuckyNumType.class); + assertEquals(1, luckyNumTypes.size()); + assertEquals(24, luckyNumTypes.get(0).luckyNum); + + assertEquals(1, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void invalid_line() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:2.1\r\n" + + "bad-line\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + reader.readNext(); + + assertEquals(1, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void invalid_version() throws Exception { + //@formatter:off + String str = + "BEGIN:VCARD\r\n" + + "VERSION:invalid\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + VCard vcard = reader.readNext(); + assertEquals(VCardVersion.V2_1, vcard.getVersion()); //default to 2.1 + + assertEquals(1, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void skip_non_vcard_components() throws Exception { + //@formatter:off + String str = + "BEGIN:VCALENDAR\r\n" + + "VERSION:2.0\r\n" + + "PRODID:-//Company//Application//EN" + + "END:VCALENDAR\r\n" + + "BEGIN:VCARD\r\n" + + "VERSION:3.0\r\n" + + "FN:John Doe\r\n" + + "END:VCARD\r\n"; + //@formatter:on + + VCardReader reader = new VCardReader(str); + + VCard vcard = reader.readNext(); + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + assertEquals("John Doe", vcard.getFormattedName().getValue()); + assertNull(vcard.getProdId()); + + assertEquals(0, reader.getWarnings().size()); + assertNull(reader.readNext()); + } + + @Test + public void evolutionVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType t = it.next(); + assertEquals("http://www.ibm.com", t.getValue()); + assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().first("X-COUCHDB-UUID")); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType t = it.next(); + assertEquals("905-666-1234", t.getText()); + Set types = t.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().first("X-COUCHDB-UUID")); + + t = it.next(); + assertEquals("905-555-1234", t.getText()); + types = t.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().first("X-COUCHDB-UUID")); + + assertFalse(it.hasNext()); + } + + //UID + { + UidType t = vcard.getUid(); + assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue()); + } + + //N + { + StructuredNameType t = vcard.getStructuredName(); + assertEquals("Doe", t.getFamily()); + assertEquals("John", t.getGiven()); + List list = t.getAdditional(); + assertEquals(Arrays.asList("Richter, James"), list); + list = t.getPrefixes(); + assertEquals(Arrays.asList("Mr."), list); + list = t.getSuffixes(); + assertEquals(Arrays.asList("Sr."), list); + } + + //FN + { + FormattedNameType t = vcard.getFormattedName(); + assertEquals("Mr. John Richter, James Doe Sr.", t.getValue()); + } + + //NICKNAME + { + NicknameType t = vcard.getNickname(); + assertEquals(Arrays.asList("Johny"), t.getValues()); + } + + //ORG + { + OrganizationType t = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType t = it.next(); + assertEquals("Money Counter", t.getValue()); + + assertFalse(it.hasNext()); + } + + //CATEGORIES + { + CategoriesType t = vcard.getCategories(); + assertEquals(Arrays.asList("VIP"), t.getValues()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + NoteType t = it.next(); + assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue()); + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType t = it.next(); + assertEquals("john.doe@ibm.com", t.getValue()); + Set types = t.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type + assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().first("X-COUCHDB-UUID")); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType t = it.next(); + assertEquals("ASB-123", t.getPoBox()); + assertEquals(null, t.getExtendedAddress()); + assertEquals("15 Crescent moon drive", t.getStreetAddress()); + assertEquals("Albaney", t.getLocality()); + assertEquals("New York", t.getRegion()); + assertEquals("12345", t.getPostalCode()); + //the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file) + assertEquals("UnitedStates of America", t.getCountry()); + + Set types = t.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType t = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1980); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 22); + Date expected = c.getTime(); + assertEquals(expected, t.getDate()); + } + + //REV + { + RevisionType t = vcard.getRevision(); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 5); + c.set(Calendar.HOUR_OF_DAY, 13); + c.set(Calendar.MINUTE, 32); + c.set(Calendar.SECOND, 54); + assertEquals(c.getTime(), t.getTimestamp()); + } + + //extended types + { + assertEquals(7, countExtTypes(vcard)); + + Iterator it = vcard.getExtendedProperties("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator(); + RawType t = it.next(); + assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName()); + assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue()); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-AIM").iterator(); + t = it.next(); + assertEquals("X-AIM", t.getTypeName()); + assertEquals("johnny5@aol.com", t.getValue()); + assertEquals("HOME", t.getSubTypes().getType()); + assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().first("X-COUCHDB-UUID")); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-EVOLUTION-FILE-AS").iterator(); + t = it.next(); + assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName()); + assertEquals("Doe\\, John", t.getValue()); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-EVOLUTION-SPOUSE").iterator(); + t = it.next(); + assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName()); + assertEquals("Maria", t.getValue()); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-EVOLUTION-MANAGER").iterator(); + t = it.next(); + assertEquals("X-EVOLUTION-MANAGER", t.getTypeName()); + assertEquals("Big Blue", t.getValue()); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-EVOLUTION-ASSISTANT").iterator(); + t = it.next(); + assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName()); + assertEquals("Little Red", t.getValue()); + assertFalse(it.hasNext()); + + it = vcard.getExtendedProperties("X-EVOLUTION-ANNIVERSARY").iterator(); + t = it.next(); + assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName()); + assertEquals("1980-03-22", t.getValue()); + assertFalse(it.hasNext()); + } + } + + @Test + public void gmailVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. John Richter, James Doe Sr.", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertEquals(Arrays.asList("Richter, James"), f.getAdditional()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("Sr."), f.getSuffixes()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("john.doe@ibm.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(new EmailTypeParameter("home"))); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType f = it.next(); + assertEquals("905-555-1234", f.getText()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + + f = it.next(); + assertEquals("905-666-1234", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals("Crescent moon drive" + NEWLINE + "555-asd" + NEWLINE + "Nice Area, Albaney, New York12345" + NEWLINE + "United States of America", f.getExtendedAddress()); + assertEquals(null, f.getStreetAddress()); + assertEquals(null, f.getLocality()); + assertEquals(null, f.getRegion()); + assertEquals(null, f.getPostalCode()); + assertEquals(null, f.getCountry()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + + assertFalse(it.hasNext()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("Money Counter", f.getValue()); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1980); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 22); + assertEquals(c.getTime(), f.getDate()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://www.ibm.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("WORK")); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue()); + + assertFalse(it.hasNext()); + } + + //extended types + { + assertEquals(6, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); + assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); + assertEquals("Jon", f.getValue()); + + f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); + assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); + assertEquals("Dow", f.getValue()); + + f = vcard.getExtendedProperties("X-ABDATE").get(0); + assertEquals("X-ABDATE", f.getTypeName()); + assertEquals("1975-03-01", f.getValue()); + assertEquals("item1", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABLABEL").get(0); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + assertEquals("item1", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABLABEL").get(1); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + assertEquals("item2", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); + assertEquals("X-ABRELATEDNAMES", f.getTypeName()); + assertEquals("Jenny", f.getValue()); + assertEquals("item2", f.getGroup()); + } + } + + /** + * This vCard was generated when selecting a list of contacts and exporting + * them as a vCard. + */ + @Test + public void gmailList() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-list.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Arnold Smith", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Smith", f.getFamily()); + assertEquals("Arnold", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertTrue(f.getPrefixes().isEmpty()); + assertTrue(f.getSuffixes().isEmpty()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("asmithk@gmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Chris Beatle", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Beatle", f.getFamily()); + assertEquals("Chris", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertTrue(f.getPrefixes().isEmpty()); + assertTrue(f.getSuffixes().isEmpty()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("chrisy55d@yahoo.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Doug White", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("White", f.getFamily()); + assertEquals("Doug", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertTrue(f.getPrefixes().isEmpty()); + assertTrue(f.getSuffixes().isEmpty()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("dwhite@gmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + assertNull(reader.readNext()); + } + + @Test + public void gmailSingle() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Greg Dartmouth", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Dartmouth", f.getFamily()); + assertEquals("Greg", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertTrue(f.getPrefixes().isEmpty()); + assertTrue(f.getSuffixes().isEmpty()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("gdartmouth@hotmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType f = it.next(); + assertEquals("555 555 1111", f.getText()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + + f = it.next(); + assertEquals("item1", f.getGroup()); + assertEquals("555 555 2222", f.getText()); + types = f.getTypes(); + assertTrue(types.isEmpty()); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("123 Home St" + NEWLINE + "Home City, HM 12345", f.getStreetAddress()); + assertEquals(null, f.getLocality()); + assertEquals(null, f.getRegion()); + assertEquals(null, f.getPostalCode()); + assertEquals(null, f.getCountry()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + + f = it.next(); + assertEquals("item2", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("321 Custom St", f.getStreetAddress()); + assertEquals("Custom City", f.getLocality()); + assertEquals("TX", f.getRegion()); + assertEquals("98765", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + types = f.getTypes(); + assertTrue(types.isEmpty()); + + assertFalse(it.hasNext()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("TheCompany"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("TheJobTitle", f.getValue()); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1960); + c.set(Calendar.MONTH, Calendar.SEPTEMBER); + c.set(Calendar.DAY_OF_MONTH, 10); + assertEquals(c.getTime(), f.getDate()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://TheProfile.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertTrue(types.isEmpty()); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("This is GMail's note field." + NEWLINE + "It should be added as a NOTE type." + NEWLINE + "ACustomField: CustomField", f.getValue()); + + assertFalse(it.hasNext()); + } + + //extended types + { + assertEquals(12, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); + assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); + assertEquals("Grregg", f.getValue()); + + f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); + assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); + assertEquals("Dart-mowth", f.getValue()); + + f = vcard.getExtendedProperties("X-ICQ").get(0); + assertEquals("X-ICQ", f.getTypeName()); + assertEquals("123456789", f.getValue()); + + Iterator abLabelIt = vcard.getExtendedProperties("X-ABLABEL").iterator(); + { + f = abLabelIt.next(); + assertEquals("item1", f.getGroup()); + assertEquals("GRAND_CENTRAL", f.getValue()); + + f = abLabelIt.next(); + assertEquals("item2", f.getGroup()); + assertEquals("CustomAdrType", f.getValue()); + + f = abLabelIt.next(); + assertEquals("item3", f.getGroup()); + assertEquals("PROFILE", f.getValue()); + + f = abLabelIt.next(); + assertEquals("item4", f.getGroup()); + assertEquals("_$!!$_", f.getValue()); + + f = abLabelIt.next(); + assertEquals("item5", f.getGroup()); + assertEquals("_$!!$_", f.getValue()); + + f = abLabelIt.next(); + assertEquals("item6", f.getGroup()); + assertEquals("CustomRelationship", f.getValue()); + + assertFalse(abLabelIt.hasNext()); + } + + f = vcard.getExtendedProperties("X-ABDATE").get(0); + assertEquals("item4", f.getGroup()); + assertEquals("X-ABDATE", f.getTypeName()); + assertEquals("1970-06-02", f.getValue()); + + f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); + assertEquals("item5", f.getGroup()); + assertEquals("X-ABRELATEDNAMES", f.getTypeName()); + assertEquals("MySpouse", f.getValue()); + + f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(1); + assertEquals("item6", f.getGroup()); + assertEquals("X-ABRELATEDNAMES", f.getTypeName()); + assertEquals("MyCustom", f.getValue()); + } + } + + @Test + public void iPhoneVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //PRODID + { + ProdIdType f = vcard.getProdId(); + assertEquals("-//Apple Inc.//iOS 5.0.1//EN", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertEquals(Arrays.asList("Richter", "James"), f.getAdditional()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("Sr."), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. John Richter James Doe Sr.", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Johny"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("Money Counter", f.getValue()); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("item1", f.getGroup()); + assertEquals("john.doe@ibm.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(EmailTypeParameter.PREF)); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType f = it.next(); + assertEquals("905-555-1234", f.getText()); + Set types = f.getTypes(); + assertEquals(3, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + assertTrue(types.contains(TelephoneTypeParameter.PREF)); + + f = it.next(); + assertEquals("905-666-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("905-777-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("905-888-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + f = it.next(); + assertEquals("905-999-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + f = it.next(); + assertEquals("905-111-1234", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.PAGER)); + + f = it.next(); + assertEquals("905-222-1234", f.getText()); + assertEquals("item2", f.getGroup()); + types = f.getTypes(); + assertEquals(0, types.size()); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals("item3", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Silicon Alley 5,", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("New York", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("United States of America", f.getCountry()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + f = it.next(); + assertEquals("item4", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals(null, f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + + assertFalse(it.hasNext()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("item5", f.getGroup()); + assertEquals("http://www.ibm.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("pref")); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.JUNE); + c.set(Calendar.DAY_OF_MONTH, 6); + assertEquals(c.getTime(), f.getDate()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(ImageTypeParameter.JPEG, f.getContentType()); + assertEquals(32531, f.getData().length); + } + + //extended types + { + assertEquals(4, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); + assertEquals("item2", f.getGroup()); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + + f = vcard.getExtendedProperties("X-ABADR").get(0); + assertEquals("item3", f.getGroup()); + assertEquals("X-ABADR", f.getTypeName()); + assertEquals("Silicon Alley", f.getValue()); + + f = vcard.getExtendedProperties("X-ABADR").get(1); + assertEquals("item4", f.getGroup()); + assertEquals("X-ABADR", f.getTypeName()); + assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue()); + + f = vcard.getExtendedProperties("X-ABLABEL").get(1); + assertEquals("item5", f.getGroup()); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + } + } + + @Test + public void lotusNotesVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //PRODID + { + ProdIdType f = vcard.getProdId(); + assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue()); + } + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertEquals(Arrays.asList("Johny"), f.getAdditional()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("I"), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. Doe John I Johny", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Johny,JayJay"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM", "SUN"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("Generic Accountant", f.getValue()); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("john.doe@ibm.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(3, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(new EmailTypeParameter("WORK"))); + assertTrue(types.contains(EmailTypeParameter.PREF)); + + f = it.next(); + assertEquals("billy_bob@gmail.com", f.getValue()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(new EmailTypeParameter("WORK"))); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + TelephoneType f = it.next(); + assertEquals("+1 (212) 204-34456", f.getText()); + Set types = f.getTypes(); + assertEquals(3, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + assertTrue(types.contains(TelephoneTypeParameter.PREF)); + + f = it.next(); + assertEquals("00-1-212-555-7777", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals("item1", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("New York", f.getRegion()); + assertEquals("NYC887", f.getPostalCode()); + assertEquals("U.S.A.", f.getCountry()); + assertNull(f.getLabel()); + + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue()); + + assertFalse(it.hasNext()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("item2", f.getGroup()); + assertEquals("http://www.sun.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("pref")); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1980); + c.set(Calendar.MONTH, Calendar.MAY); + c.set(Calendar.DAY_OF_MONTH, 21); + assertEquals(c.getTime(), f.getDate()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(ImageTypeParameter.JPEG, f.getContentType()); + assertEquals(7957, f.getData().length); + + assertFalse(it.hasNext()); + } + + //UID + { + UidType f = vcard.getUid(); + assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue()); + } + + //GEO + { + GeoType f = vcard.getGeo(); + assertEquals(-2.6, f.getLatitude(), .01); + assertEquals(3.4, f.getLongitude(), .01); + } + + //CLASS + { + ClassificationType f = vcard.getClassification(); + assertEquals("Public", f.getValue()); + } + + //PROFILE + { + ProfileType f = vcard.getProfile(); + assertEquals("VCard", f.getValue()); + } + + //TZ + { + TimezoneType f = vcard.getTimezone(); + assertIntEquals(1, f.getHourOffset()); + assertIntEquals(0, f.getMinuteOffset()); + } + + //LABEL + { + Iterator it = vcard.getOrphanedLabels().iterator(); + + LabelType f = it.next(); + assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue()); + Set types = f.getTypes(); + assertEquals(3, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + assertTrue(types.contains(AddressTypeParameter.PARCEL)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + assertFalse(it.hasNext()); + } + + //SORT-STRING + { + SortStringType f = vcard.getSortString(); + assertEquals("JOHN", f.getValue()); + } + + //ROLE + { + Iterator it = vcard.getRoles().iterator(); + + RoleType f = it.next(); + assertEquals("Counting Money", f.getValue()); + + assertFalse(it.hasNext()); + } + + //SOURCE + { + Iterator it = vcard.getSources().iterator(); + + SourceType f = it.next(); + assertEquals("Whatever", f.getValue()); + + assertFalse(it.hasNext()); + } + + //MAILER + { + MailerType f = vcard.getMailer(); + assertEquals("Mozilla Thunderbird", f.getValue()); + } + + //NAME + { + SourceDisplayTextType f = vcard.getSourceDisplayText(); + assertEquals("VCard for John Doe", f.getValue()); + } + + //extended types + { + assertEquals(4, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0); + assertEquals("item2", f.getGroup()); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + + f = vcard.getExtendedProperties("X-ABUID").get(0); + assertEquals("X-ABUID", f.getTypeName()); + assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue()); + + f = vcard.getExtendedProperties("X-GENERATOR").get(0); + assertEquals("X-GENERATOR", f.getTypeName()); + assertEquals("Cardme Generator", f.getValue()); + + f = vcard.getExtendedProperties("X-LONG-STRING").get(0); + assertEquals("X-LONG-STRING", f.getTypeName()); + assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue()); + } + } + + @Test + public void msOutlookVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V2_1, vcard.getVersion()); + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("en-us", f.getSubTypes().getLanguage()); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertEquals(Arrays.asList("Richter", "James"), f.getAdditional()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("Sr."), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. John Richter James Doe Sr.", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Johny"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("Money Counter", f.getValue()); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue()); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + TelephoneType f = it.next(); + + assertEquals("(905) 555-1234", f.getText()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("(905) 666-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Cresent moon drive", f.getStreetAddress()); + assertEquals("Albaney", f.getLocality()); + assertEquals("New York", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("United States of America", f.getCountry()); + assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Silicon Alley 5,", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("New York", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("United States of America", f.getCountry()); + assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + + assertFalse(it.hasNext()); + } + + //LABEL + { + assertTrue(vcard.getOrphanedLabels().isEmpty()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://www.ibm.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("WORK")); + + assertFalse(it.hasNext()); + } + + //ROLE + { + Iterator it = vcard.getRoles().iterator(); + + RoleType f = it.next(); + assertEquals("Counting Money", f.getValue()); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1980); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 22); + assertEquals(c.getTime(), f.getDate()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("john.doe@ibm.cm", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.PREF)); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(ImageTypeParameter.JPEG, f.getContentType()); + assertEquals(860, f.getData().length); + + assertFalse(it.hasNext()); + } + + //REV + { + RevisionType f = vcard.getRevision(); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 5); + c.set(Calendar.HOUR_OF_DAY, 13); + c.set(Calendar.MINUTE, 19); + c.set(Calendar.SECOND, 33); + assertEquals(c.getTime(), f.getTimestamp()); + } + + //extended types + { + assertEquals(6, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); + assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); + assertEquals("2", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); + assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); + assertEquals("20110113", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); + assertEquals("X-MS-IMADDRESS", f.getTypeName()); + assertEquals("johny5@aol.com", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); + assertEquals("X-MS-OL-DESIGN", f.getTypeName()); + assertEquals("", f.getValue()); + assertEquals("utf-8", f.getSubTypes().getCharset()); + + f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); + assertEquals("X-MS-MANAGER", f.getTypeName()); + assertEquals("Big Blue", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); + assertEquals("X-MS-ASSISTANT", f.getTypeName()); + assertEquals("Jenny", f.getValue()); + } + } + + @Test + public void outlook2007VCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V2_1, vcard.getVersion()); + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("en-us", f.getSubTypes().getLanguage()); + assertEquals("Angstadt", f.getFamily()); + assertEquals("Michael", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("Jr."), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. Michael Angstadt Jr.", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Mike"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("TheJobTitle", f.getValue()); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue()); + assertEquals("us-ascii", f.getSubTypes().getCharset()); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + TelephoneType f = it.next(); + + assertEquals("(111) 555-1111", f.getText()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("(111) 555-2222", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("(111) 555-4444", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("(111) 555-3333", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals("TheOffice", f.getExtendedAddress()); + assertEquals("222 Broadway", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("NY", f.getRegion()); + assertEquals("99999", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + assertFalse(it.hasNext()); + } + + //LABEL + { + assertTrue(vcard.getOrphanedLabels().isEmpty()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://mikeangstadt.name", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("HOME")); + + f = it.next(); + assertEquals("http://mikeangstadt.name", f.getValue()); + types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("WORK")); + + assertFalse(it.hasNext()); + } + + //ROLE + { + Iterator it = vcard.getRoles().iterator(); + + RoleType f = it.next(); + assertEquals("TheProfession", f.getValue()); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1922); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 10); + assertEquals(c.getTime(), f.getDate()); + } + + //KEY + { + Iterator it = vcard.getKeys().iterator(); + + KeyType f = it.next(); + assertEquals(KeyTypeParameter.X509, f.getContentType()); + assertEquals(514, f.getData().length); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("mike.angstadt@gmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.PREF)); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(ImageTypeParameter.JPEG, f.getContentType()); + assertEquals(2324, f.getData().length); + + assertFalse(it.hasNext()); + } + + //FBURL + { + //a 4.0 property in a 2.1 vCard... + Iterator it = vcard.getFbUrls().iterator(); + + FbUrlType f = it.next(); + assertEquals("http://website.com/mycal", f.getValue()); + + assertFalse(it.hasNext()); + } + + //REV + { + RevisionType f = vcard.getRevision(); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.AUGUST); + c.set(Calendar.DAY_OF_MONTH, 1); + c.set(Calendar.HOUR_OF_DAY, 18); + c.set(Calendar.MINUTE, 46); + c.set(Calendar.SECOND, 31); + assertEquals(c.getTime(), f.getTimestamp()); + } + + //extended types + { + assertEquals(8, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0); + assertEquals("X-MS-TEL", f.getTypeName()); + assertEquals("(111) 555-4444", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains("VOICE")); + assertTrue(types.contains("CALLBACK")); + + f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0); + assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName()); + assertEquals("2", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0); + assertEquals("X-MS-ANNIVERSARY", f.getTypeName()); + assertEquals("20120801", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0); + assertEquals("X-MS-IMADDRESS", f.getTypeName()); + assertEquals("im@aim.com", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0); + assertEquals("X-MS-OL-DESIGN", f.getTypeName()); + assertEquals("", f.getValue()); + assertEquals("utf-8", f.getSubTypes().getCharset()); + + f = vcard.getExtendedProperties("X-MS-MANAGER").get(0); + assertEquals("X-MS-MANAGER", f.getTypeName()); + assertEquals("TheManagerName", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0); + assertEquals("X-MS-ASSISTANT", f.getTypeName()); + assertEquals("TheAssistantName", f.getValue()); + + f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0); + assertEquals("X-MS-SPOUSE", f.getTypeName()); + assertEquals("TheSpouse", f.getValue()); + } + } + + @Test + public void macAddressBookVCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertEquals(Arrays.asList("Richter,James"), f.getAdditional()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("Sr."), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("Mr. John Richter,James Doe Sr.", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Johny"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("Money Counter", f.getValue()); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("john.doe@ibm.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(3, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(new EmailTypeParameter("work"))); + assertTrue(types.contains(EmailTypeParameter.PREF)); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType f = it.next(); + assertEquals("905-777-1234", f.getText()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.PREF)); + + f = it.next(); + assertEquals("905-666-1234", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + + f = it.next(); + assertEquals("905-555-1234", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + + f = it.next(); + assertEquals("905-888-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + f = it.next(); + assertEquals("905-999-1234", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + f = it.next(); + assertEquals("905-111-1234", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.PAGER)); + + f = it.next(); + assertEquals("905-222-1234", f.getText()); + assertEquals("item1", f.getGroup()); + types = f.getTypes(); + assertEquals(0, types.size()); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals("item2", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Silicon Alley 5,", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("New York", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("United States of America", f.getCountry()); + + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + assertTrue(types.contains(AddressTypeParameter.PREF)); + + f = it.next(); + assertEquals("item3", f.getGroup()); + assertEquals(null, f.getPoBox()); + assertEquals(null, f.getExtendedAddress()); + assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals(null, f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue()); + + assertFalse(it.hasNext()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("item4", f.getGroup()); + assertEquals("http://www.ibm.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("pref")); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.JUNE); + c.set(Calendar.DAY_OF_MONTH, 6); + assertEquals(c.getTime(), f.getDate()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(null, f.getContentType()); + assertEquals(18242, f.getData().length); + + assertFalse(it.hasNext()); + } + + //extended types + { + assertEquals(9, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0); + assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName()); + assertEquals("Jon", f.getValue()); + + f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0); + assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName()); + assertEquals("Dow", f.getValue()); + + f = vcard.getExtendedProperties("X-ABLABEL").get(0); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("AssistantPhone", f.getValue()); + assertEquals("item1", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABADR").get(0); + assertEquals("X-ABADR", f.getTypeName()); + assertEquals("Silicon Alley", f.getValue()); + assertEquals("item2", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABADR").get(1); + assertEquals("X-ABADR", f.getTypeName()); + assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue()); + assertEquals("item3", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABLABEL").get(1); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("_$!!$_", f.getValue()); + assertEquals("item4", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0); + assertEquals("X-ABRELATEDNAMES", f.getTypeName()); + assertEquals("Jenny", f.getValue()); + assertEquals("item5", f.getGroup()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("pref")); + + f = vcard.getExtendedProperties("X-ABLABEL").get(2); + assertEquals("X-ABLabel", f.getTypeName()); + assertEquals("Spouse", f.getValue()); + assertEquals("item5", f.getGroup()); + + f = vcard.getExtendedProperties("X-ABUID").get(0); + assertEquals("X-ABUID", f.getTypeName()); + assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue()); + } + } + + @Test + public void outlook2003VCard() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V2_1, vcard.getVersion()); + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertEquals(Arrays.asList("Mr."), f.getPrefixes()); + assertEquals(Arrays.asList("III"), f.getSuffixes()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("John Doe III", f.getValue()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Joey"), f.getValues()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("The Job Title", f.getValue()); + + assertFalse(it.hasNext()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue()); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + TelephoneType f = it.next(); + + assertEquals("BusinessPhone", f.getText()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("HomePhone", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("MobilePhone", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("BusinessFaxPhone", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + + assertFalse(it.hasNext()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals("TheOffice", f.getExtendedAddress()); + assertEquals("123 Main St", f.getStreetAddress()); + assertEquals("Austin", f.getLocality()); + assertEquals("TX", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("United States of America", f.getCountry()); + assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel()); + Set types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + + assertFalse(it.hasNext()); + } + + //LABEL + { + assertTrue(vcard.getOrphanedLabels().isEmpty()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://web-page-address.com", f.getValue()); + Set types = f.getSubTypes().getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains("WORK")); + + assertFalse(it.hasNext()); + } + + //ROLE + { + Iterator it = vcard.getRoles().iterator(); + + RoleType f = it.next(); + assertEquals("TheProfession", f.getValue()); + + assertFalse(it.hasNext()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1980); + c.set(Calendar.MONTH, Calendar.MARCH); + c.set(Calendar.DAY_OF_MONTH, 21); + assertEquals(c.getTime(), f.getDate()); + } + + //KEY + { + Iterator it = vcard.getKeys().iterator(); + + KeyType f = it.next(); + assertEquals(KeyTypeParameter.X509, f.getContentType()); + assertEquals(805, f.getData().length); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("jdoe@hotmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.PREF)); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + //FBURL + { + Iterator it = vcard.getFbUrls().iterator(); + + //Outlook 2003 apparently doesn't output FBURL correctly: + //http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html + FbUrlType f = it.next(); + assertEquals("????????????????s????????????" + (char) 12, f.getValue()); + + assertFalse(it.hasNext()); + } + + //REV + { + RevisionType f = vcard.getRevision(); + Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + c.clear(); + c.set(Calendar.YEAR, 2012); + c.set(Calendar.MONTH, Calendar.OCTOBER); + c.set(Calendar.DAY_OF_MONTH, 12); + c.set(Calendar.HOUR_OF_DAY, 21); + c.set(Calendar.MINUTE, 5); + c.set(Calendar.SECOND, 25); + assertEquals(c.getTime(), f.getTimestamp()); + } + } + + @Test + public void thunderbird() throws Exception { + VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf")); + VCard vcard = reader.readNext(); + + //VERSION + assertEquals(VCardVersion.V3_0, vcard.getVersion()); + + //N + { + StructuredNameType f = vcard.getStructuredName(); + assertEquals("Doe", f.getFamily()); + assertEquals("John", f.getGiven()); + assertTrue(f.getAdditional().isEmpty()); + assertTrue(f.getPrefixes().isEmpty()); + assertTrue(f.getSuffixes().isEmpty()); + } + + //FN + { + FormattedNameType f = vcard.getFormattedName(); + assertEquals("John Doe", f.getValue()); + } + + //ORG + { + OrganizationType f = vcard.getOrganization(); + assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues()); + } + + //NICKNAME + { + NicknameType f = vcard.getNickname(); + assertEquals(Arrays.asList("Johnny"), f.getValues()); + } + + //ADR + { + Iterator it = vcard.getAddresses().iterator(); + + AddressType f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals("222 Broadway", f.getExtendedAddress()); + assertEquals("Suite 100", f.getStreetAddress()); + assertEquals("New York", f.getLocality()); + assertEquals("NY", f.getRegion()); + assertEquals("98765", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.WORK)); + assertTrue(types.contains(AddressTypeParameter.POSTAL)); + + f = it.next(); + assertEquals(null, f.getPoBox()); + assertEquals("123 Main St", f.getExtendedAddress()); + assertEquals("Apt 10", f.getStreetAddress()); + assertEquals("Austin", f.getLocality()); + assertEquals("TX", f.getRegion()); + assertEquals("12345", f.getPostalCode()); + assertEquals("USA", f.getCountry()); + + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(AddressTypeParameter.HOME)); + assertTrue(types.contains(AddressTypeParameter.POSTAL)); + + assertFalse(it.hasNext()); + } + + //TEL + { + Iterator it = vcard.getTelephoneNumbers().iterator(); + + TelephoneType f = it.next(); + assertEquals("555-555-1111", f.getText()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.WORK)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("555-555-2222", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.HOME)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("555-555-5555", f.getText()); + types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.CELL)); + assertTrue(types.contains(TelephoneTypeParameter.VOICE)); + + f = it.next(); + assertEquals("555-555-3333", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.FAX)); + + f = it.next(); + assertEquals("555-555-4444", f.getText()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(TelephoneTypeParameter.PAGER)); + + assertFalse(it.hasNext()); + } + + //EMAIL + { + Iterator it = vcard.getEmails().iterator(); + + EmailType f = it.next(); + assertEquals("doe.john@hotmail.com", f.getValue()); + Set types = f.getTypes(); + assertEquals(2, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + assertTrue(types.contains(EmailTypeParameter.PREF)); + + f = it.next(); + assertEquals("additional-email@company.com", f.getValue()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + f = it.next(); + assertEquals("additional-email1@company.com", f.getValue()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + f = it.next(); + assertEquals("additional-email2@company.com", f.getValue()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + f = it.next(); + assertEquals("additional-email3@company.com", f.getValue()); + types = f.getTypes(); + assertEquals(1, types.size()); + assertTrue(types.contains(EmailTypeParameter.INTERNET)); + + assertFalse(it.hasNext()); + } + + //URL + { + Iterator it = vcard.getUrls().iterator(); + + UrlType f = it.next(); + assertEquals("http://www.private-webpage.com", f.getValue()); + assertEquals("HOME", f.getType()); + + f = it.next(); + assertEquals("http://www.work-webpage.com", f.getValue()); + assertEquals("WORK", f.getType()); + + assertFalse(it.hasNext()); + } + + //TITLE + { + Iterator it = vcard.getTitles().iterator(); + + TitleType f = it.next(); + assertEquals("TheTitle", f.getValue()); + + assertFalse(it.hasNext()); + } + + //CATEGORIES + { + //commas are incorrectly escaped, so there is only 1 item + CategoriesType f = vcard.getCategories(); + assertEquals(Arrays.asList("category1, category2, category3"), f.getValues()); + } + + //BDAY + { + BirthdayType f = vcard.getBirthday(); + Calendar c = Calendar.getInstance(); + c.clear(); + c.set(Calendar.YEAR, 1970); + c.set(Calendar.MONTH, Calendar.SEPTEMBER); + c.set(Calendar.DAY_OF_MONTH, 21); + assertEquals(c.getTime(), f.getDate()); + } + + //NOTE + { + Iterator it = vcard.getNotes().iterator(); + + NoteType f = it.next(); + assertEquals("This is the notes field." + NEWLINE + "Second Line" + NEWLINE + NEWLINE + "Fourth Line" + NEWLINE + "You can put anything in the \"note\" field; even curse words.", f.getValue()); + + assertFalse(it.hasNext()); + } + + //PHOTO + { + Iterator it = vcard.getPhotos().iterator(); + + PhotoType f = it.next(); + assertEquals(ImageTypeParameter.JPEG, f.getContentType()); + assertEquals(8940, f.getData().length); + + assertFalse(it.hasNext()); + } + + //extended types + { + assertEquals(2, countExtTypes(vcard)); + + RawType f = vcard.getExtendedProperties("X-SPOUSE").get(0); + assertEquals("X-SPOUSE", f.getTypeName()); + assertEquals("TheSpouse", f.getValue()); + + f = vcard.getExtendedProperties("X-ANNIVERSARY").get(0); + assertEquals("X-ANNIVERSARY", f.getTypeName()); + assertEquals("1990-04-30", f.getValue()); + } + } + + /** + * Counts the number of extended types in a vCard. + * @param vcard the vCard + * @return the number of extended types + */ + private int countExtTypes(VCard vcard) { + return vcard.getExtendedProperties().size(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `VCardReader(...)` at line 1219 is not released after line 1220. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void VCardReaderTest.iPhoneVCard() + +### Procedure Id: +ezvcard.io.VCardReaderTest.iPhoneVCard():void.27c511c29a31cd997d3760750b8ac50e + +### File: +src/test/java/ezvcard/io/VCardReaderTest.java + +### Key: +VCardReaderTest.java|iPhoneVCard|RESOURCE_LEAK + +### Node Key: +dfe17392a7a960e94a27d58804297f95 + +### Hash: +a1e2ab022997e6b8fc7c5d5a05e98985 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7740/instruction.md b/inferredbugs-7740/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..248c7973645f75410c40bfc1ca9120e08e2e8b70 --- /dev/null +++ b/inferredbugs-7740/instruction.md @@ -0,0 +1,201 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.nodes; + +import org.jsoup.internal.StringUtil; +import org.jsoup.helper.Validate; + +import java.io.IOException; + +/** + A text node. + + @author Jonathan Hedley, jonathan@hedley.net */ +public class TextNode extends LeafNode { + /** + Create a new TextNode representing the supplied (unencoded) text). + + @param text raw text + @see #createFromEncoded(String) + */ + public TextNode(String text) { + value = text; + } + + public String nodeName() { + return "#text"; + } + + /** + * Get the text content of this text node. + * @return Unencoded, normalised text. + * @see TextNode#getWholeText() + */ + public String text() { + return StringUtil.normaliseWhitespace(getWholeText()); + } + + /** + * Set the text content of this text node. + * @param text unencoded text + * @return this, for chaining + */ + public TextNode text(String text) { + coreValue(text); + return this; + } + + /** + Get the (unencoded) text of this text node, including any newlines and spaces present in the original. + @return text + */ + public String getWholeText() { + return coreValue(); + } + + /** + Test if this text node is blank -- that is, empty or only whitespace (including newlines). + @return true if this document is empty or only whitespace, false if it contains any text content. + */ + public boolean isBlank() { + return StringUtil.isBlank(coreValue()); + } + + /** + * Split this text node into two nodes at the specified string offset. After splitting, this node will contain the + * original text up to the offset, and will have a new text node sibling containing the text after the offset. + * @param offset string offset point to split node at. + * @return the newly created text node containing the text after the offset. + */ + public TextNode splitText(int offset) { + final String text = coreValue(); + Validate.isTrue(offset >= 0, "Split offset must be not be negative"); + Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length"); + + String head = text.substring(0, offset); + String tail = text.substring(offset); + text(head); + TextNode tailNode = new TextNode(tail); + if (parent() != null) + parent().addChildren(siblingIndex()+1, tailNode); + + return tailNode; + } + + void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException { + if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) )) + indent(accum, depth, out); + + boolean normaliseWhite = out.prettyPrint() && !Element.preserveWhitespace(parent()); + Entities.escape(accum, coreValue(), out, false, normaliseWhite, false); + } + + void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {} + + @Override + public String toString() { + return outerHtml(); + } + + @Override + public TextNode clone() { + return (TextNode) super.clone(); + } + + /** + * Create a new TextNode from HTML encoded (aka escaped) data. + * @param encodedText Text containing encoded HTML (e.g. &lt;) + * @return TextNode containing unencoded data (e.g. <) + */ + public static TextNode createFromEncoded(String encodedText) { + String text = Entities.unescape(encodedText); + return new TextNode(text); + } + + static String normaliseWhitespace(String text) { + text = StringUtil.normaliseWhitespace(text); + return text; + } + + static String stripLeadingWhitespace(String text) { + return text.replaceFirst("^\\s+", ""); + } + + static boolean lastCharIsWhitespace(StringBuilder sb) { + return sb.length() != 0 && sb.charAt(sb.length() - 1) == ' '; + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `parent()` could be null and is dereferenced by call to `preserveWhitespace(...)` at line 87. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TextNode.outerHtmlHead(Appendable,int,Document$OutputSettings) + +### Procedure Id: +org.jsoup.nodes.TextNode.outerHtmlHead(java.lang.Appendable,int,org.jsoup.nodes.Document$OutputSetti.2fac4aab764b1646fed12838c17c9e9a + +### File: +src/main/java/org/jsoup/nodes/TextNode.java + +### Key: +TextNode.java|outerHtmlHead|NULL_DEREFERENCE + +### Node Key: +2718d1e24ca659f7f809828518104f86 + +### Hash: +3ba8030b13c5e0332f00c8d2abf19212 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7741/instruction.md b/inferredbugs-7741/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..908cc377b2832f418f9bd628aa1f8e0cf44a2b78 --- /dev/null +++ b/inferredbugs-7741/instruction.md @@ -0,0 +1,799 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 34 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.nodes; + +import org.jsoup.SerializationException; +import org.jsoup.internal.StringUtil; +import org.jsoup.helper.Validate; +import org.jsoup.select.NodeFilter; +import org.jsoup.select.NodeTraversor; +import org.jsoup.select.NodeVisitor; + +import java.io.IOException; +import java.util.*; + +/** + The base, abstract Node model. Elements, Documents, Comments etc are all Node instances. + + @author Jonathan Hedley, jonathan@hedley.net */ +public abstract class Node implements Cloneable { + static final String EmptyString = ""; + Node parentNode; + int siblingIndex; + + /** + * Default constructor. Doesn't setup base uri, children, or attributes; use with caution. + */ + protected Node() { + } + + /** + Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof). + @return node name + */ + public abstract String nodeName(); + + /** + * Check if this Node has an actual Attributes object. + */ + protected abstract boolean hasAttributes(); + + public boolean hasParent() { + return parentNode != null; + } + + /** + * Get an attribute's value by its key. Case insensitive + *

+ * To get an absolute URL from an attribute that may be a relative URL, prefix the key with abs, + * which is a shortcut to the {@link #absUrl} method. + *

+ * E.g.: + *
String url = a.attr("abs:href");
+ * + * @param attributeKey The attribute key. + * @return The attribute, or empty string if not present (to avoid nulls). + * @see #attributes() + * @see #hasAttr(String) + * @see #absUrl(String) + */ + public String attr(String attributeKey) { + Validate.notNull(attributeKey); + if (!hasAttributes()) + return EmptyString; + + String val = attributes().getIgnoreCase(attributeKey); + if (val.length() > 0) + return val; + else if (attributeKey.startsWith("abs:")) + return absUrl(attributeKey.substring("abs:".length())); + else return ""; + } + + /** + * Get all of the element's attributes. + * @return attributes (which implements iterable, in same order as presented in original HTML). + */ + public abstract Attributes attributes(); + + /** + * Set an attribute (key=value). If the attribute already exists, it is replaced. The attribute key comparison is + * case insensitive. The key will be set with case sensitivity as set in the parser settings. + * @param attributeKey The attribute key. + * @param attributeValue The attribute value. + * @return this (for chaining) + */ + public Node attr(String attributeKey, String attributeValue) { + attributeKey = NodeUtils.parser(this).settings().normalizeAttribute(attributeKey); + attributes().putIgnoreCase(attributeKey, attributeValue); + return this; + } + + /** + * Test if this element has an attribute. Case insensitive + * @param attributeKey The attribute key to check. + * @return true if the attribute exists, false if not. + */ + public boolean hasAttr(String attributeKey) { + Validate.notNull(attributeKey); + + if (attributeKey.startsWith("abs:")) { + String key = attributeKey.substring("abs:".length()); + if (attributes().hasKeyIgnoreCase(key) && !absUrl(key).equals("")) + return true; + } + return attributes().hasKeyIgnoreCase(attributeKey); + } + + /** + * Remove an attribute from this node. + * @param attributeKey The attribute to remove. + * @return this (for chaining) + */ + public Node removeAttr(String attributeKey) { + Validate.notNull(attributeKey); + attributes().removeIgnoreCase(attributeKey); + return this; + } + + /** + * Clear (remove) all of the attributes in this node. + * @return this, for chaining + */ + public Node clearAttributes() { + Iterator it = attributes().iterator(); + while (it.hasNext()) { + it.next(); + it.remove(); + } + return this; + } + + /** + Get the base URI of this node. + @return base URI + */ + public abstract String baseUri(); + + /** + * Set the baseUri for just this node (not its descendants), if this Node tracks base URIs. + * @param baseUri new URI + */ + protected abstract void doSetBaseUri(String baseUri); + + /** + Update the base URI of this node and all of its descendants. + @param baseUri base URI to set + */ + public void setBaseUri(final String baseUri) { + Validate.notNull(baseUri); + + traverse(new NodeVisitor() { + public void head(Node node, int depth) { + node.doSetBaseUri(baseUri); + } + + public void tail(Node node, int depth) { + } + }); + } + + /** + * Get an absolute URL from a URL attribute that may be relative (i.e. an <a href> or + * <img src>). + *

+ * E.g.: String absUrl = linkEl.absUrl("href"); + *

+ *

+ * If the attribute value is already absolute (i.e. it starts with a protocol, like + * http:// or https:// etc), and it successfully parses as a URL, the attribute is + * returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made + * absolute using that. + *

+ *

+ * As an alternate, you can use the {@link #attr} method with the abs: prefix, e.g.: + * String absUrl = linkEl.attr("abs:href"); + *

+ * + * @param attributeKey The attribute key + * @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or + * could not be made successfully into a URL. + * @see #attr + * @see java.net.URL#URL(java.net.URL, String) + */ + public String absUrl(String attributeKey) { + Validate.notEmpty(attributeKey); + + if (!hasAttr(attributeKey)) { + return ""; // nothing to make absolute with + } else { + return StringUtil.resolve(baseUri(), attr(attributeKey)); + } + } + + protected abstract List ensureChildNodes(); + + /** + Get a child node by its 0-based index. + @param index index of child node + @return the child node at this index. Throws a {@code IndexOutOfBoundsException} if the index is out of bounds. + */ + public Node childNode(int index) { + return ensureChildNodes().get(index); + } + + /** + Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes + themselves can be manipulated. + @return list of children. If no children, returns an empty list. + */ + public List childNodes() { + return Collections.unmodifiableList(ensureChildNodes()); + } + + /** + * Returns a deep copy of this node's children. Changes made to these nodes will not be reflected in the original + * nodes + * @return a deep copy of this node's children + */ + public List childNodesCopy() { + final List nodes = ensureChildNodes(); + final ArrayList children = new ArrayList<>(nodes.size()); + for (Node node : nodes) { + children.add(node.clone()); + } + return children; + } + + /** + * Get the number of child nodes that this node holds. + * @return the number of child nodes that this node holds. + */ + public abstract int childNodeSize(); + + protected Node[] childNodesAsArray() { + return ensureChildNodes().toArray(new Node[0]); + } + + /** + Gets this node's parent node. + @return parent node; or null if no parent. + */ + public Node parent() { + return parentNode; + } + + /** + Gets this node's parent node. Not overridable by extending classes, so useful if you really just need the Node type. + @return parent node; or null if no parent. + */ + public final Node parentNode() { + return parentNode; + } + + /** + * Get this node's root node; that is, its topmost ancestor. If this node is the top ancestor, returns {@code this}. + * @return topmost ancestor. + */ + public Node root() { + Node node = this; + while (node.parentNode != null) + node = node.parentNode; + return node; + } + + /** + * Gets the Document associated with this Node. + * @return the Document associated with this Node, or null if there is no such Document. + */ + public Document ownerDocument() { + Node root = root(); + return (root instanceof Document) ? (Document) root : null; + } + + /** + * Remove (delete) this node from the DOM tree. If this node has children, they are also removed. + */ + public void remove() { + Validate.notNull(parentNode); + parentNode.removeChild(this); + } + + /** + * Insert the specified HTML into the DOM before this node (i.e. as a preceding sibling). + * @param html HTML to add before this node + * @return this node, for chaining + * @see #after(String) + */ + public Node before(String html) { + addSiblingHtml(siblingIndex, html); + return this; + } + + /** + * Insert the specified node into the DOM before this node (i.e. as a preceding sibling). + * @param node to add before this node + * @return this node, for chaining + * @see #after(Node) + */ + public Node before(Node node) { + Validate.notNull(node); + Validate.notNull(parentNode); + + parentNode.addChildren(siblingIndex, node); + return this; + } + + /** + * Insert the specified HTML into the DOM after this node (i.e. as a following sibling). + * @param html HTML to add after this node + * @return this node, for chaining + * @see #before(String) + */ + public Node after(String html) { + addSiblingHtml(siblingIndex + 1, html); + return this; + } + + /** + * Insert the specified node into the DOM after this node (i.e. as a following sibling). + * @param node to add after this node + * @return this node, for chaining + * @see #before(Node) + */ + public Node after(Node node) { + Validate.notNull(node); + Validate.notNull(parentNode); + + parentNode.addChildren(siblingIndex + 1, node); + return this; + } + + private void addSiblingHtml(int index, String html) { + Validate.notNull(html); + Validate.notNull(parentNode); + + Element context = parent() instanceof Element ? (Element) parent() : null; + List nodes = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri()); + parentNode.addChildren(index, nodes.toArray(new Node[0])); + } + + /** + Wrap the supplied HTML around this node. + @param html HTML to wrap around this element, e.g. {@code
}. Can be arbitrarily deep. + @return this node, for chaining. + */ + public Node wrap(String html) { + Validate.notEmpty(html); + + Element context = parent() instanceof Element ? (Element) parent() : null; + List wrapChildren = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri()); + Node wrapNode = wrapChildren.get(0); + if (!(wrapNode instanceof Element)) // nothing to wrap with; noop + return null; + + Element wrap = (Element) wrapNode; + Element deepest = getDeepChild(wrap); + parentNode.replaceChild(this, wrap); + deepest.addChildren(this); + + // remainder (unbalanced wrap, like

-- The

is remainder + if (wrapChildren.size() > 0) { + //noinspection ForLoopReplaceableByForEach (beacause it allocates an Iterator which is wasteful here) + for (int i = 0; i < wrapChildren.size(); i++) { + Node remainder = wrapChildren.get(i); + remainder.parentNode.removeChild(remainder); + wrap.appendChild(remainder); + } + } + return this; + } + + /** + * Removes this node from the DOM, and moves its children up into the node's parent. This has the effect of dropping + * the node but keeping its children. + *

+ * For example, with the input html: + *

+ *

{@code

One Two Three
}

+ * Calling {@code element.unwrap()} on the {@code span} element will result in the html: + *

{@code

One Two Three
}

+ * and the {@code "Two "} {@link TextNode} being returned. + * + * @return the first child of this node, after the node has been unwrapped. Null if the node had no children. + * @see #remove() + * @see #wrap(String) + */ + public Node unwrap() { + Validate.notNull(parentNode); + final List childNodes = ensureChildNodes(); + Node firstChild = childNodes.size() > 0 ? childNodes.get(0) : null; + parentNode.addChildren(siblingIndex, this.childNodesAsArray()); + this.remove(); + + return firstChild; + } + + private Element getDeepChild(Element el) { + List children = el.children(); + if (children.size() > 0) + return getDeepChild(children.get(0)); + else + return el; + } + + void nodelistChanged() { + // Element overrides this to clear its shadow children elements + } + + /** + * Replace this node in the DOM with the supplied node. + * @param in the node that will will replace the existing node. + */ + public void replaceWith(Node in) { + Validate.notNull(in); + Validate.notNull(parentNode); + parentNode.replaceChild(this, in); + } + + protected void setParentNode(Node parentNode) { + Validate.notNull(parentNode); + if (this.parentNode != null) + this.parentNode.removeChild(this); + this.parentNode = parentNode; + } + + protected void replaceChild(Node out, Node in) { + Validate.isTrue(out.parentNode == this); + Validate.notNull(in); + if (in.parentNode != null) + in.parentNode.removeChild(in); + + final int index = out.siblingIndex; + ensureChildNodes().set(index, in); + in.parentNode = this; + in.setSiblingIndex(index); + out.parentNode = null; + } + + protected void removeChild(Node out) { + Validate.isTrue(out.parentNode == this); + final int index = out.siblingIndex; + ensureChildNodes().remove(index); + reindexChildren(index); + out.parentNode = null; + } + + protected void addChildren(Node... children) { + //most used. short circuit addChildren(int), which hits reindex children and array copy + final List nodes = ensureChildNodes(); + + for (Node child: children) { + reparentChild(child); + nodes.add(child); + child.setSiblingIndex(nodes.size()-1); + } + } + + protected void addChildren(int index, Node... children) { + Validate.noNullElements(children); + final List nodes = ensureChildNodes(); + + for (Node child : children) { + reparentChild(child); + } + nodes.addAll(index, Arrays.asList(children)); + reindexChildren(index); + } + + protected void reparentChild(Node child) { + child.setParentNode(this); + } + + private void reindexChildren(int start) { + final List childNodes = ensureChildNodes(); + + for (int i = start; i < childNodes.size(); i++) { + childNodes.get(i).setSiblingIndex(i); + } + } + + /** + Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not + include this node (a node is not a sibling of itself). + @return node siblings. If the node has no parent, returns an empty list. + */ + public List siblingNodes() { + if (parentNode == null) + return Collections.emptyList(); + + List nodes = parentNode.ensureChildNodes(); + List siblings = new ArrayList<>(nodes.size() - 1); + for (Node node: nodes) + if (node != this) + siblings.add(node); + return siblings; + } + + /** + Get this node's next sibling. + @return next sibling, or null if this is the last sibling + */ + public Node nextSibling() { + if (parentNode == null) + return null; // root + + final List siblings = parentNode.ensureChildNodes(); + final int index = siblingIndex+1; + if (siblings.size() > index) + return siblings.get(index); + else + return null; + } + + /** + Get this node's previous sibling. + @return the previous sibling, or null if this is the first sibling + */ + public Node previousSibling() { + if (parentNode == null) + return null; // root + + if (siblingIndex > 0) + return parentNode.ensureChildNodes().get(siblingIndex-1); + else + return null; + } + + /** + * Get the list index of this node in its node sibling list. I.e. if this is the first node + * sibling, returns 0. + * @return position in node sibling list + * @see org.jsoup.nodes.Element#elementSiblingIndex() + */ + public int siblingIndex() { + return siblingIndex; + } + + protected void setSiblingIndex(int siblingIndex) { + this.siblingIndex = siblingIndex; + } + + /** + * Perform a depth-first traversal through this node and its descendants. + * @param nodeVisitor the visitor callbacks to perform on each node + * @return this node, for chaining + */ + public Node traverse(NodeVisitor nodeVisitor) { + Validate.notNull(nodeVisitor); + NodeTraversor.traverse(nodeVisitor, this); + return this; + } + + /** + * Perform a depth-first filtering through this node and its descendants. + * @param nodeFilter the filter callbacks to perform on each node + * @return this node, for chaining + */ + public Node filter(NodeFilter nodeFilter) { + Validate.notNull(nodeFilter); + NodeTraversor.filter(nodeFilter, this); + return this; + } + + /** + Get the outer HTML of this node. For example, on a {@code p} element, may return {@code

Para

}. + @return outer HTML + @see Element#html() + @see Element#text() + */ + public String outerHtml() { + StringBuilder accum = StringUtil.borrowBuilder(); + outerHtml(accum); + return StringUtil.releaseBuilder(accum); + } + + protected void outerHtml(Appendable accum) { + NodeTraversor.traverse(new OuterHtmlVisitor(accum, NodeUtils.outputSettings(this)), this); + } + + /** + Get the outer HTML of this node. + @param accum accumulator to place HTML into + @throws IOException if appending to the given accumulator fails. + */ + abstract void outerHtmlHead(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException; + + abstract void outerHtmlTail(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException; + + /** + * Write this node and its children to the given {@link Appendable}. + * + * @param appendable the {@link Appendable} to write to. + * @return the supplied {@link Appendable}, for chaining. + */ + public T html(T appendable) { + outerHtml(appendable); + return appendable; + } + + /** + * Gets this node's outer HTML. + * @return outer HTML. + * @see #outerHtml() + */ + public String toString() { + return outerHtml(); + } + + protected void indent(Appendable accum, int depth, Document.OutputSettings out) throws IOException { + accum.append('\n').append(StringUtil.padding(depth * out.indentAmount())); + } + + /** + * Check if this node is the same instance of another (object identity test). + * @param o other object to compare to + * @return true if the content of this node is the same as the other + * @see Node#hasSameValue(Object) to compare nodes by their value + */ + @Override + public boolean equals(Object o) { + // implemented just so that javadoc is clear this is an identity test + return this == o; + } + + /** + * Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the + * other node; particularly its position in the tree does not influence its similarity. + * @param o other object to compare to + * @return true if the content of this node is the same as the other + */ + public boolean hasSameValue(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + return this.outerHtml().equals(((Node) o).outerHtml()); + } + + /** + * Create a stand-alone, deep copy of this node, and all of its children. The cloned node will have no siblings or + * parent node. As a stand-alone object, any changes made to the clone or any of its children will not impact the + * original node. + *

+ * The cloned node may be adopted into another Document or node structure using {@link Element#appendChild(Node)}. + * @return a stand-alone cloned node, including clones of any children + * @see #shallowClone() + */ + @Override + public Node clone() { + Node thisClone = doClone(null); // splits for orphan + + // Queue up nodes that need their children cloned (BFS). + final LinkedList nodesToProcess = new LinkedList<>(); + nodesToProcess.add(thisClone); + + while (!nodesToProcess.isEmpty()) { + Node currParent = nodesToProcess.remove(); + + final int size = currParent.childNodeSize(); + for (int i = 0; i < size; i++) { + final List childNodes = currParent.ensureChildNodes(); + Node childClone = childNodes.get(i).doClone(currParent); + childNodes.set(i, childClone); + nodesToProcess.add(childClone); + } + } + + return thisClone; + } + + /** + * Create a stand-alone, shallow copy of this node. None of its children (if any) will be cloned, and it will have + * no parent or sibling nodes. + * @return a single independent copy of this node + * @see #clone() + */ + public Node shallowClone() { + return doClone(null); + } + + /* + * Return a clone of the node using the given parent (which can be null). + * Not a deep copy of children. + */ + protected Node doClone(Node parent) { + Node clone; + + try { + clone = (Node) super.clone(); + } catch (CloneNotSupportedException e) { + throw new RuntimeException(e); + } + + clone.parentNode = parent; // can be null, to create an orphan split + clone.siblingIndex = parent == null ? 0 : siblingIndex; + + return clone; + } + + private static class OuterHtmlVisitor implements NodeVisitor { + private Appendable accum; + private Document.OutputSettings out; + + OuterHtmlVisitor(Appendable accum, Document.OutputSettings out) { + this.accum = accum; + this.out = out; + out.prepareEncoder(); + } + + public void head(Node node, int depth) { + try { + node.outerHtmlHead(accum, depth, out); + } catch (IOException exception) { + throw new SerializationException(exception); + } + } + + public void tail(Node node, int depth) { + if (!node.nodeName().equals("#text")) { // saves a void hit. + try { + node.outerHtmlTail(accum, depth, out); + } catch (IOException exception) { + throw new SerializationException(exception); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `child` last assigned on line 460 could be null and is dereferenced by call to `reparentChild(...)` at line 461. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Node.addChildren(int,org.jsoup.nodes.Node[]) + +### Procedure Id: +org.jsoup.nodes.Node.addChildren(int,org.jsoup.nodes.Node[]):void.1c563cf9a573e91d8ff039b24328d601 + +### File: +src/main/java/org/jsoup/nodes/Node.java + +### Key: +Node.java|addChildren|NULL_DEREFERENCE + +### Node Key: +1e8a282e4d8c8468066073fa4d86785d + +### Hash: +fffb6896d3942b534cd26c8518520da9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7746/instruction.md b/inferredbugs-7746/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00feafa763b33b945528f9b433e07f6de8dc9c1a --- /dev/null +++ b/inferredbugs-7746/instruction.md @@ -0,0 +1,459 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.nodes; + +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.StringUtils; +import org.jsoup.select.NodeVisitor; +import org.jsoup.select.NodeTraversor; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + The base, abstract Node model. Elements, Documents, Comments etc are all Node instances. + + @author Jonathan Hedley, jonathan@hedley.net */ +public abstract class Node { + Node parentNode; + final List childNodes; + final Attributes attributes; + String baseUri; + + /** + Create a new Node. + @param baseUri base URI + @param attributes attributes (not null, but may be empty) + */ + protected Node(String baseUri, Attributes attributes) { + Validate.notNull(baseUri); + Validate.notNull(attributes); + + childNodes = new ArrayList(4); + this.baseUri = baseUri.trim(); + this.attributes = attributes; + } + + protected Node(String baseUri) { + this(baseUri, new Attributes()); + } + + /** + Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof). + @return node name + */ + public abstract String nodeName(); + + /** + * Get an attribute's value by its key. + *

+ * To get an absolute URL from an attribute that may be a relative URL, prefix the key with abs, + * which is a shortcut to the {@link #absUrl} method. + * E.g.:

String url = a.attr("abs:href");
+ * @param attributeKey The attribute key. + * @return The attribute, or empty string if not present (to avoid nulls). + * @see #attributes() + * @see #hasAttr(String) + * @see #absUrl(String) + */ + public String attr(String attributeKey) { + Validate.notNull(attributeKey); + + if (hasAttr(attributeKey)) + return attributes.get(attributeKey); + else if (attributeKey.toLowerCase().startsWith("abs:")) + return absUrl(attributeKey.substring("abs:".length())); + else return ""; + } + + /** + * Get all of the element's attributes. + * @return attributes (which implements iterable, in same order as presented in original HTML). + */ + public Attributes attributes() { + return attributes; + } + + /** + * Set an attribute (key=value). If the attribute already exists, it is replaced. + * @param attributeKey The attribute key. + * @param attributeValue The attribute value. + * @return this (for chaining) + */ + public Node attr(String attributeKey, String attributeValue) { + attributes.put(attributeKey, attributeValue); + return this; + } + + /** + * Test if this element has an attribute. + * @param attributeKey The attribute key to check. + * @return true if the attribute exists, false if not. + */ + public boolean hasAttr(String attributeKey) { + Validate.notNull(attributeKey); + return attributes.hasKey(attributeKey); + } + + /** + * Remove an attribute from this element. + * @param attributeKey The attribute to remove. + * @return this (for chaining) + */ + public Node removeAttr(String attributeKey) { + Validate.notNull(attributeKey); + attributes.remove(attributeKey); + return this; + } + + /** + Get the base URI of this node. + @return base URI + */ + public String baseUri() { + return baseUri; + } + + /** + Update the base URI of this node. + @param baseUri base URI to set + */ + public void setBaseUri(String baseUri) { + Validate.notNull(baseUri); + this.baseUri = baseUri; + } + + /** + * Get an absolute URL from a URL attribute that may be relative (i.e. an <a href> or + * <img src>. + *

+ * If the attribute value is already absolute (i.e. it starts with a protocol, like + * http:// or https:// etc), and it successfully parses as a URL, the attribute is + * returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made + * absolute using that. + *

+ * As an alternate, you can use the {@link #attr} method with the abs: prefix. + * + * @param attributeKey The attribute key + * @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or + * could not be made successfully into a URL. + * @see #attr + * @see java.net.URL#URL(java.net.URL, String) + */ + public String absUrl(String attributeKey) { + Validate.notEmpty(attributeKey); + + String relUrl = attr(attributeKey); + if (!hasAttr(attributeKey)) { + return ""; // nothing to make absolute with + } else { + URL base; + try { + try { + base = new URL(baseUri); + } catch (MalformedURLException e) { + // the base is unsuitable, but the attribute may be abs on its own, so try that + URL abs = new URL(relUrl); + return abs.toExternalForm(); + } + URL abs = new URL(base, relUrl); + return abs.toExternalForm(); + } catch (MalformedURLException e) { + return ""; + } + } + } + + /** + Get a child node by index + @param index index of child node + @return the child node at this index. + */ + public Node childNode(int index) { + return childNodes.get(index); + } + + /** + Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes + themselves can be manipulated. + @return list of children. If no children, returns an empty list. + */ + public List childNodes() { + return Collections.unmodifiableList(childNodes); + } + + protected Node[] childNodesAsArray() { + return childNodes.toArray(new Node[childNodes().size()]); + } + + /** + Gets this node's parent node. + @return parent node; or null if no parent. + */ + public Node parent() { + return parentNode; + } + + /** + * Remove (delete) this node from the DOM tree. If this node has children, they are also removed. + */ + public void remove() { + Validate.notNull(parentNode); + parentNode.removeChild(this); + } + + /** + * Replace this node in the DOM with the supplied node. + * @param in the node that will will replace the existing node. + */ + public void replaceWith(Node in) { + Validate.notNull(in); + Validate.notNull(parentNode); + parentNode.replaceChild(this, in); + } + + protected void setParentNode(Node parentNode) { + if (this.parentNode != null) + this.parentNode.removeChild(this); + this.parentNode = parentNode; + } + + protected void replaceChild(Node out, Node in) { + Validate.isTrue(out.parentNode == this); + Validate.notNull(in); + if (in.parentNode != null) + in.parentNode.removeChild(in); + + Integer index = indexInList(out, childNodes); + childNodes.set(index, in); + in.parentNode = this; + out.parentNode = null; + } + + protected void removeChild(Node out) { + Validate.isTrue(out.parentNode == this); + int index = indexInList(out, childNodes); + childNodes.remove(index); + out.parentNode = null; + } + + protected void addChildren(Node... children) { + addChildren(childNodes.size(), children); + } + + protected void addChildren(int index, Node... children) { + Validate.noNullElements(children); + for (int i = children.length - 1; i >= 0; i--) { + Node in = children[i]; + if (in.parentNode != null) + in.parentNode.removeChild(in); + + childNodes.add(index, in); + in.setParentNode(this); + } + } + + protected int nodeDepth() { + if (parentNode == null) + return 0; + else + return parentNode.nodeDepth() + 1; + } + + /** + Retrieves this node's sibling nodes. Effectively, {@link #childNodes() node.parent.childNodes()}. + @return node siblings, including this node + */ + public List siblingNodes() { + return parent().childNodes(); // TODO: should this strip out this node? i.e. not a sibling of self? + } + + /** + Get this node's next sibling. + @return next sibling, or null if this is the last sibling + */ + public Node nextSibling() { + if (parentNode == null) + return null; // root + + List siblings = parentNode.childNodes; + Integer index = indexInList(this, siblings); + Validate.notNull(index); + if (siblings.size() > index+1) + return siblings.get(index+1); + else + return null; + } + + /** + Get this node's previous sibling. + @return the previous sibling, or null if this is the first sibling + */ + public Node previousSibling() { + List siblings = parentNode.childNodes; + Integer index = indexInList(this, siblings); + Validate.notNull(index); + if (index > 0) + return siblings.get(index-1); + else + return null; + } + + /** + * Get the list index of this node in its node sibling list. I.e. if this is the first node + * sibling, returns 0. + * @return position in node sibling list + * @see org.jsoup.nodes.Element#elementSiblingIndex() + */ + public Integer siblingIndex() { + return indexInList(this, parent().childNodes); + } + + protected static Integer indexInList(N search, List nodes) { + Validate.notNull(search); + Validate.notNull(nodes); + + for (int i = 0; i < nodes.size(); i++) { + N node = nodes.get(i); + if (node.equals(search)) + return i; + } + return null; + } + + /** + Get the outer HTML of this node. + @return HTML + */ + public String outerHtml() { + StringBuilder accum = new StringBuilder(); + outerHtml(accum); + return accum.toString(); + } + + protected void outerHtml(StringBuilder accum) { + new NodeTraversor(new OuterHtmlVisitor(accum)).traverse(this); + } + + /** + Get the outer HTML of this node. + @param accum accumulator to place HTML into + */ + abstract void outerHtmlHead(StringBuilder accum, int depth); + + abstract void outerHtmlTail(StringBuilder accum, int depth); + + public String toString() { + return outerHtml(); + } + + protected void indent(StringBuilder accum, int depth) { + accum.append("\n").append(StringUtils.leftPad("", depth)); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + // todo: have nodes hold a child index, compare against that and parent (not children) + return false; + } + + @Override + public int hashCode() { + int result = parentNode != null ? parentNode.hashCode() : 0; + // not children, or will block stack as they go back up to parent) + result = 31 * result + (attributes != null ? attributes.hashCode() : 0); + return result; + } + + private static class OuterHtmlVisitor implements NodeVisitor { + private StringBuilder accum; + + OuterHtmlVisitor(StringBuilder accum) { + this.accum = accum; + } + + public void head(Node node, int depth) { + node.outerHtmlHead(accum, depth); + } + + public void tail(Node node, int depth) { + node.outerHtmlTail(accum, depth); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `indexInList(out,Node.childNodes)` could be null and is dereferenced at line 236. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Node.removeChild(Node) + +### Procedure Id: +org.jsoup.nodes.Node.removeChild(org.jsoup.nodes.Node):void.14a714f387f2af8a6bad230be38659a3 + +### File: +src/main/java/org/jsoup/nodes/Node.java + +### Key: +Node.java|removeChild|NULL_DEREFERENCE + +### Node Key: +3673c4de52f870dfd662aca72d369e76 + +### Hash: +bc8613c64e4495ff25707b14d1eeaa7a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7747/instruction.md b/inferredbugs-7747/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..66f3be44dc5c6cf64b2574a2a497a5bb9522f3b9 --- /dev/null +++ b/inferredbugs-7747/instruction.md @@ -0,0 +1,459 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.nodes; + +import org.apache.commons.lang.Validate; +import org.apache.commons.lang.StringUtils; +import org.jsoup.select.NodeVisitor; +import org.jsoup.select.NodeTraversor; + +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + The base, abstract Node model. Elements, Documents, Comments etc are all Node instances. + + @author Jonathan Hedley, jonathan@hedley.net */ +public abstract class Node { + Node parentNode; + final List childNodes; + final Attributes attributes; + String baseUri; + + /** + Create a new Node. + @param baseUri base URI + @param attributes attributes (not null, but may be empty) + */ + protected Node(String baseUri, Attributes attributes) { + Validate.notNull(baseUri); + Validate.notNull(attributes); + + childNodes = new ArrayList(4); + this.baseUri = baseUri.trim(); + this.attributes = attributes; + } + + protected Node(String baseUri) { + this(baseUri, new Attributes()); + } + + /** + Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof). + @return node name + */ + public abstract String nodeName(); + + /** + * Get an attribute's value by its key. + *

+ * To get an absolute URL from an attribute that may be a relative URL, prefix the key with abs, + * which is a shortcut to the {@link #absUrl} method. + * E.g.:

String url = a.attr("abs:href");
+ * @param attributeKey The attribute key. + * @return The attribute, or empty string if not present (to avoid nulls). + * @see #attributes() + * @see #hasAttr(String) + * @see #absUrl(String) + */ + public String attr(String attributeKey) { + Validate.notNull(attributeKey); + + if (hasAttr(attributeKey)) + return attributes.get(attributeKey); + else if (attributeKey.toLowerCase().startsWith("abs:")) + return absUrl(attributeKey.substring("abs:".length())); + else return ""; + } + + /** + * Get all of the element's attributes. + * @return attributes (which implements iterable, in same order as presented in original HTML). + */ + public Attributes attributes() { + return attributes; + } + + /** + * Set an attribute (key=value). If the attribute already exists, it is replaced. + * @param attributeKey The attribute key. + * @param attributeValue The attribute value. + * @return this (for chaining) + */ + public Node attr(String attributeKey, String attributeValue) { + attributes.put(attributeKey, attributeValue); + return this; + } + + /** + * Test if this element has an attribute. + * @param attributeKey The attribute key to check. + * @return true if the attribute exists, false if not. + */ + public boolean hasAttr(String attributeKey) { + Validate.notNull(attributeKey); + return attributes.hasKey(attributeKey); + } + + /** + * Remove an attribute from this element. + * @param attributeKey The attribute to remove. + * @return this (for chaining) + */ + public Node removeAttr(String attributeKey) { + Validate.notNull(attributeKey); + attributes.remove(attributeKey); + return this; + } + + /** + Get the base URI of this node. + @return base URI + */ + public String baseUri() { + return baseUri; + } + + /** + Update the base URI of this node. + @param baseUri base URI to set + */ + public void setBaseUri(String baseUri) { + Validate.notNull(baseUri); + this.baseUri = baseUri; + } + + /** + * Get an absolute URL from a URL attribute that may be relative (i.e. an <a href> or + * <img src>. + *

+ * If the attribute value is already absolute (i.e. it starts with a protocol, like + * http:// or https:// etc), and it successfully parses as a URL, the attribute is + * returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made + * absolute using that. + *

+ * As an alternate, you can use the {@link #attr} method with the abs: prefix. + * + * @param attributeKey The attribute key + * @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or + * could not be made successfully into a URL. + * @see #attr + * @see java.net.URL#URL(java.net.URL, String) + */ + public String absUrl(String attributeKey) { + Validate.notEmpty(attributeKey); + + String relUrl = attr(attributeKey); + if (!hasAttr(attributeKey)) { + return ""; // nothing to make absolute with + } else { + URL base; + try { + try { + base = new URL(baseUri); + } catch (MalformedURLException e) { + // the base is unsuitable, but the attribute may be abs on its own, so try that + URL abs = new URL(relUrl); + return abs.toExternalForm(); + } + URL abs = new URL(base, relUrl); + return abs.toExternalForm(); + } catch (MalformedURLException e) { + return ""; + } + } + } + + /** + Get a child node by index + @param index index of child node + @return the child node at this index. + */ + public Node childNode(int index) { + return childNodes.get(index); + } + + /** + Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes + themselves can be manipulated. + @return list of children. If no children, returns an empty list. + */ + public List childNodes() { + return Collections.unmodifiableList(childNodes); + } + + protected Node[] childNodesAsArray() { + return childNodes.toArray(new Node[childNodes().size()]); + } + + /** + Gets this node's parent node. + @return parent node; or null if no parent. + */ + public Node parent() { + return parentNode; + } + + /** + * Remove (delete) this node from the DOM tree. If this node has children, they are also removed. + */ + public void remove() { + Validate.notNull(parentNode); + parentNode.removeChild(this); + } + + /** + * Replace this node in the DOM with the supplied node. + * @param in the node that will will replace the existing node. + */ + public void replaceWith(Node in) { + Validate.notNull(in); + Validate.notNull(parentNode); + parentNode.replaceChild(this, in); + } + + protected void setParentNode(Node parentNode) { + if (this.parentNode != null) + this.parentNode.removeChild(this); + this.parentNode = parentNode; + } + + protected void replaceChild(Node out, Node in) { + Validate.isTrue(out.parentNode == this); + Validate.notNull(in); + if (in.parentNode != null) + in.parentNode.removeChild(in); + + Integer index = indexInList(out, childNodes); + childNodes.set(index, in); + in.parentNode = this; + out.parentNode = null; + } + + protected void removeChild(Node out) { + Validate.isTrue(out.parentNode == this); + int index = indexInList(out, childNodes); + childNodes.remove(index); + out.parentNode = null; + } + + protected void addChildren(Node... children) { + addChildren(childNodes.size(), children); + } + + protected void addChildren(int index, Node... children) { + Validate.noNullElements(children); + for (int i = children.length - 1; i >= 0; i--) { + Node in = children[i]; + if (in.parentNode != null) + in.parentNode.removeChild(in); + + childNodes.add(index, in); + in.setParentNode(this); + } + } + + protected int nodeDepth() { + if (parentNode == null) + return 0; + else + return parentNode.nodeDepth() + 1; + } + + /** + Retrieves this node's sibling nodes. Effectively, {@link #childNodes() node.parent.childNodes()}. + @return node siblings, including this node + */ + public List siblingNodes() { + return parent().childNodes(); // TODO: should this strip out this node? i.e. not a sibling of self? + } + + /** + Get this node's next sibling. + @return next sibling, or null if this is the last sibling + */ + public Node nextSibling() { + if (parentNode == null) + return null; // root + + List siblings = parentNode.childNodes; + Integer index = indexInList(this, siblings); + Validate.notNull(index); + if (siblings.size() > index+1) + return siblings.get(index+1); + else + return null; + } + + /** + Get this node's previous sibling. + @return the previous sibling, or null if this is the first sibling + */ + public Node previousSibling() { + List siblings = parentNode.childNodes; + Integer index = indexInList(this, siblings); + Validate.notNull(index); + if (index > 0) + return siblings.get(index-1); + else + return null; + } + + /** + * Get the list index of this node in its node sibling list. I.e. if this is the first node + * sibling, returns 0. + * @return position in node sibling list + * @see org.jsoup.nodes.Element#elementSiblingIndex() + */ + public Integer siblingIndex() { + return indexInList(this, parent().childNodes); + } + + protected static Integer indexInList(N search, List nodes) { + Validate.notNull(search); + Validate.notNull(nodes); + + for (int i = 0; i < nodes.size(); i++) { + N node = nodes.get(i); + if (node.equals(search)) + return i; + } + return null; + } + + /** + Get the outer HTML of this node. + @return HTML + */ + public String outerHtml() { + StringBuilder accum = new StringBuilder(); + outerHtml(accum); + return accum.toString(); + } + + protected void outerHtml(StringBuilder accum) { + new NodeTraversor(new OuterHtmlVisitor(accum)).traverse(this); + } + + /** + Get the outer HTML of this node. + @param accum accumulator to place HTML into + */ + abstract void outerHtmlHead(StringBuilder accum, int depth); + + abstract void outerHtmlTail(StringBuilder accum, int depth); + + public String toString() { + return outerHtml(); + } + + protected void indent(StringBuilder accum, int depth) { + accum.append("\n").append(StringUtils.leftPad("", depth)); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + // todo: have nodes hold a child index, compare against that and parent (not children) + return false; + } + + @Override + public int hashCode() { + int result = parentNode != null ? parentNode.hashCode() : 0; + // not children, or will block stack as they go back up to parent) + result = 31 * result + (attributes != null ? attributes.hashCode() : 0); + return result; + } + + private static class OuterHtmlVisitor implements NodeVisitor { + private StringBuilder accum; + + OuterHtmlVisitor(StringBuilder accum) { + this.accum = accum; + } + + public void head(Node node, int depth) { + node.outerHtmlHead(accum, depth); + } + + public void tail(Node node, int depth) { + node.outerHtmlTail(accum, depth); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `index` last assigned on line 295 could be null and is dereferenced at line 297. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Node Node.previousSibling() + +### Procedure Id: +org.jsoup.nodes.Node.previousSibling():org.jsoup.nodes.Node.0de6c6abf3e28ae4df2e166437430a89 + +### File: +src/main/java/org/jsoup/nodes/Node.java + +### Key: +Node.java|previousSibling|NULL_DEREFERENCE + +### Node Key: +b0332e11c33066b7b27fa03971d6db83 + +### Hash: +3767ee7400b2924ad7c165175448bf2a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7749/instruction.md b/inferredbugs-7749/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63c8284ba47dc65fec35122596356b6888aeb876 --- /dev/null +++ b/inferredbugs-7749/instruction.md @@ -0,0 +1,1430 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.nodes; + +import org.jsoup.Jsoup; +import org.jsoup.TextUtil; +import org.jsoup.parser.Tag; +import org.jsoup.select.Elements; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +/** + * Tests for Element (DOM stuff mostly). + * + * @author Jonathan Hedley + */ +public class ElementTest { + private String reference = "

Hello

Another element

"; + + @Test public void getElementsByTagName() { + Document doc = Jsoup.parse(reference); + List divs = doc.getElementsByTag("div"); + assertEquals(2, divs.size()); + assertEquals("div1", divs.get(0).id()); + assertEquals("div2", divs.get(1).id()); + + List ps = doc.getElementsByTag("p"); + assertEquals(2, ps.size()); + assertEquals("Hello", ((TextNode) ps.get(0).childNode(0)).getWholeText()); + assertEquals("Another ", ((TextNode) ps.get(1).childNode(0)).getWholeText()); + List ps2 = doc.getElementsByTag("P"); + assertEquals(ps, ps2); + + List imgs = doc.getElementsByTag("img"); + assertEquals("foo.png", imgs.get(0).attr("src")); + + List empty = doc.getElementsByTag("wtf"); + assertEquals(0, empty.size()); + } + + @Test public void getNamespacedElementsByTag() { + Document doc = Jsoup.parse("
Hello
"); + Elements els = doc.getElementsByTag("abc:def"); + assertEquals(1, els.size()); + assertEquals("1", els.first().id()); + assertEquals("abc:def", els.first().tagName()); + } + + @Test public void testGetElementById() { + Document doc = Jsoup.parse(reference); + Element div = doc.getElementById("div1"); + assertEquals("div1", div.id()); + assertNull(doc.getElementById("none")); + + Document doc2 = Jsoup.parse("

Hello world!

"); + Element div2 = doc2.getElementById("2"); + assertEquals("div", div2.tagName()); // not the span + Element span = div2.child(0).getElementById("2"); // called from

context should be span + assertEquals("span", span.tagName()); + } + + @Test public void testGetText() { + Document doc = Jsoup.parse(reference); + assertEquals("Hello Another element", doc.text()); + assertEquals("Another element", doc.getElementsByTag("p").get(1).text()); + } + + @Test public void testGetChildText() { + Document doc = Jsoup.parse("

Hello there now"); + Element p = doc.select("p").first(); + assertEquals("Hello there now", p.text()); + assertEquals("Hello now", p.ownText()); + } + + @Test public void testNormalisesText() { + String h = "

Hello

There.

\n

Here is \n some text."; + Document doc = Jsoup.parse(h); + String text = doc.text(); + assertEquals("Hello There. Here is some text.", text); + } + + @Test public void testKeepsPreText() { + String h = "

Hello \n \n there.

  What's \n\n  that?
"; + Document doc = Jsoup.parse(h); + assertEquals("Hello there. What's \n\n that?", doc.text()); + } + + @Test public void testKeepsPreTextInCode() { + String h = "
code\n\ncode
"; + Document doc = Jsoup.parse(h); + assertEquals("code\n\ncode", doc.text()); + assertEquals("
code\n\ncode
", doc.body().html()); + } + + @Test public void testKeepsPreTextAtDepth() { + String h = "
code\n\ncode
"; + Document doc = Jsoup.parse(h); + assertEquals("code\n\ncode", doc.text()); + assertEquals("
code\n\ncode
", doc.body().html()); + } + + @Test public void testBrHasSpace() { + Document doc = Jsoup.parse("

Hello
there

"); + assertEquals("Hello there", doc.text()); + assertEquals("Hello there", doc.select("p").first().ownText()); + + doc = Jsoup.parse("

Hello
there

"); + assertEquals("Hello there", doc.text()); + } + + @Test public void testWholeText() { + Document doc = Jsoup.parse("

Hello\nthere  

"); + assertEquals(" Hello\nthere   ", doc.wholeText()); + + doc = Jsoup.parse("

Hello \n there

"); + assertEquals("Hello \n there", doc.wholeText()); + + doc = Jsoup.parse("

Hello

\n there

"); + assertEquals("Hello \n there", doc.wholeText()); + } + + @Test public void testGetSiblings() { + Document doc = Jsoup.parse("

Hello

there

this

is

an

element

"); + Element p = doc.getElementById("1"); + assertEquals("there", p.text()); + assertEquals("Hello", p.previousElementSibling().text()); + assertEquals("this", p.nextElementSibling().text()); + assertEquals("Hello", p.firstElementSibling().text()); + assertEquals("element", p.lastElementSibling().text()); + } + + @Test public void testGetSiblingsWithDuplicateContent() { + Document doc = Jsoup.parse("

Hello

there

this

this

is

an

element

"); + Element p = doc.getElementById("1"); + assertEquals("there", p.text()); + assertEquals("Hello", p.previousElementSibling().text()); + assertEquals("this", p.nextElementSibling().text()); + assertEquals("this", p.nextElementSibling().nextElementSibling().text()); + assertEquals("is", p.nextElementSibling().nextElementSibling().nextElementSibling().text()); + assertEquals("Hello", p.firstElementSibling().text()); + assertEquals("element", p.lastElementSibling().text()); + } + + @Test public void testGetParents() { + Document doc = Jsoup.parse("

Hello there

"); + Element span = doc.select("span").first(); + Elements parents = span.parents(); + + assertEquals(4, parents.size()); + assertEquals("p", parents.get(0).tagName()); + assertEquals("div", parents.get(1).tagName()); + assertEquals("body", parents.get(2).tagName()); + assertEquals("html", parents.get(3).tagName()); + } + + @Test public void testElementSiblingIndex() { + Document doc = Jsoup.parse("

One

...

Two

...

Three

"); + Elements ps = doc.select("p"); + assertTrue(0 == ps.get(0).elementSiblingIndex()); + assertTrue(1 == ps.get(1).elementSiblingIndex()); + assertTrue(2 == ps.get(2).elementSiblingIndex()); + } + + @Test public void testElementSiblingIndexSameContent() { + Document doc = Jsoup.parse("

One

...

One

...

One

"); + Elements ps = doc.select("p"); + assertTrue(0 == ps.get(0).elementSiblingIndex()); + assertTrue(1 == ps.get(1).elementSiblingIndex()); + assertTrue(2 == ps.get(2).elementSiblingIndex()); + } + + @Test public void testGetElementsWithClass() { + Document doc = Jsoup.parse("
Hello Yellow!

Empty

"); + + List els = doc.getElementsByClass("mellow"); + assertEquals(2, els.size()); + assertEquals("div", els.get(0).tagName()); + assertEquals("span", els.get(1).tagName()); + + List els2 = doc.getElementsByClass("yellow"); + assertEquals(2, els2.size()); + assertEquals("div", els2.get(0).tagName()); + assertEquals("b", els2.get(1).tagName()); + + List none = doc.getElementsByClass("solo"); + assertEquals(0, none.size()); + } + + @Test public void testGetElementsWithAttribute() { + Document doc = Jsoup.parse("

"); + List els = doc.getElementsByAttribute("style"); + assertEquals(2, els.size()); + assertEquals("div", els.get(0).tagName()); + assertEquals("b", els.get(1).tagName()); + + List none = doc.getElementsByAttribute("class"); + assertEquals(0, none.size()); + } + + @Test public void testGetElementsWithAttributeDash() { + Document doc = Jsoup.parse("
"); + Elements meta = doc.select("meta[http-equiv=content-type], meta[charset]"); + assertEquals(1, meta.size()); + assertEquals("1", meta.first().id()); + } + + @Test public void testGetElementsWithAttributeValue() { + Document doc = Jsoup.parse("

"); + List els = doc.getElementsByAttributeValue("style", "bold"); + assertEquals(1, els.size()); + assertEquals("div", els.get(0).tagName()); + + List none = doc.getElementsByAttributeValue("style", "none"); + assertEquals(0, none.size()); + } + + @Test public void testClassDomMethods() { + Document doc = Jsoup.parse("
Hello Yellow
"); + List els = doc.getElementsByAttribute("class"); + Element span = els.get(0); + assertEquals("mellow yellow", span.className()); + assertTrue(span.hasClass("mellow")); + assertTrue(span.hasClass("yellow")); + Set classes = span.classNames(); + assertEquals(2, classes.size()); + assertTrue(classes.contains("mellow")); + assertTrue(classes.contains("yellow")); + + assertEquals("", doc.className()); + classes = doc.classNames(); + assertEquals(0, classes.size()); + assertFalse(doc.hasClass("mellow")); + } + + @Test public void testHasClassDomMethods() { + Tag tag = Tag.valueOf("a"); + Attributes attribs = new Attributes(); + Element el = new Element(tag, "", attribs); + + attribs.put("class", "toto"); + boolean hasClass = el.hasClass("toto"); + assertTrue(hasClass); + + attribs.put("class", " toto"); + hasClass = el.hasClass("toto"); + assertTrue(hasClass); + + attribs.put("class", "toto "); + hasClass = el.hasClass("toto"); + assertTrue(hasClass); + + attribs.put("class", "\ttoto "); + hasClass = el.hasClass("toto"); + assertTrue(hasClass); + + attribs.put("class", " toto "); + hasClass = el.hasClass("toto"); + assertTrue(hasClass); + + attribs.put("class", "ab"); + hasClass = el.hasClass("toto"); + assertFalse(hasClass); + + attribs.put("class", " "); + hasClass = el.hasClass("toto"); + assertFalse(hasClass); + + attribs.put("class", "tototo"); + hasClass = el.hasClass("toto"); + assertFalse(hasClass); + + attribs.put("class", "raulpismuth "); + hasClass = el.hasClass("raulpismuth"); + assertTrue(hasClass); + + attribs.put("class", " abcd raulpismuth efgh "); + hasClass = el.hasClass("raulpismuth"); + assertTrue(hasClass); + + attribs.put("class", " abcd efgh raulpismuth"); + hasClass = el.hasClass("raulpismuth"); + assertTrue(hasClass); + + attribs.put("class", " abcd efgh raulpismuth "); + hasClass = el.hasClass("raulpismuth"); + assertTrue(hasClass); + } + + + @Test public void testClassUpdates() { + Document doc = Jsoup.parse("
"); + Element div = doc.select("div").first(); + + div.addClass("green"); + assertEquals("mellow yellow green", div.className()); + div.removeClass("red"); // noop + div.removeClass("yellow"); + assertEquals("mellow green", div.className()); + div.toggleClass("green").toggleClass("red"); + assertEquals("mellow red", div.className()); + } + + @Test public void testOuterHtml() { + Document doc = Jsoup.parse("

Hello

there"); + assertEquals("

Hello

there

", + TextUtil.stripNewlines(doc.outerHtml())); + } + + @Test public void testInnerHtml() { + Document doc = Jsoup.parse("
\n

Hello

"); + assertEquals("

Hello

", doc.getElementsByTag("div").get(0).html()); + } + + @Test public void testFormatHtml() { + Document doc = Jsoup.parse("Format test

Hello jsoup users

Good.

"); + assertEquals("\n \n Format test\n \n \n
\n

Hello jsoup users

\n

Good.

\n
\n \n", doc.html()); + } + + @Test public void testFormatOutline() { + Document doc = Jsoup.parse("Format test

Hello jsoup users

Good.

"); + doc.outputSettings().outline(true); + assertEquals("\n \n Format test\n \n \n
\n

\n Hello \n \n jsoup \n users\n \n

\n

Good.

\n
\n \n", doc.html()); + } + + @Test public void testSetIndent() { + Document doc = Jsoup.parse("

Hello\nthere

"); + doc.outputSettings().indentAmount(0); + assertEquals("\n\n\n
\n

Hello there

\n
\n\n", doc.html()); + } + + @Test public void testNotPretty() { + Document doc = Jsoup.parse("
\n

Hello\n there\n

"); + doc.outputSettings().prettyPrint(false); + assertEquals("
\n

Hello\n there\n

", doc.html()); + + Element div = doc.select("div").first(); + assertEquals(" \n

Hello\n there\n

", div.html()); + } + + @Test public void testEmptyElementFormatHtml() { + // don't put newlines into empty blocks + Document doc = Jsoup.parse("
"); + assertEquals("
\n
\n
", doc.select("section").first().outerHtml()); + } + + @Test public void testNoIndentOnScriptAndStyle() { + // don't newline+indent closing and tags + Document doc = Jsoup.parse("\n"); + assertEquals(" \n", doc.head().html()); + } + + @Test public void testContainerOutput() { + Document doc = Jsoup.parse("Hello there

Hello

there

Another
"); + assertEquals("Hello there", doc.select("title").first().outerHtml()); + assertEquals("
\n

Hello

\n

there

\n
", doc.select("div").first().outerHtml()); + assertEquals("
\n

Hello

\n

there

\n
\n
\n Another\n
", doc.select("body").first().html()); + } + + @Test public void testSetText() { + String h = "
Hello

there now

"; + Document doc = Jsoup.parse(h); + assertEquals("Hello there now", doc.text()); // need to sort out node whitespace + assertEquals("there now", doc.select("p").get(0).text()); + + Element div = doc.getElementById("1").text("Gone"); + assertEquals("Gone", div.text()); + assertEquals(0, doc.select("p").size()); + } + + @Test public void testAddNewElement() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.appendElement("p").text("there"); + div.appendElement("P").attr("CLASS", "second").text("now"); + // manually specifying tag and attributes should maintain case based on parser settings + assertEquals("

Hello

there

now

", + TextUtil.stripNewlines(doc.html())); + + // check sibling index (with short circuit on reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testAddBooleanAttribute() { + Element div = new Element(Tag.valueOf("div"), ""); + + div.attr("true", true); + + div.attr("false", "value"); + div.attr("false", false); + + assertTrue(div.hasAttr("true")); + assertEquals("", div.attr("true")); + + List attributes = div.attributes().asList(); + assertEquals("There should be one attribute", 1, attributes.size()); + assertTrue("Attribute should be boolean", attributes.get(0) instanceof BooleanAttribute); + + assertFalse(div.hasAttr("false")); + + assertEquals("
", div.outerHtml()); + } + + @Test public void testAppendRowToTable() { + Document doc = Jsoup.parse("
(.*?)
1
"); + Element table = doc.select("tbody").first(); + table.append("2"); + + assertEquals("
1
2
", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testPrependRowToTable() { + Document doc = Jsoup.parse("
1
"); + Element table = doc.select("tbody").first(); + table.prepend("2"); + + assertEquals("
2
1
", TextUtil.stripNewlines(doc.body().html())); + + // check sibling index (reindexChildren): + Elements ps = doc.select("tr"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testPrependElement() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.prependElement("p").text("Before"); + assertEquals("Before", div.child(0).text()); + assertEquals("Hello", div.child(1).text()); + } + + @Test public void testAddNewText() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.appendText(" there & now >"); + assertEquals("

Hello

there & now >", TextUtil.stripNewlines(div.html())); + } + + @Test public void testPrependText() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.prependText("there & now > "); + assertEquals("there & now > Hello", div.text()); + assertEquals("there & now >

Hello

", TextUtil.stripNewlines(div.html())); + } + + @Test(expected = IllegalArgumentException.class) public void testThrowsOnAddNullText() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.appendText(null); + } + + @Test(expected = IllegalArgumentException.class) public void testThrowsOnPrependNullText() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.prependText(null); + } + + @Test public void testAddNewHtml() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.append("

there

now

"); + assertEquals("

Hello

there

now

", TextUtil.stripNewlines(div.html())); + + // check sibling index (no reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testPrependNewHtml() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.prepend("

there

now

"); + assertEquals("

there

now

Hello

", TextUtil.stripNewlines(div.html())); + + // check sibling index (reindexChildren): + Elements ps = doc.select("p"); + for (int i = 0; i < ps.size(); i++) { + assertEquals(i, ps.get(i).siblingIndex); + } + } + + @Test public void testSetHtml() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.getElementById("1"); + div.html("

there

now

"); + assertEquals("

there

now

", TextUtil.stripNewlines(div.html())); + } + + @Test public void testSetHtmlTitle() { + Document doc = Jsoup.parse(""); + + Element title = doc.getElementById("1"); + title.html("good"); + assertEquals("good", title.html()); + title.html("bad"); + assertEquals("<i>bad</i>", title.html()); + + Element head = doc.getElementById("2"); + head.html("<i>bad</i>"); + assertEquals("<i>bad</i>", head.html()); + } + + @Test public void testWrap() { + Document doc = Jsoup.parse("

Hello

There

"); + Element p = doc.select("p").first(); + p.wrap("
"); + assertEquals("

Hello

There

", TextUtil.stripNewlines(doc.body().html())); + + Element ret = p.wrap("

What?

"); + assertEquals("

Hello

What?

There

", + TextUtil.stripNewlines(doc.body().html())); + + assertEquals(ret, p); + } + + @Test public void before() { + Document doc = Jsoup.parse("

Hello

There

"); + Element p1 = doc.select("p").first(); + p1.before("
one
two
"); + assertEquals("
one
two

Hello

There

", TextUtil.stripNewlines(doc.body().html())); + + doc.select("p").last().before("

Three

"); + assertEquals("
one
two

Hello

Three

There

", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void after() { + Document doc = Jsoup.parse("

Hello

There

"); + Element p1 = doc.select("p").first(); + p1.after("
one
two
"); + assertEquals("

Hello

one
two

There

", TextUtil.stripNewlines(doc.body().html())); + + doc.select("p").last().after("

Three

"); + assertEquals("

Hello

one
two

There

Three

", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testWrapWithRemainder() { + Document doc = Jsoup.parse("

Hello

"); + Element p = doc.select("p").first(); + p.wrap("

There!

"); + assertEquals("

Hello

There!

", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testHasText() { + Document doc = Jsoup.parse("

Hello

"); + Element div = doc.select("div").first(); + Elements ps = doc.select("p"); + + assertTrue(div.hasText()); + assertTrue(ps.first().hasText()); + assertFalse(ps.last().hasText()); + } + + @Test public void dataset() { + Document doc = Jsoup.parse("
Hello

Hello

"); + Element div = doc.select("div").first(); + Map dataset = div.dataset(); + Attributes attributes = div.attributes(); + + // size, get, set, add, remove + assertEquals(2, dataset.size()); + assertEquals("jsoup", dataset.get("name")); + assertEquals("jar", dataset.get("package")); + + dataset.put("name", "jsoup updated"); + dataset.put("language", "java"); + dataset.remove("package"); + + assertEquals(2, dataset.size()); + assertEquals(4, attributes.size()); + assertEquals("jsoup updated", attributes.get("data-name")); + assertEquals("jsoup updated", dataset.get("name")); + assertEquals("java", attributes.get("data-language")); + assertEquals("java", dataset.get("language")); + + attributes.put("data-food", "bacon"); + assertEquals(3, dataset.size()); + assertEquals("bacon", dataset.get("food")); + + attributes.put("data-", "empty"); + assertEquals(null, dataset.get("")); // data- is not a data attribute + + Element p = doc.select("p").first(); + assertEquals(0, p.dataset().size()); + + } + + @Test public void parentlessToString() { + Document doc = Jsoup.parse(""); + Element img = doc.select("img").first(); + assertEquals("", img.toString()); + + img.remove(); // lost its parent + assertEquals("", img.toString()); + } + + @Test public void testClone() { + Document doc = Jsoup.parse("

One

Two

"); + + Element p = doc.select("p").get(1); + Element clone = p.clone(); + + assertNull(clone.parent()); // should be orphaned + assertEquals(0, clone.siblingIndex); + assertEquals(1, p.siblingIndex); + assertNotNull(p.parent()); + + clone.append("Three"); + assertEquals("

TwoThree

", TextUtil.stripNewlines(clone.outerHtml())); + assertEquals("

One

Two

", TextUtil.stripNewlines(doc.body().html())); // not modified + + doc.body().appendChild(clone); // adopt + assertNotNull(clone.parent()); + assertEquals("

One

Two

TwoThree

", TextUtil.stripNewlines(doc.body().html())); + } + + @Test public void testClonesClassnames() { + Document doc = Jsoup.parse("
"); + Element div = doc.select("div").first(); + Set classes = div.classNames(); + assertEquals(2, classes.size()); + assertTrue(classes.contains("one")); + assertTrue(classes.contains("two")); + + Element copy = div.clone(); + Set copyClasses = copy.classNames(); + assertEquals(2, copyClasses.size()); + assertTrue(copyClasses.contains("one")); + assertTrue(copyClasses.contains("two")); + copyClasses.add("three"); + copyClasses.remove("one"); + + assertTrue(classes.contains("one")); + assertFalse(classes.contains("three")); + assertFalse(copyClasses.contains("one")); + assertTrue(copyClasses.contains("three")); + + assertEquals("", div.html()); + assertEquals("", copy.html()); + } + + @Test public void testShallowClone() { + String base = "http://example.com/"; + Document doc = Jsoup.parse("

One", base); + Element d = doc.selectFirst("div"); + Element p = doc.selectFirst("p"); + TextNode t = p.textNodes().get(0); + + Element d2 = d.shallowClone(); + Element p2 = p.shallowClone(); + TextNode t2 = (TextNode) t.shallowClone(); + + assertEquals(1, d.childNodeSize()); + assertEquals(0, d2.childNodeSize()); + + assertEquals(1, p.childNodeSize()); + assertEquals(0, p2.childNodeSize()); + assertEquals("", p2.text()); + + assertEquals("two", p2.className()); + assertEquals("One", t2.text()); + + d2.append("

Three"); + assertEquals(1, d2.childNodeSize()); + assertEquals("Three", d2.text()); + assertEquals("One", d.text()); + assertEquals(base, d2.baseUri()); + } + + @Test public void testTagNameSet() { + Document doc = Jsoup.parse("

Hello"); + doc.select("i").first().tagName("em"); + assertEquals(0, doc.select("i").size()); + assertEquals(1, doc.select("em").size()); + assertEquals("Hello", doc.select("div").first().html()); + } + + @Test public void testHtmlContainsOuter() { + Document doc = Jsoup.parse("Check
Hello there
"); + doc.outputSettings().indentAmount(0); + assertTrue(doc.html().contains(doc.select("title").outerHtml())); + assertTrue(doc.html().contains(doc.select("div").outerHtml())); + } + + @Test public void testGetTextNodes() { + Document doc = Jsoup.parse("

One Two Three
Four

"); + List textNodes = doc.select("p").first().textNodes(); + + assertEquals(3, textNodes.size()); + assertEquals("One ", textNodes.get(0).text()); + assertEquals(" Three ", textNodes.get(1).text()); + assertEquals(" Four", textNodes.get(2).text()); + + assertEquals(0, doc.select("br").first().textNodes().size()); + } + + @Test public void testManipulateTextNodes() { + Document doc = Jsoup.parse("

One Two Three
Four

"); + Element p = doc.select("p").first(); + List textNodes = p.textNodes(); + + textNodes.get(1).text(" three-more "); + textNodes.get(2).splitText(3).text("-ur"); + + assertEquals("One Two three-more Fo-ur", p.text()); + assertEquals("One three-more Fo-ur", p.ownText()); + assertEquals(4, p.textNodes().size()); // grew because of split + } + + @Test public void testGetDataNodes() { + Document doc = Jsoup.parse("

Fix Six

"); + Element script = doc.select("script").first(); + Element style = doc.select("style").first(); + Element p = doc.select("p").first(); + + List scriptData = script.dataNodes(); + assertEquals(1, scriptData.size()); + assertEquals("One Two", scriptData.get(0).getWholeData()); + + List styleData = style.dataNodes(); + assertEquals(1, styleData.size()); + assertEquals("Three Four", styleData.get(0).getWholeData()); + + List pData = p.dataNodes(); + assertEquals(0, pData.size()); + } + + @Test public void elementIsNotASiblingOfItself() { + Document doc = Jsoup.parse("

One

Two

Three

"); + Element p2 = doc.select("p").get(1); + + assertEquals("Two", p2.text()); + Elements els = p2.siblingElements(); + assertEquals(2, els.size()); + assertEquals("

One

", els.get(0).outerHtml()); + assertEquals("

Three

", els.get(1).outerHtml()); + } + + @Test public void testChildThrowsIndexOutOfBoundsOnMissing() { + Document doc = Jsoup.parse("

One

Two

"); + Element div = doc.select("div").first(); + + assertEquals(2, div.children().size()); + assertEquals("One", div.child(0).text()); + + try { + div.child(3); + fail("Should throw index out of bounds"); + } catch (IndexOutOfBoundsException e) {} + } + + @Test + public void moveByAppend() { + // test for https://github.com/jhy/jsoup/issues/239 + // can empty an element and append its children to another element + Document doc = Jsoup.parse("
Text

One

Text

Two

"); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + + assertEquals(4, div1.childNodeSize()); + List children = div1.childNodes(); + assertEquals(4, children.size()); + + div2.insertChildren(0, children); + + assertEquals(0, children.size()); // children is backed by div1.childNodes, moved, so should be 0 now + assertEquals(0, div1.childNodeSize()); + assertEquals(4, div2.childNodeSize()); + assertEquals("
\n
\n Text \n

One

Text \n

Two

\n
", + doc.body().html()); + } + + @Test + public void insertChildrenArgumentValidation() { + Document doc = Jsoup.parse("
Text

One

Text

Two

"); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + List children = div1.childNodes(); + + try { + div2.insertChildren(6, children); + fail(); + } catch (IllegalArgumentException e) {} + + try { + div2.insertChildren(-5, children); + fail(); + } catch (IllegalArgumentException e) { + } + + try { + div2.insertChildren(0, (Collection) null); + fail(); + } catch (IllegalArgumentException e) { + } + } + + @Test + public void insertChildrenAtPosition() { + Document doc = Jsoup.parse("
Text1

One

Text2

Two

Text3

Three

"); + Element div1 = doc.select("div").get(0); + Elements p1s = div1.select("p"); + Element div2 = doc.select("div").get(1); + + assertEquals(2, div2.childNodeSize()); + div2.insertChildren(-1, p1s); + assertEquals(2, div1.childNodeSize()); // moved two out + assertEquals(4, div2.childNodeSize()); + assertEquals(3, p1s.get(1).siblingIndex()); // should be last + + List els = new ArrayList<>(); + Element el1 = new Element(Tag.valueOf("span"), "").text("Span1"); + Element el2 = new Element(Tag.valueOf("span"), "").text("Span2"); + TextNode tn1 = new TextNode("Text4"); + els.add(el1); + els.add(el2); + els.add(tn1); + + assertNull(el1.parent()); + div2.insertChildren(-2, els); + assertEquals(div2, el1.parent()); + assertEquals(7, div2.childNodeSize()); + assertEquals(3, el1.siblingIndex()); + assertEquals(4, el2.siblingIndex()); + assertEquals(5, tn1.siblingIndex()); + } + + @Test + public void insertChildrenAsCopy() { + Document doc = Jsoup.parse("
Text

One

Text

Two

"); + Element div1 = doc.select("div").get(0); + Element div2 = doc.select("div").get(1); + Elements ps = doc.select("p").clone(); + ps.first().text("One cloned"); + div2.insertChildren(-1, ps); + + assertEquals(4, div1.childNodeSize()); // not moved -- cloned + assertEquals(2, div2.childNodeSize()); + assertEquals("
Text

One

Text

Two

One cloned

Two

", + TextUtil.stripNewlines(doc.body().html())); + } + + @Test + public void testCssPath() { + Document doc = Jsoup.parse("
A
B
C
"); + Element divA = doc.select("div").get(0); + Element divB = doc.select("div").get(1); + Element divC = doc.select("div").get(2); + assertEquals(divA.cssSelector(), "#id1"); + assertEquals(divB.cssSelector(), "html > body > div:nth-child(2)"); + assertEquals(divC.cssSelector(), "html > body > div.c1.c2"); + + assertTrue(divA == doc.select(divA.cssSelector()).first()); + assertTrue(divB == doc.select(divB.cssSelector()).first()); + assertTrue(divC == doc.select(divC.cssSelector()).first()); + } + + + @Test + public void testClassNames() { + Document doc = Jsoup.parse("
C
"); + Element div = doc.select("div").get(0); + + assertEquals("c1 c2", div.className()); + + final Set set1 = div.classNames(); + final Object[] arr1 = set1.toArray(); + assertTrue(arr1.length==2); + assertEquals("c1", arr1[0]); + assertEquals("c2", arr1[1]); + + // Changes to the set should not be reflected in the Elements getters + set1.add("c3"); + assertTrue(2==div.classNames().size()); + assertEquals("c1 c2", div.className()); + + // Update the class names to a fresh set + final Set newSet = new LinkedHashSet<>(3); + newSet.addAll(set1); + newSet.add("c3"); + + div.classNames(newSet); + + + assertEquals("c1 c2 c3", div.className()); + + final Set set2 = div.classNames(); + final Object[] arr2 = set2.toArray(); + assertTrue(arr2.length==3); + assertEquals("c1", arr2[0]); + assertEquals("c2", arr2[1]); + assertEquals("c3", arr2[2]); + } + + @Test + public void testHashAndEqualsAndValue() { + // .equals and hashcode are identity. value is content. + + String doc1 = "

One

One

Two

One

" + + "

One

One

Two

One

"; + + Document doc = Jsoup.parse(doc1); + Elements els = doc.select("p"); + + /* + for (Element el : els) { + System.out.println(el.hashCode() + " - " + el.outerHtml()); + } + + 0 1534787905 -

One

+ 1 1534787905 -

One

+ 2 1539683239 -

Two

+ 3 1535455211 -

One

+ 4 1534787905 -

One

+ 5 1534787905 -

One

+ 6 1539683239 -

Two

+ 7 1535455211 -

One

+ */ + assertEquals(8, els.size()); + Element e0 = els.get(0); + Element e1 = els.get(1); + Element e2 = els.get(2); + Element e3 = els.get(3); + Element e4 = els.get(4); + Element e5 = els.get(5); + Element e6 = els.get(6); + Element e7 = els.get(7); + + assertEquals(e0, e0); + assertTrue(e0.hasSameValue(e1)); + assertTrue(e0.hasSameValue(e4)); + assertTrue(e0.hasSameValue(e5)); + assertFalse(e0.equals(e2)); + assertFalse(e0.hasSameValue(e2)); + assertFalse(e0.hasSameValue(e3)); + assertFalse(e0.hasSameValue(e6)); + assertFalse(e0.hasSameValue(e7)); + + assertEquals(e0.hashCode(), e0.hashCode()); + assertFalse(e0.hashCode() == (e2.hashCode())); + assertFalse(e0.hashCode() == (e3).hashCode()); + assertFalse(e0.hashCode() == (e6).hashCode()); + assertFalse(e0.hashCode() == (e7).hashCode()); + } + + @Test public void testRelativeUrls() { + String html = "One two Three Four Five"; + Document doc = Jsoup.parse(html, "http://example.com/bar/"); + Elements els = doc.select("a"); + + assertEquals("http://example.com/bar/one.html", els.get(0).absUrl("href")); + assertEquals("http://example.com/bar/two.html", els.get(1).absUrl("href")); + assertEquals("http://example.com/three.html", els.get(2).absUrl("href")); + assertEquals("http://example2.com/four/", els.get(3).absUrl("href")); + assertEquals("https://example2.com/five/", els.get(4).absUrl("href")); + } + + @Test + public void appendMustCorrectlyMoveChildrenInsideOneParentElement() { + Document doc = new Document(""); + Element body = doc.appendElement("body"); + body.appendElement("div1"); + body.appendElement("div2"); + final Element div3 = body.appendElement("div3"); + div3.text("Check"); + final Element div4 = body.appendElement("div4"); + + ArrayList toMove = new ArrayList<>(); + toMove.add(div3); + toMove.add(div4); + + body.insertChildren(0, toMove); + + String result = doc.toString().replaceAll("\\s+", ""); + assertEquals("Check", result); + } + + @Test + public void testHashcodeIsStableWithContentChanges() { + Element root = new Element(Tag.valueOf("root"), ""); + + HashSet set = new HashSet<>(); + // Add root node: + set.add(root); + + root.appendChild(new Element(Tag.valueOf("a"), "")); + assertTrue(set.contains(root)); + } + + @Test + public void testNamespacedElements() { + // Namespaces with ns:tag in HTML must be translated to ns|tag in CSS. + String html = ""; + Document doc = Jsoup.parse(html, "http://example.com/bar/"); + Elements els = doc.select("fb|comments"); + assertEquals(1, els.size()); + assertEquals("html > body > fb|comments", els.get(0).cssSelector()); + } + + @Test + public void testChainedRemoveAttributes() { + String html = "Text"; + Document doc = Jsoup.parse(html); + Element a = doc.select("a").first(); + a + .removeAttr("zero") + .removeAttr("one") + .removeAttr("two") + .removeAttr("three") + .removeAttr("four") + .removeAttr("five"); + assertEquals("Text", a.outerHtml()); + } + + @Test + public void testLoopedRemoveAttributes() { + String html = "Text

Two

"; + Document doc = Jsoup.parse(html); + for (Element el : doc.getAllElements()) { + el.clearAttributes(); + } + + assertEquals("Text\n

Two

", doc.body().html()); + } + + @Test + public void testIs() { + String html = "

One Two Three

Another

"; + Document doc = Jsoup.parse(html); + Element p = doc.select("p").first(); + + assertTrue(p.is("p")); + assertFalse(p.is("div")); + assertTrue(p.is("p:has(a)")); + assertTrue(p.is("p:first-child")); + assertFalse(p.is("p:last-child")); + assertTrue(p.is("*")); + assertTrue(p.is("div p")); + + Element q = doc.select("p").last(); + assertTrue(q.is("p")); + assertTrue(q.is("p ~ p")); + assertTrue(q.is("p + p")); + assertTrue(q.is("p:last-child")); + assertFalse(q.is("p a")); + assertFalse(q.is("a")); + } + + + @Test public void elementByTagName() { + Element a = new Element("P"); + assertTrue(a.tagName().equals("P")); + } + + @Test public void testChildrenElements() { + String html = "

One

Two

Three
Four"; + Document doc = Jsoup.parse(html); + Element div = doc.select("div").first(); + Element p = doc.select("p").first(); + Element span = doc.select("span").first(); + Element foo = doc.select("foo").first(); + Element img = doc.select("img").first(); + + Elements docChildren = div.children(); + assertEquals(2, docChildren.size()); + assertEquals("

One

", docChildren.get(0).outerHtml()); + assertEquals("

Two

", docChildren.get(1).outerHtml()); + assertEquals(3, div.childNodes().size()); + assertEquals("Three", div.childNodes().get(2).outerHtml()); + + assertEquals(1, p.children().size()); + assertEquals("One", p.children().text()); + + assertEquals(0, span.children().size()); + assertEquals(1, span.childNodes().size()); + assertEquals("Four", span.childNodes().get(0).outerHtml()); + + assertEquals(0, foo.children().size()); + assertEquals(0, foo.childNodes().size()); + assertEquals(0, img.children().size()); + assertEquals(0, img.childNodes().size()); + } + + @Test public void testShadowElementsAreUpdated() { + String html = "

One

Two

Three
Four"; + Document doc = Jsoup.parse(html); + Element div = doc.select("div").first(); + Elements els = div.children(); + List nodes = div.childNodes(); + + assertEquals(2, els.size()); // the two Ps + assertEquals(3, nodes.size()); // the "Three" textnode + + Element p3 = new Element("p").text("P3"); + Element p4 = new Element("p").text("P4"); + div.insertChildren(1, p3); + div.insertChildren(3, p4); + Elements els2 = div.children(); + + // first els should not have changed + assertEquals(2, els.size()); + assertEquals(4, els2.size()); + + assertEquals("

One

\n" + + "

P3

\n" + + "

Two

\n" + + "

P4

Three", div.html()); + assertEquals("P3", els2.get(1).text()); + assertEquals("P4", els2.get(3).text()); + + p3.after("AnotherOne

\n" + + "

P3

\n" + + "Another\n" + + "

Two

\n" + + "

P4

Three", div.html()); + } + + @Test public void classNamesAndAttributeNameIsCaseInsensitive() { + String html = "

One

"; + Document doc = Jsoup.parse(html); + Element p = doc.select("p").first(); + assertEquals("SomeText AnotherText", p.className()); + assertTrue(p.classNames().contains("SomeText")); + assertTrue(p.classNames().contains("AnotherText")); + assertTrue(p.hasClass("SomeText")); + assertTrue(p.hasClass("sometext")); + assertTrue(p.hasClass("AnotherText")); + assertTrue(p.hasClass("anothertext")); + + Element p1 = doc.select(".SomeText").first(); + Element p2 = doc.select(".sometext").first(); + Element p3 = doc.select("[class=SomeText AnotherText]").first(); + Element p4 = doc.select("[Class=SomeText AnotherText]").first(); + Element p5 = doc.select("[class=sometext anothertext]").first(); + Element p6 = doc.select("[class=SomeText AnotherText]").first(); + Element p7 = doc.select("[class^=sometext]").first(); + Element p8 = doc.select("[class$=nothertext]").first(); + Element p9 = doc.select("[class^=sometext]").first(); + Element p10 = doc.select("[class$=AnotherText]").first(); + + assertEquals("One", p1.text()); + assertEquals(p1, p2); + assertEquals(p1, p3); + assertEquals(p1, p4); + assertEquals(p1, p5); + assertEquals(p1, p6); + assertEquals(p1, p7); + assertEquals(p1, p8); + assertEquals(p1, p9); + assertEquals(p1, p10); + } + + @Test + public void testAppendTo() { + String parentHtml = "
"; + String childHtml = "

Two

"; + + Document parentDoc = Jsoup.parse(parentHtml); + Element parent = parentDoc.body(); + Document childDoc = Jsoup.parse(childHtml); + + Element div = childDoc.select("div").first(); + Element p = childDoc.select("p").first(); + Element appendTo1 = div.appendTo(parent); + assertEquals(div, appendTo1); + + Element appendTo2 = p.appendTo(div); + assertEquals(p, appendTo2); + + assertEquals("
\n
\n

Two

\n
", parentDoc.body().html()); + assertEquals("", childDoc.body().html()); // got moved out + } + + @Test public void testNormalizesNbspInText() { + String escaped = "You can't always get what you want."; + String withNbsp = "You can't always get what you want."; // there is an nbsp char in there + Document doc = Jsoup.parse("

" + escaped); + Element p = doc.select("p").first(); + assertEquals("You can't always get what you want.", p.text()); // text is normalized + + assertEquals("

" + escaped + "

", p.outerHtml()); // html / whole text keeps   + assertEquals(withNbsp, p.textNodes().get(0).getWholeText()); + assertEquals(160, withNbsp.charAt(29)); + + Element matched = doc.select("p:contains(get what you want)").first(); + assertEquals("p", matched.nodeName()); + assertTrue(matched.is(":containsOwn(get what you want)")); + } + + @Test public void testNormalizesInvisiblesInText() { + // return Character.getType(c) == 16 && (c == 8203 || c == 8204 || c == 8205 || c == 173); + String escaped = "This­is​one‌long‍word"; + String decoded = "This\u00ADis\u200Bone\u200Clong\u200Dword"; // browser would not display those soft hyphens / other chars, so we don't want them in the text + + Document doc = Jsoup.parse("

" + escaped); + Element p = doc.select("p").first(); + doc.outputSettings().charset("ascii"); // so that the outer html is easier to see with escaped invisibles + assertEquals("Thisisonelongword", p.text()); // text is normalized + assertEquals("

" + escaped + "

", p.outerHtml()); // html / whole text keeps ­ etc; + assertEquals(decoded, p.textNodes().get(0).getWholeText()); + + Element matched = doc.select("p:contains(Thisisonelongword)").first(); // really just oneloneword, no invisibles + assertEquals("p", matched.nodeName()); + assertTrue(matched.is(":containsOwn(Thisisonelongword)")); + + } + + @Test + public void testRemoveBeforeIndex() { + Document doc = Jsoup.parse( + "

before1

before2

XXX

after1

after2

", + ""); + Element body = doc.select("body").first(); + Elements elems = body.select("p:matchesOwn(XXX)"); + Element xElem = elems.first(); + Elements beforeX = xElem.parent().getElementsByIndexLessThan(xElem.elementSiblingIndex()); + + for(Element p : beforeX) { + p.remove(); + } + + assertEquals("

XXX

after1

after2

", TextUtil.stripNewlines(body.outerHtml())); + } + + @Test + public void testRemoveAfterIndex() { + Document doc2 = Jsoup.parse( + "

before1

before2

XXX

after1

after2

", + ""); + Element body = doc2.select("body").first(); + Elements elems = body.select("p:matchesOwn(XXX)"); + Element xElem = elems.first(); + Elements afterX = xElem.parent().getElementsByIndexGreaterThan(xElem.elementSiblingIndex()); + + for(Element p : afterX) { + p.remove(); + } + + assertEquals("

before1

before2

XXX

", TextUtil.stripNewlines(body.outerHtml())); + } + + @Test + public void whiteSpaceClassElement(){ + Tag tag = Tag.valueOf("a"); + Attributes attribs = new Attributes(); + Element el = new Element(tag, "", attribs); + + attribs.put("class", "abc "); + boolean hasClass = el.hasClass("ab"); + assertFalse(hasClass); + } + + @Test + public void testNextElementSiblingAfterClone() { + // via https://github.com/jhy/jsoup/issues/951 + String html = "
Initial element
"; + String expectedText = "New element"; + String cloneExpect = "New element in clone"; + + Document original = Jsoup.parse(html); + Document clone = original.clone(); + + Element originalElement = original.body().child(0); + originalElement.after("
" + expectedText + "
"); + Element originalNextElementSibling = originalElement.nextElementSibling(); + Element originalNextSibling = (Element) originalElement.nextSibling(); + assertEquals(expectedText, originalNextElementSibling.text()); + assertEquals(expectedText, originalNextSibling.text()); + + Element cloneElement = clone.body().child(0); + cloneElement.after("
" + cloneExpect + "
"); + Element cloneNextElementSibling = cloneElement.nextElementSibling(); + Element cloneNextSibling = (Element) cloneElement.nextSibling(); + assertEquals(cloneExpect, cloneNextElementSibling.text()); + assertEquals(cloneExpect, cloneNextSibling.text()); + } + + @Test + public void testRemovingEmptyClassAttributeWhenLastClassRemoved() { + // https://github.com/jhy/jsoup/issues/947 + Document doc = Jsoup.parse(""); + Element img = doc.select("img").first(); + img.removeClass("one"); + img.removeClass("two"); + assertFalse(doc.body().html().contains("class=\"\"")); + } + + @Test + public void booleanAttributeOutput() { + Document doc = Jsoup.parse(""); + Element img = doc.selectFirst("img"); + + assertEquals("", img.outerHtml()); + } + + @Test + public void textHasSpaceAfterBlockTags() { + Document doc = Jsoup.parse("
One
Two"); + assertEquals("One Two", doc.text()); + } + + @Test + public void testNextElementSiblings() { + Document doc = Jsoup.parse("
  • a
  • " + + "
  • b
  • " + + "
  • c
  • "); + Element element = doc.getElementById("a"); + List elementSiblings = element.nextElementSiblings(); + assertNotNull(elementSiblings); + assertEquals(2, elementSiblings.size()); + + Element element1 = doc.getElementById("c"); + List elementSiblings1 = element1.nextElementSiblings(); + assertNull(elementSiblings1); + } + + @Test + public void testPreviousElementSiblings() { + Document doc = Jsoup.parse("
  • a
  • " + + "
  • b
  • " + + "
  • c
  • "); + Element element = doc.getElementById("b"); + List elementSiblings = element.previousElementSiblings(); + assertNotNull(elementSiblings); + assertEquals(1, elementSiblings.size()); + + Element element1 = doc.getElementById("a"); + List elementSiblings1 = element1.previousElementSiblings(); + assertNull(elementSiblings1); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `elementSiblings` last assigned on line 1333 could be null and is dereferenced at line 1335. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ElementTest.testNextElementSiblings() + +### Procedure Id: +org.jsoup.nodes.ElementTest.testNextElementSiblings():void.bf77f718a6d39fdca370947bef5f3817 + +### File: +src/test/java/org/jsoup/nodes/ElementTest.java + +### Key: +ElementTest.java|testNextElementSiblings|NULL_DEREFERENCE + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +4003154e544e011ab6e00c5cd27c1171 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7770/instruction.md b/inferredbugs-7770/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcb1a0dfbe5a66e11e2807c2fd4d0b5ad1dd7eb2 --- /dev/null +++ b/inferredbugs-7770/instruction.md @@ -0,0 +1,296 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.parser; + +import org.apache.commons.lang.Validate; +import org.jsoup.nodes.*; + +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + Parses HTML into a {@link Document} + + @author Jonathan Hedley, jonathan@hedley.net */ +public class Parser { + private static String SQ = "'"; + private static String DQ = "\""; + + private static Tag htmlTag = Tag.valueOf("html"); + private static Tag headTag = Tag.valueOf("head"); + private static Tag bodyTag = Tag.valueOf("body"); + private static Tag titleTag = Tag.valueOf("title"); + + private LinkedList stack; + private TokenQueue tq; + private Document doc; + + public Parser(String html) { + Validate.notNull(html); + + stack = new LinkedList(); + tq = new TokenQueue(html); + + doc = new Document(); + stack.add(doc); + stack.add(doc.getHead()); + } + + public static Document parse(String html) { + Parser parser = new Parser(html); + return parser.parse(); + } + + public Document parse() { + while (!tq.isEmpty()) { + if (tq.matches(" + data = data.substring(0, data.length()-1); + Comment comment = new Comment(data); + last().addChild(comment); + } + + private void parseXmlDecl() { + tq.consume("<"); tq.consume(); // "); + + XmlDeclaration decl = new XmlDeclaration(data); + last().addChild(decl); + } + + private void parseEndTag() { + tq.consume(""); + + if (!tagName.isEmpty()) { + Tag tag = Tag.valueOf(tagName); + Element closed = popStackToClose(tag); + } + } + + private void parseStartTag() { + tq.consume("<"); + Attributes attributes = new Attributes(); + + String tagName = tq.consumeWord(); + while (!tq.matches("<") && !tq.matches("/>") && !tq.matches(">") && !tq.isEmpty()) { + Attribute attribute = parseAttribute(); + if (attribute != null) + attributes.put(attribute); + } + + Tag tag = Tag.valueOf(tagName); + StartTag startTag = new StartTag(tag, attributes); + Element child = new Element(startTag); + + boolean emptyTag; + if (tq.matchChomp("/>")) { // empty tag, don't add to stack + emptyTag = true; + } else { + tq.matchChomp(">"); // safe because checked above (or ran out of data) + emptyTag = false; + } + + // pc data only tags (textarea, script): chomp to end tag, add content as text node + if (tag.isData()) { + String data = tq.chompTo(""); + TextNode textNode = TextNode.createFromEncoded(data); + child.addChild(textNode); + + if (tag.equals(titleTag)) + doc.setTitle(child.text()); + } + + // switch between html, head, body, to preserve doc structure + if (tag.equals(htmlTag)) { + doc.getAttributes().mergeAttributes(attributes); + } else if (tag.equals(headTag)) { + doc.getHead().getAttributes().mergeAttributes(attributes); + // head is on stack from start, no action required + } else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) { + // switch to body + stack.removeLast(); + stack.addLast(doc.getBody()); + last().addChild(child); + if (!emptyTag) + stack.addLast(child); + } else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) { + doc.getBody().getAttributes().mergeAttributes(attributes); + stack.removeLast(); + stack.addLast(doc.getBody()); + } else { + Element parent = popStackToSuitableContainer(tag); + parent.addChild(child); + if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head + stack.addLast(child); + } + } + + private Attribute parseAttribute() { + tq.consumeWhitespace(); + String key = tq.consumeWord(); + String value = ""; + tq.consumeWhitespace(); + if (tq.matchChomp("=")) { + tq.consumeWhitespace(); + + if (tq.matchChomp(SQ)) { + value = tq.chompTo(SQ); + } else if (tq.matchChomp(DQ)) { + value = tq.chompTo(DQ); + } else { + StringBuilder valueAccum = new StringBuilder(); + // no ' or " to look for, so scan to end tag or space (or end of stream) + while (!tq.matches("<") && !tq.matches("/>") && !tq.matches(">") && !tq.matchesWhitespace() && !tq.isEmpty()) { + valueAccum.append(tq.consume()); + } + value = valueAccum.toString(); + } + tq.consumeWhitespace(); + } + if (!key.isEmpty()) + return Attribute.createFromEncoded(key, value); + else { + tq.consume(); // unknown char, keep popping so not get stuck + return null; + } + } + + private void parseTextNode() { + // TODO: work out whitespace requirements (between blocks, between inlines) + StringBuilder textAccum = new StringBuilder(); + while (!tq.matches("<") && !tq.isEmpty()) { // scan to next tag + textAccum.append(tq.consume()); + } + TextNode textNode = TextNode.createFromEncoded(textAccum.toString()); + last().addChild(textNode); + } + + private Element popStackToSuitableContainer(Tag tag) { + while (!stack.isEmpty()) { + if (last().getTag().canContain(tag)) + return last(); + else + stack.removeLast(); + } + return null; + } + + private Element popStackToClose(Tag tag) { + // first check to see if stack contains this tag; if so pop to there, otherwise ignore + int counter = 0; + Element elToClose = null; + for (int i = stack.size() -1; i > 0; i--) { + counter++; + Element el = stack.get(i); + if (el.getTag().equals(tag)) { + elToClose = el; + break; + } + } + if (elToClose != null) { + for (int i = 0; i < counter; i++) { + stack.removeLast(); + } + } + return elToClose; + } + + private Element last() { + return stack.getLast(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `parent` last assigned on line 142 could be null and is dereferenced at line 143. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Parser.parseStartTag() + +### Procedure Id: +org.jsoup.parser.Parser.parseStartTag():void.2eb6a50b5349c716ab22859b69102fe3 + +### File: +src/main/java/org/jsoup/parser/Parser.java + +### Key: +Parser.java|parseStartTag|NULL_DEREFERENCE + +### Node Key: +d74069611bcc65648adfc91df7f1c71f + +### Hash: +80b02e41940c52b0c3e5542a27a54c9d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7771/instruction.md b/inferredbugs-7771/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..568b181366cd72889ee26b340bb1b751449b8d04 --- /dev/null +++ b/inferredbugs-7771/instruction.md @@ -0,0 +1,450 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jsoup +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jsoup.parser; + +import org.apache.commons.lang.Validate; + +/** + * A character queue with parsing helpers. + * + * @author Jonathan Hedley + */ +public class TokenQueue { + private String queue; + private int pos = 0; + + private static final Character ESC = '\\'; // escape char for chomp balanced. + + /** + Create a new TokenQueue. + @param data string of data to back queue. + */ + public TokenQueue(String data) { + Validate.notNull(data); + queue = data; + } + + /** + * Is the queue empty? + * @return true if no data left in queue. + */ + public boolean isEmpty() { + return remainingLength() == 0; + } + + private int remainingLength() { + return queue.length() - pos; + } + + /** + * Retrieves but does not remove the first character from the queue. + * @return First character, or null if empty. + */ + public Character peek() { + return isEmpty() ? null : queue.charAt(pos); + } + + /** + Add a character to the start of the queue (will be the next character retrieved). + @param c character to add + */ + public void addFirst(Character c) { + addFirst(c.toString()); + } + + /** + Add a string to the start of the queue. + @param seq string to add. + */ + public void addFirst(String seq) { + // not very performant, but an edge case + queue = seq + queue.substring(pos); + pos = 0; + } + + /** + * Tests if the next characters on the queue match the sequence. Case insensitive. + * @param seq String to check queue for. + * @return true if the next characters match. + */ + public boolean matches(String seq) { + int count = seq.length(); + if (count > remainingLength()) + return false; + + while (--count >= 0) { + if (Character.toLowerCase(seq.charAt(count)) != Character.toLowerCase(queue.charAt(pos+count))) + return false; + } + return true; + } + + + /** + Tests if the next characters match any of the sequences. + @param seq + @return + */ + public boolean matchesAny(String... seq) { + for (String s : seq) { + if (matches(s)) + return true; + } + return false; + } + + /** + * Tests if the queue matches the sequence (as with match), and if they do, removes the matched string from the + * queue. + * @param seq String to search for, and if found, remove from queue. + * @return true if found and removed, false if not found. + */ + public boolean matchChomp(String seq) { + if (matches(seq)) { + consume(seq); + return true; + } else { + return false; + } + } + + /** + Tests if queue starts with a whitespace character. + @return if starts with whitespace + */ + public boolean matchesWhitespace() { + return !isEmpty() && Character.isWhitespace(peek()); + } + + /** + Test if the queue matches a word character (letter or digit). + @return if matches a word character + */ + public boolean matchesWord() { + return !isEmpty() && Character.isLetterOrDigit(peek()); + } + + /** + * Drops the next character off the queue. + */ + public void advance() { + if (!isEmpty()) pos++; + } + + /** + * Consume one character off queue. + * @return first character on queue. + */ + public Character consume() { + Character c= queue.charAt(pos); + pos++; + return c; + } + + /** + * Consumes the supplied sequence of the queue. If the queue does not start with the supplied sequence, will + * throw an illegal state exception -- but you should be running match() against that condition. +

    + Case insensitive. + * @param seq sequence to remove from head of queue. + */ + public void consume(String seq) { + if (!matches(seq)) + throw new IllegalStateException("Queue did not match expected sequence"); + int len = seq.length(); + if (len > remainingLength()) + throw new IllegalStateException("Queue not long enough to consume sequence"); + + pos += len; + } + + /** + * Pulls a string off the queue, up to but exclusive of the match sequence, or to the queue running out. + * @param seq String to end on (and not include in return, but leave on queue). Case sensitive. + * @return The matched data consumed from queue. + */ + public String consumeTo(String seq) { + int offset = queue.indexOf(seq, pos); + if (offset != -1) { + String consumed = queue.substring(pos, offset); + pos += consumed.length(); + return consumed; + } else { + return remainder(); + } + } + + public String consumeToIgnoreCase(String seq) { + int start = pos; + String first = seq.substring(0, 1); + boolean canScan = first.toLowerCase().equals(first.toUpperCase()); // if first is not cased, use index of + while (!isEmpty() && !matches(seq)) { + if (canScan) { + int skip = queue.indexOf(first, pos) - pos; + if (skip <= 0) + pos++; + else if (skip < 0) // no chance of finding, grab to end + pos = queue.length() - 1; + else + pos += skip; + } + else + pos++; + } + + String data = queue.substring(start, pos); + return data; + } + + /** + Consumes to the first sequence provided, or to the end of the queue. Leaves the terminator on the queue. + @param seq any number of terminators to consume to. Case insensitive. + @return consumed string + */ + // todo: method name. not good that consumeTo cares for case, and consume to any doesn't. And the only use for this + // is is a case sensitive time... + public String consumeToAny(String... seq) { + int start = pos; + while (!isEmpty() && !matchesAny(seq)) { + pos++; + } + + String data = queue.substring(start, pos); + return data; + } + + /** + * Pulls a string off the queue (like consumeTo), and then pulls off the matched string (but does not return it). + *

    + * If the queue runs out of characters before finding the seq, will return as much as it can (and queue will go + * isEmpty() == true). + * @param seq String to match up to, and not include in return, and to pull off queue. Case sensitive. + * @return Data matched from queue. + */ + public String chompTo(String seq) { + String data = consumeTo(seq); + matchChomp(seq); + return data; + } + + public String chompToIgnoreCase(String seq) { + String data = consumeToIgnoreCase(seq); // case insensitive scan + matchChomp(seq); + return data; + } + + /** + * Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three", + * and leave " four" on the queue. Unbalanced openers and closers can be escaped (with \). Those escapes will be left + * in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for + * contains text strings; use unescape for that. + * @param open opener + * @param close closer + * @return data matched from the queue + */ + public String chompBalanced(Character open, Character close) { + StringBuilder accum = new StringBuilder(); + int depth = 0; + Character last = null; + + do { + if (isEmpty()) break; + Character c = consume(); + if (last == null || !last.equals(ESC)) { + if (c.equals(open)) + depth++; + else if (c.equals(close)) + depth--; + } + + if (depth > 0 && last != null) + accum.append(c); // don't include the outer match pair in the return + last = c; + } while (depth > 0); + return accum.toString(); + } + + /** + * Unescaped a \ escaped string. + * @param in backslash escaped string + * @return unescaped string + */ + public static String unescape(String in) { + StringBuilder out = new StringBuilder(); + Character last = null; + for (Character c : in.toCharArray()) { + if (c.equals(ESC)) { + if (last != null && last.equals(ESC)) + out.append(c); + } + else + out.append(c); + last = c; + } + return out.toString(); + } + + /** + * Pulls the next run of whitespace characters of the queue. + */ + public boolean consumeWhitespace() { + boolean seen = false; + while (matchesWhitespace()) { + consume(); + seen = true; + } + return seen; + } + + /** + * Retrieves the next run of word type (letter or digit) off the queue. + * @return String of word characters from queue, or empty string if none. + */ + public String consumeWord() { + int start = pos; + while (matchesWord()) + pos++; + return queue.substring(start, pos); + } + + /** + * Consume an tag name off the queue (word or :, _, -) + * + * @return tag name + */ + public String consumeTagName() { + int start = pos; + while (!isEmpty() && (matchesWord() || matchesAny(":", "_", "-"))) + pos++; + + return queue.substring(start, pos); + } + + /** + * Consume a CSS element selector (tag name, but | instead of : for namespaces, to not conflict with :pseudo selects). + * + * @return tag name + */ + public String consumeElementSelector() { + int start = pos; + while (!isEmpty() && (matchesWord() || matchesAny("|", "_", "-"))) + pos++; + + return queue.substring(start, pos); + } + + /** + Consume a CSS identifier (ID or class) off the queue (letter, digit, -, _) + http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier + @return identifier + */ + public String consumeCssIdentifier() { + StringBuilder accum = new StringBuilder(); + Character c = peek(); + while (!isEmpty() && (Character.isLetterOrDigit(c) || c.equals('-') || c.equals('_'))) { + accum.append(consume()); + c = peek(); + } + return accum.toString(); + } + + /** + Consume an attribute key off the queue (letter, digit, -, _, :") + @return attribute key + */ + public String consumeAttributeKey() { + int start = pos; + while (!isEmpty() && (matchesWord() || matchesAny("-", "_", ":"))) + pos++; + + return queue.substring(start, pos); + } + + /** + Consume and return whatever is left on the queue. + @return remained of queue. + */ + public String remainder() { + StringBuilder accum = new StringBuilder(); + while (!isEmpty()) { + accum.append(consume()); + } + return accum.toString(); + } + + public String toString() { + return queue.substring(pos); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `peek()` could be null and is dereferenced at line 114. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean TokenQueue.matchesWhitespace() + +### Procedure Id: +org.jsoup.parser.TokenQueue.matchesWhitespace():boolean.82b912e7979ffe06cd9ac887935622c8 + +### File: +src/main/java/org/jsoup/parser/TokenQueue.java + +### Key: +TokenQueue.java|matchesWhitespace|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +d64186f55e182f704a1a7ccf940fcf37 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7776/instruction.md b/inferredbugs-7776/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba5121d9e492b4f0ea771771ed391a20d24ded01 --- /dev/null +++ b/inferredbugs-7776/instruction.md @@ -0,0 +1,369 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** exp4j +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.congrace.exp4j; + +import static org.junit.Assert.assertTrue; + +import java.text.DecimalFormat; +import java.util.Arrays; +import java.util.Random; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; + +import org.junit.Test; + +public class ExpressionBuilderTest { + @Test + public void testCustomFunction1() throws Exception { + CustomFunction custom = new CustomFunction("timespi") { + @Override + public double applyFunction(double value) { + return value * Math.PI; + } + }; + Calculable calc = new ExpressionBuilder("timespi(x)").withVariable("x", 1).withCustomFunction(custom).build(); + double result = calc.calculate(); + assertTrue(result == Math.PI); + } + + @Test + public void testCustomFunction2() throws Exception { + CustomFunction custom = new CustomFunction("loglog") { + @Override + public double applyFunction(double value) { + return Math.log(Math.log(value)); + } + }; + Calculable calc = new ExpressionBuilder("loglog(x)").withVariable("x", 1).withCustomFunction(custom).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(Math.log(1))); + } + + @Test + public void testCustomFunction3() throws Exception { + CustomFunction custom1 = new CustomFunction("foo") { + @Override + public double applyFunction(double value) { + return value * Math.E; + } + }; + CustomFunction custom2 = new CustomFunction("bar") { + @Override + public double applyFunction(double value) { + return value * Math.PI; + } + }; + Calculable calc = new ExpressionBuilder("foo(bar(x))").withVariable("x", 1).withCustomFunction(custom1).withCustomFunction(custom2).build(); + double result = calc.calculate(); + assertTrue(result == 1 * Math.E * Math.PI); + } + + @Test + public void testCustomFunction4() throws Exception { + CustomFunction custom1 = new CustomFunction("foo") { + @Override + public double applyFunction(double value) { + return value * Math.E; + } + }; + double varX = 32.24979131d; + Calculable calc = new ExpressionBuilder("foo(log(x))").withVariable("x", varX).withCustomFunction(custom1).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(varX) * Math.E); + } + + @Test + public void testCustomFunction5() throws Exception { + CustomFunction custom1 = new CustomFunction("foo") { + @Override + public double applyFunction(double value) { + return value * Math.E; + } + }; + CustomFunction custom2 = new CustomFunction("bar") { + @Override + public double applyFunction(double value) { + return value * Math.PI; + } + }; + double varX = 32.24979131d; + Calculable calc = new ExpressionBuilder("bar(foo(log(x)))").withVariable("x", varX).withCustomFunction(custom1).withCustomFunction(custom2).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(varX) * Math.E * Math.PI); + } + + @Test + public void testCustomFunction6() throws Exception { + CustomFunction custom1 = new CustomFunction("foo") { + @Override + public double applyFunction(double value) { + return value * Math.E; + } + }; + CustomFunction custom2 = new CustomFunction("bar") { + @Override + public double applyFunction(double value) { + return value * Math.PI; + } + }; + double varX = 32.24979131d; + Calculable calc = new ExpressionBuilder("bar(foo(log(x)))").withVariable("x", varX).withCustomFunctions(Arrays.asList(custom1, custom2)).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(varX) * Math.E * Math.PI); + } + + @Test + public void testCustomFunction7() throws Exception { + CustomFunction custom1 = new CustomFunction("half") { + @Override + public double applyFunction(double value) { + return value/2; + } + }; + Calculable calc = new ExpressionBuilder("half(x)").withVariable("x", 1d).withCustomFunction(custom1).build(); + assertTrue(0.5d == calc.calculate()); + } + + @Test(expected=InvalidCustomFunctionException.class) + public void testCustomFunction8() throws Exception { + CustomFunction custom1 = new CustomFunction("log") { + @Override + public double applyFunction(double value) { + return value/2; + } + }; + Calculable calc = new ExpressionBuilder("half(x)").withVariable("x", 1d).withCustomFunction(custom1).build(); + assertTrue(0.5d == calc.calculate()); + } + + @Test + public void testExpressionBuilder1() throws Exception { + Calculable calc = new ExpressionBuilder("f(x,y)=7*x + 3*y").withVariable("x", 1).withVariable("y", 2).build(); + double result = calc.calculate(); + assertTrue(result == 13d); + } + + @Test + public void testExpressionBuilder2() throws Exception { + Calculable calc = new ExpressionBuilder("7*x + 3*y").withVariable("x", 1).withVariable("y", 2).build(); + double result = calc.calculate(); + assertTrue(result == 13d); + } + + @Test + public void testExpressionBuilder3() throws Exception { + double varX = 1.3d; + double varY = 4.22d; + Calculable calc = new ExpressionBuilder("7*x + 3*y - log(y/x*12)^y").withVariable("x", varX).withVariable("y", varY).build(); + double result = calc.calculate(); + assertTrue(result == 7 * varX + 3 * varY - Math.pow(Math.log(varY / varX * 12), varY)); + } + + @Test + public void testExpressionBuilder4() throws Exception { + double varX = 1.3d; + double varY = 4.22d; + Calculable calc = new ExpressionBuilder("7*x + 3*y - log(y/x*12)^y").withVariable("x", varX).withVariable("y", varY).build(); + double result = calc.calculate(); + assertTrue(result == 7 * varX + 3 * varY - Math.pow(Math.log(varY / varX * 12), varY)); + varX = 1.79854d; + varY = 9281.123d; + calc.setVariable("x", varX); + calc.setVariable("y", varY); + result = calc.calculate(); + assertTrue(result == 7 * varX + 3 * varY - Math.pow(Math.log(varY / varX * 12), varY)); + } + + @Test + public void testExpressionBuilder5() throws Exception { + double varX = 1.3d; + double varY = 4.22d; + Calculable calc = new ExpressionBuilder("3*y").withVariable("x", varX).withVariable("y", varY).build(); + double result = calc.calculate(); + assertTrue(result == 3 * varY); + } + + @Test + public void testExpressionBuilder6() throws Exception { + double varX = 1.3d; + double varY = 4.22d; + double varZ = 4.22d; + Calculable calc = new ExpressionBuilder("x * y * z").withVariableNames("x", "y", "z").build(); + calc.setVariable("x", varX); + calc.setVariable("y", varY); + calc.setVariable("z", varZ); + double result = calc.calculate(); + assertTrue(result == varX * varY * varZ); + } + + @Test + public void testExpressionBuilder7() throws Exception { + double varX = 1.3d; + Calculable calc = new ExpressionBuilder("log(sin(x))").withVariable("x", varX).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(Math.sin(varX))); + } + + @Test + public void testExpressionBuilder8() throws Exception { + double varX = 1.3d; + Calculable calc = new ExpressionBuilder("f(x)=log(sin(x))").withVariable("x", varX).build(); + double result = calc.calculate(); + assertTrue(result == Math.log(Math.sin(varX))); + } + + @Test(expected = UnparsableExpressionException.class) + public void testSameName() throws Exception { + CustomFunction custom = new CustomFunction("bar") { + @Override + public double applyFunction(double value) { + return value / 2; + } + }; + double varBar = 1.3d; + Calculable calc = new ExpressionBuilder("f(bar)=bar(bar)").withVariable("bar", varBar).withCustomFunction(custom).build(); + double result = calc.calculate(); + assertTrue(result == varBar / 2); + } + + @Test(expected = UnparsableExpressionException.class) + public void testInvalidFunction() throws Exception { + double varY = 4.22d; + Calculable calc = new ExpressionBuilder("3*invalid_function(y)").withVariable("y", varY).build(); + calc.calculate(); + } + + @Test(expected = UnparsableExpressionException.class) + public void testMissingVar() throws Exception { + double varY = 4.22d; + Calculable calc = new ExpressionBuilder("3*y*z").withVariable("y", varY).build(); + calc.calculate(); + } + + @Test + public void testBench1() throws Exception { + if (System.getProperty("skipBenchmark") != null && System.getProperty("skipBenchmark").equals("true")) { + System.out.println(":: skipping naive benchmarks..."); + return; + } + System.out.println(":: running naive benchmarks, set -DskipBenchmark to skip"); + String expr = "foo(x,y)=log(x) - y * (sqrt(x^cos(y)))"; + Calculable calc = new ExpressionBuilder(expr).build(); + double val = 0; + Random rnd = new Random(); + long timeout = 2; + long time = System.currentTimeMillis() + (1000 * timeout); + int count = 0; + while (time > System.currentTimeMillis()) { + calc.setVariable("x", rnd.nextDouble()); + calc.setVariable("y", rnd.nextDouble()); + val = calc.calculate(); + count++; + } + System.out.println("\n:: [PostfixExpression] simple benchmark"); + System.out.println("expression\t\t" + expr); + double rate = count / timeout; + System.out.println("exp4j\t\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); + time = System.currentTimeMillis() + (1000 * timeout); + double x, y; + count = 0; + while (time > System.currentTimeMillis()) { + x = rnd.nextDouble(); + y = rnd.nextDouble(); + val = Math.log(x) - y * (Math.sqrt(Math.pow(x, Math.cos(y)))); + count++; + } + rate = count / timeout; + System.out.println("Java Math\t\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + " calc/sec]"); + ScriptEngineManager mgr = new ScriptEngineManager(); + ScriptEngine engine = mgr.getEngineByName("JavaScript"); + if (engine == null) { + System.err.println("Unable to instantiate javascript engine. skipping naive JS bench."); + } else { + time = System.currentTimeMillis() + (1000 * timeout); + count = 0; + while (time > System.currentTimeMillis()) { + x = rnd.nextDouble(); + y = rnd.nextDouble(); + engine.eval("Math.log(" + x + ") - " + y + "* (Math.sqrt(" + x + "^Math.cos(" + y + ")))"); + count++; + } + rate = count / timeout; + System.out.println("JSR 223(Javascript)\t" + count + " [" + (rate > 1000 ? new DecimalFormat("#.##").format(rate / 1000) + "k" : rate) + + " calc/sec]"); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("skipBenchmark")` could be null and is dereferenced at line 244. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ExpressionBuilderTest.testBench1() + +### Procedure Id: +de.congrace.exp4j.ExpressionBuilderTest.testBench1():void.f165b6c5cc7c0dfbefc09db51714781f + +### File: +src/test/java/de/congrace/exp4j/ExpressionBuilderTest.java + +### Key: +ExpressionBuilderTest.java|testBench1|NULL_DEREFERENCE + +### Node Key: +965bbf0a29188a78e25245c992eef045 + +### Hash: +a91134f7a8b283da4309a8caaf188e0c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7777/instruction.md b/inferredbugs-7777/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9ee1af264014cc832f3df10cab880c5a3b5cf82 --- /dev/null +++ b/inferredbugs-7777/instruction.md @@ -0,0 +1,417 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** JNCryptor +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* Copyright 2014 Duncan Jones + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.cryptonode.jncryptor; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Random; + +import javax.crypto.SecretKey; + +import org.apache.commons.io.IOUtils; +import org.junit.Test; + +public class AES256JNCryptorInputStreamTest { + private static final Random RANDOM = new Random(); + + /** + * Test reading using read() method. + * + * @throws Exception + */ + @Test + public void testUsingRead() throws Exception { + byte[] plaintext = getRandomBytes(1); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + byte[] result = new byte[plaintext.length]; + int offset = 0; + int b; + while ((b = in.read()) != -1) { + result[offset++] = (byte) b; + } + + assertTrue(offset == plaintext.length); + assertArrayEquals(plaintext, result); + + } finally { + in.close(); + } + } + + /** + * Test reading using read(byte[]) method. + * + * @throws Exception + */ + @Test + public void testUsingReadByteArrayWithOffset() throws Exception { + byte[] plaintext = getRandomBytes(256); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + + byte[] result = new byte[256]; + IOUtils.readFully(in, result); + + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + + /** + * Test reading using read(byte[]) method. + * + * @throws Exception + */ + @Test + public void testUsingReadByteArray() throws Exception { + byte[] plaintext = getRandomBytes(256); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + + byte[] result = new byte[256]; + in.read(result); + + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + /** + * Test reading using read(byte[]) method, with larger data amount and buffers, + * testing Issue #6. + * + * @throws Exception + */ + @Test + public void testUsingReadByteArrayLargeBufferIssue6() throws Exception { + byte[] plaintext = getRandomBytes(50000); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + byte[] buffer = new byte[16383]; + ByteArrayOutputStream outStream = new ByteArrayOutputStream(); + int len; + do { + len = in.read(buffer); + if (len > 0) + outStream.write(buffer, 0, len); + } while (len >= 0); + byte[] result = outStream.toByteArray(); + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + /** + * Test reading of mismatched data (e.g. encrypted using keys, decrypted with + * password). + * + * @throws Exception + */ + @Test(expected = IOException.class) + // TODO check for specific message + public void testUsingMismatchedKeys() throws Exception { + + byte[] plaintext = getRandomBytes(256); + byte[] encryptionSalt = getRandomBytes(8); + byte[] hmacSalt = getRandomBytes(8); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + + SecretKey hmacKey = cryptor + .keyForPassword(password.toCharArray(), hmacSalt); + SecretKey encryptionKey = cryptor.keyForPassword(password.toCharArray(), + encryptionSalt); + + byte[] data = cryptor.encryptData(plaintext, encryptionKey, hmacKey); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + + byte[] result = new byte[256]; + IOUtils.readFully(in, result); + + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + /** + * Test reading of data with keys. + * + * @throws Exception + */ + @Test + public void testUsingKeys() throws Exception { + + byte[] plaintext = getRandomBytes(256); + byte[] encryptionSalt = getRandomBytes(8); + byte[] hmacSalt = getRandomBytes(8); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + + SecretKey hmacKey = cryptor + .keyForPassword(password.toCharArray(), hmacSalt); + SecretKey encryptionKey = cryptor.keyForPassword(password.toCharArray(), + encryptionSalt); + + byte[] data = cryptor.encryptData(plaintext, encryptionKey, hmacKey); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), encryptionKey, hmacKey); + + try { + + byte[] result = new byte[256]; + IOUtils.readFully(in, result); + + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + /** + * Test failure if MAC is broken. + * + * @throws Exception + */ + @Test(expected = StreamIntegrityException.class) + public void testBadHMAC() throws Exception { + byte[] plaintext = getRandomBytes(256); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + data[data.length - 1] = (byte) (data[data.length - 1] + 1); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + byte[] result = new byte[plaintext.length]; + IOUtils.readFully(in, result); + + assertArrayEquals(plaintext, result); + } finally { + in.close(); + } + } + + /** + * Test failure if MAC is broken, by reading exactly the right number of + * bytes. + * + * @throws Exception + */ + @Test(expected = StreamIntegrityException.class) + public void testBadHMACExactLength() throws Exception { + byte[] plaintext = getRandomBytes(256); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + data[data.length - 1] = (byte) (data[data.length - 1] + 1); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + byte[] result = new byte[plaintext.length]; + int read = in.read(result); + assertEquals(result.length, read); + } finally { + in.close(); + } + } + + /** + * Test failure if MAC is broken, by reading exactly the right number of + * bytes. + * + * @throws Exception + */ + @Test(expected = StreamIntegrityException.class) + public void testBadHMACExactLengthByByte() throws Exception { + byte[] plaintext = getRandomBytes(256); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + data[data.length - 1] = (byte) (data[data.length - 1] + 1); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + try { + byte[] result = new byte[plaintext.length]; + + for (int i = 0; i < result.length; i++) { + result[i] = (byte) in.read(); + } + + } finally { + in.close(); + } + } + + + @Test + public void testMarkNotSupported() throws Exception { + byte[] plaintext = getRandomBytes(1); + + final String password = "Testing1234"; + + JNCryptor cryptor = new AES256JNCryptor(); + byte[] data = cryptor.encryptData(plaintext, password.toCharArray()); + + InputStream in = new AES256JNCryptorInputStream(new ByteArrayInputStream( + data), password.toCharArray()); + + assertFalse(in.markSupported()); + } + + private static byte[] getRandomBytes(int length) { + byte[] result = new byte[length]; + RANDOM.nextBytes(result); + return result; + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.cryptonode.jncryptor.AES256JNCryptorInputStream` acquired by call to `new()` at line 334 is not released after line 336. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AES256JNCryptorInputStreamTest.testMarkNotSupported() + +### Procedure Id: +org.cryptonode.jncryptor.AES256JNCryptorInputStreamTest.testMarkNotSupported():void.90adba06d0a1ef40744409994d3c2957 + +### File: +src/test/java/org/cryptonode/jncryptor/AES256JNCryptorInputStreamTest.java + +### Key: +AES256JNCryptorInputStreamTest.java|testMarkNotSupported|RESOURCE_LEAK + +### Node Key: +37f4cc7a17f8001fbd4a4245352b84d7 + +### Hash: +9c5ca520eb41ddac5240b12070d6b403 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7778/instruction.md b/inferredbugs-7778/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7560399cc210b2edbb158a754ea64705dc7997e9 --- /dev/null +++ b/inferredbugs-7778/instruction.md @@ -0,0 +1,281 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.hamcrest.Matchers; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class TestObjectIdHandling extends MongoDBTestBase { + + @Test + public void testObjectIdGenerated() { + ObjectIdId object = new ObjectIdId(); + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + org.bson.types.ObjectId id = coll.insert(object).getSavedId(); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdSaved() { + ObjectIdId object = new ObjectIdId(); + org.bson.types.ObjectId id = new org.bson.types.ObjectId(); + object._id = id; + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + coll.insert(object); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ObjectIdId { + public org.bson.types.ObjectId _id; + } + + @Test + public void testObjectIdAnnotationOnStringGenerated() { + StringId object = new StringId(); + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + String id = coll.insert(object).getSavedId(); + // Check that it's a valid object id + assertTrue(org.bson.types.ObjectId.isValid(id)); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnStringSaved() { + StringId object = new StringId(); + String id = new org.bson.types.ObjectId().toString(); + object._id = id; + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + coll.insert(object); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testRemoveByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + String id = coll.insert(new StringId()).getSavedId(); + coll.insert(new StringId()); + assertThat(coll.find().toArray(), hasSize(2)); + coll.removeById(id); + List results = coll.find().toArray(); + assertThat(results, hasSize(1)); + assertThat(results.get(0)._id, not(Matchers.equalTo(id))); + } + + @Test + public void testFindOneByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + StringId object = new StringId(); + net.vz.mongodb.jackson.WriteResult writeResult = coll.insert(object); + assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); + String id = writeResult.getSavedId(); + assertThat(id, instanceOf(String.class)); + StringId result = coll.findOneById(id); + assertThat(result._id, Matchers.equalTo(id)); + } + + public static class StringId { + @ObjectId + public String _id; + } + + @Test + public void testObjectIdAnnotationOnByteArrayGenerated() { + ByteArrayId object = new ByteArrayId(); + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + byte[] id = coll.insert(object).getSavedId(); + // Check that it's a valid object id, should be 12 bytes + assertEquals(12, id.length); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnByteArraySaved() { + ByteArrayId object = new ByteArrayId(); + byte[] id = new org.bson.types.ObjectId().toByteArray(); + object._id = id; + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + coll.insert(object); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ByteArrayId { + @ObjectId + public byte[] _id; + } + + @Test + public void testCollectionOfObjectIds() { + ObjectIdCollection object = new ObjectIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get(), org.bson.types.ObjectId.get()); + + JacksonDBCollection coll = getCollection(ObjectIdCollection.class, String.class); + coll.insert(object); + + ObjectIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class ObjectIdCollection { + public String _id; + public List list; + } + + @Test + public void testCollectionOfObjectIdStrings() { + StringIdCollection object = new StringIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toString(), org.bson.types.ObjectId.get().toString()); + + JacksonDBCollection coll = getCollection(StringIdCollection.class, String.class); + coll.insert(object); + + StringIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class StringIdCollection { + public String _id; + @ObjectId + public List list; + } + + @Test + public void testCollectionOfObjectIdByteArrays() { + ByteArrayIdCollection object = new ByteArrayIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toByteArray(), org.bson.types.ObjectId.get().toByteArray()); + + JacksonDBCollection coll = getCollection(ByteArrayIdCollection.class, String.class); + coll.insert(object); + + ByteArrayIdCollection result = coll.findOneById("id"); + assertThat(result.list, hasSize(2)); + assertThat(result.list.get(0), equalTo(object.list.get(0))); + assertThat(result.list.get(1), equalTo(object.list.get(1))); + } + + public static class ByteArrayIdCollection { + public String _id; + @ObjectId + public List list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 110 could be null and is dereferenced at line 111. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestObjectIdHandling.testFindOneByIdWithObjectId() + +### Procedure Id: +net.vz.mongodb.jackson.TestObjectIdHandling.testFindOneByIdWithObjectId():void.c249c98a5ed3090eabd2121f91bde2b6 + +### File: +src/test/java/net/vz/mongodb/jackson/TestObjectIdHandling.java + +### Key: +TestObjectIdHandling.java|testFindOneByIdWithObjectId|NULL_DEREFERENCE + +### Node Key: +2acc12e05b0902ef2ca0b1741f78fa6e + +### Hash: +3f7fa7014d0f22fca3aaf58b60b82343 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7779/instruction.md b/inferredbugs-7779/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f5d338beb3ab78a432c6672f0457b65c78374af --- /dev/null +++ b/inferredbugs-7779/instruction.md @@ -0,0 +1,281 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.hamcrest.Matchers; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class TestObjectIdHandling extends MongoDBTestBase { + + @Test + public void testObjectIdGenerated() { + ObjectIdId object = new ObjectIdId(); + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + org.bson.types.ObjectId id = coll.insert(object).getSavedId(); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdSaved() { + ObjectIdId object = new ObjectIdId(); + org.bson.types.ObjectId id = new org.bson.types.ObjectId(); + object._id = id; + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + coll.insert(object); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ObjectIdId { + public org.bson.types.ObjectId _id; + } + + @Test + public void testObjectIdAnnotationOnStringGenerated() { + StringId object = new StringId(); + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + String id = coll.insert(object).getSavedId(); + // Check that it's a valid object id + assertTrue(org.bson.types.ObjectId.isValid(id)); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnStringSaved() { + StringId object = new StringId(); + String id = new org.bson.types.ObjectId().toString(); + object._id = id; + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + coll.insert(object); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testRemoveByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + String id = coll.insert(new StringId()).getSavedId(); + coll.insert(new StringId()); + assertThat(coll.find().toArray(), hasSize(2)); + coll.removeById(id); + List results = coll.find().toArray(); + assertThat(results, hasSize(1)); + assertThat(results.get(0)._id, not(Matchers.equalTo(id))); + } + + @Test + public void testFindOneByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + StringId object = new StringId(); + net.vz.mongodb.jackson.WriteResult writeResult = coll.insert(object); + assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); + String id = writeResult.getSavedId(); + assertThat(id, instanceOf(String.class)); + StringId result = coll.findOneById(id); + assertThat(result._id, Matchers.equalTo(id)); + } + + public static class StringId { + @ObjectId + public String _id; + } + + @Test + public void testObjectIdAnnotationOnByteArrayGenerated() { + ByteArrayId object = new ByteArrayId(); + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + byte[] id = coll.insert(object).getSavedId(); + // Check that it's a valid object id, should be 12 bytes + assertEquals(12, id.length); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnByteArraySaved() { + ByteArrayId object = new ByteArrayId(); + byte[] id = new org.bson.types.ObjectId().toByteArray(); + object._id = id; + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + coll.insert(object); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ByteArrayId { + @ObjectId + public byte[] _id; + } + + @Test + public void testCollectionOfObjectIds() { + ObjectIdCollection object = new ObjectIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get(), org.bson.types.ObjectId.get()); + + JacksonDBCollection coll = getCollection(ObjectIdCollection.class, String.class); + coll.insert(object); + + ObjectIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class ObjectIdCollection { + public String _id; + public List list; + } + + @Test + public void testCollectionOfObjectIdStrings() { + StringIdCollection object = new StringIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toString(), org.bson.types.ObjectId.get().toString()); + + JacksonDBCollection coll = getCollection(StringIdCollection.class, String.class); + coll.insert(object); + + StringIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class StringIdCollection { + public String _id; + @ObjectId + public List list; + } + + @Test + public void testCollectionOfObjectIdByteArrays() { + ByteArrayIdCollection object = new ByteArrayIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toByteArray(), org.bson.types.ObjectId.get().toByteArray()); + + JacksonDBCollection coll = getCollection(ByteArrayIdCollection.class, String.class); + coll.insert(object); + + ByteArrayIdCollection result = coll.findOneById("id"); + assertThat(result.list, hasSize(2)); + assertThat(result.list.get(0), equalTo(object.list.get(0))); + assertThat(result.list.get(1), equalTo(object.list.get(1))); + } + + public static class ByteArrayIdCollection { + public String _id; + @ObjectId + public List list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 73 could be null and is dereferenced at line 74. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestObjectIdHandling.testObjectIdAnnotationOnStringGenerated() + +### Procedure Id: +net.vz.mongodb.jackson.TestObjectIdHandling.testObjectIdAnnotationOnStringGenerated():void.c7664f6c0407da894fdae33d06d1a744 + +### File: +src/test/java/net/vz/mongodb/jackson/TestObjectIdHandling.java + +### Key: +TestObjectIdHandling.java|testObjectIdAnnotationOnStringGenerated|NULL_DEREFERENCE + +### Node Key: +2acc12e05b0902ef2ca0b1741f78fa6e + +### Hash: +8435e842189410f0050957a844d7f42d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7782/instruction.md b/inferredbugs-7782/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3ad07db0c82805b80f24db803f93309f34770e2 --- /dev/null +++ b/inferredbugs-7782/instruction.md @@ -0,0 +1,320 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.junit.Ignore; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +public class TestDBRefHandling extends MongoDBTestBase { + + @Test + public void simpleDbRefShouldBeSavedAsDbRef() { + JacksonDBCollection coll = getCollection(Owner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class); + + refColl.insert(new Referenced("hello", 10)); + String id = coll.insert(new Owner(new DBRef("hello", refColl.getName()))).getSavedId(); + + Owner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo("hello")); + assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); + + // Try loading it + Referenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + } + + @Test + public void dbRefWithObjectIdShouldBeSavedAsDbRef() { + JacksonDBCollection coll = getCollection(ObjectIdOwner.class, String.class); + JacksonDBCollection refColl = getCollection(ObjectIdReferenced.class, byte[].class); + + byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); + String id = coll.insert(new ObjectIdOwner(new DBRef(refId, refColl.getName()))).getSavedId(); + + ObjectIdOwner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo(refId)); + assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); + + // Try loading it + ObjectIdReferenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId)); + assertThat(ref.i, equalTo(10)); + } + + @Test + public void testUsingMongoCollectionAnnotation() { + JacksonDBCollection coll = getCollection(Owner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + String id = coll.insert(new Owner(new DBRef("hello", Referenced.class))).getSavedId(); + + Owner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo("hello")); + assertThat(saved.ref.getCollectionName(), equalTo("referenced")); + + // Try loading it + Referenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + } + + public static class Owner { + public Owner(DBRef ref) { + this.ref = ref; + } + + public Owner() { + } + + @ObjectId + public String _id; + public DBRef ref; + } + + @MongoCollection(name = "referenced") + public static class Referenced { + public Referenced(String _id, int i) { + this._id = _id; + this.i = i; + } + + public Referenced() { + } + + public String _id; + public int i; + } + + public static class ObjectIdOwner { + public ObjectIdOwner(DBRef ref) { + this.ref = ref; + } + + public ObjectIdOwner() { + } + + @ObjectId + public String _id; + @ObjectId + public DBRef ref; + } + + public static class ObjectIdReferenced { + public ObjectIdReferenced(int i) { + this.i = i; + } + + public ObjectIdReferenced() { + } + + @ObjectId + public byte[] _id; + public int i; + } + + @Test + public void collectionOfDbRefsShouldBeSavedAsDbRefs() { + JacksonDBCollection coll = getCollection(CollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + refColl.insert(new Referenced("world", 20)); + + CollectionOwner owner = new CollectionOwner(); + owner.list = Arrays.asList(new DBRef("hello", refColl.getName()), new DBRef("world", refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + CollectionOwner saved = coll.findOneById("foo"); + assertThat(saved.list, notNullValue()); + assertThat(saved.list, hasSize(2)); + assertThat(saved.list.get(0).getId(), equalTo("hello")); + assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); + assertThat(saved.list.get(1).getId(), equalTo("world")); + assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); + + // Try loading them + Referenced ref = saved.list.get(0).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + + ref = saved.list.get(1).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("world")); + assertThat(ref.i, equalTo(20)); + } + + @Test + public void fetchCollectionOfDBRefsShouldReturnRightResults() { + JacksonDBCollection coll = getCollection(CollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + refColl.insert(new Referenced("world", 20)); + + CollectionOwner owner = new CollectionOwner(); + owner.list = Arrays.asList(new DBRef("hello", refColl.getName()), new DBRef("world", refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + CollectionOwner saved = coll.findOneById("foo"); + List fetched = coll.fetch(saved.list); + assertThat(fetched, hasSize(2)); + assertThat(fetched.get(0)._id, equalTo("hello")); + assertThat(fetched.get(0).i, equalTo(10)); + assertThat(fetched.get(1)._id, equalTo("world")); + assertThat(fetched.get(1).i, equalTo(20)); + } + + public static class CollectionOwner { + public String _id; + public List> list; + } + + @Test + public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { + JacksonDBCollection coll = getCollection(ObjectIdCollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); + + byte[] refId1 = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); + byte[] refId2 = refColl.insert(new ObjectIdReferenced(20)).getSavedId(); + + ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); + owner.list = Arrays.asList(new DBRef(refId1, refColl.getName()), new DBRef(refId2, refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + ObjectIdCollectionOwner saved = coll.findOneById("foo"); + assertThat(saved.list, notNullValue()); + assertThat(saved.list, hasSize(2)); + assertThat(saved.list.get(0).getId(), equalTo(refId1)); + assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); + assertThat(saved.list.get(1).getId(), equalTo(refId2)); + assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); + + + // Try loading them + ObjectIdReferenced ref = saved.list.get(0).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId1)); + assertThat(ref.i, equalTo(10)); + + ref = saved.list.get(1).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId2)); + assertThat(ref.i, equalTo(20)); + } + + public static class ObjectIdCollectionOwner { + public String _id; + @ObjectId + public List> list; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `ref` last assigned on line 86 could be null and is dereferenced at line 88. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestDBRefHandling.testUsingMongoCollectionAnnotation() + +### Procedure Id: +net.vz.mongodb.jackson.TestDBRefHandling.testUsingMongoCollectionAnnotation():void.e095220ffb1eb9766119b119aed8f322 + +### File: +src/test/java/net/vz/mongodb/jackson/TestDBRefHandling.java + +### Key: +TestDBRefHandling.java|testUsingMongoCollectionAnnotation|NULL_DEREFERENCE + +### Node Key: +c3e9b7adf0862874433e40544c2a4023 + +### Hash: +dbcafd7fde179004c6b6f7ac4ad26893 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7783/instruction.md b/inferredbugs-7783/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17cbe550e3fc525aa55c9ccfdd8f248bdad72b4c --- /dev/null +++ b/inferredbugs-7783/instruction.md @@ -0,0 +1,281 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.hamcrest.Matchers; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.not; +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +public class TestObjectIdHandling extends MongoDBTestBase { + + @Test + public void testObjectIdGenerated() { + ObjectIdId object = new ObjectIdId(); + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + org.bson.types.ObjectId id = coll.insert(object).getSavedId(); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdSaved() { + ObjectIdId object = new ObjectIdId(); + org.bson.types.ObjectId id = new org.bson.types.ObjectId(); + object._id = id; + + JacksonDBCollection coll = getCollection(ObjectIdId.class, + org.bson.types.ObjectId.class); + + coll.insert(object); + ObjectIdId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ObjectIdId { + public org.bson.types.ObjectId _id; + } + + @Test + public void testObjectIdAnnotationOnStringGenerated() { + StringId object = new StringId(); + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + String id = coll.insert(object).getSavedId(); + // Check that it's a valid object id + assertTrue(org.bson.types.ObjectId.isValid(id)); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnStringSaved() { + StringId object = new StringId(); + String id = new org.bson.types.ObjectId().toString(); + object._id = id; + + JacksonDBCollection coll = getCollection(StringId.class, String.class); + + coll.insert(object); + StringId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testRemoveByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + String id = coll.insert(new StringId()).getSavedId(); + coll.insert(new StringId()); + assertThat(coll.find().toArray(), hasSize(2)); + coll.removeById(id); + List results = coll.find().toArray(); + assertThat(results, hasSize(1)); + assertThat(results.get(0)._id, not(Matchers.equalTo(id))); + } + + @Test + public void testFindOneByIdWithObjectId() { + JacksonDBCollection coll = getCollection(StringId.class, String.class); + StringId object = new StringId(); + net.vz.mongodb.jackson.WriteResult writeResult = coll.insert(object); + assertThat(writeResult.getDbObject().get("_id"), instanceOf(org.bson.types.ObjectId.class)); + String id = writeResult.getSavedId(); + assertThat(id, instanceOf(String.class)); + StringId result = coll.findOneById(id); + assertThat(result._id, Matchers.equalTo(id)); + } + + public static class StringId { + @ObjectId + public String _id; + } + + @Test + public void testObjectIdAnnotationOnByteArrayGenerated() { + ByteArrayId object = new ByteArrayId(); + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + byte[] id = coll.insert(object).getSavedId(); + // Check that it's a valid object id, should be 12 bytes + assertEquals(12, id.length); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + @Test + public void testObjectIdAnnotationOnByteArraySaved() { + ByteArrayId object = new ByteArrayId(); + byte[] id = new org.bson.types.ObjectId().toByteArray(); + object._id = id; + + JacksonDBCollection coll = getCollection(ByteArrayId.class, byte[].class); + + coll.insert(object); + ByteArrayId result = coll.findOneById(id); + assertThat(result._id, equalTo(id)); + } + + public static class ByteArrayId { + @ObjectId + public byte[] _id; + } + + @Test + public void testCollectionOfObjectIds() { + ObjectIdCollection object = new ObjectIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get(), org.bson.types.ObjectId.get()); + + JacksonDBCollection coll = getCollection(ObjectIdCollection.class, String.class); + coll.insert(object); + + ObjectIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class ObjectIdCollection { + public String _id; + public List list; + } + + @Test + public void testCollectionOfObjectIdStrings() { + StringIdCollection object = new StringIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toString(), org.bson.types.ObjectId.get().toString()); + + JacksonDBCollection coll = getCollection(StringIdCollection.class, String.class); + coll.insert(object); + + StringIdCollection result = coll.findOneById("id"); + assertThat(result.list, equalTo(object.list)); + } + + public static class StringIdCollection { + public String _id; + @ObjectId + public List list; + } + + @Test + public void testCollectionOfObjectIdByteArrays() { + ByteArrayIdCollection object = new ByteArrayIdCollection(); + object._id = "id"; + object.list = Arrays.asList(org.bson.types.ObjectId.get().toByteArray(), org.bson.types.ObjectId.get().toByteArray()); + + JacksonDBCollection coll = getCollection(ByteArrayIdCollection.class, String.class); + coll.insert(object); + + ByteArrayIdCollection result = coll.findOneById("id"); + assertThat(result.list, hasSize(2)); + assertThat(result.list.get(0), equalTo(object.list.get(0))); + assertThat(result.list.get(1), equalTo(object.list.get(1))); + } + + public static class ByteArrayIdCollection { + public String _id; + @ObjectId + public List list; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `result` last assigned on line 42 could be null and is dereferenced at line 43. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestObjectIdHandling.testObjectIdGenerated() + +### Procedure Id: +net.vz.mongodb.jackson.TestObjectIdHandling.testObjectIdGenerated():void.abb55851fe01491e794651c259977707 + +### File: +src/test/java/net/vz/mongodb/jackson/TestObjectIdHandling.java + +### Key: +TestObjectIdHandling.java|testObjectIdGenerated|NULL_DEREFERENCE + +### Node Key: +2acc12e05b0902ef2ca0b1741f78fa6e + +### Hash: +94ba7d4922162dcc652425b2c6aaf172 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7784/instruction.md b/inferredbugs-7784/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ebf0ace565ff7605f64e4d7f0f9d9ba2ede0437 --- /dev/null +++ b/inferredbugs-7784/instruction.md @@ -0,0 +1,320 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** mongojack +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2011 VZ Netzwerke Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.vz.mongodb.jackson; + +import org.junit.Ignore; +import org.junit.Test; + +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import static org.hamcrest.collection.IsCollectionWithSize.hasSize; +import static org.hamcrest.core.IsEqual.equalTo; +import static org.hamcrest.core.IsNull.notNullValue; +import static org.junit.Assert.assertThat; + +public class TestDBRefHandling extends MongoDBTestBase { + + @Test + public void simpleDbRefShouldBeSavedAsDbRef() { + JacksonDBCollection coll = getCollection(Owner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class); + + refColl.insert(new Referenced("hello", 10)); + String id = coll.insert(new Owner(new DBRef("hello", refColl.getName()))).getSavedId(); + + Owner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo("hello")); + assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); + + // Try loading it + Referenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + } + + @Test + public void dbRefWithObjectIdShouldBeSavedAsDbRef() { + JacksonDBCollection coll = getCollection(ObjectIdOwner.class, String.class); + JacksonDBCollection refColl = getCollection(ObjectIdReferenced.class, byte[].class); + + byte[] refId = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); + String id = coll.insert(new ObjectIdOwner(new DBRef(refId, refColl.getName()))).getSavedId(); + + ObjectIdOwner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo(refId)); + assertThat(saved.ref.getCollectionName(), equalTo(refColl.getName())); + + // Try loading it + ObjectIdReferenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId)); + assertThat(ref.i, equalTo(10)); + } + + @Test + public void testUsingMongoCollectionAnnotation() { + JacksonDBCollection coll = getCollection(Owner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + String id = coll.insert(new Owner(new DBRef("hello", Referenced.class))).getSavedId(); + + Owner saved = coll.findOneById(id); + assertThat(saved.ref, notNullValue()); + assertThat(saved.ref.getId(), equalTo("hello")); + assertThat(saved.ref.getCollectionName(), equalTo("referenced")); + + // Try loading it + Referenced ref = saved.ref.fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + } + + public static class Owner { + public Owner(DBRef ref) { + this.ref = ref; + } + + public Owner() { + } + + @ObjectId + public String _id; + public DBRef ref; + } + + @MongoCollection(name = "referenced") + public static class Referenced { + public Referenced(String _id, int i) { + this._id = _id; + this.i = i; + } + + public Referenced() { + } + + public String _id; + public int i; + } + + public static class ObjectIdOwner { + public ObjectIdOwner(DBRef ref) { + this.ref = ref; + } + + public ObjectIdOwner() { + } + + @ObjectId + public String _id; + @ObjectId + public DBRef ref; + } + + public static class ObjectIdReferenced { + public ObjectIdReferenced(int i) { + this.i = i; + } + + public ObjectIdReferenced() { + } + + @ObjectId + public byte[] _id; + public int i; + } + + @Test + public void collectionOfDbRefsShouldBeSavedAsDbRefs() { + JacksonDBCollection coll = getCollection(CollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + refColl.insert(new Referenced("world", 20)); + + CollectionOwner owner = new CollectionOwner(); + owner.list = Arrays.asList(new DBRef("hello", refColl.getName()), new DBRef("world", refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + CollectionOwner saved = coll.findOneById("foo"); + assertThat(saved.list, notNullValue()); + assertThat(saved.list, hasSize(2)); + assertThat(saved.list.get(0).getId(), equalTo("hello")); + assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); + assertThat(saved.list.get(1).getId(), equalTo("world")); + assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); + + // Try loading them + Referenced ref = saved.list.get(0).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("hello")); + assertThat(ref.i, equalTo(10)); + + ref = saved.list.get(1).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo("world")); + assertThat(ref.i, equalTo(20)); + } + + @Test + public void fetchCollectionOfDBRefsShouldReturnRightResults() { + JacksonDBCollection coll = getCollection(CollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(Referenced.class, String.class, "referenced"); + + refColl.insert(new Referenced("hello", 10)); + refColl.insert(new Referenced("world", 20)); + + CollectionOwner owner = new CollectionOwner(); + owner.list = Arrays.asList(new DBRef("hello", refColl.getName()), new DBRef("world", refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + CollectionOwner saved = coll.findOneById("foo"); + List fetched = coll.fetch(saved.list); + assertThat(fetched, hasSize(2)); + assertThat(fetched.get(0)._id, equalTo("hello")); + assertThat(fetched.get(0).i, equalTo(10)); + assertThat(fetched.get(1)._id, equalTo("world")); + assertThat(fetched.get(1).i, equalTo(20)); + } + + public static class CollectionOwner { + public String _id; + public List> list; + } + + @Test + public void collectionOfObjectIdDbRefsShouldBeSavedAsObjectIdDbRefs() { + JacksonDBCollection coll = getCollection(ObjectIdCollectionOwner.class, String.class); + JacksonDBCollection refColl = getCollection(ObjectIdReferenced.class, byte[].class, "referenced"); + + byte[] refId1 = refColl.insert(new ObjectIdReferenced(10)).getSavedId(); + byte[] refId2 = refColl.insert(new ObjectIdReferenced(20)).getSavedId(); + + ObjectIdCollectionOwner owner = new ObjectIdCollectionOwner(); + owner.list = Arrays.asList(new DBRef(refId1, refColl.getName()), new DBRef(refId2, refColl.getName())); + owner._id = "foo"; + coll.insert(owner); + + ObjectIdCollectionOwner saved = coll.findOneById("foo"); + assertThat(saved.list, notNullValue()); + assertThat(saved.list, hasSize(2)); + assertThat(saved.list.get(0).getId(), equalTo(refId1)); + assertThat(saved.list.get(0).getCollectionName(), equalTo(refColl.getName())); + assertThat(saved.list.get(1).getId(), equalTo(refId2)); + assertThat(saved.list.get(1).getCollectionName(), equalTo(refColl.getName())); + + + // Try loading them + ObjectIdReferenced ref = saved.list.get(0).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId1)); + assertThat(ref.i, equalTo(10)); + + ref = saved.list.get(1).fetch(); + assertThat(ref, notNullValue()); + assertThat(ref._id, equalTo(refId2)); + assertThat(ref.i, equalTo(20)); + } + + public static class ObjectIdCollectionOwner { + public String _id; + @ObjectId + public List> list; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `saved` last assigned on line 80 could be null and is dereferenced at line 81. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestDBRefHandling.testUsingMongoCollectionAnnotation() + +### Procedure Id: +net.vz.mongodb.jackson.TestDBRefHandling.testUsingMongoCollectionAnnotation():void.e095220ffb1eb9766119b119aed8f322 + +### File: +src/test/java/net/vz/mongodb/jackson/TestDBRefHandling.java + +### Key: +TestDBRefHandling.java|testUsingMongoCollectionAnnotation|NULL_DEREFERENCE + +### Node Key: +d887119113509058883b021107809049 + +### Hash: +2809f5d5476d1a14136e92147904d9bb + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7851/instruction.md b/inferredbugs-7851/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..567e581ce70b1a474214bc1f5c5d2498508999e1 --- /dev/null +++ b/inferredbugs-7851/instruction.md @@ -0,0 +1,793 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.layout; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.logging.log4j.Level; +import org.apache.logging.log4j.LoggingException; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.TLSSyslogFrame; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.helpers.Booleans; +import org.apache.logging.log4j.core.helpers.Charsets; +import org.apache.logging.log4j.core.helpers.Integers; +import org.apache.logging.log4j.core.helpers.NetUtils; +import org.apache.logging.log4j.core.helpers.Strings; +import org.apache.logging.log4j.core.net.Facility; +import org.apache.logging.log4j.core.net.Priority; +import org.apache.logging.log4j.core.pattern.LogEventPatternConverter; +import org.apache.logging.log4j.core.pattern.PatternConverter; +import org.apache.logging.log4j.core.pattern.PatternFormatter; +import org.apache.logging.log4j.core.pattern.PatternParser; +import org.apache.logging.log4j.core.pattern.ThrowablePatternConverter; +import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.message.StructuredDataId; +import org.apache.logging.log4j.message.StructuredDataMessage; + + +/** + * Formats a log event in accordance with RFC 5424. + * + * @see RFC 5424 + */ +@Plugin(name = "RFC5424Layout", category = "Core", elementType = "layout", printObject = true) +public class RFC5424Layout extends AbstractStringLayout { + + private static final String LF = "\n"; + + /** + * Not a very good default - it is the Apache Software Foundation's enterprise number. + */ + public static final int DEFAULT_ENTERPRISE_NUMBER = 18060; + /** + * The default event id. + */ + public static final String DEFAULT_ID = "Audit"; + /** + * Match newlines in a platform-independent manner. + */ + public static final Pattern NEWLINE_PATTERN = Pattern.compile("\\r?\\n"); + /** + * Match characters which require escaping + */ + public static final Pattern PARAM_VALUE_ESCAPE_PATTERN = Pattern.compile("[\\\"\\]\\\\]"); + + protected static final String DEFAULT_MDCID = "mdc"; + private static final int TWO_DIGITS = 10; + private static final int THREE_DIGITS = 100; + private static final int MILLIS_PER_MINUTE = 60000; + private static final int MINUTES_PER_HOUR = 60; + + private static final String COMPONENT_KEY = "RFC5424-Converter"; + + private final Facility facility; + private final String defaultId; + private final int enterpriseNumber; + private final boolean includeMDC; + private final String mdcId; + private final StructuredDataId mdcSDID; + private final String localHostName; + private final String appName; + private final String messageId; + private final String configName; + private final String mdcPrefix; + private final String eventPrefix; + private final List mdcExcludes; + private final List mdcIncludes; + private final List mdcRequired; + private final ListChecker checker; + private final ListChecker noopChecker = new NoopChecker(); + private final boolean includeNewLine; + private final String escapeNewLine; + private final boolean useTLSMessageFormat; + + private long lastTimestamp = -1; + private String timestamppStr; + + private final List exceptionFormatters; + private final Map fieldFormatters; + + private RFC5424Layout(final Configuration config, final Facility facility, final String id, final int ein, + final boolean includeMDC, final boolean includeNL, final String escapeNL, final String mdcId, + final String mdcPrefix, final String eventPrefix, + final String appName, final String messageId, final String excludes, final String includes, + final String required, final Charset charset, final String exceptionPattern, + final boolean useTLSMessageFormat, final LoggerFields[] loggerFields) { + super(charset); + final PatternParser exceptionParser = createPatternParser(config, ThrowablePatternConverter.class); + exceptionFormatters = exceptionPattern == null ? null : exceptionParser.parse(exceptionPattern, false); + this.facility = facility; + this.defaultId = id == null ? DEFAULT_ID : id; + this.enterpriseNumber = ein; + this.includeMDC = includeMDC; + this.includeNewLine = includeNL; + this.escapeNewLine = escapeNL == null ? null : Matcher.quoteReplacement(escapeNL); + this.mdcId = mdcId; + this.mdcSDID = new StructuredDataId(mdcId, enterpriseNumber, null, null); + this.mdcPrefix = mdcPrefix; + this.eventPrefix = eventPrefix; + this.appName = appName; + this.messageId = messageId; + this.useTLSMessageFormat = useTLSMessageFormat; + this.localHostName = NetUtils.getLocalHostname(); + ListChecker c = null; + if (excludes != null) { + final String[] array = excludes.split(","); + if (array.length > 0) { + c = new ExcludeChecker(); + mdcExcludes = new ArrayList(array.length); + for (final String str : array) { + mdcExcludes.add(str.trim()); + } + } else { + mdcExcludes = null; + } + } else { + mdcExcludes = null; + } + if (includes != null) { + final String[] array = includes.split(","); + if (array.length > 0) { + c = new IncludeChecker(); + mdcIncludes = new ArrayList(array.length); + for (final String str : array) { + mdcIncludes.add(str.trim()); + } + } else { + mdcIncludes = null; + } + } else { + mdcIncludes = null; + } + if (required != null) { + final String[] array = required.split(","); + if (array.length > 0) { + mdcRequired = new ArrayList(array.length); + for (final String str : array) { + mdcRequired.add(str.trim()); + } + } else { + mdcRequired = null; + } + + } else { + mdcRequired = null; + } + this.checker = c != null ? c : noopChecker; + final String name = config == null ? null : config.getName(); + configName = name != null && name.length() > 0 ? name : null; + this.fieldFormatters = createFieldFormatters(loggerFields, config); + } + + private Map createFieldFormatters(final LoggerFields[] loggerFields, + final Configuration config) { + final Map sdIdMap = new HashMap(); + + if (loggerFields != null) { + for (final LoggerFields lField : loggerFields) { + final StructuredDataId key = lField.getSdId() == null ? mdcSDID : lField.getSdId(); + final Map> sdParams = new HashMap>(); + final Map fields = lField.getMap(); + if (!fields.isEmpty()) { + final PatternParser fieldParser = createPatternParser(config, null); + + for (final Map.Entry entry : fields.entrySet()) { + final List formatters = fieldParser.parse(entry.getValue(), false); + sdParams.put(entry.getKey(), formatters); + } + final FieldFormatter fieldFormatter = new FieldFormatter(sdParams, + lField.getDiscardIfAllFieldsAreEmpty()); + sdIdMap.put(key.toString(), fieldFormatter); + } + } + } + return sdIdMap.size() > 0 ? sdIdMap : null; + } + + /** + * Create a PatternParser. + * + * @param config The Configuration. + * @param filterClass Filter the returned plugins after calling the plugin manager. + * @return The PatternParser. + */ + private static PatternParser createPatternParser(final Configuration config, + final Class filterClass) { + if (config == null) { + return new PatternParser(config, PatternLayout.KEY, LogEventPatternConverter.class, filterClass); + } + PatternParser parser = config.getComponent(COMPONENT_KEY); + if (parser == null) { + parser = new PatternParser(config, PatternLayout.KEY, ThrowablePatternConverter.class); + config.addComponent(COMPONENT_KEY, parser); + parser = (PatternParser) config.getComponent(COMPONENT_KEY); + } + return parser; + } + + /** + * RFC5424Layout's content format is specified by:

    + * Key: "structured" Value: "true"

    + * Key: "format" Value: "RFC5424"

    + * + * @return Map of content format keys supporting RFC5424Layout + */ + @Override + public Map getContentFormat() { + final Map result = new HashMap(); + result.put("structured", "true"); + result.put("formatType", "RFC5424"); + return result; + } + + /** + * Formats a {@link org.apache.logging.log4j.core.LogEvent} in conformance with the RFC 5424 Syslog specification. + * + * @param event The LogEvent. + * @return The RFC 5424 String representation of the LogEvent. + */ + @Override + public String toSerializable(final LogEvent event) { + final StringBuilder buf = new StringBuilder(); + appendPriority(buf, event.getLevel()); + appendTimestamp(buf, event.getMillis()); + appendSpace(buf); + appendHostName(buf); + appendSpace(buf); + appendAppName(buf); + appendSpace(buf); + appendProcessId(buf); + appendSpace(buf); + appendMessageId(buf, event.getMessage()); + appendSpace(buf); + appendStructuredElements(buf, event); + appendMessage(buf, event); + if (useTLSMessageFormat) { + return new TLSSyslogFrame(buf.toString()).toString(); + } + return buf.toString(); + } + + private void appendPriority(final StringBuilder buffer, final Level logLevel) { + buffer.append("<"); + buffer.append(Priority.getPriority(facility, logLevel)); + buffer.append(">1 "); + } + + private void appendTimestamp(final StringBuilder buffer, final long milliseconds) { + buffer.append(computeTimeStampString(milliseconds)); + } + + private void appendSpace(final StringBuilder buffer) { + buffer.append(" "); + } + + private void appendHostName(final StringBuilder buffer) { + buffer.append(localHostName); + } + + private void appendAppName(final StringBuilder buffer) { + if (appName != null) { + buffer.append(appName); + } else if (configName != null) { + buffer.append(configName); + } else { + buffer.append("-"); + } + } + + private void appendProcessId(final StringBuilder buffer) { + buffer.append(getProcId()); + } + + private void appendMessageId(final StringBuilder buffer, final Message message) { + final boolean isStructured = message instanceof StructuredDataMessage; + final String type = isStructured ? ((StructuredDataMessage) message).getType() : null; + if (type != null) { + buffer.append(type); + } else if (messageId != null) { + buffer.append(messageId); + } else { + buffer.append("-"); + } + } + + private void appendMessage(final StringBuilder buffer, final LogEvent event) { + final Message message = event.getMessage(); + final String text = message.getFormat(); + + if (text != null && text.length() > 0) { + buffer.append(" ").append(escapeNewlines(text, escapeNewLine)); + } + + if (exceptionFormatters != null && event.getThrown() != null) { + final StringBuilder exception = new StringBuilder(LF); + for (final PatternFormatter formatter : exceptionFormatters) { + formatter.format(event, exception); + } + buffer.append(escapeNewlines(exception.toString(), escapeNewLine)); + } + if (includeNewLine) { + buffer.append(LF); + } + } + + private void appendStructuredElements(final StringBuilder buffer, final LogEvent event) { + final Message message = event.getMessage(); + final boolean isStructured = message instanceof StructuredDataMessage; + + if (!isStructured && (fieldFormatters!= null && fieldFormatters.size() == 0) && !includeMDC) { + buffer.append("-"); + return; + } + + final Map sdElements = new HashMap(); + final Map contextMap = event.getContextMap(); + + if (mdcRequired != null) { + checkRequired(contextMap); + } + + if (fieldFormatters != null) { + for (final Map.Entry sdElement: fieldFormatters.entrySet()) { + final String sdId = sdElement.getKey(); + final StructuredDataElement elem = sdElement.getValue().format(event); + sdElements.put(sdId, elem); + } + } + + if (includeMDC && contextMap.size() > 0) { + if (sdElements.containsKey(mdcSDID.toString())) { + final StructuredDataElement union = sdElements.get(mdcSDID.toString()); + union.union(contextMap); + sdElements.put(mdcSDID.toString(), union); + } else { + final StructuredDataElement formattedContextMap = new StructuredDataElement(contextMap, false); + sdElements.put(mdcSDID.toString(), formattedContextMap); + } + } + + if (isStructured) { + final StructuredDataMessage data = (StructuredDataMessage) message; + final Map map = data.getData(); + final StructuredDataId id = data.getId(); + + if (sdElements.containsKey(id.toString())) { + final StructuredDataElement union = sdElements.get(id.toString()); + union.union(map); + sdElements.put(id.toString(), union); + } else { + final StructuredDataElement formattedData = new StructuredDataElement(map, false); + sdElements.put(id.toString(), formattedData); + } + } + + if (sdElements.size() == 0) { + buffer.append("-"); + return; + } + + for (final Map.Entry entry: sdElements.entrySet()) { + formatStructuredElement(entry.getKey(), mdcPrefix, entry.getValue(), buffer, checker); + } + } + + private String escapeNewlines(final String text, final String escapeNewLine) { + if (null == escapeNewLine) { + return text; + } + return NEWLINE_PATTERN.matcher(text).replaceAll(escapeNewLine); + } + + protected String getProcId() { + return "-"; + } + + protected List getMdcExcludes() { + return mdcExcludes; + } + + protected List getMdcIncludes() { + return mdcIncludes; + } + + private String computeTimeStampString(final long now) { + long last; + synchronized (this) { + last = lastTimestamp; + if (now == lastTimestamp) { + return timestamppStr; + } + } + + final StringBuilder buffer = new StringBuilder(); + final Calendar cal = new GregorianCalendar(); + cal.setTimeInMillis(now); + buffer.append(Integer.toString(cal.get(Calendar.YEAR))); + buffer.append("-"); + pad(cal.get(Calendar.MONTH) + 1, TWO_DIGITS, buffer); + buffer.append("-"); + pad(cal.get(Calendar.DAY_OF_MONTH), TWO_DIGITS, buffer); + buffer.append("T"); + pad(cal.get(Calendar.HOUR_OF_DAY), TWO_DIGITS, buffer); + buffer.append(":"); + pad(cal.get(Calendar.MINUTE), TWO_DIGITS, buffer); + buffer.append(":"); + pad(cal.get(Calendar.SECOND), TWO_DIGITS, buffer); + + final int millis = cal.get(Calendar.MILLISECOND); + if (millis != 0) { + buffer.append('.'); + pad(millis, THREE_DIGITS, buffer); + } + + int tzmin = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / MILLIS_PER_MINUTE; + if (tzmin == 0) { + buffer.append("Z"); + } else { + if (tzmin < 0) { + tzmin = -tzmin; + buffer.append("-"); + } else { + buffer.append("+"); + } + final int tzhour = tzmin / MINUTES_PER_HOUR; + tzmin -= tzhour * MINUTES_PER_HOUR; + pad(tzhour, TWO_DIGITS, buffer); + buffer.append(":"); + pad(tzmin, TWO_DIGITS, buffer); + } + synchronized (this) { + if (last == lastTimestamp) { + lastTimestamp = now; + timestamppStr = buffer.toString(); + } + } + return buffer.toString(); + } + + private void pad(final int val, int max, final StringBuilder buf) { + while (max > 1) { + if (val < max) { + buf.append("0"); + } + max = max / TWO_DIGITS; + } + buf.append(Integer.toString(val)); + } + + private void formatStructuredElement(final String id, final String prefix, final StructuredDataElement data, + final StringBuilder sb, final ListChecker checker) { + if ((id == null && defaultId == null) || data.discard()) { + return; + } + + sb.append("["); + sb.append(id); + if (!mdcSDID.toString().equals(id)) { + appendMap(prefix, data.getFields(), sb, noopChecker); + } else { + appendMap(prefix, data.getFields(), sb, checker); + } + sb.append("]"); + } + + private String getId(final StructuredDataId id) { + final StringBuilder sb = new StringBuilder(); + if (id == null || id.getName() == null) { + sb.append(defaultId); + } else { + sb.append(id.getName()); + } + int ein = id != null ? id.getEnterpriseNumber() : enterpriseNumber; + if (ein < 0) { + ein = enterpriseNumber; + } + if (ein >= 0) { + sb.append("@").append(ein); + } + return sb.toString(); + } + + private void checkRequired(final Map map) { + for (final String key : mdcRequired) { + final String value = map.get(key); + if (value == null) { + throw new LoggingException("Required key " + key + " is missing from the " + mdcId); + } + } + } + + private void appendMap(final String prefix, final Map map, final StringBuilder sb, + final ListChecker checker) { + final SortedMap sorted = new TreeMap(map); + for (final Map.Entry entry : sorted.entrySet()) { + if (checker.check(entry.getKey()) && entry.getValue() != null) { + sb.append(" "); + if (prefix != null) { + sb.append(prefix); + } + sb.append(escapeNewlines(escapeSDParams(entry.getKey()), escapeNewLine)).append("=\"") + .append(escapeNewlines(escapeSDParams(entry.getValue()), escapeNewLine)).append("\""); + } + } + } + + private String escapeSDParams(final String value) { + return PARAM_VALUE_ESCAPE_PATTERN.matcher(value).replaceAll("\\\\$0"); + } + + /** + * Interface used to check keys in a Map. + */ + private interface ListChecker { + boolean check(String key); + } + + /** + * Includes only the listed keys. + */ + private class IncludeChecker implements ListChecker { + @Override + public boolean check(final String key) { + return mdcIncludes.contains(key); + } + } + + /** + * Excludes the listed keys. + */ + private class ExcludeChecker implements ListChecker { + @Override + public boolean check(final String key) { + return !mdcExcludes.contains(key); + } + } + + /** + * Does nothing. + */ + private class NoopChecker implements ListChecker { + @Override + public boolean check(final String key) { + return true; + } + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(); + sb.append("facility=").append(facility.name()); + sb.append(" appName=").append(appName); + sb.append(" defaultId=").append(defaultId); + sb.append(" enterpriseNumber=").append(enterpriseNumber); + sb.append(" newLine=").append(includeNewLine); + sb.append(" includeMDC=").append(includeMDC); + sb.append(" messageId=").append(messageId); + return sb.toString(); + } + + /** + * Create the RFC 5424 Layout. + * + * @param facility The Facility is used to try to classify the message. + * @param id The default structured data id to use when formatting according to RFC 5424. + * @param ein The IANA enterprise number. + * @param includeMDC Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog + * record. Defaults to "true:. + * @param mdcId The id to use for the MDC Structured Data Element. + * @param mdcPrefix The prefix to add to MDC key names. + * @param eventPrefix The prefix to add to event key names. + * @param includeNL If true, a newline will be appended to the end of the syslog record. The default is false. + * @param escapeNL String that should be used to replace newlines within the message text. + * @param appName The value to use as the APP-NAME in the RFC 5424 syslog record. + * @param msgId The default value to be used in the MSGID field of RFC 5424 syslog records. + * @param excludes A comma separated list of MDC keys that should be excluded from the LogEvent. + * @param includes A comma separated list of MDC keys that should be included in the FlumeEvent. + * @param required A comma separated list of MDC keys that must be present in the MDC. + * @param exceptionPattern The pattern for formatting exceptions. + * @param useTLSMessageFormat If true the message will be formatted according to RFC 5425. + * @param loggerFields Container for the KeyValuePairs containing the patterns + * @param config The Configuration. Some Converters require access to the Interpolator. + * @return An RFC5424Layout. + */ + @PluginFactory + public static RFC5424Layout createLayout( + @PluginAttribute("facility") final String facility, + @PluginAttribute("id") final String id, + @PluginAttribute("enterpriseNumber") final String ein, + @PluginAttribute("includeMDC") final String includeMDC, + @PluginAttribute("mdcId") String mdcId, + @PluginAttribute("mdcPrefix") final String mdcPrefix, + @PluginAttribute("eventPrefix") final String eventPrefix, + @PluginAttribute("newLine") final String includeNL, + @PluginAttribute("newLineEscape") final String escapeNL, + @PluginAttribute("appName") final String appName, + @PluginAttribute("messageId") final String msgId, + @PluginAttribute("mdcExcludes") final String excludes, + @PluginAttribute("mdcIncludes") String includes, + @PluginAttribute("mdcRequired") final String required, + @PluginAttribute("exceptionPattern") final String exceptionPattern, + @PluginAttribute("useTLSMessageFormat") final String useTLSMessageFormat, // RFC 5425 + @PluginElement("LoggerFields") final LoggerFields[] loggerFields, + @PluginConfiguration final Configuration config) { + final Charset charset = Charsets.UTF_8; + if (includes != null && excludes != null) { + LOGGER.error("mdcIncludes and mdcExcludes are mutually exclusive. Includes wil be ignored"); + includes = null; + } + final Facility f = Facility.toFacility(facility, Facility.LOCAL0); + final int enterpriseNumber = Integers.parseInt(ein, DEFAULT_ENTERPRISE_NUMBER); + final boolean isMdc = Booleans.parseBoolean(includeMDC, true); + final boolean includeNewLine = Boolean.parseBoolean(includeNL); + final boolean useTlsMessageFormat = Booleans.parseBoolean(useTLSMessageFormat, false); + if (mdcId == null) { + mdcId = DEFAULT_MDCID; + } + + return new RFC5424Layout(config, f, id, enterpriseNumber, isMdc, includeNewLine, escapeNL, mdcId, mdcPrefix, + eventPrefix, appName, msgId, excludes, includes, required, charset, exceptionPattern, + useTlsMessageFormat, loggerFields); + } + + private class FieldFormatter { + + private final Map> delegateMap; + private final boolean discardIfEmpty; + + public FieldFormatter(final Map> fieldMap, final boolean discardIfEmpty) { + this.discardIfEmpty = discardIfEmpty; + this.delegateMap = fieldMap; + } + + public StructuredDataElement format(final LogEvent event) { + final Map map = new HashMap(); + + for (final Map.Entry> entry : delegateMap.entrySet()) { + final StringBuilder buffer = new StringBuilder(); + for (final PatternFormatter formatter : entry.getValue()) { + formatter.format(event, buffer); + } + map.put(entry.getKey(), buffer.toString()); + } + return new StructuredDataElement(map, discardIfEmpty); + } + } + + private class StructuredDataElement { + + private final Map fields; + private final boolean discardIfEmpty; + + public StructuredDataElement(final Map fields, final boolean discardIfEmpty) { + this.discardIfEmpty = discardIfEmpty; + this.fields = fields; + } + + boolean discard() { + if (discardIfEmpty == false) { + return false; + } + boolean foundNotEmptyValue = false; + for (final Map.Entry entry : fields.entrySet()) { + if (Strings.isNotEmpty(entry.getValue())) { + foundNotEmptyValue = true; + break; + } + } + return !foundNotEmptyValue; + } + + void union(final Map fields) { + this.fields.putAll(fields); + } + + Map getFields() { + return this.fields; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `union` last assigned on line 386 could be null and is dereferenced at line 387. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RFC5424Layout.appendStructuredElements(StringBuilder,LogEvent) + +### Procedure Id: +org.apache.logging.log4j.core.layout.RFC5424Layout.appendStructuredElements(java.lang.StringBuilder,.2997c14ae76f21cda76dfd1156f13dc7 + +### File: +log4j-core/src/main/java/org/apache/logging/log4j/core/layout/RFC5424Layout.java + +### Key: +RFC5424Layout.java|appendStructuredElements|NULL_DEREFERENCE + +### Node Key: +09634589313b8637b1fe1e1bb0135b05 + +### Hash: +a422c6a77ceda54d123a2451e249fa79 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7856/instruction.md b/inferredbugs-7856/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf52d92e8866b4834dd6028e47da1469319040bc --- /dev/null +++ b/inferredbugs-7856/instruction.md @@ -0,0 +1,468 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.flume.appender; + +import org.apache.avro.AvroRemoteException; +import org.apache.avro.ipc.NettyTransceiver; +import org.apache.avro.ipc.Transceiver; +import org.apache.avro.ipc.specific.SpecificRequestor; +import org.apache.flume.event.SimpleEvent; +import org.apache.flume.source.avro.AvroFlumeEvent; +import org.apache.flume.source.avro.AvroSourceProtocol; +import org.apache.flume.source.avro.Status; +import org.apache.logging.log4j.core.appender.AppenderRuntimeException; +import org.apache.logging.log4j.core.appender.ManagerFactory; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Manager for FlumeAvroAppenders. + */ +public class FlumeAvroManager extends AbstractFlumeManager { + + /** + The default reconnection delay (500 milliseconds or .5 seconds). + */ + public static final int DEFAULT_RECONNECTION_DELAY = 500; + + private static final int DEFAULT_RECONNECTS = 3; + + private static ManagerFactory factory = new AvroManagerFactory(); + + private AvroSourceProtocol client; + + private final Agent[] agents; + + private final int batchSize; + + private final EventList events = new EventList(); + + private int current = 0; + + private Transceiver transceiver; + + /** + * Constructor + * @param name The unique name of this manager. + * @param agents An array of Agents. + * @param batchSize The number of events to include in a batch. + */ + protected FlumeAvroManager(final String name, final String shortName, final Agent[] agents, final int batchSize) { + super(name); + this.agents = agents; + this.batchSize = batchSize; + this.client = connect(agents); + } + + /** + * Returns a FlumeAvroManager. + * @param name The name of the manager. + * @param agents The agents to use. + * @param batchSize The number of events to include in a batch. + * @return A FlumeAvroManager. + */ + public static FlumeAvroManager getManager(final String name, final Agent[] agents, int batchSize) { + if (agents == null || agents.length == 0) { + throw new IllegalArgumentException("At least one agent is required"); + } + + if (batchSize <= 0) { + batchSize = 1; + } + + final StringBuilder sb = new StringBuilder("FlumeAvro["); + boolean first = true; + for (final Agent agent : agents) { + if (!first) { + sb.append(","); + } + sb.append(agent.getHost()).append(":").append(agent.getPort()); + first = false; + } + sb.append("]"); + return (FlumeAvroManager) getManager(sb.toString(), factory, new FactoryData(name, agents, batchSize)); + } + + /** + * Returns the agents. + * @return The agent array. + */ + public Agent[] getAgents() { + return agents; + } + + /** + * Returns the index of the current agent. + * @return The index for the current agent. + */ + public int getCurrent() { + return current; + } + + public synchronized void send(final BatchEvent events) { + if (client == null) { + client = connect(agents); + } + + if (client != null) { + final List list = events.getEvents(); + final List batch = new ArrayList(list.size()); + for (SimpleEvent event : list) { + final AvroFlumeEvent avroEvent = new AvroFlumeEvent(); + avroEvent.setBody(ByteBuffer.wrap(event.getBody())); + avroEvent.setHeaders(new HashMap()); + + for (final Map.Entry entry : event.getHeaders().entrySet()) { + avroEvent.getHeaders().put(entry.getKey(), entry.getValue()); + } + batch.add(avroEvent); + } + + try { + final Status status = client.appendBatch(batch); + if (status.equals(Status.OK)) { + return; + } else { + LOGGER.warn("RPC communication failed to " + agents[current].getHost() + + ":" + agents[current].getPort()); + } + } catch (final Exception ex) { + String msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + + agents[current].getPort(); + LOGGER.warn(msg, ex); + } + + for (int index = 0; index < agents.length; ++index) { + if (index == current) { + continue; + } + final Agent agent = agents[index]; + try { + transceiver = null; + final AvroSourceProtocol c = connect(agent.getHost(), agent.getPort()); + final Status status = c.appendBatch(batch); + if (!status.equals(Status.OK)) { + final String warnMsg = "RPC communication failed to " + getName() + " at " + + agent.getHost() + ":" + agent.getPort(); + LOGGER.warn(warnMsg); + continue; + } + client = c; + current = index; + return; + } catch (final Exception ex) { + final String warnMsg = "Unable to write to " + getName() + " at " + agent.getHost() + ":" + + agent.getPort(); + LOGGER.warn(warnMsg, ex); + } + } + } + throw new AppenderRuntimeException("No Flume agents are available"); + } + + @Override + public synchronized void send(final SimpleEvent event, int delay, int retries) { + if (delay == 0) { + delay = DEFAULT_RECONNECTION_DELAY; + } + if (retries == 0) { + retries = DEFAULT_RECONNECTS; + } + if (client == null) { + client = connect(agents); + } + String msg = "No Flume agents are available"; + if (client != null) { + final AvroFlumeEvent avroEvent = new AvroFlumeEvent(); + avroEvent.setBody(ByteBuffer.wrap(event.getBody())); + avroEvent.setHeaders(new HashMap()); + + for (final Map.Entry entry : event.getHeaders().entrySet()) { + avroEvent.getHeaders().put(entry.getKey(), entry.getValue()); + } + + final List batch = batchSize > 1 ? events.addAndGet(avroEvent, batchSize) : null; + if (batch == null && batchSize > 1) { + return; + } + + int i = 0; + + msg = "Error writing to " + getName(); + + do { + try { + final Status status = (batch == null) ? client.append(avroEvent) : client.appendBatch(batch); + if (!status.equals(Status.OK)) { + throw new AvroRemoteException("RPC communication failed to " + agents[current].getHost() + + ":" + agents[current].getPort()); + } + return; + } catch (final Exception ex) { + if (i == retries - 1) { + msg = "Unable to write to " + getName() + " at " + agents[current].getHost() + ":" + + agents[current].getPort(); + LOGGER.warn(msg, ex); + break; + } + sleep(delay); + } + } while (++i < retries); + + for (int index = 0; index < agents.length; ++index) { + if (index == current) { + continue; + } + final Agent agent = agents[index]; + i = 0; + do { + try { + transceiver = null; + final AvroSourceProtocol c = connect(agent.getHost(), agent.getPort()); + final Status status = (batch == null) ? c.append(avroEvent) : c.appendBatch(batch); + if (!status.equals(Status.OK)) { + if (i == retries - 1) { + final String warnMsg = "RPC communication failed to " + getName() + " at " + + agent.getHost() + ":" + agent.getPort(); + LOGGER.warn(warnMsg); + } + continue; + } + client = c; + current = index; + return; + } catch (final Exception ex) { + if (i == retries - 1) { + final String warnMsg = "Unable to write to " + getName() + " at " + agent.getHost() + ":" + + agent.getPort(); + LOGGER.warn(warnMsg, ex); + break; + } + sleep(delay); + } + } while (++i < retries); + } + } + + throw new AppenderRuntimeException(msg); + + } + + private void sleep(final int delay) { + try { + Thread.sleep(delay); + } catch (final InterruptedException ex) { + Thread.currentThread().interrupt(); + } + } + + /** + * There is a very good chance that this will always return the first agent even if it isn't available. + * @param agents The list of agents to choose from + * @return The FlumeEventAvroServer. + */ + private AvroSourceProtocol connect(final Agent[] agents) { + int i = 0; + for (final Agent agent : agents) { + final AvroSourceProtocol server = connect(agent.getHost(), agent.getPort()); + if (server != null) { + current = i; + return server; + } + ++i; + } + LOGGER.error("Flume manager " + getName() + " was unable to connect to any agents"); + return null; + } + + private AvroSourceProtocol connect(final String hostname, final int port) { + try { + if (transceiver == null) { + transceiver = new NettyTransceiver(new InetSocketAddress(hostname, port)); + } + } catch (final IOException ioe) { + LOGGER.error("Unable to create transceiver", ioe); + return null; + } + try { + return SpecificRequestor.getClient(AvroSourceProtocol.class, transceiver); + } catch (final IOException ioe) { + LOGGER.error("Unable to create Avro client"); + return null; + } + } + + @Override + protected void releaseSub() { + if (transceiver != null) { + try { + transceiver.close(); + } catch (final IOException ioe) { + LOGGER.error("Attempt to clean up Avro transceiver failed", ioe); + } + } + client = null; + } + + /** + * Thread-safe List management of a batch. + */ + private static class EventList extends ArrayList { + + /** + * Generated serial version ID. + */ + private static final long serialVersionUID = -1599817377315957495L; + + public synchronized List addAndGet(final AvroFlumeEvent event, final int batchSize) { + super.add(event); + if (this.size() >= batchSize) { + final List events = new ArrayList(); + events.addAll(this); + clear(); + return events; + } else { + return null; + } + } + } + + /** + * Factory data. + */ + private static class FactoryData { + private final String name; + private final Agent[] agents; + private final int batchSize; + + /** + * Constructor. + * @param name The name of the Appender. + * @param agents The agents. + * @param batchSize The number of events to include in a batch. + */ + public FactoryData(final String name, final Agent[] agents, final int batchSize) { + this.name = name; + this.agents = agents; + this.batchSize = batchSize; + } + } + + /** + * Avro Manager Factory. + */ + private static class AvroManagerFactory implements ManagerFactory { + + /** + * Create the FlumeAvroManager. + * @param name The name of the entity to manage. + * @param data The data required to create the entity. + * @return The FlumeAvroManager. + */ + public FlumeAvroManager createManager(final String name, final FactoryData data) { + try { + + return new FlumeAvroManager(name, data.name, data.agents, data.batchSize); + } catch (final Exception ex) { + LOGGER.error("Could not create FlumeAvroManager", ex); + } + return null; + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.logging.log4j.flume.appender.FlumeAvroManager.releaseSub` reads without synchronization from `this.org.apache.logging.log4j.flume.appender.FlumeAvroManager.transceiver`. Potentially races with write in method `FlumeAvroManager.send(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FlumeAvroManager.releaseSub() + +### Procedure Id: +org.apache.logging.log4j.flume.appender.FlumeAvroManager.releaseSub():void.66289e2f21b919aa552086f4576962c7 + +### File: +flume-ng/src/main/java/org/apache/logging/log4j/flume/appender/FlumeAvroManager.java + +### Key: +FlumeAvroManager.java|releaseSub|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +5fdb02a8e2deaa3a76b708917407c899 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7912/instruction.md b/inferredbugs-7912/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5715aaf7f86ae3bb14d0d35d962fa2083a8ec0e0 --- /dev/null +++ b/inferredbugs-7912/instruction.md @@ -0,0 +1,221 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 64 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.appender.rolling.action; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + + +/** + * Compresses a file using Zip compression. + */ +public final class ZipCompressAction extends AbstractAction { + + private static final int BUF_SIZE = 8102; + + /** + * Source file. + */ + private final File source; + + /** + * Destination file. + */ + private final File destination; + + /** + * If true, attempt to delete file on completion. + */ + private final boolean deleteSource; + + /** + * Compression level. + */ + private final int level; + + /** + * Create new instance of GzCompressAction. + * + * @param source file to compress, may not be null. + * @param destination compressed file, may not be null. + * @param deleteSource if true, attempt to delete file on completion. Failure to delete + * does not cause an exception to be thrown or affect return value. + * @param level TODO + */ + public ZipCompressAction(final File source, final File destination, final boolean deleteSource, final int level) { + if (source == null) { + throw new NullPointerException("source"); + } + + if (destination == null) { + throw new NullPointerException("destination"); + } + + this.source = source; + this.destination = destination; + this.deleteSource = deleteSource; + this.level = level; + } + + /** + * Compress. + * + * @return true if successfully compressed. + * @throws IOException on IO exception. + */ + @Override + public boolean execute() throws IOException { + return execute(source, destination, deleteSource, level); + } + + /** + * Compress a file. + * + * @param source file to compress, may not be null. + * @param destination compressed file, may not be null. + * @param deleteSource if true, attempt to delete file on completion. Failure to delete + * does not cause an exception to be thrown or affect return value. + * @param level the compression level + * @return true if source file compressed. + * @throws IOException on IO exception. + */ + public static boolean execute(final File source, final File destination, final boolean deleteSource, final int level) + throws IOException { + if (source.exists()) { + final FileInputStream fis = new FileInputStream(source); + final FileOutputStream fos = new FileOutputStream(destination); + final ZipOutputStream zos = new ZipOutputStream(fos); + zos.setLevel(level); + + final ZipEntry zipEntry = new ZipEntry(source.getName()); + zos.putNextEntry(zipEntry); + + final byte[] inbuf = new byte[BUF_SIZE]; + int n; + + while ((n = fis.read(inbuf)) != -1) { + zos.write(inbuf, 0, n); + } + + zos.close(); + fis.close(); + + if (deleteSource && !source.delete()) { + LOGGER.warn("Unable to delete " + source.toString() + '.'); + } + + return true; + } + + return false; + } + + /** + * Capture exception. + * + * @param ex exception. + */ + @Override + protected void reportException(final Exception ex) { + LOGGER.warn("Exception during compression of '" + source.toString() + "'.", ex); + } + + @Override + public String toString() { + return ZipCompressAction.class.getSimpleName() + '[' + source + " to " + destination // + + ", level=" + level + ", deleteSource=" + deleteSource + ']'; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.zip.ZipOutputStream` acquired to `zos` by call to `new()` at line 105 is not released after line 128. +**Note**: potential exception at line 114 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean ZipCompressAction.execute(File,File,boolean,int) + +### Procedure Id: +org.apache.logging.log4j.core.appender.rolling.action.ZipCompressAction.execute(java.io.File,java.io.cfe0e01a033460c6ac7298996fe6fd3c + +### File: +log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/action/ZipCompressAction.java + +### Key: +ZipCompressAction.java|execute|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +2a4e649b158627d4d593a58262161196 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7913/instruction.md b/inferredbugs-7913/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..668ab06a33d18d09699dd0d32cf13e43582e3a2c --- /dev/null +++ b/inferredbugs-7913/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 90 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.layout; + +import java.io.IOException; +import java.nio.charset.Charset; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.QuoteMode; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.Node; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.status.StatusLogger; + +/** + * A Comma-Separated Value (CSV) layout to log event parameters. + * The event message is currently ignored. + * + *

    + * Best used with: + *

    + *

    + * {@code logger.debug(new ObjectArrayMessage(1, 2, "Bob"));} + *

    + * + * Depends on Apache Commons CSV 1.2. + * + * @since 2.4 + */ +@Plugin(name = "CsvParameterLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) +public class CsvParameterLayout extends AbstractCsvLayout { + + private static final long serialVersionUID = 1L; + + private static ThreadLocal strBuilder = newStringBuilderThreadLocal(); + + public static AbstractCsvLayout createDefaultLayout() { + return new CsvParameterLayout(Charset.forName(DEFAULT_CHARSET), CSVFormat.valueOf(DEFAULT_FORMAT), null, null); + } + + public static AbstractCsvLayout createLayout(final CSVFormat format) { + return new CsvParameterLayout(Charset.forName(DEFAULT_CHARSET), format, null, null); + } + + @PluginFactory + public static AbstractCsvLayout createLayout( + // @formatter:off + @PluginAttribute(value = "format", defaultString = DEFAULT_FORMAT) final String format, + @PluginAttribute("delimiter") final Character delimiter, + @PluginAttribute("escape") final Character escape, + @PluginAttribute("quote") final Character quote, + @PluginAttribute("quoteMode") final QuoteMode quoteMode, + @PluginAttribute("nullString") final String nullString, + @PluginAttribute("recordSeparator") final String recordSeparator, + @PluginAttribute(value = "charset", defaultString = DEFAULT_CHARSET) final Charset charset, + @PluginAttribute("header") final String header, + @PluginAttribute("footer") final String footer) + // @formatter:on + { + + final CSVFormat csvFormat = createFormat(format, delimiter, escape, quote, quoteMode, nullString, recordSeparator); + return new CsvParameterLayout(charset, csvFormat, header, footer); + } + + public CsvParameterLayout(final Charset charset, final CSVFormat csvFormat, final String header, final String footer) { + super(charset, csvFormat, header, footer); + } + + @Override + public String toSerializable(final LogEvent event) { + final Message message = event.getMessage(); + final Object[] parameters = message.getParameters(); + final StringBuilder buffer = prepareStringBuilder(strBuilder); + try { + // Revisit when 1.3 is out so that we do not need to create a new + // printer for each event. + // No need to close the printer. + final CSVPrinter printer = new CSVPrinter(buffer, getFormat()); + printer.printRecord(parameters); + return buffer.toString(); + } catch (final IOException e) { + StatusLogger.getLogger().error(message, e); + return getFormat().getCommentMarker() + " " + e; + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.csv.CSVPrinter` acquired to `printer` by call to `new()` at line 97 is not released after line 98. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String CsvParameterLayout.toSerializable(LogEvent) + +### Procedure Id: +org.apache.logging.log4j.core.layout.CsvParameterLayout.toSerializable(org.apache.logging.log4j.core.26bf55ed37099b11e50e8562fcc4740a + +### File: +log4j-core/src/main/java/org/apache/logging/log4j/core/layout/CsvParameterLayout.java + +### Key: +CsvParameterLayout.java|toSerializable|RESOURCE_LEAK + +### Node Key: +729b19e05503d6470a9fb971e9a5d7c8 + +### Hash: +24895251081086233405307ba2b5623c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7914/instruction.md b/inferredbugs-7914/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8087a4f5d8f8f608ab483ef73134d7010af1b4f7 --- /dev/null +++ b/inferredbugs-7914/instruction.md @@ -0,0 +1,212 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.logging.log4j.streams; + +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringWriter; +import java.io.Writer; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; + +public abstract class AbstractLoggerWriterTest extends AbstractStreamTest { + protected StringWriter wrapped; + protected Writer writer; + + @Before + public void createStream() { + this.wrapped = createWriter(); + this.writer = createWriterWrapper(); + } + + protected abstract StringWriter createWriter(); + + protected abstract Writer createWriterWrapper(); + + @Test + public void testClose_HasRemainingData() throws IOException { + this.writer.write(FIRST); + assertMessages(); + this.writer.close(); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST, this.wrapped.toString()); + } + } + + @Test + public void testClose_NoRemainingData() throws IOException { + this.writer.close(); + assertMessages(); + if (this.wrapped != null) { + assertEquals("", this.wrapped.toString()); + } + } + + @Test + public void testFlush() throws IOException { + final OutputStream out = EasyMock.createMock(OutputStream.class); + out.flush(); // expect the flush to come through to the mocked OutputStream + out.close(); + replay(out); + + final LoggerOutputStream los = new LoggerOutputStream(out, getExtendedLogger(), LEVEL); + los.flush(); + los.close(); + verify(out); + } + + @Test + public void testWrite_Character() throws Exception { + for (final char c : FIRST.toCharArray()) { + this.writer.write(c); + assertMessages(); + } + this.writer.write('\n'); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_CharArray() throws Exception { + final char[] chars = FIRST.toCharArray(); + this.writer.write(chars); + assertMessages(); + this.writer.write('\n'); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_CharArray_Offset_Length() throws Exception { + final char[] chars = FIRST.toCharArray(); + final int middle = chars.length / 2; + final int length = chars.length - middle; + final String right = new String(chars, middle, length); + this.writer.write(chars, middle, length); + assertMessages(); + this.writer.write('\n'); + assertMessages(right); + if (this.wrapped != null) { + assertEquals(FIRST.substring(middle, FIRST.length()) + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_IgnoresWindowsNewline() throws IOException { + this.writer.write(FIRST + "\r\n"); + this.writer.write(LAST); + this.writer.close(); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + "\r\n" + LAST, this.wrapped.toString()); + } + } + + @Test + public void testWrite_MultipleLines() throws IOException { + this.writer.write(FIRST + '\n' + LAST + '\n'); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n' + LAST + '\n', this.wrapped.toString()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `LoggerOutputStream(...)` at line 73 is not released after line 75. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractLoggerWriterTest.testFlush() + +### Procedure Id: +org.apache.logging.log4j.streams.AbstractLoggerWriterTest.testFlush():void.0e4aef438480bc8be1ed7703970600dc + +### File: +log4j-streams/src/test/java/org/apache/logging/log4j/streams/AbstractLoggerWriterTest.java + +### Key: +AbstractLoggerWriterTest.java|testFlush|RESOURCE_LEAK + +### Node Key: +a908b4223ca7d0afb8ea757ec9d1ac09 + +### Hash: +89595943b95bb04e71357ae7a2355ee8 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7915/instruction.md b/inferredbugs-7915/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d11ceeda38c41db03c0e241b241e94686f095ef --- /dev/null +++ b/inferredbugs-7915/instruction.md @@ -0,0 +1,216 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 79 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.logging.log4j.io; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; + +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.*; + +public abstract class AbstractLoggerOutputStreamTest extends AbstractStreamTest { + protected OutputStream out; + protected ByteArrayOutputStream wrapped; + + protected abstract ByteArrayOutputStream createOutputStream(); + + protected abstract OutputStream createOutputStreamWrapper(); + + @Before + public void createStream() { + this.wrapped = createOutputStream(); + this.out = createOutputStreamWrapper(); + } + + @Test + public void testClose_HasRemainingData() throws IOException { + this.out.write(FIRST.getBytes()); + assertMessages(); + this.out.close(); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST, this.wrapped.toString()); + } + } + + @Test + public void testClose_NoRemainingData() throws IOException { + this.out.close(); + assertMessages(); + if (this.wrapped != null) { + assertEquals("", this.wrapped.toString()); + } + } + + @Test + public void testFlush() throws IOException { + final OutputStream out = EasyMock.createMock("out", OutputStream.class); + out.flush(); // expect the flush to come through to the mocked OutputStream + out.close(); + replay(out); + + final OutputStream filteredOut = + IoBuilder.forLogger(getExtendedLogger()) + .filter(out) + .setLevel(LEVEL) + .buildOutputStream(); + filteredOut.flush(); + filteredOut.close(); + verify(out); + } + + @Test + public void testWrite_ByteArray() throws Exception { + final byte[] bytes = "byte[]".getBytes(); + this.out.write(bytes); + assertMessages(); + this.out.write('\n'); + assertMessages("byte[]"); + if (this.wrapped != null) { + assertEquals("byte[]\n", this.wrapped.toString()); + } + } + + @Test + public void testWrite_ByteArray_Offset_Length() throws Exception { + final byte[] bytes = "byte[]".getBytes(); + final int middle = bytes.length / 2; + final int length = bytes.length - middle; + final String right = new String(bytes, middle, length); + this.out.write(bytes, middle, length); + assertMessages(); + this.out.write('\n'); + assertMessages(right); + if (this.wrapped != null) { + assertEquals("byte[]".substring(middle, bytes.length) + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_IgnoresWindowsNewline() throws IOException { + this.out.write(FIRST.getBytes()); + this.out.write("\r\n".getBytes()); + this.out.write(LAST.getBytes()); + this.out.close(); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + "\r\n" + LAST, this.wrapped.toString()); + } + } + + @Test + public void testWrite_Int() throws Exception { + for (final byte b : "int".getBytes()) { + this.out.write(b); + assertMessages(); + } + this.out.write('\n'); + assertMessages("int"); + if (this.wrapped != null) { + assertEquals("int" + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_MultipleLines() throws IOException { + this.out.write((FIRST + '\n' + LAST + '\n').getBytes()); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n' + LAST + '\n', this.wrapped.toString()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `buildOutputStream()` at line 76 is not released after line 78. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractLoggerOutputStreamTest.testFlush() + +### Procedure Id: +org.apache.logging.log4j.io.AbstractLoggerOutputStreamTest.testFlush():void.63fe97a54356d1648d61b407d8469c84 + +### File: +log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractLoggerOutputStreamTest.java + +### Key: +AbstractLoggerOutputStreamTest.java|testFlush|RESOURCE_LEAK + +### Node Key: +ba6daf65b8ec829a8ca35510289aa557 + +### Hash: +c9efbdf3fef2946bfe9cd8c76de9430d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7924/instruction.md b/inferredbugs-7924/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..068c67a654a3b2ec7beb404af7b977b443905a19 --- /dev/null +++ b/inferredbugs-7924/instruction.md @@ -0,0 +1,217 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 84 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.logging.log4j.io; + +import java.io.IOException; +import java.io.OutputStream; +import java.io.StringWriter; +import java.io.Writer; + +import org.easymock.EasyMock; +import org.junit.Before; +import org.junit.Test; + +import static org.easymock.EasyMock.replay; +import static org.easymock.EasyMock.verify; +import static org.junit.Assert.*; + +public abstract class AbstractLoggerWriterTest extends AbstractStreamTest { + protected StringWriter wrapped; + protected Writer writer; + + @Before + public void createStream() { + this.wrapped = createWriter(); + this.writer = createWriterWrapper(); + } + + protected abstract StringWriter createWriter(); + + protected abstract Writer createWriterWrapper(); + + @Test + public void testClose_HasRemainingData() throws IOException { + this.writer.write(FIRST); + assertMessages(); + this.writer.close(); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST, this.wrapped.toString()); + } + } + + @Test + public void testClose_NoRemainingData() throws IOException { + this.writer.close(); + assertMessages(); + if (this.wrapped != null) { + assertEquals("", this.wrapped.toString()); + } + } + + @Test + public void testFlush() throws IOException { + final OutputStream out = EasyMock.createMock(OutputStream.class); + out.flush(); // expect the flush to come through to the mocked OutputStream + out.close(); + replay(out); + + final OutputStream filteredOut = + IoBuilder.forLogger(getExtendedLogger()) + .filter(out) + .setLevel(LEVEL) + .buildOutputStream(); + filteredOut.flush(); + filteredOut.close(); + verify(out); + } + + @Test + public void testWrite_Character() throws Exception { + for (final char c : FIRST.toCharArray()) { + this.writer.write(c); + assertMessages(); + } + this.writer.write('\n'); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_CharArray() throws Exception { + final char[] chars = FIRST.toCharArray(); + this.writer.write(chars); + assertMessages(); + this.writer.write('\n'); + assertMessages(FIRST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_CharArray_Offset_Length() throws Exception { + final char[] chars = FIRST.toCharArray(); + final int middle = chars.length / 2; + final int length = chars.length - middle; + final String right = new String(chars, middle, length); + this.writer.write(chars, middle, length); + assertMessages(); + this.writer.write('\n'); + assertMessages(right); + if (this.wrapped != null) { + assertEquals(FIRST.substring(middle, FIRST.length()) + '\n', this.wrapped.toString()); + } + } + + @Test + public void testWrite_IgnoresWindowsNewline() throws IOException { + this.writer.write(FIRST + "\r\n"); + this.writer.write(LAST); + this.writer.close(); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + "\r\n" + LAST, this.wrapped.toString()); + } + } + + @Test + public void testWrite_MultipleLines() throws IOException { + this.writer.write(FIRST + '\n' + LAST + '\n'); + assertMessages(FIRST, LAST); + if (this.wrapped != null) { + assertEquals(FIRST + '\n' + LAST + '\n', this.wrapped.toString()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.logging.log4j.io.LoggerFilterOutputStream` acquired by call to `buildOutputStream()` at line 77 is not released after line 81. +**Note**: potential exception at line 78 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractLoggerWriterTest.testFlush() + +### Procedure Id: +org.apache.logging.log4j.io.AbstractLoggerWriterTest.testFlush():void.714dc95ae9aa7e08c3a3e68c8bd8ae5a + +### File: +log4j-iostreams/src/test/java/org/apache/logging/log4j/io/AbstractLoggerWriterTest.java + +### Key: +AbstractLoggerWriterTest.java|testFlush|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +5425067216ba8af7ee8c4082f1e398fb + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7925/instruction.md b/inferredbugs-7925/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..131f5fcf6878a707099e3e536e63c883fa14e2b4 --- /dev/null +++ b/inferredbugs-7925/instruction.md @@ -0,0 +1,326 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.jmx; + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.Reader; +import java.io.StringWriter; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.Charset; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicLong; +import javax.management.MBeanNotificationInfo; +import javax.management.Notification; +import javax.management.NotificationBroadcasterSupport; +import javax.management.ObjectName; + +import org.apache.logging.log4j.core.LoggerContext; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.ConfigurationFactory; +import org.apache.logging.log4j.core.config.ConfigurationFactory.ConfigurationSource; +import org.apache.logging.log4j.core.helpers.Assert; +import org.apache.logging.log4j.core.helpers.Charsets; +import org.apache.logging.log4j.status.StatusLogger; + +/** + * Implementation of the {@code LoggerContextAdminMBean} interface. + */ +public class LoggerContextAdmin extends NotificationBroadcasterSupport + implements LoggerContextAdminMBean, PropertyChangeListener { + private static final int PAGE = 4 * 1024; + private static final int TEXT_BUFFER = 64 * 1024; + private static final int BUFFER_SIZE = 2048; + private static final StatusLogger LOGGER = StatusLogger.getLogger(); + + private final AtomicLong sequenceNo = new AtomicLong(); + private final ObjectName objectName; + private final LoggerContext loggerContext; + private String customConfigText; + + /** + * Constructs a new {@code LoggerContextAdmin} with the {@code Executor} to + * be used for sending {@code Notification}s asynchronously to listeners. + * + * @param executor used to send notifications asynchronously + * @param loggerContext the instrumented object + */ + public LoggerContextAdmin(final LoggerContext loggerContext, final Executor executor) { + super(executor, createNotificationInfo()); + this.loggerContext = Assert.isNotNull(loggerContext, "loggerContext"); + try { + final String ctxName = Server.escape(loggerContext.getName()); + final String name = String.format(PATTERN, ctxName); + objectName = new ObjectName(name); + } catch (final Exception e) { + throw new IllegalStateException(e); + } + loggerContext.addPropertyChangeListener(this); + } + + private static MBeanNotificationInfo createNotificationInfo() { + final String[] notifTypes = new String[] {// + NOTIF_TYPE_RECONFIGURED }; + final String name = Notification.class.getName(); + final String description = "Configuration reconfigured"; + return new MBeanNotificationInfo(notifTypes, name, description); + } + + @Override + public String getStatus() { + return loggerContext.getStatus().toString(); + } + + @Override + public String getName() { + return loggerContext.getName(); + } + + private Configuration getConfig() { + return loggerContext.getConfiguration(); + } + + @Override + public String getConfigLocationURI() { + if (loggerContext.getConfigLocation() != null) { + return String.valueOf(loggerContext.getConfigLocation()); + } + if (getConfigName() != null) { + return String.valueOf(new File(getConfigName()).toURI()); + } + return ""; + } + + @Override + public void setConfigLocationURI(final String configLocation) + throws URISyntaxException, IOException { + LOGGER.debug("---------"); + LOGGER.debug("Remote request to reconfigure using location " + + configLocation); + final URI uri = new URI(configLocation); + + // validate the location first: invalid location will result in + // default configuration being configured, try to avoid that... + uri.toURL().openStream().close(); + + loggerContext.setConfigLocation(uri); + LOGGER.debug("Completed remote request to reconfigure."); + } + + @Override + public void propertyChange(final PropertyChangeEvent evt) { + if (!LoggerContext.PROPERTY_CONFIG.equals(evt.getPropertyName())) { + return; + } + // erase custom text if new configuration was read from a location + if (loggerContext.getConfiguration().getName() != null) { + customConfigText = null; + } + final Notification notif = new Notification(NOTIF_TYPE_RECONFIGURED, + getObjectName(), nextSeqNo(), now(), null); + sendNotification(notif); + } + + @Override + public String getConfigText() throws IOException { + return getConfigText(Charsets.UTF_8.name()); + } + + @Override + public String getConfigText(final String charsetName) throws IOException { + if (customConfigText != null) { + return customConfigText; + } + try { + final Charset charset = Charset.forName(charsetName); + return readContents(new URI(getConfigLocationURI()), charset); + } catch (final Exception ex) { + final StringWriter sw = new StringWriter(BUFFER_SIZE); + ex.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + } + + @Override + public void setConfigText(final String configText, final String charsetName) { + final String old = customConfigText; + customConfigText = Assert.isNotNull(configText, "configText"); + LOGGER.debug("---------"); + LOGGER.debug("Remote request to reconfigure from config text."); + + try { + final InputStream in = new ByteArrayInputStream( + configText.getBytes(charsetName)); + final ConfigurationSource source = new ConfigurationSource(in); + final Configuration updated = ConfigurationFactory.getInstance() + .getConfiguration(source); + loggerContext.start(updated); + LOGGER.debug("Completed remote request to reconfigure from config text."); + } catch (final Exception ex) { + customConfigText = old; + final String msg = "Could not reconfigure from config text"; + LOGGER.error(msg, ex); + throw new IllegalArgumentException(msg, ex); + } + } + + private String readContents(final URI uri, final Charset charset) throws IOException { + InputStream in = null; + try { + in = uri.toURL().openStream(); + final Reader reader = new InputStreamReader(in, charset); + final StringBuilder result = new StringBuilder(TEXT_BUFFER); + final char[] buff = new char[PAGE]; + int count = -1; + while ((count = reader.read(buff)) >= 0) { + result.append(buff, 0, count); + } + return result.toString(); + } finally { + try { + in.close(); + } catch (final Exception ignored) { + // ignored + } + } + } + + @Override + public String getConfigName() { + return getConfig().getName(); + } + + @Override + public String getConfigClassName() { + return getConfig().getClass().getName(); + } + + @Override + public String getConfigFilter() { + return String.valueOf(getConfig().getFilter()); + } + + @Override + public String getConfigMonitorClassName() { + return getConfig().getConfigurationMonitor().getClass().getName(); + } + + @Override + public Map getConfigProperties() { + return getConfig().getProperties(); + } + + /** + * Returns the {@code ObjectName} of this mbean. + * + * @return the {@code ObjectName} + * @see LoggerContextAdminMBean#PATTERN + */ + public ObjectName getObjectName() { + return objectName; + } + + private long nextSeqNo() { + return sequenceNo.getAndIncrement(); + } + + private long now() { + return System.currentTimeMillis(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 193 is not released after line 200. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String LoggerContextAdmin.readContents(URI,Charset) + +### Procedure Id: +org.apache.logging.log4j.core.jmx.LoggerContextAdmin.readContents(java.net.URI,java.nio.charset.Char.a31fbb175bcd5be4f70b4bd1b7470245 + +### File: +core/src/main/java/org/apache/logging/log4j/core/jmx/LoggerContextAdmin.java + +### Key: +LoggerContextAdmin.java|readContents|RESOURCE_LEAK + +### Node Key: +c3a0f41ebe4e1f490ccd067c600659db + +### Hash: +f2457bf5ac894828bc778ba70dadf5a5 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7941/instruction.md b/inferredbugs-7941/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03927637af489bc11129cb39272f36a9ac02a97e --- /dev/null +++ b/inferredbugs-7941/instruction.md @@ -0,0 +1,185 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 78 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.config; + +import java.io.File; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Configuration monitor that periodically checks the timestamp of the configuration file and calls the + * ConfigurationListeners when an update occurs. + */ +public class FileConfigurationMonitor implements ConfigurationMonitor { + + private static final int MASK = 0x0f; + + private static final int MIN_INTERVAL = 5; + + private static final int MILLIS_PER_SECOND = 1000; + + private final File file; + + private long lastModified; + + private final List listeners; + + private final int intervalSeconds; + + private long nextCheck; + + private final AtomicInteger counter = new AtomicInteger(0); + + private static final Lock LOCK = new ReentrantLock(); + + private final Reconfigurable reconfigurable; + + /** + * Constructor. + * @param reconfigurable The Configuration that can be reconfigured. + * @param file The File to monitor. + * @param listeners The List of ConfigurationListeners to notify upon a change. + * @param intervalSeconds The monitor interval in seconds. The minimum interval is 5 seconds. + */ + public FileConfigurationMonitor(final Reconfigurable reconfigurable, final File file, + final List listeners, + final int intervalSeconds) { + this.reconfigurable = reconfigurable; + this.file = file; + this.lastModified = file.lastModified(); + this.listeners = listeners; + this.intervalSeconds = (intervalSeconds < MIN_INTERVAL ? MIN_INTERVAL : intervalSeconds) * MILLIS_PER_SECOND; + this.nextCheck = System.currentTimeMillis() + intervalSeconds; + } + + /** + * Called to determine if the configuration has changed. + */ + @Override + public void checkConfiguration() { + final long current; + if (((counter.incrementAndGet() & MASK) == 0) && ((current = System.currentTimeMillis()) >= nextCheck)) { + LOCK.lock(); + try { + nextCheck = current + intervalSeconds; + if (file.lastModified() > lastModified) { + lastModified = file.lastModified(); + for (final ConfigurationListener listener : listeners) { + final Thread thread = new Thread(new ReconfigurationWorker(listener, reconfigurable)); + thread.setDaemon(true); + thread.start(); + } + } + } finally { + LOCK.unlock(); + } + } + } + + private class ReconfigurationWorker implements Runnable { + + private final ConfigurationListener listener; + private final Reconfigurable reconfigurable; + + public ReconfigurationWorker(final ConfigurationListener listener, final Reconfigurable reconfigurable) { + this.listener = listener; + this.reconfigurable = reconfigurable; + } + + @Override + public void run() { + listener.onChange(reconfigurable); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.logging.log4j.core.config.FileConfigurationMonitor.checkConfiguration` reads without synchronization from `this.org.apache.logging.log4j.core.config.FileConfigurationMonitor.nextCheck`. Potentially races with write in method `FileConfigurationMonitor.checkConfiguration()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileConfigurationMonitor.checkConfiguration() + +### Procedure Id: +org.apache.logging.log4j.core.config.FileConfigurationMonitor.checkConfiguration():void.2f9c742a5adef5d66081fdf9eebbb51b + +### File: +log4j-core/src/main/java/org/apache/logging/log4j/core/config/FileConfigurationMonitor.java + +### Key: +FileConfigurationMonitor.java|checkConfiguration|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c3eff2f7a0d7530efd1d50c1498734e3 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7946/instruction.md b/inferredbugs-7946/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8d087bf4a6e9807840ca01c59da48266367fa74 --- /dev/null +++ b/inferredbugs-7946/instruction.md @@ -0,0 +1,224 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** logging-log4j2 +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache license, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the license for the specific language governing permissions and + * limitations under the license. + */ +package org.apache.logging.log4j.core.appender; + +import java.io.Serializable; + +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttr; +import org.apache.logging.log4j.core.config.plugins.PluginConfiguration; +import org.apache.logging.log4j.core.config.plugins.PluginElement; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.layout.LoggerFields; +import org.apache.logging.log4j.core.layout.RFC5424Layout; +import org.apache.logging.log4j.core.layout.SyslogLayout; +import org.apache.logging.log4j.core.net.AbstractSocketManager; +import org.apache.logging.log4j.core.net.Advertiser; +import org.apache.logging.log4j.core.net.Protocol; +import org.apache.logging.log4j.util.EnglishEnums; + +/** + * The Syslog Appender. + * + * @param The {@link Layout}'s {@link Serializable} type. + */ +@Plugin(name = "Syslog", category = "Core", elementType = "appender", printObject = true) +public class SyslogAppender extends SocketAppender { + + private static final String BSD = "bsd"; + + private static final String RFC5424 = "RFC5424"; + + protected SyslogAppender(final String name, final Layout layout, final Filter filter, + final boolean handleException, final boolean immediateFlush, + final AbstractSocketManager manager, final Advertiser advertiser) { + super(name, layout, filter, manager, handleException, immediateFlush, advertiser); + + } + + /** + * Create a SyslogAppender. + * @param host The name of the host to connect to. + * @param portNum The port to connect to on the target host. + * @param protocol The Protocol to use. + * @param delay The interval in which failed writes should be retried. + * @param immediateFail True if the write should fail if no socket is immediately available. + * @param name The name of the Appender. + * @param immediateFlush "true" if data should be flushed on each write. + * @param suppress "true" if exceptions should be hidden from the application, "false" otherwise. + * The default is "true". + * @param facility The Facility is used to try to classify the message. + * @param id The default structured data id to use when formatting according to RFC 5424. + * @param ein The IANA enterprise number. + * @param includeMDC Indicates whether data from the ThreadContextMap will be included in the RFC 5424 Syslog + * record. Defaults to "true:. + * @param mdcId The id to use for the MDC Structured Data Element. + * @param mdcPrefix The prefix to add to MDC key names. + * @param eventPrefix The prefix to add to event key names. + * @param includeNL If true, a newline will be appended to the end of the syslog record. The default is false. + * @param escapeNL String that should be used to replace newlines within the message text. + * @param appName The value to use as the APP-NAME in the RFC 5424 syslog record. + * @param msgId The default value to be used in the MSGID field of RFC 5424 syslog records. + * @param excludes A comma separated list of mdc keys that should be excluded from the LogEvent. + * @param includes A comma separated list of mdc keys that should be included in the FlumeEvent. + * @param required A comma separated list of mdc keys that must be present in the MDC. + * @param format If set to "RFC5424" the data will be formatted in accordance with RFC 5424. Otherwise, + * it will be formatted as a BSD Syslog record. + * @param filter A Filter to determine if the event should be handled by this Appender. + * @param config The Configuration. + * @param charsetName The character set to use when converting the syslog String to a byte array. + * @param exceptionPattern The converter pattern to use for formatting exceptions. + * @param loggerFields The logger fields + * @param advertise Whether to advertise + * @param The {@link Layout}'s {@link Serializable} type. + * @return A SyslogAppender. + */ + @PluginFactory + public static SyslogAppender createAppender(@PluginAttr("host") final String host, + @PluginAttr("port") final String portNum, + @PluginAttr("protocol") final String protocol, + @PluginAttr("reconnectionDelay") final String delay, + @PluginAttr("immediateFail") final String immediateFail, + @PluginAttr("name") final String name, + @PluginAttr("immediateFlush") final String immediateFlush, + @PluginAttr("suppressExceptions") final String suppress, + @PluginAttr("facility") final String facility, + @PluginAttr("id") final String id, + @PluginAttr("enterpriseNumber") final String ein, + @PluginAttr("includeMDC") final String includeMDC, + @PluginAttr("mdcId") final String mdcId, + @PluginAttr("mdcPrefix") final String mdcPrefix, + @PluginAttr("eventPrefix") final String eventPrefix, + @PluginAttr("newLine") final String includeNL, + @PluginAttr("newLineEscape") final String escapeNL, + @PluginAttr("appName") final String appName, + @PluginAttr("messageId") final String msgId, + @PluginAttr("mdcExcludes") final String excludes, + @PluginAttr("mdcIncludes") final String includes, + @PluginAttr("mdcRequired") final String required, + @PluginAttr("format") final String format, + @PluginElement("filters") final Filter filter, + @PluginConfiguration final Configuration config, + @PluginAttr("charset") final String charsetName, + @PluginAttr("exceptionPattern") final String exceptionPattern, + @PluginElement("LoggerFields") final LoggerFields loggerFields, + @PluginAttr("advertise") final String advertise) { + + final boolean isFlush = immediateFlush == null ? true : Boolean.valueOf(immediateFlush); + final boolean handleExceptions = suppress == null ? true : Boolean.valueOf(suppress); + final int reconnectDelay = delay == null ? 0 : Integer.parseInt(delay); + final boolean fail = immediateFail == null ? true : Boolean.valueOf(immediateFail); + final int port = portNum == null ? 0 : Integer.parseInt(portNum); + final boolean isAdvertise = advertise == null ? false : Boolean.valueOf(advertise); + @SuppressWarnings("unchecked") + final Layout layout = (Layout) (RFC5424.equalsIgnoreCase(format) ? + RFC5424Layout.createLayout(facility, id, ein, includeMDC, mdcId, mdcPrefix, eventPrefix, includeNL, + escapeNL, appName, msgId, excludes, includes, required, exceptionPattern, loggerFields, config) : + SyslogLayout.createLayout(facility, includeNL, escapeNL, charsetName)); + + if (name == null) { + LOGGER.error("No name provided for SyslogAppender"); + return null; + } + final String prot = protocol != null ? protocol : Protocol.UDP.name(); + final Protocol p = EnglishEnums.valueOf(Protocol.class, protocol); + final AbstractSocketManager manager = createSocketManager(p, host, port, reconnectDelay, fail, layout); + if (manager == null) { + return null; + } + + return new SyslogAppender(name, layout, filter, handleExceptions, isFlush, manager, + isAdvertise ? config.getAdvertiser() : null); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `p` last assigned on line 141 could be null and is dereferenced by call to `createSocketManager(...)` at line 142. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SyslogAppender SyslogAppender.createAppender(String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,Filter,Configuration,String,String,LoggerFields,String) + +### Procedure Id: +org.apache.logging.log4j.core.appender.SyslogAppender.createAppender(java.lang.String,java.lang.Stri.d0d9b54c32249048290e30a451732d83 + +### File: +core/src/main/java/org/apache/logging/log4j/core/appender/SyslogAppender.java + +### Key: +SyslogAppender.java|createAppender|NULL_DEREFERENCE + +### Node Key: +dd9ca3717f6177bdf4b1ff3644b6e43a + +### Hash: +bc1d8f5898e8371337ccb65059940423 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7948/instruction.md b/inferredbugs-7948/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..473b49f4b404b5fe281354bf8af0f391511f405b --- /dev/null +++ b/inferredbugs-7948/instruction.md @@ -0,0 +1,573 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2013-2015 YCSB contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. See accompanying LICENSE file. + * + * Submitted by Chrisjan Matser on 10/11/2010. + */ +package com.yahoo.ycsb.db; + +import com.datastax.driver.core.Cluster; +import com.datastax.driver.core.ColumnDefinitions; +import com.datastax.driver.core.ConsistencyLevel; +import com.datastax.driver.core.Host; +import com.datastax.driver.core.HostDistance; +import com.datastax.driver.core.Metadata; +import com.datastax.driver.core.ResultSet; +import com.datastax.driver.core.Row; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.SimpleStatement; +import com.datastax.driver.core.Statement; +import com.datastax.driver.core.querybuilder.Insert; +import com.datastax.driver.core.querybuilder.QueryBuilder; +import com.datastax.driver.core.querybuilder.Select; +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DB; +import com.yahoo.ycsb.DBException; +import com.yahoo.ycsb.Status; + +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Cassandra 2.x CQL client. + * + * See {@code cassandra2/README.md} for details. + * + * @author cmatser + */ +public class CassandraCQLClient extends DB { + + private static Cluster cluster = null; + private static Session session = null; + + private static ConsistencyLevel readConsistencyLevel = ConsistencyLevel.ONE; + private static ConsistencyLevel writeConsistencyLevel = ConsistencyLevel.ONE; + + public static final String YCSB_KEY = "y_id"; + public static final String KEYSPACE_PROPERTY = "cassandra.keyspace"; + public static final String KEYSPACE_PROPERTY_DEFAULT = "ycsb"; + public static final String USERNAME_PROPERTY = "cassandra.username"; + public static final String PASSWORD_PROPERTY = "cassandra.password"; + + public static final String HOSTS_PROPERTY = "hosts"; + public static final String PORT_PROPERTY = "port"; + public static final String PORT_PROPERTY_DEFAULT = "9042"; + + public static final String READ_CONSISTENCY_LEVEL_PROPERTY = + "cassandra.readconsistencylevel"; + public static final String READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = "ONE"; + public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY = + "cassandra.writeconsistencylevel"; + public static final String WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT = "ONE"; + + public static final String MAX_CONNECTIONS_PROPERTY = + "cassandra.maxconnections"; + public static final String CORE_CONNECTIONS_PROPERTY = + "cassandra.coreconnections"; + public static final String CONNECT_TIMEOUT_MILLIS_PROPERTY = + "cassandra.connecttimeoutmillis"; + public static final String READ_TIMEOUT_MILLIS_PROPERTY = + "cassandra.readtimeoutmillis"; + + public static final String TRACING_PROPERTY = "cassandra.tracing"; + public static final String TRACING_PROPERTY_DEFAULT = "false"; + + /** + * Count the number of times initialized to teardown on the last + * {@link #cleanup()}. + */ + private static final AtomicInteger INIT_COUNT = new AtomicInteger(0); + + private static boolean debug = false; + + private static boolean trace = false; + + /** + * Initialize any state for this DB. Called once per DB instance; there is one + * DB instance per client thread. + */ + @Override + public void init() throws DBException { + + // Keep track of number of calls to init (for later cleanup) + INIT_COUNT.incrementAndGet(); + + // Synchronized so that we only have a single + // cluster/session instance for all the threads. + synchronized (INIT_COUNT) { + + // Check if the cluster has already been initialized + if (cluster != null) { + return; + } + + try { + + debug = + Boolean.parseBoolean(getProperties().getProperty("debug", "false")); + trace = Boolean.valueOf(getProperties().getProperty(TRACING_PROPERTY, TRACING_PROPERTY_DEFAULT)); + + String host = getProperties().getProperty(HOSTS_PROPERTY); + if (host == null) { + throw new DBException(String.format( + "Required property \"%s\" missing for CassandraCQLClient", + HOSTS_PROPERTY)); + } + String[] hosts = host.split(","); + String port = getProperties().getProperty(PORT_PROPERTY, PORT_PROPERTY_DEFAULT); + + String username = getProperties().getProperty(USERNAME_PROPERTY); + String password = getProperties().getProperty(PASSWORD_PROPERTY); + + String keyspace = getProperties().getProperty(KEYSPACE_PROPERTY, + KEYSPACE_PROPERTY_DEFAULT); + + readConsistencyLevel = ConsistencyLevel.valueOf( + getProperties().getProperty(READ_CONSISTENCY_LEVEL_PROPERTY, + READ_CONSISTENCY_LEVEL_PROPERTY_DEFAULT)); + writeConsistencyLevel = ConsistencyLevel.valueOf( + getProperties().getProperty(WRITE_CONSISTENCY_LEVEL_PROPERTY, + WRITE_CONSISTENCY_LEVEL_PROPERTY_DEFAULT)); + + if ((username != null) && !username.isEmpty()) { + cluster = Cluster.builder().withCredentials(username, password) + .withPort(Integer.valueOf(port)).addContactPoints(hosts).build(); + } else { + cluster = Cluster.builder().withPort(Integer.valueOf(port)) + .addContactPoints(hosts).build(); + } + + String maxConnections = getProperties().getProperty( + MAX_CONNECTIONS_PROPERTY); + if (maxConnections != null) { + cluster.getConfiguration().getPoolingOptions() + .setMaxConnectionsPerHost(HostDistance.LOCAL, + Integer.valueOf(maxConnections)); + } + + String coreConnections = getProperties().getProperty( + CORE_CONNECTIONS_PROPERTY); + if (coreConnections != null) { + cluster.getConfiguration().getPoolingOptions() + .setCoreConnectionsPerHost(HostDistance.LOCAL, + Integer.valueOf(coreConnections)); + } + + String connectTimoutMillis = getProperties().getProperty( + CONNECT_TIMEOUT_MILLIS_PROPERTY); + if (connectTimoutMillis != null) { + cluster.getConfiguration().getSocketOptions() + .setConnectTimeoutMillis(Integer.valueOf(connectTimoutMillis)); + } + + String readTimoutMillis = getProperties().getProperty( + READ_TIMEOUT_MILLIS_PROPERTY); + if (readTimoutMillis != null) { + cluster.getConfiguration().getSocketOptions() + .setReadTimeoutMillis(Integer.valueOf(readTimoutMillis)); + } + + Metadata metadata = cluster.getMetadata(); + System.err.printf("Connected to cluster: %s\n", + metadata.getClusterName()); + + for (Host discoveredHost : metadata.getAllHosts()) { + System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", + discoveredHost.getDatacenter(), discoveredHost.getAddress(), + discoveredHost.getRack()); + } + + session = cluster.connect(keyspace); + + } catch (Exception e) { + throw new DBException(e); + } + } // synchronized + } + + /** + * Cleanup any state for this DB. Called once per DB instance; there is one DB + * instance per client thread. + */ + @Override + public void cleanup() throws DBException { + synchronized (INIT_COUNT) { + final int curInitCount = INIT_COUNT.decrementAndGet(); + if (curInitCount <= 0) { + session.close(); + cluster.close(); + cluster = null; + session = null; + } + if (curInitCount < 0) { + // This should never happen. + throw new DBException( + String.format("initCount is negative: %d", curInitCount)); + } + } + } + + /** + * Read a record from the database. Each field/value pair from the result will + * be stored in a HashMap. + * + * @param table + * The name of the table + * @param key + * The record key of the record to read. + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A HashMap of field/value pairs for the result + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status read(String table, String key, Set fields, + Map result) { + try { + Statement stmt; + Select.Builder selectBuilder; + + if (fields == null) { + selectBuilder = QueryBuilder.select().all(); + } else { + selectBuilder = QueryBuilder.select(); + for (String col : fields) { + ((Select.Selection) selectBuilder).column(col); + } + } + + stmt = selectBuilder.from(table).where(QueryBuilder.eq(YCSB_KEY, key)) + .limit(1); + stmt.setConsistencyLevel(readConsistencyLevel); + + if (debug) { + System.out.println(stmt.toString()); + } + if (trace) { + stmt.enableTracing(); + } + + ResultSet rs = session.execute(stmt); + + if (rs.isExhausted()) { + return Status.NOT_FOUND; + } + + // Should be only 1 row + Row row = rs.one(); + ColumnDefinitions cd = row.getColumnDefinitions(); + + for (ColumnDefinitions.Definition def : cd) { + ByteBuffer val = row.getBytesUnsafe(def.getName()); + if (val != null) { + result.put(def.getName(), new ByteArrayByteIterator(val.array())); + } else { + result.put(def.getName(), null); + } + } + + return Status.OK; + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Error reading key: " + key); + return Status.ERROR; + } + + } + + /** + * Perform a range scan for a set of records in the database. Each field/value + * pair from the result will be stored in a HashMap. + * + * Cassandra CQL uses "token" method for range scan which doesn't always yield + * intuitive results. + * + * @param table + * The name of the table + * @param startkey + * The record key of the first record to read. + * @param recordcount + * The number of records to read + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A Vector of HashMaps, where each HashMap is a set field/value + * pairs for one record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + + try { + Statement stmt; + Select.Builder selectBuilder; + + if (fields == null) { + selectBuilder = QueryBuilder.select().all(); + } else { + selectBuilder = QueryBuilder.select(); + for (String col : fields) { + ((Select.Selection) selectBuilder).column(col); + } + } + + stmt = selectBuilder.from(table); + + // The statement builder is not setup right for tokens. + // So, we need to build it manually. + String initialStmt = stmt.toString(); + StringBuilder scanStmt = new StringBuilder(); + scanStmt.append(initialStmt.substring(0, initialStmt.length() - 1)); + scanStmt.append(" WHERE "); + scanStmt.append(QueryBuilder.token(YCSB_KEY)); + scanStmt.append(" >= "); + scanStmt.append("token('"); + scanStmt.append(startkey); + scanStmt.append("')"); + scanStmt.append(" LIMIT "); + scanStmt.append(recordcount); + + stmt = new SimpleStatement(scanStmt.toString()); + stmt.setConsistencyLevel(readConsistencyLevel); + + if (debug) { + System.out.println(stmt.toString()); + } + if (trace) { + stmt.enableTracing(); + } + + ResultSet rs = session.execute(stmt); + + HashMap tuple; + while (!rs.isExhausted()) { + Row row = rs.one(); + tuple = new HashMap(); + + ColumnDefinitions cd = row.getColumnDefinitions(); + + for (ColumnDefinitions.Definition def : cd) { + ByteBuffer val = row.getBytesUnsafe(def.getName()); + if (val != null) { + tuple.put(def.getName(), new ByteArrayByteIterator(val.array())); + } else { + tuple.put(def.getName(), null); + } + } + + result.add(tuple); + } + + return Status.OK; + + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Error scanning with startkey: " + startkey); + return Status.ERROR; + } + + } + + /** + * Update a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key, overwriting any existing values with the same field name. + * + * @param table + * The name of the table + * @param key + * The record key of the record to write. + * @param values + * A HashMap of field/value pairs to update in the record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status update(String table, String key, + Map values) { + // Insert and updates provide the same functionality + return insert(table, key, values); + } + + /** + * Insert a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key. + * + * @param table + * The name of the table + * @param key + * The record key of the record to insert. + * @param values + * A HashMap of field/value pairs to insert in the record + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status insert(String table, String key, + Map values) { + + try { + Insert insertStmt = QueryBuilder.insertInto(table); + + // Add key + insertStmt.value(YCSB_KEY, key); + + // Add fields + for (Map.Entry entry : values.entrySet()) { + Object value; + ByteIterator byteIterator = entry.getValue(); + value = byteIterator.toString(); + + insertStmt.value(entry.getKey(), value); + } + + insertStmt.setConsistencyLevel(writeConsistencyLevel); + + if (debug) { + System.out.println(insertStmt.toString()); + } + if (trace) { + insertStmt.enableTracing(); + } + + session.execute(insertStmt); + + return Status.OK; + } catch (Exception e) { + e.printStackTrace(); + } + + return Status.ERROR; + } + + /** + * Delete a record from the database. + * + * @param table + * The name of the table + * @param key + * The record key of the record to delete. + * @return Zero on success, a non-zero error code on error + */ + @Override + public Status delete(String table, String key) { + + try { + Statement stmt; + + stmt = QueryBuilder.delete().from(table) + .where(QueryBuilder.eq(YCSB_KEY, key)); + stmt.setConsistencyLevel(writeConsistencyLevel); + + if (debug) { + System.out.println(stmt.toString()); + } + if (trace) { + stmt.enableTracing(); + } + + session.execute(stmt); + + return Status.OK; + } catch (Exception e) { + e.printStackTrace(); + System.out.println("Error deleting key: " + key); + } + + return Status.ERROR; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.CassandraCQLClient.scan` reads without synchronization from `db.CassandraCQLClient.com.yahoo.ycsb.db.CassandraCQLClient.debug`. Potentially races with write in method `CassandraCQLClient.init()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Status CassandraCQLClient.scan(String,String,int,Set,Vector) + +### Procedure Id: +com.yahoo.ycsb.db.CassandraCQLClient.scan(java.lang.String,java.lang.String,int,java.util.Set,java.u.a6b8e9ca1face0d0eb3e4b578de5f521 + +### File: +cassandra/src/main/java/com/yahoo/ycsb/db/CassandraCQLClient.java + +### Key: +CassandraCQLClient.java|scan|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +16d94574f43438249fbe45d4242dd0be + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7970/instruction.md b/inferredbugs-7970/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..226d2a02d9861e874e4461153b564f272dd991ac --- /dev/null +++ b/inferredbugs-7970/instruction.md @@ -0,0 +1,530 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2016 YCSB contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You + * may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. See accompanying + * LICENSE file. + */ +package com.yahoo.ycsb.db; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Iterator; +import java.util.List; +import java.util.Map.Entry; +import java.util.Properties; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.hbase.HBaseConfiguration; +import org.apache.hadoop.hbase.util.Bytes; + +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.ExecutionException; + +import com.google.bigtable.repackaged.com.google.protobuf.ByteString; +import com.google.bigtable.v2.Column; +import com.google.bigtable.v2.Family; +import com.google.bigtable.v2.MutateRowRequest; +import com.google.bigtable.v2.Mutation; +import com.google.bigtable.v2.ReadRowsRequest; +import com.google.bigtable.v2.Row; +import com.google.bigtable.v2.RowFilter; +import com.google.bigtable.v2.RowRange; +import com.google.bigtable.v2.RowSet; +import com.google.bigtable.v2.Mutation.DeleteFromRow; +import com.google.bigtable.v2.Mutation.SetCell; +import com.google.bigtable.v2.RowFilter.Chain.Builder; +import com.google.cloud.bigtable.config.BigtableOptions; +import com.google.cloud.bigtable.grpc.BigtableDataClient; +import com.google.cloud.bigtable.grpc.BigtableSession; +import com.google.cloud.bigtable.grpc.BigtableTableName; +import com.google.cloud.bigtable.grpc.async.AsyncExecutor; +import com.google.cloud.bigtable.grpc.async.BulkMutation; +import com.google.cloud.bigtable.hbase.BigtableOptionsFactory; +import com.google.cloud.bigtable.util.ByteStringer; +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DBException; +import com.yahoo.ycsb.Status; + +/** + * Google Bigtable Proto client for YCSB framework. + * + * Bigtable offers two APIs. These include a native Protobuf GRPC API as well as + * an HBase API wrapper for the GRPC API. This client implements the Protobuf + * API to test the underlying calls wrapped up in the HBase API. To use the + * HBase API, see the hbase10 client binding. + */ +public class GoogleBigtableClient extends com.yahoo.ycsb.DB { + public static final Charset UTF8_CHARSET = Charset.forName("UTF8"); + + /** Property names for the CLI. */ + private static final String ASYNC_MUTATOR_MAX_MEMORY = "mutatorMaxMemory"; + private static final String ASYNC_MAX_INFLIGHT_RPCS = "mutatorMaxInflightRPCs"; + private static final String CLIENT_SIDE_BUFFERING = "clientbuffering"; + + /** Tracks running thread counts so we know when to close the session. */ + private static int threadCount = 0; + + /** This will load the hbase-site.xml config file and/or store CLI options. */ + private static final Configuration CONFIG = HBaseConfiguration.create(); + + /** Print debug information to standard out. */ + private boolean debug = false; + + /** Global Bigtable native API objects. */ + private static BigtableOptions options; + private static BigtableSession session; + + /** Thread loacal Bigtable native API objects. */ + private BigtableDataClient client; + private AsyncExecutor asyncExecutor; + + /** The column family use for the workload. */ + private byte[] columnFamilyBytes; + + /** Cache for the last table name/ID to avoid byte conversions. */ + private String lastTable = ""; + private byte[] lastTableBytes; + + /** + * If true, buffer mutations on the client. For measuring insert/update/delete + * latencies, client side buffering should be disabled. + */ + private boolean clientSideBuffering = false; + + private BulkMutation bulkMutation; + + @Override + public void init() throws DBException { + Properties props = getProperties(); + + // Defaults the user can override if needed + if (getProperties().containsKey(ASYNC_MUTATOR_MAX_MEMORY)) { + CONFIG.set(BigtableOptionsFactory.BIGTABLE_BUFFERED_MUTATOR_MAX_MEMORY_KEY, + getProperties().getProperty(ASYNC_MUTATOR_MAX_MEMORY)); + } + if (getProperties().containsKey(ASYNC_MAX_INFLIGHT_RPCS)) { + CONFIG.set(BigtableOptionsFactory.BIGTABLE_BULK_MAX_ROW_KEY_COUNT, + getProperties().getProperty(ASYNC_MAX_INFLIGHT_RPCS)); + } + // make it easy on ourselves by copying all CLI properties into the config object. + final Iterator> it = props.entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it.next(); + CONFIG.set((String)entry.getKey(), (String)entry.getValue()); + } + + clientSideBuffering = getProperties().getProperty(CLIENT_SIDE_BUFFERING, "false") + .equals("true") ? true : false; + + System.err.println("Running Google Bigtable with Proto API" + + (clientSideBuffering ? " and client side buffering." : ".")); + + synchronized (CONFIG) { + ++threadCount; + if (session == null) { + try { + options = BigtableOptionsFactory.fromConfiguration(CONFIG); + session = new BigtableSession(options); + // important to instantiate the first client here, otherwise the + // other threads may receive an NPE from the options when they try + // to read the cluster name. + client = session.getDataClient(); + } catch (IOException e) { + throw new DBException("Error loading options from config: ", e); + } + } else { + client = session.getDataClient(); + } + + if (clientSideBuffering) { + asyncExecutor = session.createAsyncExecutor(); + } + } + + if ((getProperties().getProperty("debug") != null) + && (getProperties().getProperty("debug").compareTo("true") == 0)) { + debug = true; + } + + final String columnFamily = getProperties().getProperty("columnfamily"); + if (columnFamily == null) { + System.err.println("Error, must specify a columnfamily for Bigtable table"); + throw new DBException("No columnfamily specified"); + } + columnFamilyBytes = Bytes.toBytes(columnFamily); + } + + @Override + public void cleanup() throws DBException { + if (bulkMutation != null) { + try { + bulkMutation.flush(); + } catch(RuntimeException e){ + throw new DBException(e); + } + } + if (asyncExecutor != null) { + try { + asyncExecutor.flush(); + } catch (IOException e) { + throw new DBException(e); + } + } + synchronized (CONFIG) { + --threadCount; + if (threadCount <= 0) { + try { + session.close(); + } catch (IOException e) { + throw new DBException(e); + } + } + } + } + + @Override + public Status read(String table, String key, Set fields, + Map result) { + if (debug) { + System.out.println("Doing read from Bigtable columnfamily " + + new String(columnFamilyBytes)); + System.out.println("Doing read for key: " + key); + } + + setTable(table); + + RowFilter filter = RowFilter.newBuilder() + .setFamilyNameRegexFilterBytes(ByteStringer.wrap(columnFamilyBytes)) + .build(); + if (fields != null && fields.size() > 0) { + Builder filterChain = RowFilter.Chain.newBuilder(); + filterChain.addFilters(filter); + filterChain.addFilters(RowFilter.newBuilder() + .setCellsPerColumnLimitFilter(1) + .build()); + int count = 0; + // usually "field#" so pre-alloc + final StringBuilder regex = new StringBuilder(fields.size() * 6); + for (final String field : fields) { + if (count++ > 0) { + regex.append("|"); + } + regex.append(field); + } + filterChain.addFilters(RowFilter.newBuilder() + .setColumnQualifierRegexFilter( + ByteStringer.wrap(regex.toString().getBytes()))).build(); + filter = RowFilter.newBuilder().setChain(filterChain.build()).build(); + } + + final ReadRowsRequest.Builder rrr = ReadRowsRequest.newBuilder() + .setTableNameBytes(ByteStringer.wrap(lastTableBytes)) + .setFilter(filter) + .setRows(RowSet.newBuilder() + .addRowKeys(ByteStringer.wrap(key.getBytes()))); + + List rows; + try { + rows = client.readRowsAsync(rrr.build()).get(); + if (rows == null || rows.isEmpty()) { + return Status.NOT_FOUND; + } + for (final Row row : rows) { + for (final Family family : row.getFamiliesList()) { + if (Arrays.equals(family.getNameBytes().toByteArray(), columnFamilyBytes)) { + for (final Column column : family.getColumnsList()) { + // we should only have a single cell per column + result.put(column.getQualifier().toString(UTF8_CHARSET), + new ByteArrayByteIterator(column.getCells(0).getValue().toByteArray())); + if (debug) { + System.out.println( + "Result for field: " + column.getQualifier().toString(UTF8_CHARSET) + + " is: " + column.getCells(0).getValue().toString(UTF8_CHARSET)); + } + } + } + } + } + + return Status.OK; + } catch (InterruptedException e) { + System.err.println("Interrupted during get: " + e); + Thread.currentThread().interrupt(); + return Status.ERROR; + } catch (ExecutionException e) { + System.err.println("Exception during get: " + e); + return Status.ERROR; + } + } + + @Override + public Status scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + setTable(table); + + RowFilter filter = RowFilter.newBuilder() + .setFamilyNameRegexFilterBytes(ByteStringer.wrap(columnFamilyBytes)) + .build(); + if (fields != null && fields.size() > 0) { + Builder filterChain = RowFilter.Chain.newBuilder(); + filterChain.addFilters(filter); + filterChain.addFilters(RowFilter.newBuilder() + .setCellsPerColumnLimitFilter(1) + .build()); + int count = 0; + // usually "field#" so pre-alloc + final StringBuilder regex = new StringBuilder(fields.size() * 6); + for (final String field : fields) { + if (count++ > 0) { + regex.append("|"); + } + regex.append(field); + } + filterChain.addFilters(RowFilter.newBuilder() + .setColumnQualifierRegexFilter( + ByteStringer.wrap(regex.toString().getBytes()))).build(); + filter = RowFilter.newBuilder().setChain(filterChain.build()).build(); + } + + final RowRange range = RowRange.newBuilder() + .setStartKeyClosed(ByteStringer.wrap(startkey.getBytes())) + .build(); + + final RowSet rowSet = RowSet.newBuilder() + .addRowRanges(range) + .build(); + + final ReadRowsRequest.Builder rrr = ReadRowsRequest.newBuilder() + .setTableNameBytes(ByteStringer.wrap(lastTableBytes)) + .setFilter(filter) + .setRows(rowSet); + + List rows; + try { + rows = client.readRowsAsync(rrr.build()).get(); + if (rows == null || rows.isEmpty()) { + return Status.NOT_FOUND; + } + int numResults = 0; + + for (final Row row : rows) { + final HashMap rowResult = + new HashMap(fields != null ? fields.size() : 10); + + for (final Family family : row.getFamiliesList()) { + if (Arrays.equals(family.getNameBytes().toByteArray(), columnFamilyBytes)) { + for (final Column column : family.getColumnsList()) { + // we should only have a single cell per column + rowResult.put(column.getQualifier().toString(UTF8_CHARSET), + new ByteArrayByteIterator(column.getCells(0).getValue().toByteArray())); + if (debug) { + System.out.println( + "Result for field: " + column.getQualifier().toString(UTF8_CHARSET) + + " is: " + column.getCells(0).getValue().toString(UTF8_CHARSET)); + } + } + } + } + + result.add(rowResult); + + numResults++; + if (numResults >= recordcount) {// if hit recordcount, bail out + break; + } + } + return Status.OK; + } catch (InterruptedException e) { + System.err.println("Interrupted during scan: " + e); + Thread.currentThread().interrupt(); + return Status.ERROR; + } catch (ExecutionException e) { + System.err.println("Exception during scan: " + e); + return Status.ERROR; + } + } + + @Override + public Status update(String table, String key, + Map values) { + if (debug) { + System.out.println("Setting up put for key: " + key); + } + + setTable(table); + + final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder(); + rowMutation.setRowKey(ByteString.copyFromUtf8(key)); + rowMutation.setTableNameBytes(ByteStringer.wrap(lastTableBytes)); + + for (final Entry entry : values.entrySet()) { + final Mutation.Builder mutationBuilder = rowMutation.addMutationsBuilder(); + final SetCell.Builder setCellBuilder = mutationBuilder.getSetCellBuilder(); + + setCellBuilder.setFamilyNameBytes(ByteStringer.wrap(columnFamilyBytes)); + setCellBuilder.setColumnQualifier(ByteStringer.wrap(entry.getKey().getBytes())); + setCellBuilder.setValue(ByteStringer.wrap(entry.getValue().toArray())); + + // Bigtable uses a 1ms granularity + setCellBuilder.setTimestampMicros(System.currentTimeMillis() * 1000); + } + + try { + if (clientSideBuffering) { + bulkMutation.add(rowMutation.build()); + } else { + client.mutateRow(rowMutation.build()); + } + return Status.OK; + } catch (RuntimeException e) { + System.err.println("Failed to insert key: " + key + " " + e.getMessage()); + return Status.ERROR; + } + } + + @Override + public Status insert(String table, String key, + Map values) { + return update(table, key, values); + } + + @Override + public Status delete(String table, String key) { + if (debug) { + System.out.println("Doing delete for key: " + key); + } + + setTable(table); + + final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder() + .setRowKey(ByteString.copyFromUtf8(key)) + .setTableNameBytes(ByteStringer.wrap(lastTableBytes)); + rowMutation.addMutationsBuilder().setDeleteFromRow( + DeleteFromRow.getDefaultInstance()); + + try { + if (clientSideBuffering) { + bulkMutation.add(rowMutation.build()); + } else { + client.mutateRow(rowMutation.build()); + } + return Status.OK; + } catch (RuntimeException e) { + System.err.println("Failed to delete key: " + key + " " + e.getMessage()); + return Status.ERROR; + } + } + + /** + * Little helper to set the table byte array. If it's different than the last + * table we reset the byte array. Otherwise we just use the existing array. + * @param table The table we're operating against + */ + private void setTable(final String table) { + if (!lastTable.equals(table)) { + lastTable = table; + BigtableTableName tableName = options + .getInstanceName() + .toTableName(table); + lastTableBytes = tableName + .toString() + .getBytes(); + synchronized(this) { + if (bulkMutation != null) { + bulkMutation.flush(); + } + bulkMutation = session.createBulkMutation(tableName, asyncExecutor); + } + } + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.GoogleBigtableClient.cleanup` reads without synchronization from `this.com.yahoo.ycsb.db.GoogleBigtableClient.asyncExecutor`. Potentially races with write in method `GoogleBigtableClient.init()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GoogleBigtableClient.cleanup() + +### Procedure Id: +com.yahoo.ycsb.db.GoogleBigtableClient.cleanup():void.f579963d8366e91b27bd84ebbf691525 + +### File: +googlebigtable/src/main/java/com/yahoo/ycsb/db/GoogleBigtableClient.java + +### Key: +GoogleBigtableClient.java|cleanup|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +3bf01f6fda4c5334870d72f77c2df321 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7971/instruction.md b/inferredbugs-7971/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..59a0abafa303c162c7374e2aa5a629c5b05fd720 --- /dev/null +++ b/inferredbugs-7971/instruction.md @@ -0,0 +1,938 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2010 Yahoo! Inc., Copyright (c) 2016 YCSB contributors. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you + * may not use this file except in compliance with the License. You + * may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing + * permissions and limitations under the License. See accompanying + * LICENSE file. + */ + +package com.yahoo.ycsb.workloads; + +import java.util.Properties; + +import com.yahoo.ycsb.*; +import com.yahoo.ycsb.generator.AcknowledgedCounterGenerator; +import com.yahoo.ycsb.generator.ConstantIntegerGenerator; +import com.yahoo.ycsb.generator.CounterGenerator; +import com.yahoo.ycsb.generator.DiscreteGenerator; +import com.yahoo.ycsb.generator.ExponentialGenerator; +import com.yahoo.ycsb.generator.HistogramGenerator; +import com.yahoo.ycsb.generator.HotspotIntegerGenerator; +import com.yahoo.ycsb.generator.NumberGenerator; +import com.yahoo.ycsb.generator.ScrambledZipfianGenerator; +import com.yahoo.ycsb.generator.SequentialGenerator; +import com.yahoo.ycsb.generator.SkewedLatestGenerator; +import com.yahoo.ycsb.generator.UniformIntegerGenerator; +import com.yahoo.ycsb.generator.ZipfianGenerator; +import com.yahoo.ycsb.measurements.Measurements; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Vector; + + +/** + * The core benchmark scenario. Represents a set of clients doing simple CRUD operations. The + * relative proportion of different kinds of operations, and other properties of the workload, + * are controlled by parameters specified at runtime. + * + * Properties to control the client: + *
      + *
    • fieldcount: the number of fields in a record (default: 10) + *
    • fieldlength: the size of each field (default: 100) + *
    • readallfields: should reads read all fields (true) or just one (false) (default: true) + *
    • writeallfields: should updates and read/modify/writes update all fields (true) or just + * one (false) (default: false) + *
    • readproportion: what proportion of operations should be reads (default: 0.95) + *
    • updateproportion: what proportion of operations should be updates (default: 0.05) + *
    • insertproportion: what proportion of operations should be inserts (default: 0) + *
    • scanproportion: what proportion of operations should be scans (default: 0) + *
    • readmodifywriteproportion: what proportion of operations should be read a record, + * modify it, write it back (default: 0) + *
    • requestdistribution: what distribution should be used to select the records to operate + * on - uniform, zipfian, hotspot, sequential, exponential or latest (default: uniform) + *
    • maxscanlength: for scans, what is the maximum number of records to scan (default: 1000) + *
    • scanlengthdistribution: for scans, what distribution should be used to choose the + * number of records to scan, for each scan, between 1 and maxscanlength (default: uniform) + *
    • insertstart: for parallel loads and runs, defines the starting record for this + * YCSB instance (default: 0) + *
    • insertcount: for parallel loads and runs, defines the number of records for this + * YCSB instance (default: recordcount) + *
    • zeropadding: for generating a record sequence compatible with string sort order by + * 0 padding the record number. Controls the number of 0s to use for padding. (default: 1) + * For example for row 5, with zeropadding=1 you get 'user5' key and with zeropading=8 you get + * 'user00000005' key. In order to see its impact, zeropadding needs to be bigger than number of + * digits in the record number. + *
    • insertorder: should records be inserted in order by key ("ordered"), or in hashed + * order ("hashed") (default: hashed) + *
    + */ +public class CoreWorkload extends Workload { + /** + * The name of the database table to run queries against. + */ + public static final String TABLENAME_PROPERTY = "table"; + + /** + * The default name of the database table to run queries against. + */ + public static final String TABLENAME_PROPERTY_DEFAULT = "usertable"; + + public static String table; + + + /** + * The name of the property for the number of fields in a record. + */ + public static final String FIELD_COUNT_PROPERTY = "fieldcount"; + + /** + * Default number of fields in a record. + */ + public static final String FIELD_COUNT_PROPERTY_DEFAULT = "10"; + + int fieldcount; + + private List fieldnames; + + /** + * The name of the property for the field length distribution. Options are "uniform", "zipfian" + * (favouring short records), "constant", and "histogram". + * + * If "uniform", "zipfian" or "constant", the maximum field length will be that specified by the + * fieldlength property. If "histogram", then the histogram will be read from the filename + * specified in the "fieldlengthhistogram" property. + */ + public static final String FIELD_LENGTH_DISTRIBUTION_PROPERTY = "fieldlengthdistribution"; + + /** + * The default field length distribution. + */ + public static final String FIELD_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT = "constant"; + + /** + * The name of the property for the length of a field in bytes. + */ + public static final String FIELD_LENGTH_PROPERTY = "fieldlength"; + + /** + * The default maximum length of a field in bytes. + */ + public static final String FIELD_LENGTH_PROPERTY_DEFAULT = "100"; + + /** + * The name of a property that specifies the filename containing the field length histogram (only + * used if fieldlengthdistribution is "histogram"). + */ + public static final String FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY = "fieldlengthhistogram"; + + /** + * The default filename containing a field length histogram. + */ + public static final String FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY_DEFAULT = "hist.txt"; + + /** + * Generator object that produces field lengths. The value of this depends on the properties that + * start with "FIELD_LENGTH_". + */ + NumberGenerator fieldlengthgenerator; + + /** + * The name of the property for deciding whether to read one field (false) or all fields (true) of + * a record. + */ + public static final String READ_ALL_FIELDS_PROPERTY = "readallfields"; + + /** + * The default value for the readallfields property. + */ + public static final String READ_ALL_FIELDS_PROPERTY_DEFAULT = "true"; + + boolean readallfields; + + /** + * The name of the property for deciding whether to write one field (false) or all fields (true) + * of a record. + */ + public static final String WRITE_ALL_FIELDS_PROPERTY = "writeallfields"; + + /** + * The default value for the writeallfields property. + */ + public static final String WRITE_ALL_FIELDS_PROPERTY_DEFAULT = "false"; + + boolean writeallfields; + + + /** + * The name of the property for deciding whether to check all returned + * data against the formation template to ensure data integrity. + */ + public static final String DATA_INTEGRITY_PROPERTY = "dataintegrity"; + + /** + * The default value for the dataintegrity property. + */ + public static final String DATA_INTEGRITY_PROPERTY_DEFAULT = "false"; + + /** + * Set to true if want to check correctness of reads. Must also + * be set to true during loading phase to function. + */ + private boolean dataintegrity; + + /** + * The name of the property for the proportion of transactions that are reads. + */ + public static final String READ_PROPORTION_PROPERTY = "readproportion"; + + /** + * The default proportion of transactions that are reads. + */ + public static final String READ_PROPORTION_PROPERTY_DEFAULT = "0.95"; + + /** + * The name of the property for the proportion of transactions that are updates. + */ + public static final String UPDATE_PROPORTION_PROPERTY = "updateproportion"; + + /** + * The default proportion of transactions that are updates. + */ + public static final String UPDATE_PROPORTION_PROPERTY_DEFAULT = "0.05"; + + /** + * The name of the property for the proportion of transactions that are inserts. + */ + public static final String INSERT_PROPORTION_PROPERTY = "insertproportion"; + + /** + * The default proportion of transactions that are inserts. + */ + public static final String INSERT_PROPORTION_PROPERTY_DEFAULT = "0.0"; + + /** + * The name of the property for the proportion of transactions that are scans. + */ + public static final String SCAN_PROPORTION_PROPERTY = "scanproportion"; + + /** + * The default proportion of transactions that are scans. + */ + public static final String SCAN_PROPORTION_PROPERTY_DEFAULT = "0.0"; + + /** + * The name of the property for the proportion of transactions that are read-modify-write. + */ + public static final String READMODIFYWRITE_PROPORTION_PROPERTY = "readmodifywriteproportion"; + + /** + * The default proportion of transactions that are scans. + */ + public static final String READMODIFYWRITE_PROPORTION_PROPERTY_DEFAULT = "0.0"; + + /** + * The name of the property for the the distribution of requests across the keyspace. Options are + * "uniform", "zipfian" and "latest" + */ + public static final String REQUEST_DISTRIBUTION_PROPERTY = "requestdistribution"; + + /** + * The default distribution of requests across the keyspace. + */ + public static final String REQUEST_DISTRIBUTION_PROPERTY_DEFAULT = "uniform"; + + /** + * The name of the property for adding zero padding to record numbers in order to match + * string sort order. Controls the number of 0s to left pad with. + */ + public static final String ZERO_PADDING_PROPERTY = "zeropadding"; + + /** + * The default zero padding value. Matches integer sort order + */ + public static final String ZERO_PADDING_PROPERTY_DEFAULT = "1"; + + + /** + * The name of the property for the max scan length (number of records). + */ + public static final String MAX_SCAN_LENGTH_PROPERTY = "maxscanlength"; + + /** + * The default max scan length. + */ + public static final String MAX_SCAN_LENGTH_PROPERTY_DEFAULT = "1000"; + + /** + * The name of the property for the scan length distribution. Options are "uniform" and "zipfian" + * (favoring short scans) + */ + public static final String SCAN_LENGTH_DISTRIBUTION_PROPERTY = "scanlengthdistribution"; + + /** + * The default max scan length. + */ + public static final String SCAN_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT = "uniform"; + + /** + * The name of the property for the order to insert records. Options are "ordered" or "hashed" + */ + public static final String INSERT_ORDER_PROPERTY = "insertorder"; + + /** + * Default insert order. + */ + public static final String INSERT_ORDER_PROPERTY_DEFAULT = "hashed"; + + /** + * Percentage data items that constitute the hot set. + */ + public static final String HOTSPOT_DATA_FRACTION = "hotspotdatafraction"; + + /** + * Default value of the size of the hot set. + */ + public static final String HOTSPOT_DATA_FRACTION_DEFAULT = "0.2"; + + /** + * Percentage operations that access the hot set. + */ + public static final String HOTSPOT_OPN_FRACTION = "hotspotopnfraction"; + + /** + * Default value of the percentage operations accessing the hot set. + */ + public static final String HOTSPOT_OPN_FRACTION_DEFAULT = "0.8"; + + /** + * How many times to retry when insertion of a single item to a DB fails. + */ + public static final String INSERTION_RETRY_LIMIT = "core_workload_insertion_retry_limit"; + public static final String INSERTION_RETRY_LIMIT_DEFAULT = "0"; + + /** + * On average, how long to wait between the retries, in seconds. + */ + public static final String INSERTION_RETRY_INTERVAL = "core_workload_insertion_retry_interval"; + public static final String INSERTION_RETRY_INTERVAL_DEFAULT = "3"; + + NumberGenerator keysequence; + + DiscreteGenerator operationchooser; + + NumberGenerator keychooser; + + NumberGenerator fieldchooser; + + AcknowledgedCounterGenerator transactioninsertkeysequence; + + NumberGenerator scanlength; + + boolean orderedinserts; + + int recordcount; + int zeropadding; + + int insertionRetryLimit; + int insertionRetryInterval; + + private Measurements _measurements = Measurements.getMeasurements(); + + protected static NumberGenerator getFieldLengthGenerator(Properties p) throws WorkloadException { + NumberGenerator fieldlengthgenerator; + String fieldlengthdistribution = p.getProperty( + FIELD_LENGTH_DISTRIBUTION_PROPERTY, FIELD_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT); + int fieldlength = + Integer.parseInt(p.getProperty(FIELD_LENGTH_PROPERTY, FIELD_LENGTH_PROPERTY_DEFAULT)); + String fieldlengthhistogram = p.getProperty( + FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY, FIELD_LENGTH_HISTOGRAM_FILE_PROPERTY_DEFAULT); + if (fieldlengthdistribution.compareTo("constant") == 0) { + fieldlengthgenerator = new ConstantIntegerGenerator(fieldlength); + } else if (fieldlengthdistribution.compareTo("uniform") == 0) { + fieldlengthgenerator = new UniformIntegerGenerator(1, fieldlength); + } else if (fieldlengthdistribution.compareTo("zipfian") == 0) { + fieldlengthgenerator = new ZipfianGenerator(1, fieldlength); + } else if (fieldlengthdistribution.compareTo("histogram") == 0) { + try { + fieldlengthgenerator = new HistogramGenerator(fieldlengthhistogram); + } catch (IOException e) { + throw new WorkloadException( + "Couldn't read field length histogram file: " + fieldlengthhistogram, e); + } + } else { + throw new WorkloadException( + "Unknown field length distribution \"" + fieldlengthdistribution + "\""); + } + return fieldlengthgenerator; + } + + /** + * Initialize the scenario. + * Called once, in the main client thread, before any operations are started. + */ + @Override + public void init(Properties p) throws WorkloadException { + table = p.getProperty(TABLENAME_PROPERTY, TABLENAME_PROPERTY_DEFAULT); + + fieldcount = + Integer.parseInt(p.getProperty(FIELD_COUNT_PROPERTY, FIELD_COUNT_PROPERTY_DEFAULT)); + fieldnames = new ArrayList(); + for (int i = 0; i < fieldcount; i++) { + fieldnames.add("field" + i); + } + fieldlengthgenerator = CoreWorkload.getFieldLengthGenerator(p); + + recordcount = + Integer.parseInt(p.getProperty(Client.RECORD_COUNT_PROPERTY, Client.DEFAULT_RECORD_COUNT)); + if (recordcount == 0) { + recordcount = Integer.MAX_VALUE; + } + String requestdistrib = + p.getProperty(REQUEST_DISTRIBUTION_PROPERTY, REQUEST_DISTRIBUTION_PROPERTY_DEFAULT); + int maxscanlength = + Integer.parseInt(p.getProperty(MAX_SCAN_LENGTH_PROPERTY, MAX_SCAN_LENGTH_PROPERTY_DEFAULT)); + String scanlengthdistrib = + p.getProperty(SCAN_LENGTH_DISTRIBUTION_PROPERTY, SCAN_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT); + + int insertstart = + Integer.parseInt(p.getProperty(INSERT_START_PROPERTY, INSERT_START_PROPERTY_DEFAULT)); + int insertcount = + Integer.parseInt(p.getProperty(INSERT_COUNT_PROPERTY, String.valueOf(recordcount - insertstart))); + // Confirm valid values for insertstart and insertcount in relation to recordcount + if (recordcount < (insertstart + insertcount)) { + System.err.println("Invalid combination of insertstart, insertcount and recordcount."); + System.err.println("recordcount must be bigger than insertstart + insertcount."); + System.exit(-1); + } + zeropadding = + Integer.parseInt(p.getProperty(ZERO_PADDING_PROPERTY, ZERO_PADDING_PROPERTY_DEFAULT)); + + readallfields = Boolean.parseBoolean( + p.getProperty(READ_ALL_FIELDS_PROPERTY, READ_ALL_FIELDS_PROPERTY_DEFAULT)); + writeallfields = Boolean.parseBoolean( + p.getProperty(WRITE_ALL_FIELDS_PROPERTY, WRITE_ALL_FIELDS_PROPERTY_DEFAULT)); + + dataintegrity = Boolean.parseBoolean( + p.getProperty(DATA_INTEGRITY_PROPERTY, DATA_INTEGRITY_PROPERTY_DEFAULT)); + // Confirm that fieldlengthgenerator returns a constant if data + // integrity check requested. + if (dataintegrity && !(p.getProperty( + FIELD_LENGTH_DISTRIBUTION_PROPERTY, + FIELD_LENGTH_DISTRIBUTION_PROPERTY_DEFAULT)).equals("constant")) { + System.err.println("Must have constant field size to check data integrity."); + System.exit(-1); + } + + if (p.getProperty(INSERT_ORDER_PROPERTY, INSERT_ORDER_PROPERTY_DEFAULT).compareTo("hashed") == 0) { + orderedinserts = false; + } else if (requestdistrib.compareTo("exponential") == 0) { + double percentile = Double.parseDouble(p.getProperty( + ExponentialGenerator.EXPONENTIAL_PERCENTILE_PROPERTY, + ExponentialGenerator.EXPONENTIAL_PERCENTILE_DEFAULT)); + double frac = Double.parseDouble(p.getProperty( + ExponentialGenerator.EXPONENTIAL_FRAC_PROPERTY, + ExponentialGenerator.EXPONENTIAL_FRAC_DEFAULT)); + keychooser = new ExponentialGenerator(percentile, recordcount * frac); + } else { + orderedinserts = true; + } + + keysequence = new CounterGenerator(insertstart); + operationchooser = createOperationGenerator(p); + + transactioninsertkeysequence = new AcknowledgedCounterGenerator(recordcount); + if (requestdistrib.compareTo("uniform") == 0) { + keychooser = new UniformIntegerGenerator(insertstart, insertstart + insertcount - 1); + } else if (requestdistrib.compareTo("sequential") == 0) { + keychooser = new SequentialGenerator(insertstart, insertstart + insertcount - 1); + }else if (requestdistrib.compareTo("zipfian") == 0) { + // it does this by generating a random "next key" in part by taking the modulus over the + // number of keys. + // If the number of keys changes, this would shift the modulus, and we don't want that to + // change which keys are popular so we'll actually construct the scrambled zipfian generator + // with a keyspace that is larger than exists at the beginning of the test. that is, we'll predict + // the number of inserts, and tell the scrambled zipfian generator the number of existing keys + // plus the number of predicted keys as the total keyspace. then, if the generator picks a key + // that hasn't been inserted yet, will just ignore it and pick another key. this way, the size of + // the keyspace doesn't change from the perspective of the scrambled zipfian generator + final double insertproportion = Double.parseDouble( + p.getProperty(INSERT_PROPORTION_PROPERTY, INSERT_PROPORTION_PROPERTY_DEFAULT)); + int opcount = Integer.parseInt(p.getProperty(Client.OPERATION_COUNT_PROPERTY)); + int expectednewkeys = (int) ((opcount) * insertproportion * 2.0); // 2 is fudge factor + + keychooser = new ScrambledZipfianGenerator(insertstart, insertstart + insertcount + expectednewkeys); + } else if (requestdistrib.compareTo("latest") == 0) { + keychooser = new SkewedLatestGenerator(transactioninsertkeysequence); + } else if (requestdistrib.equals("hotspot")) { + double hotsetfraction = + Double.parseDouble(p.getProperty(HOTSPOT_DATA_FRACTION, HOTSPOT_DATA_FRACTION_DEFAULT)); + double hotopnfraction = + Double.parseDouble(p.getProperty(HOTSPOT_OPN_FRACTION, HOTSPOT_OPN_FRACTION_DEFAULT)); + keychooser = new HotspotIntegerGenerator(insertstart, insertstart + insertcount - 1, + hotsetfraction, hotopnfraction); + } else { + throw new WorkloadException("Unknown request distribution \"" + requestdistrib + "\""); + } + + fieldchooser = new UniformIntegerGenerator(0, fieldcount - 1); + + if (scanlengthdistrib.compareTo("uniform") == 0) { + scanlength = new UniformIntegerGenerator(1, maxscanlength); + } else if (scanlengthdistrib.compareTo("zipfian") == 0) { + scanlength = new ZipfianGenerator(1, maxscanlength); + } else { + throw new WorkloadException( + "Distribution \"" + scanlengthdistrib + "\" not allowed for scan length"); + } + + insertionRetryLimit = Integer.parseInt(p.getProperty( + INSERTION_RETRY_LIMIT, INSERTION_RETRY_LIMIT_DEFAULT)); + insertionRetryInterval = Integer.parseInt(p.getProperty( + INSERTION_RETRY_INTERVAL, INSERTION_RETRY_INTERVAL_DEFAULT)); + } + + public String buildKeyName(long keynum) { + if (!orderedinserts) { + keynum = Utils.hash(keynum); + } + String value = Long.toString(keynum); + int fill = zeropadding - value.length(); + String prekey = "user"; + for(int i=0; i buildSingleValue(String key) { + HashMap value = new HashMap(); + + String fieldkey = fieldnames.get(fieldchooser.nextValue().intValue()); + ByteIterator data; + if (dataintegrity) { + data = new StringByteIterator(buildDeterministicValue(key, fieldkey)); + } else { + // fill with random data + data = new RandomByteIterator(fieldlengthgenerator.nextValue().longValue()); + } + value.put(fieldkey, data); + + return value; + } + + /** + * Builds values for all fields. + */ + private HashMap buildValues(String key) { + HashMap values = new HashMap(); + + for (String fieldkey : fieldnames) { + ByteIterator data; + if (dataintegrity) { + data = new StringByteIterator(buildDeterministicValue(key, fieldkey)); + } else { + // fill with random data + data = new RandomByteIterator(fieldlengthgenerator.nextValue().longValue()); + } + values.put(fieldkey, data); + } + return values; + } + + /** + * Build a deterministic value given the key information. + */ + private String buildDeterministicValue(String key, String fieldkey) { + int size = fieldlengthgenerator.nextValue().intValue(); + StringBuilder sb = new StringBuilder(size); + sb.append(key); + sb.append(':'); + sb.append(fieldkey); + while (sb.length() < size) { + sb.append(':'); + sb.append(sb.toString().hashCode()); + } + sb.setLength(size); + + return sb.toString(); + } + + /** + * Do one insert operation. Because it will be called concurrently from multiple client threads, + * this function must be thread safe. However, avoid synchronized, or the threads will block waiting + * for each other, and it will be difficult to reach the target throughput. Ideally, this function would + * have no side effects other than DB operations. + */ + @Override + public boolean doInsert(DB db, Object threadstate) { + int keynum = keysequence.nextValue().intValue(); + String dbkey = buildKeyName(keynum); + HashMap values = buildValues(dbkey); + + Status status; + int numOfRetries = 0; + do { + status = db.insert(table, dbkey, values); + if (null != status && status.isOk()) { + break; + } + // Retry if configured. Without retrying, the load process will fail + // even if one single insertion fails. User can optionally configure + // an insertion retry limit (default is 0) to enable retry. + if (++numOfRetries <= insertionRetryLimit) { + System.err.println("Retrying insertion, retry count: " + numOfRetries); + try { + // Sleep for a random number between [0.8, 1.2)*insertionRetryInterval. + int sleepTime = (int) (1000 * insertionRetryInterval * (0.8 + 0.4 * Math.random())); + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + break; + } + + } else { + System.err.println("Error inserting, not retrying any more. number of attempts: " + numOfRetries + + "Insertion Retry Limit: " + insertionRetryLimit); + break; + + } + } while (true); + + return null != status && status.isOk(); + } + + /** + * Do one transaction operation. Because it will be called concurrently from multiple client + * threads, this function must be thread safe. However, avoid synchronized, or the threads will block waiting + * for each other, and it will be difficult to reach the target throughput. Ideally, this function would + * have no side effects other than DB operations. + */ + @Override + public boolean doTransaction(DB db, Object threadstate) { + switch (operationchooser.nextString()) { + case "READ": + doTransactionRead(db); + break; + case "UPDATE": + doTransactionUpdate(db); + break; + case "INSERT": + doTransactionInsert(db); + break; + case "SCAN": + doTransactionScan(db); + break; + default: + doTransactionReadModifyWrite(db); + } + + return true; + } + + /** + * Results are reported in the first three buckets of the histogram under + * the label "VERIFY". + * Bucket 0 means the expected data was returned. + * Bucket 1 means incorrect data was returned. + * Bucket 2 means null data was returned when some data was expected. + */ + protected void verifyRow(String key, HashMap cells) { + Status verifyStatus = Status.OK; + long startTime = System.nanoTime(); + if (!cells.isEmpty()) { + for (Map.Entry entry : cells.entrySet()) { + if (!entry.getValue().toString().equals(buildDeterministicValue(key, entry.getKey()))) { + verifyStatus = Status.UNEXPECTED_STATE; + break; + } + } + } else { + // This assumes that null data is never valid + verifyStatus = Status.ERROR; + } + long endTime = System.nanoTime(); + _measurements.measure("VERIFY", (int) (endTime - startTime) / 1000); + _measurements.reportStatus("VERIFY", verifyStatus); + } + + int nextKeynum() { + int keynum; + if (keychooser instanceof ExponentialGenerator) { + do { + keynum = transactioninsertkeysequence.lastValue() - keychooser.nextValue().intValue(); + } while (keynum < 0); + } else { + do { + keynum = keychooser.nextValue().intValue(); + } while (keynum > transactioninsertkeysequence.lastValue()); + } + return keynum; + } + + public void doTransactionRead(DB db) { + // choose a random key + int keynum = nextKeynum(); + + String keyname = buildKeyName(keynum); + + HashSet fields = null; + + if (!readallfields) { + // read a random field + String fieldname = fieldnames.get(fieldchooser.nextValue().intValue()); + + fields = new HashSet(); + fields.add(fieldname); + } else if (dataintegrity) { + // pass the full field list if dataintegrity is on for verification + fields = new HashSet(fieldnames); + } + + HashMap cells = new HashMap(); + db.read(table, keyname, fields, cells); + + if (dataintegrity) { + verifyRow(keyname, cells); + } + } + + public void doTransactionReadModifyWrite(DB db) { + // choose a random key + int keynum = nextKeynum(); + + String keyname = buildKeyName(keynum); + + HashSet fields = null; + + if (!readallfields) { + // read a random field + String fieldname = fieldnames.get(fieldchooser.nextValue().intValue()); + + fields = new HashSet(); + fields.add(fieldname); + } + + HashMap values; + + if (writeallfields) { + // new data for all the fields + values = buildValues(keyname); + } else { + // update a random field + values = buildSingleValue(keyname); + } + + // do the transaction + + HashMap cells = new HashMap(); + + + long ist = _measurements.getIntendedtartTimeNs(); + long st = System.nanoTime(); + db.read(table, keyname, fields, cells); + + db.update(table, keyname, values); + + long en = System.nanoTime(); + + if (dataintegrity) { + verifyRow(keyname, cells); + } + + _measurements.measure("READ-MODIFY-WRITE", (int) ((en - st) / 1000)); + _measurements.measureIntended("READ-MODIFY-WRITE", (int) ((en - ist) / 1000)); + } + + public void doTransactionScan(DB db) { + // choose a random key + int keynum = nextKeynum(); + + String startkeyname = buildKeyName(keynum); + + // choose a random scan length + int len = scanlength.nextValue().intValue(); + + HashSet fields = null; + + if (!readallfields) { + // read a random field + String fieldname = fieldnames.get(fieldchooser.nextValue().intValue()); + + fields = new HashSet(); + fields.add(fieldname); + } + + db.scan(table, startkeyname, len, fields, new Vector>()); + } + + public void doTransactionUpdate(DB db) { + // choose a random key + int keynum = nextKeynum(); + + String keyname = buildKeyName(keynum); + + HashMap values; + + if (writeallfields) { + // new data for all the fields + values = buildValues(keyname); + } else { + // update a random field + values = buildSingleValue(keyname); + } + + db.update(table, keyname, values); + } + + public void doTransactionInsert(DB db) { + // choose the next key + int keynum = transactioninsertkeysequence.nextValue(); + + try { + String dbkey = buildKeyName(keynum); + + HashMap values = buildValues(dbkey); + db.insert(table, dbkey, values); + } finally { + transactioninsertkeysequence.acknowledge(keynum); + } + } + + /** + * Creates a weighted discrete values with database operations for a workload to perform. + * Weights/proportions are read from the properties list and defaults are used + * when values are not configured. + * Current operations are "READ", "UPDATE", "INSERT", "SCAN" and "READMODIFYWRITE". + * @param p The properties list to pull weights from. + * @return A generator that can be used to determine the next operation to perform. + * @throws IllegalArgumentException if the properties object was null. + */ + public static DiscreteGenerator createOperationGenerator(final Properties p) { + if (p == null) { + throw new IllegalArgumentException("Properties object cannot be null"); + } + final double readproportion = Double.parseDouble( + p.getProperty(READ_PROPORTION_PROPERTY, READ_PROPORTION_PROPERTY_DEFAULT)); + final double updateproportion = Double.parseDouble( + p.getProperty(UPDATE_PROPORTION_PROPERTY, UPDATE_PROPORTION_PROPERTY_DEFAULT)); + final double insertproportion = Double.parseDouble( + p.getProperty(INSERT_PROPORTION_PROPERTY, INSERT_PROPORTION_PROPERTY_DEFAULT)); + final double scanproportion = Double.parseDouble( + p.getProperty(SCAN_PROPORTION_PROPERTY, SCAN_PROPORTION_PROPERTY_DEFAULT)); + final double readmodifywriteproportion = Double.parseDouble(p.getProperty( + READMODIFYWRITE_PROPORTION_PROPERTY, READMODIFYWRITE_PROPORTION_PROPERTY_DEFAULT)); + + final DiscreteGenerator operationchooser = new DiscreteGenerator(); + if (readproportion > 0) { + operationchooser.addValue(readproportion, "READ"); + } + + if (updateproportion > 0) { + operationchooser.addValue(updateproportion, "UPDATE"); + } + + if (insertproportion > 0) { + operationchooser.addValue(insertproportion, "INSERT"); + } + + if (scanproportion > 0) { + operationchooser.addValue(scanproportion, "SCAN"); + } + + if (readmodifywriteproportion > 0) { + operationchooser.addValue(readmodifywriteproportion, "READMODIFYWRITE"); + } + return operationchooser; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `CoreWorkload.operationchooser.nextString()` could be null and is dereferenced at line 629. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean CoreWorkload.doTransaction(DB,Object) + +### Procedure Id: +com.yahoo.ycsb.workloads.CoreWorkload.doTransaction(com.yahoo.ycsb.DB,java.lang.Object):boolean.117bbfc804df4535a1381692a84b31c1 + +### File: +core/src/main/java/com/yahoo/ycsb/workloads/CoreWorkload.java + +### Key: +CoreWorkload.java|doTransaction|NULL_DEREFERENCE + +### Node Key: +7bd17c1126d78fe17b36ab2ac6be1419 + +### Hash: +83000c9a6152d263407d58886edc3d29 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7977/instruction.md b/inferredbugs-7977/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..373e8ecf7baa182aee6285f1963ae7d586571238 --- /dev/null +++ b/inferredbugs-7977/instruction.md @@ -0,0 +1,508 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** YCSB +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * MongoDB client binding for YCSB. + * + * Submitted by Yen Pai on 5/11/2010. + * + * https://gist.github.com/000a66b8db2caf42467b#file_mongo_database.java + * + */ + +package com.yahoo.ycsb.db; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.Vector; +import java.util.concurrent.atomic.AtomicInteger; + +import com.mongodb.client.model.InsertManyOptions; +import org.bson.Document; +import org.bson.types.Binary; + +import com.mongodb.MongoClient; +import com.mongodb.MongoClientURI; +import com.mongodb.ReadPreference; +import com.mongodb.WriteConcern; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.FindIterable; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.MongoCursor; +import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.BulkWriteOptions; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.UpdateOptions; +import com.mongodb.client.result.DeleteResult; +import com.mongodb.client.result.UpdateResult; +import com.yahoo.ycsb.ByteArrayByteIterator; +import com.yahoo.ycsb.ByteIterator; +import com.yahoo.ycsb.DB; +import com.yahoo.ycsb.DBException; + +/** + * MongoDB client for YCSB framework. + * + * Properties to set: + * + * mongodb.url=mongodb://localhost:27017 + * mongodb.writeConcern=acknowledged + * + * @author ypai + */ +public class MongoDbClient extends DB { + + /** Used to include a field in a response. */ + protected static final Integer INCLUDE = Integer.valueOf(1); + + /** The options to use for inserting many documents */ + protected static final InsertManyOptions INSERT_MANY_OPTIONS = + new InsertManyOptions().ordered(false); + + /** + * The database name to access. + */ + private static String databaseName; + + /** The database name to access. */ + private static MongoDatabase database; + + /** + * Count the number of times initialized to teardown on the last + * {@link #cleanup()}. + */ + private static final AtomicInteger initCount = new AtomicInteger(0); + + /** A singleton Mongo instance. */ + private static MongoClient mongoClient; + + /** The default read preference for the test */ + private static ReadPreference readPreference; + + /** The default write concern for the test. */ + private static WriteConcern writeConcern; + + /** The batch size to use for inserts. */ + private static int batchSize; + + /** The bulk inserts pending for the thread. */ + private final List bulkInserts = new ArrayList(); + + /** + * Cleanup any state for this DB. Called once per DB instance; there is one + * DB instance per client thread. + */ + @Override + public void cleanup() throws DBException { + if (initCount.decrementAndGet() == 0) { + try { + mongoClient.close(); + } + catch (Exception e1) { + System.err.println("Could not close MongoDB connection pool: " + + e1.toString()); + e1.printStackTrace(); + return; + } + finally { + database = null; + mongoClient = null; + } + } + } + + /** + * Delete a record from the database. + * + * @param table + * The name of the table + * @param key + * The record key of the record to delete. + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int delete(String table, String key) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + DeleteResult result = collection.withWriteConcern(writeConcern) + .deleteOne(query); + if (result.wasAcknowledged() && result.getDeletedCount() == 0) { + System.err.println("Nothing deleted for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Initialize any state for this DB. Called once per DB instance; there is + * one DB instance per client thread. + */ + @Override + public void init() throws DBException { + initCount.incrementAndGet(); + synchronized (INCLUDE) { + if (mongoClient != null) { + return; + } + + Properties props = getProperties(); + + // Set insert batchsize, default 1 - to be YCSB-original equivalent + batchSize = Integer.parseInt(props.getProperty("batchsize", "1")); + + // Just use the standard connection format URL + // http://docs.mongodb.org/manual/reference/connection-string/ + // to configure the client. + String url = props.getProperty("mongodb.url", null); + boolean defaultedUrl = false; + if (url == null) { + defaultedUrl = true; + url = "mongodb://localhost:27017/ycsb?w=1"; + } + + url = OptionsSupport.updateUrl(url, props); + + if (!url.startsWith("mongodb://")) { + System.err + .println("ERROR: Invalid URL: '" + + url + + "'. Must be of the form " + + "'mongodb://:,:/database?options'. " + + "http://docs.mongodb.org/manual/reference/connection-string/"); + System.exit(1); + } + + try { + MongoClientURI uri = new MongoClientURI(url); + + String uriDb = uri.getDatabase(); + if (!defaultedUrl && (uriDb != null) && !uriDb.isEmpty() + && !"admin".equals(uriDb)) { + databaseName = uriDb; + } + else { + //If no database is specified in URI, use "ycsb" + databaseName = "ycsb"; + + } + + + readPreference = uri.getOptions().getReadPreference(); + writeConcern = uri.getOptions().getWriteConcern(); + + mongoClient = new MongoClient(uri); + database = mongoClient.getDatabase(databaseName); + + System.out.println("mongo client connection created with " + + url); + } + catch (Exception e1) { + System.err + .println("Could not initialize MongoDB connection pool for Loader: " + + e1.toString()); + e1.printStackTrace(); + return; + } + } + } + + /** + * Insert a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key. + * + * @param table + * The name of the table + * @param key + * The record key of the record to insert. + * @param values + * A HashMap of field/value pairs to insert in the record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int insert(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + Document toInsert = new Document("_id", key); + for (Map.Entry entry : values.entrySet()) { + toInsert.put(entry.getKey(), entry.getValue().toArray()); + } + + bulkInserts.add(toInsert); + if (bulkInserts.size() == batchSize) { + collection.withWriteConcern(writeConcern) + .insertMany(bulkInserts, INSERT_MANY_OPTIONS); + bulkInserts.clear(); + } + return 0; + } + catch (Exception e) { + System.err.println("Exception while trying bulk insert with " + + bulkInserts.size()); + e.printStackTrace(); + return 1; + } + + } + + /** + * Read a record from the database. Each field/value pair from the result + * will be stored in a HashMap. + * + * @param table + * The name of the table + * @param key + * The record key of the record to read. + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A HashMap of field/value pairs for the result + * @return Zero on success, a non-zero error code on error or "not found". + */ + @Override + public int read(String table, String key, Set fields, + HashMap result) { + try { + MongoCollection collection = database + .getCollection(table); + Document query = new Document("_id", key); + + FindIterable findIterable = collection + .withReadPreference(readPreference) + .find(query); + + Document queryResult = null; + if (fields != null) { + Document projection = new Document(); + for (String field : fields) { + projection.put(field, INCLUDE); + } + findIterable.projection(projection); + } + + queryResult = findIterable.first(); + + if (queryResult != null) { + fillMap(result, queryResult); + } + return queryResult != null ? 0 : 1; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Perform a range scan for a set of records in the database. Each + * field/value pair from the result will be stored in a HashMap. + * + * @param table + * The name of the table + * @param startkey + * The record key of the first record to read. + * @param recordcount + * The number of records to read + * @param fields + * The list of fields to read, or null for all of them + * @param result + * A Vector of HashMaps, where each HashMap is a set field/value + * pairs for one record + * @return Zero on success, a non-zero error code on error. See the + * {@link DB} class's description for a discussion of error codes. + */ + @Override + public int scan(String table, String startkey, int recordcount, + Set fields, Vector> result) { + MongoCursor cursor = null; + try { + MongoCollection collection = database + .getCollection(table); + + Document scanRange = new Document("$gte", startkey); + Document query = new Document("_id", scanRange); + Document sort = new Document("_id", INCLUDE); + Document projection = null; + if (fields != null) { + projection = new Document(); + for (String fieldName : fields) { + projection.put(fieldName, INCLUDE); + } + } + + cursor = collection.withReadPreference(readPreference).find(query) + .projection(projection).sort(sort).limit(recordcount).iterator(); + if (!cursor.hasNext()) { + System.err.println("Nothing found in scan for key " + startkey); + return 1; + } + while (cursor.hasNext()) { + HashMap resultMap = new HashMap(); + + Document obj = cursor.next(); + fillMap(resultMap, obj); + + result.add(resultMap); + } + + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + finally { + if (cursor != null) { + cursor.close(); + } + } + } + + /** + * Update a record in the database. Any field/value pairs in the specified + * values HashMap will be written into the record with the specified record + * key, overwriting any existing values with the same field name. + * + * @param table + * The name of the table + * @param key + * The record key of the record to write. + * @param values + * A HashMap of field/value pairs to update in the record + * @return Zero on success, a non-zero error code on error. See this class's + * description for a discussion of error codes. + */ + @Override + public int update(String table, String key, + HashMap values) { + try { + MongoCollection collection = database + .getCollection(table); + + Document query = new Document("_id", key); + Document fieldsToSet = new Document(); + for (Map.Entry entry : values.entrySet()) { + fieldsToSet.put(entry.getKey(), entry.getValue().toArray()); + } + Document update = new Document("$set", fieldsToSet); + + UpdateResult result = collection.withWriteConcern(writeConcern) + .updateOne(query, update); + if (result.wasAcknowledged() && result.getMatchedCount() == 0) { + System.err.println("Nothing updated for key " + key); + return 1; + } + return 0; + } + catch (Exception e) { + System.err.println(e.toString()); + return 1; + } + } + + /** + * Fills the map with the values from the DBObject. + * + * @param resultMap + * The map to fill/ + * @param obj + * The object to copy values from. + */ + protected void fillMap(HashMap resultMap, Document obj) { + for (Map.Entry entry : obj.entrySet()) { + if (entry.getValue() instanceof Binary) { + resultMap.put(entry.getKey(), new ByteArrayByteIterator( + ((Binary) entry.getValue()).getData())); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.yahoo.ycsb.db.MongoDbClient.insert` reads without synchronization from `db.MongoDbClient.com.yahoo.ycsb.db.MongoDbClient.writeConcern`. Potentially races with write in method `MongoDbClient.init()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int MongoDbClient.insert(String,String,HashMap) + +### Procedure Id: +com.yahoo.ycsb.db.MongoDbClient.insert(java.lang.String,java.lang.String,java.util.HashMap):int.758466ac0c6193407dff469c509787f5 + +### File: +mongodb/src/main/java/com/yahoo/ycsb/db/MongoDbClient.java + +### Key: +MongoDbClient.java|insert|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +38b153d647714b323148304c8b03389f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7983/instruction.md b/inferredbugs-7983/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11432caed2445d0f1c0bfaf2c62e3b73e6fb1eff --- /dev/null +++ b/inferredbugs-7983/instruction.md @@ -0,0 +1,236 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dicoogle +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ + * + * This file is part of Dicoogle/dicoogle. + * + * Dicoogle/dicoogle is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dicoogle/dicoogle is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dicoogle. If not, see . + */ +package pt.ua.dicoogle.server.users; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyGenerator; +import javax.crypto.NoSuchPaddingException; +import org.slf4j.LoggerFactory; + +import pt.ua.dicoogle.core.settings.ServerSettingsManager; +import pt.ua.dicoogle.sdk.Utils.Platform; + +/** + * This class provides encryptation to the file that saves users information + * Uses the AES algorithim with 128 bit key + * + * @author Samuel Campos + */ +public class UserFileHandle { + + private String filename; + private String keyFile; + + private Cipher cipher; + private Key key; + private boolean encrypt; + + public UserFileHandle() throws IOException { + filename = Platform.homePath() + "users.xml"; + encrypt = true; //ServerSettingsManager.getSettings().isEncryptUsersFile(); + try { + + if(encrypt){ + keyFile = "users.key"; + + try { + ObjectInputStream in = new ObjectInputStream(new FileInputStream(keyFile)); + key = (Key) in.readObject(); + in.close(); + + } catch (FileNotFoundException ex) { + KeyGenerator gen = KeyGenerator.getInstance("AES"); + + gen.init(128, new SecureRandom()); + key = gen.generateKey(); + + try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(keyFile))) { + out.writeObject(key); + } + } + + cipher = Cipher.getInstance("AES"); + } + + } catch (NoSuchAlgorithmException | ClassNotFoundException | NoSuchPaddingException ex) { + LoggerFactory.getLogger(UserFileHandle.class).error(ex.getMessage(), ex); + } + } + + /** + * Print one byte array in File + * Encrypt that file with the key + * @param bytes + */ + public void printFile(byte[] bytes) throws Exception { + InputStream in; + + if(encrypt){ + cipher.init(Cipher.ENCRYPT_MODE, key); + + byte[] encryptedBytes = cipher.doFinal(bytes); + in = new ByteArrayInputStream(encryptedBytes); + } + else + in = new ByteArrayInputStream(bytes); + + FileOutputStream out = new FileOutputStream(filename); + + + byte[] input = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(input)) != -1) { + out.write(input, 0, bytesRead); + out.flush(); + } + + out.close(); + in.close(); + } + + /** Retrieve the contents of the users configuration file. + * @return a byte array, or null if the configuration file is not available or corrupted + * @throws IOException on a failed attempt to read the file + */ + public byte[] getFileContent() throws IOException { + try { + try (FileInputStream fin = new FileInputStream(filename); + ByteArrayOutputStream out = new ByteArrayOutputStream()) { + byte[] data = new byte[1024]; + int bytesRead; + + while ((bytesRead = fin.read(data)) != -1) { + out.write(data, 0, bytesRead); + out.flush(); + } + + if(encrypt){ + cipher.init(Cipher.DECRYPT_MODE, key); + byte[] Bytes = cipher.doFinal(out.toByteArray()); + return Bytes; + } + + return out.toByteArray(); + } + } catch (FileNotFoundException ex) { + LoggerFactory.getLogger(UserFileHandle.class).info("No such users file \"{}\", will create one with default settings.", filename); + } catch (IllegalBlockSizeException ex) { + LoggerFactory.getLogger(UserFileHandle.class).error("Users file \"{}\" is corrupted, will override it with default settings.", filename, ex); + } catch (InvalidKeyException ex) { + LoggerFactory.getLogger(UserFileHandle.class).error("Invalid Key to decrypt users file! Please contact your system administator."); + System.exit(1); // FIXME this is too dangerous + } + catch(BadPaddingException ex){ + LoggerFactory.getLogger(UserFileHandle.class).error("Invalid Key to decrypt users file! Please contact your system administator."); + System.exit(2); // FIXME this is too dangerous + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `out` by call to `FileOutputStream(...)` at line 109 is not released after line 121. +**Note**: potential exception at line 114 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void UserFileHandle.printFile(byte[]) + +### Procedure Id: +pt.ua.dicoogle.server.users.UserFileHandle.printFile(byte[]):void.64a2cc6a1c4899f3ab8ef0bcf80ce269 + +### File: +dicoogle/src/main/java/pt/ua/dicoogle/server/users/UserFileHandle.java + +### Key: +UserFileHandle.java|printFile|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +d432292b3293128bb1a65ada833c52fc + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-7984/instruction.md b/inferredbugs-7984/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f75b54b4506d6ece83a375a2429307c21b4c30c0 --- /dev/null +++ b/inferredbugs-7984/instruction.md @@ -0,0 +1,184 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dicoogle +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (C) 2014 Universidade de Aveiro, DETI/IEETA, Bioinformatics Group - http://bioinformatics.ua.pt/ + * + * This file is part of Dicoogle/dicoogle. + * + * Dicoogle/dicoogle is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Dicoogle/dicoogle is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Dicoogle. If not, see . + */ + +package pt.ua.dicoogle.server.web.servlets.accounts; + +import java.io.IOException; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import net.sf.json.JSONArray; +import net.sf.json.JSONObject; +import pt.ua.dicoogle.server.users.Role; +import pt.ua.dicoogle.server.users.User; +import pt.ua.dicoogle.server.users.UsersStruct; +import pt.ua.dicoogle.server.web.auth.LoggedIn; +import pt.ua.dicoogle.server.web.auth.LoggedInStatus; +import pt.ua.dicoogle.server.web.auth.Session; + +/** + * + * @author Frederico Silva + */ +public class LoginServlet extends HttpServlet { + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + //Try login + // Does not require admin rights. + LoggedInStatus loginStatus = Session.webappLogin(req, resp, false); + LoggedIn mLoggedIn = loginStatus.getLogin(); + + if (mLoggedIn == null) { + resp.sendError(401, "Login failed"); + return; + } + + JSONObject json_resp = new JSONObject(); + json_resp.put("user", mLoggedIn.getUserName()); + json_resp.put("admin", mLoggedIn.isAdmin()); + User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName()); + JSONArray rolesObj = new JSONArray(); + if (u!=null&&u.getRoles()!=null) { + for (Role r : u.getRoles()) { + if (r!=null) + rolesObj.add(r.getName()); + } + + json_resp.put("roles", rolesObj); + } + json_resp.put("token", mLoggedIn.getToken()); + + //Set response content type + resp.setContentType("application/json"); + + //Write response + json_resp.write(resp.getWriter()); + } + + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) + throws ServletException, IOException { + //resp.addHeader("Access-Control-Allow-Origin", "*"); + HttpSession session = req.getSession(false); + + LoggedIn mLoggedIn = Session.getUserLoggedIn(session); + if(mLoggedIn == null){ + resp.sendError(401); + return; + } + + JSONObject json_resp = new JSONObject(); + json_resp.put("user", mLoggedIn.getUserName()); + json_resp.put("admin", mLoggedIn.isAdmin()); + User u = UsersStruct.getInstance().getUser(mLoggedIn.getUserName()); + JSONArray rolesObj = new JSONArray(); + for (Role r : u.getRoles()) + { + rolesObj.add(r.getName()); + } + + json_resp.put("roles", rolesObj); + + //Set response content type + resp.setContentType("application/json"); + + //Write response + json_resp.write(resp.getWriter()); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `u` last assigned on line 94 could be null and is dereferenced at line 96. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void LoginServlet.doGet(HttpServletRequest,HttpServletResponse) + +### Procedure Id: +pt.ua.dicoogle.server.web.servlets.accounts.LoginServlet.doGet(javax.servlet.http.HttpServletRequest.8aa2cabb5561e4f1fee76a121a1280ec + +### File: +dicoogle/src/main/java/pt/ua/dicoogle/server/web/servlets/accounts/LoginServlet.java + +### Key: +LoginServlet.java|doGet|NULL_DEREFERENCE + +### Node Key: +50eb9480b1a39477599a8d0ef0064573 + +### Hash: +29593849ea0c1e8071c88e0e815dc95d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8025/instruction.md b/inferredbugs-8025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e0919f740d60c7ad99017c6efdc8bcf24064742 --- /dev/null +++ b/inferredbugs-8025/instruction.md @@ -0,0 +1,472 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** azure-iot-sdk-java +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +package com.microsoft.azure.sdk.iot.device.transport.mqtt; + +import mockit.Deencapsulation; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +public class TopicParserTest +{ + + /* + Tests_SRS_TopicParser_25_001: [**The constructor shall spilt the topic by "/" and save the tokens.**]** + */ + @Test + public void constructorSucceeds() + { + //arrange + String validString = "$iothub/twin/res/"; + + //act + TopicParser testParser = new TopicParser(validString); + + //assert + assertNotNull(testParser); + String[] tokens = Deencapsulation.getField(testParser, "topicTokens"); + assertNotNull(tokens); + assertTrue(tokens.length > 1); + } + + /* + Tests_SRS_TopicParser_25_002: [**The constructor shall throw IllegalArgument exception if topic is null or empty.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void constructorFailsInvalidTopic() + { + //arrange + String validString = ""; + + //act + TopicParser testParser = new TopicParser(validString); + + } + + /* + Tests_SRS_TopicParser_25_004: [**This method shall return the status corresponding to the tokenIndexStatus from tokens if it is not null.**]** + */ + @Test + public void getStatusGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/status"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getStatus(3); + + //assert + assertNotNull(status); + assertTrue(status.equals("status")); + + } + + /* + Tests_SRS_TopicParser_25_003: [**If tokenIndexStatus is not valid i.e less than or equal to zero or greater then token length then getStatus shall throw IllegalArgumentException.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void getStatusInvalidTokenThrows() throws IOException + { + String validString = "$iothub/twin/res/status"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getStatus(4); + + } + + /* + Tests_SRS_TopicParser_25_005: [**If token corresponding to tokenIndexStatus is null then this method shall throw IoException.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void getStatusMandatoryStatusExpected() throws IOException + { + String validString = "$iothub/twin/res/"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getStatus(3); + } + + /* + Tests_SRS_TopicParser_25_007: [**This method shall return the request ID value corresponding to the tokenIndexReqID from tokens.**]** + */ + @Test + public void getRequestIdGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNotNull(status); + assertTrue(status.equals(String.valueOf(5))); + } + + @Test + public void getRequestIdGets_pattern1() throws IOException + { + //arrange + String validString = "$iothub/twin/res/$rid=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNull(status); + } + + @Test + public void getRequestIdGets_pattern2() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid="; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNotNull(status); + } + + @Test + public void getRequestIdGets_pattern3() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid5&$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + assertNull(status); + } + /* + Tests_SRS_TopicParser_25_008: [**If the topic token does not contain request id then this method shall return null.**]** + */ + @Test + public void getRequestIdGetsNullIfNotFound() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNull(status); + + } + + @Test + public void getRequestIdOnTopicWithVersionGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version=7&$rid=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNotNull(status); + assertTrue(status.equals(String.valueOf(5))); + + } + + @Test + public void getRequestIdOnTopicWithVersionBeforeRidGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid=5&$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(3); + + //assert + assertNotNull(status); + assertTrue(status.equals(String.valueOf(5))); + + } + + /* + Tests_SRS_TopicParser_25_006: [**If tokenIndexReqID is not valid i.e less than or equal to zero or greater then token length then getRequestId shall throw IllegalArgumentException.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void getRequestIdInvalidTokenThrows() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid=5&$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getRequestId(4); + + } + + /* + Tests_SRS_TopicParser_25_010: [**This method shall return the version value(if present) corresponding to the tokenIndexVersion from tokens.**]** + */ + @Test + public void getVersionGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String version = testParser.getVersion(3); + + //assert + assertNotNull(version); + assertTrue(version.equals(String.valueOf(7))); + } + + @Test + public void getVersionGets_pattern1() throws IOException + { + //arrange + String validString = "$iothub/twin/res/$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getVersion(3); + + //assert + assertNull(status); + } + + @Test + public void getVersionGets_pattern2() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version="; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getVersion(3); + + //assert + assertNotNull(status); + } + + @Test + public void getVersionGets_pattern3() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid5&$version7"; + TopicParser testParser = new TopicParser(validString); + + //act + String status = testParser.getVersion(3); + + assertNull(status); + } + + /* + Tests_SRS_TopicParser_25_011: [**If the topic token does not contain version then this method shall return null.**]** + */ + @Test + public void getVersionGetsNullIfNotPresent() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String version = testParser.getVersion(3); + + //assert + assertNull(version); + } + @Test + public void getVersionOnTopicWithRIDGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$rid=5&$version=7"; + TopicParser testParser = new TopicParser(validString); + + //act + String version = testParser.getVersion(3); + + //assert + assertNotNull(version); + assertTrue(version.equals(String.valueOf(7))); + + } + + @Test + public void getVersionOnTopicWithVersionBeforeRIDGets() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version=7&$rid=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String version = testParser.getVersion(3); + + //assert + assertNotNull(version); + assertTrue(version.equals(String.valueOf(7))); + + } + /* + Tests_SRS_TopicParser_25_009: [**If tokenIndexVersion is not valid i.e less than or equal to zero or greater then token length then getVersion shall throw IllegalArgumentException.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void getVersionInvalidTokenThrows() throws IOException + { + //arrange + String validString = "$iothub/twin/res/?$version=7&$rid=5"; + TopicParser testParser = new TopicParser(validString); + + //act + String version = testParser.getVersion(0); + + } + + /* + Tests_SRS_TopicParser_25_013: [**This method shall return the method name(if present) corresponding to the tokenIndexMethod from tokens.**]** + + Tests_SRS_TopicParser_25_014: [**If the topic token does not contain method name or is null then this method shall throw IOException.**]** + */ + @Test + public void getMethodNameGets() throws IOException + { + //arrange + String validString = "$iothub/methods/res/methodName"; + TopicParser testParser = new TopicParser(validString); + + //act + String methodName = testParser.getMethodName(3); + + //assert + assertNotNull(methodName); + assertTrue(methodName.equals("methodName")); + + + } + + /* + Tests_SRS_TopicParser_25_012: [**If tokenIndexMethod is not valid i.e less than or equal to zero or greater then token length then getMethodName shall throw IllegalArgumentException.**]** + */ + @Test (expected = IllegalArgumentException.class) + public void getMethodNameInvalidTokenThrows() throws IOException + { + //arrange + String validString = "$iothub/methods/res/methodName"; + TopicParser testParser = new TopicParser(validString); + + //act + String methodName = testParser.getMethodName(4); + } + + @Test (expected = IllegalArgumentException.class) + public void getMethodNameInvalidTokenThrows_1() throws IOException + { + //arrange + String validString = "$iothub/methods/res/"; + TopicParser testParser = new TopicParser(validString); + + //act + String methodName = testParser.getMethodName(3); + } + + @Test (expected = IllegalArgumentException.class) + public void getMethodNameInvalidTokenThrows_2() throws IOException + { + //arrange + String validString = "$iothub/methods/res//"; + TopicParser testParser = new TopicParser(validString); + + //act + String methodName = testParser.getMethodName(3); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `status` last assigned on line 197 could be null and is dereferenced at line 201. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TopicParserTest.getRequestIdOnTopicWithVersionBeforeRidGets() + +### Procedure Id: +com.microsoft.azure.sdk.iot.device.transport.mqtt.TopicParserTest.getRequestIdOnTopicWithVersionBefo.c539ba5e0229e9ebd0fe4671a643ee0b + +### File: +device/iot-device-client/src/test/java/tests/unit/com/microsoft/azure/sdk/iot/device/transport/mqtt/TopicParserTest.java + +### Key: +TopicParserTest.java|getRequestIdOnTopicWithVersionBeforeRidGets|NULL_DEREFERENCE + +### Node Key: +f133a6dfaa072505a5ed16416e655ea0 + +### Hash: +74667c195ceccb4fb835051551b3357d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8103/instruction.md b/inferredbugs-8103/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38e9d497527a12c66b9b7c32586a472b77f63cba --- /dev/null +++ b/inferredbugs-8103/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 962 is not released after line 967. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testExecutionException(JDBCDatabaseMetaData,JDBCResultSet) + +### Procedure Id: +sqlline.SqlLineArgsTest.testExecutionException(org.hsqldb.jdbc.JDBCDatabaseMetaData,org.hsqldb.jdbc..281d2ab4b16ce7a76452b4a728f2ad46 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testExecutionException|RESOURCE_LEAK + +### Node Key: +4e7cf70e3290ea52366c5949eac877d2 + +### Hash: +cc18d62e032108d93ee5e71473d44e12 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8105/instruction.md b/inferredbugs-8105/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77e71a1ea91632316a7d9ea75e5a177b69fb6087 --- /dev/null +++ b/inferredbugs-8105/instruction.md @@ -0,0 +1,316 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.ByteArrayOutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import org.jline.utils.AttributedString; +import org.jline.utils.AttributedStringBuilder; +import org.jline.utils.AttributedStyle; +import org.junit.jupiter.api.Test; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static sqlline.SqlLineArgsTest.begin; + +/** + * Test cases for prompt and right prompt. + */ +public class PromptTest { + @Test + public void testPromptWithoutConnection() { + SqlLine sqlLine = new SqlLine(); + // default prompt + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is(BuiltInProperty.PROMPT.defaultValue())); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), + is(BuiltInProperty.RIGHT_PROMPT.defaultValue())); + + // custom constant prompt + final SqlLineOpts opts = sqlLine.getOpts(); + opts.set(BuiltInProperty.PROMPT, "custom_prompt"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "custom_right_prompt"); + assertThat(sqlLine.getPromptHandler().getPrompt(), + is(new AttributedString("custom_prompt"))); + assertThat(sqlLine.getPromptHandler().getRightPrompt(), + is(new AttributedString("custom_right_prompt"))); + + // custom constant multiline prompt + opts.set(BuiltInProperty.PROMPT, "custom\nprompt\n"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "custom\nright\nprompt\n"); + assertThat(sqlLine.getPromptHandler().getPrompt(), + is(new AttributedString("custom\nprompt\n"))); + assertThat(sqlLine.getPromptHandler().getRightPrompt(), + is(new AttributedString("custom\nright\nprompt\n"))); + + // custom constant colored prompt + opts.set(BuiltInProperty.PROMPT, "%[f:y%]sqlline%[default%]>>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "%[bold%]end"); + AttributedStringBuilder promptBuilder = new AttributedStringBuilder(); + promptBuilder.append("sqlline", AttributedStyles.YELLOW).append(">>"); + AttributedStringBuilder rightPromptBuilder = new AttributedStringBuilder(); + rightPromptBuilder.append("end", AttributedStyle.BOLD); + assertThat(sqlLine.getPromptHandler().getPrompt(), + is(promptBuilder.toAttributedString())); + assertThat(sqlLine.getPromptHandler().getRightPrompt(), + is(rightPromptBuilder.toAttributedString())); + + opts.set(BuiltInProperty.PROMPT, "%[f:b,italic%]sqlline%[default%]>>"); + promptBuilder = new AttributedStringBuilder(); + promptBuilder.append("sqlline", AttributedStyles.ITALIC_BLUE); + promptBuilder.append(">>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "[%[underline,f:m%]end%[default%]]"); + rightPromptBuilder = new AttributedStringBuilder(); + rightPromptBuilder.append("["); + rightPromptBuilder + .append("end", + AttributedStyle.DEFAULT + .foreground(AttributedStyle.MAGENTA).underline()); + rightPromptBuilder.append("]"); + assertThat(sqlLine.getPromptHandler().getPrompt(), + is(promptBuilder.toAttributedString())); + assertThat(sqlLine.getPromptHandler().getRightPrompt(), + is(rightPromptBuilder.toAttributedString())); + + // custom prompt with date values + opts.set(BuiltInProperty.PROMPT, "%w_%W_%o_%O_%y_%Y>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "[%w_%W_%o_%O_%y_%Y]"); + final SimpleDateFormat sdf = + new SimpleDateFormat("d_E_MM_MMM_YY_YYYY", Locale.ROOT); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is(sdf.format(new Date()) + ">")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), + is("[" + sdf.format(new Date()) + "]")); + + // custom prompt with data from connection (empty if there is no connection) + opts.set(BuiltInProperty.PROMPT, "%u%n"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "%d%c"); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), is("")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), is("")); + + opts.set(BuiltInProperty.PROMPT, "%u%c>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "<<<%n%d"); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), is(">")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), is("<<<")); + + // custom prompt with property value + opts.set(BuiltInProperty.PROMPT, "%:color:>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "%:outputformat:"); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is(opts.getColor() + ">")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), + is(opts.getOutputFormat())); + } + + @Test + public void testPromptWithNickname() { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine sqlLine = new SqlLine(); + try { + final SqlLine.Status status = + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + sqlLine.runCommands(dc, "!connect " + + SqlLineArgsTest.ConnectionSpec.H2.url + " " + + SqlLineArgsTest.ConnectionSpec.H2.username + " \"\""); + + // custom prompt with data from connection + final SqlLineOpts opts = sqlLine.getOpts(); + sqlLine.getDatabaseConnection().setNickname("nickname"); + opts.set(BuiltInProperty.PROMPT, "%u@%n>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c"); + // if nickname is specified for the connection + // it has more priority than prompt. + // Right prompt does not care about nickname + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("0: nickname> ")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), + is("//H20")); + sqlLine.getDatabaseConnection().close(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testPromptWithConnection() { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine sqlLine = new SqlLine(); + try { + final SqlLine.Status status = + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + sqlLine.runCommands(dc, "!connect " + + SqlLineArgsTest.ConnectionSpec.H2.url + " " + + SqlLineArgsTest.ConnectionSpec.H2.username + " \"\""); + + // custom prompt with data from connection + final SqlLineOpts opts = sqlLine.getOpts(); + opts.set(BuiltInProperty.PROMPT, "%u@%n>"); + opts.set(BuiltInProperty.RIGHT_PROMPT, "//%d%c"); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("jdbc:h2:mem:@SA>")); + assertThat(sqlLine.getPromptHandler().getRightPrompt().toAnsi(), + is("//H20")); + sqlLine.getDatabaseConnection().close(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testPromptWithSchema() { + SqlLine sqlLine = new SqlLine(); + sqlLine.getOpts().set(BuiltInProperty.PROMPT, "%u%S>"); + + sqlLine.runCommands(new DispatchCallback(), + "!connect " + + SqlLineArgsTest.ConnectionSpec.H2.url + " " + + SqlLineArgsTest.ConnectionSpec.H2.username + " \"\""); + + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("jdbc:h2:mem:PUBLIC>")); + + sqlLine.runCommands(new DispatchCallback(), "use information_schema"); + + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("jdbc:h2:mem:INFORMATION_SCHEMA>")); + + sqlLine.getDatabaseConnection().close(); + } + + @Test + public void testPromptScript() { + SqlLine sqlLine = new SqlLine(); + sqlLine.getOpts().set(BuiltInProperty.PROMPT_SCRIPT, "'hel' + 'lo'"); + + sqlLine.runCommands(new DispatchCallback(), + "!connect " + + SqlLineArgsTest.ConnectionSpec.H2.url + " " + + SqlLineArgsTest.ConnectionSpec.H2.username + " \"\""); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("hello")); + + sqlLine.getOpts().set(BuiltInProperty.PROMPT_SCRIPT, "" + + "'i=' + connectionIndex + ',p=' + databaseProductName +" + + " ',n=' + userName + ',u=' + url + ',s=' + currentSchema + '>'"); + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("i=0,p=H2,n=SA,u=jdbc:h2:mem:,s=PUBLIC>")); + + sqlLine.getDatabaseConnection().close(); + } + + @Test + public void testCustomPromptHandler() { + SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), + "!connect " + + SqlLineArgsTest.ConnectionSpec.H2.url + " " + + SqlLineArgsTest.ConnectionSpec.H2.username + " \"\"", + "!prompthandler sqlline.extensions.CustomPromptHandler"); + + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("my_app (PUBLIC)>")); + + sqlLine.runCommands(new DispatchCallback(), "!prompthandler default"); + + assertThat(sqlLine.getPromptHandler().getPrompt().toAnsi(), + is("0: jdbc:h2:mem:> ")); + + sqlLine.getDatabaseConnection().close(); + } + +} + +// End PromptTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `sqlLine.getDatabaseConnection()` could be null and is dereferenced at line 237. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromptTest.testCustomPromptHandler() + +### Procedure Id: +sqlline.PromptTest.testCustomPromptHandler():void.39ace0d3f0baf7d503b6077804cd260f + +### File: +src/test/java/sqlline/PromptTest.java + +### Key: +PromptTest.java|testCustomPromptHandler|NULL_DEREFERENCE + +### Node Key: +6a7cfd397a248d76b64a279c7288aceb + +### Hash: +37bafee6008e1e7d65e5a6a215010325 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8132/instruction.md b/inferredbugs-8132/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b94597532cbd5c0dcd9175d4c2da55acd521b51 --- /dev/null +++ b/inferredbugs-8132/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 627 is not released after line 629. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testManual() + +### Procedure Id: +sqlline.SqlLineArgsTest.testManual():void.af344b365611edd991fd4201af4b2c0d + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testManual|RESOURCE_LEAK + +### Node Key: +b2d15307b6382364ce2ba477b6f118cb + +### Hash: +0d664e6e00536cbc79dd17a59d557cac + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8135/instruction.md b/inferredbugs-8135/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3069a9c639a2a47d36cb90d75836aae2212a9ff3 --- /dev/null +++ b/inferredbugs-8135/instruction.md @@ -0,0 +1,2662 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* +// Licensed to Julian Hyde under one or more contributor license +// agreements. See the NOTICE file distributed with this work for +// additional information regarding copyright ownership. +// +// Julian Hyde licenses this file to you under the Modified BSD License +// (the "License"); you may not use this file except in compliance with +// the License. You may obtain a copy of the License at: +// +// http://opensource.org/licenses/BSD-3-Clause +*/ +package sqlline; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.TreeSet; +import java.util.stream.Collectors; + +import org.h2.util.StringUtils; +import org.hamcrest.BaseMatcher; +import org.hamcrest.CoreMatchers; +import org.hamcrest.Description; +import org.hamcrest.Matcher; +import org.hsqldb.jdbc.CustomDatabaseMetadata; +import org.hsqldb.jdbc.JDBCConnection; +import org.hsqldb.jdbc.JDBCDatabaseMetaData; +import org.hsqldb.jdbc.JDBCResultSet; +import org.hsqldb.jdbc.JDBCResultSetMetaData; +import org.jline.builtins.Commands; +import org.jline.terminal.Terminal; +import org.junit.jupiter.api.Test; + +import mockit.Expectations; +import mockit.Mock; +import mockit.MockUp; +import mockit.Mocked; +import mockit.internal.reflection.FieldReflection; +import net.hydromatic.scott.data.hsqldb.ScottHsqldb; +import sqlline.extensions.CustomApplication; + +import static org.hamcrest.CoreMatchers.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; + +/** + * Executes tests of the command-line arguments to SqlLine. + */ +public class SqlLineArgsTest { + private static final ConnectionSpec CONNECTION_SPEC = ConnectionSpec.HSQLDB; + private ConnectionSpec connectionSpec; + + public SqlLineArgsTest() { + connectionSpec = CONNECTION_SPEC; + } + + static SqlLine.Status begin(SqlLine sqlLine, OutputStream os, + boolean saveHistory, String... args) { + try { + PrintStream beelineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(beelineOutputStream); + sqlLine.setErrorStream(beelineOutputStream); + final InputStream is = new ByteArrayInputStream(new byte[0]); + return sqlLine.begin(args, is, saveHistory); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Execute a script with "beeline -f". + * + * @return The stderr and stdout from running the script + * @param args Script arguments + */ + private static Pair run(String... args) { + try { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = begin(beeLine, os, false, args); + return new Pair(status, os.toString("UTF8")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + private Pair runScript(File scriptFile, boolean flag, String outputFileName) { + return runScript(connectionSpec, scriptFile, flag, outputFileName); + } + + private static Pair runScript(ConnectionSpec connectionSpec, File scriptFile, + boolean flag, String outputFileName) { + List args = new ArrayList<>(); + Collections.addAll(args, + "-d", connectionSpec.driver, + "-u", connectionSpec.url, + "-n", connectionSpec.username, + "-p", connectionSpec.password); + if (flag) { + args.add("-f"); + args.add(scriptFile.getAbsolutePath()); + } else { + args.add("--run=" + scriptFile.getAbsolutePath()); + } + if (outputFileName != null) { + args.add("-log"); + args.add(outputFileName); + } + return run(args.toArray(new String[0])); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * Tests for presence of an expected pattern in the output (stdout or stderr). + * + * @param scriptText Script text + * @param flag Command flag (--run or -f) + * @param statusMatcher Checks whether status is as expected + * @param outputMatcher Checks whether output is as expected + */ + private void checkScriptFile(String scriptText, boolean flag, + Matcher statusMatcher, + Matcher outputMatcher) { + try { + // Put the script content in a temp file + File scriptFile = createTempFile("foo", "temp"); + PrintStream os = + new PrintStream( + new FileOutputStream(scriptFile), + false, + StandardCharsets.UTF_8.name()); + os.print(scriptText); + os.close(); + + Pair pair = runScript(scriptFile, flag, null); + + // Check output before status. It gives a better clue what went wrong. + assertThat(toLinux(pair.output), outputMatcher); + assertThat(pair.status, statusMatcher); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Windows line separators in a string into Linux line separators; + * a Linux string is unchanged. */ + private static String toLinux(String s) { + return s.replaceAll("\r\n", "\n"); + } + + private File createTempFile(String prefix, String suffix) { + return createTempFile(prefix, suffix, null); + } + + private File createTempFile(String prefix, String suffix, Path directory) { + try { + final File file = directory == null + ? Files.createTempFile(prefix, suffix).toFile() + : Files.createTempFile(directory, prefix, suffix).toFile(); + file.deleteOnExit(); + return file; + } catch (IOException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMultilineScriptWithComments() { + final String script1Text = + "!set incremental true\n" + + "-- a comment \n values\n--comment\n (\n1\n, ' ab'\n--comment\n)\n;\n"; + + checkScriptFile(script1Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-------------+-----+\n" + + "| C1 | C2 |\n" + + "+-------------+-----+\n" + + "| 1 | ab |\n" + + "+-------------+-----+")); + + final String script2Text = + "!set incremental true\n" + + "--comment \n --comment2 \nvalues (';\n' /* comment */, '\"'" + + "/*multiline;\n ;\n comment*/)\n -- ; \n; -- comment"; + + checkScriptFile(script2Text, true, + equalTo(SqlLine.Status.OK), + containsString("+-----+----+\n" + + "| C1 | C2 |\n" + + "+-----+----+\n" + + "| ; \n" + + " | \" |\n" + + "+-----+----+")); + } + + /** + * Attempt to execute a simple script file with the -f option to SqlLine. + * Test for presence of an expected pattern + * in the output (stdout or stderr), fail if not found. + */ + @Test + public void testPositiveScriptFile() { + checkScriptFile("call 100 + 23;\n", + true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * As above, but using '-run' rather than '-f'. + */ + @Test + public void testPositiveScriptFileUsingRun() { + checkScriptFile("call 100 + 23;\n", + false, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + /** + * Test case for + * [SQLLINE-42], + * Script fails if first line is a comment. + */ + @Test + public void testScriptFileStartsWithComment() { + final String scriptText = "-- a comment\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileStartsWithEmptyLine() { + final String scriptText = "\n" + + "call 100 + 23;\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + containsString(" 123 ")); + } + + @Test + public void testScriptFileContainsComment() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithComments() { + final String scriptText = "--comment\n\n" + + "values \n10 \n+ \n23;\n\n\n" + + "-- a comment\n" + + "\n\nvalues " + + "--comment inside\n\n" + + "100 --comment inside\n\n" + + "+ \n\n23\n\n\n;\n\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString(" 33 "), containsString(" 123 "))); + } + + @Test + public void testMultilineScriptFileWithMultilineQuotedStrings() { + final String scriptText = "--comment\n\n" + + "values '\nmultiline;\n;\n; string\n'" + + ";\n\n\n" + + "values '\nmultiline2;\n;\n; string2\n'" + + ";\n\n\n"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf(containsString("multiline2;"), containsString("; string2"))); + } + + @Test + public void testScriptWithMultilineStatementsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment\n\n" + + "values 1;values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 1 |\n" + + "+----+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + + @Test + public void testScriptWithMultilineStatementsAndCommentsInARow() { + final String scriptText = "!set incremental false\n" + + "--comment;;\n\n" + + "select * from (values ';') t (\";\");/*;select 1;*/values 2;"; + checkScriptFile(scriptText, true, + equalTo(SqlLine.Status.OK), + allOf( + containsString("+---+\n" + + "| ; |\n" + + "+---+\n" + + "| ; |\n" + + "+---+"), + containsString("+----+\n" + + "| C1 |\n" + + "+----+\n" + + "| 2 |\n" + + "+----+"))); + } + /** + * Tests sql with H2 specific one-line comment '//' + */ + @Test + public void testMultilineScriptWithH2Comments() { + final SqlLine sqlLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + final File tmpHistoryFile = createTempFile("queryToExecute", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter(new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + final String script = "\n" + + "\n" + + "!set incremental true\n" + + "\n" + + "\n" + + "select * from information_schema.tables// ';\n" + + "// \";" + + ";\n" + + "\n" + + "\n"; + bw.write(script); + bw.flush(); + } + SqlLine.Status status = + begin(sqlLine, os, false, + "-u", ConnectionSpec.H2.url, + "-n", ConnectionSpec.H2.username, + "--run=" + tmpHistoryFile.getAbsolutePath()); + assertThat(status, equalTo(SqlLine.Status.OK)); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CATALOG | TABLE_SCHEMA |" + + " TABLE_NAME | TABLE_TYPE | STORAGE_TYPE | SQL |"; + assertThat(output, containsString(expected)); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-72] + * Allow quoted file names (including spaces) in !record, + * !run and !script commands. */ + @Test + public void testScriptFilenameWithSpace() { + final String scriptText = "values 10 + 23;\n" + + "-- a comment\n" + + "values 100 + 23;\n"; + File scriptFile = createTempFile("Script with Spaces", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + allOf(containsString(" 33 "), containsString(" 123 "))); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScriptWithOutput() { + final String scriptText = "!set maxcolumnwidth 20\n" + + "!set incremental true\n" + + "values 100 + 123;\n" + + "-- a comment\n" + + "values 100 + 253;\n"; + + File scriptFile = createTempFile("Script file name", ".sql"); + try (PrintStream os = getPrintStream(new FileOutputStream(scriptFile))) { + os.print(scriptText); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + + File outputFile = createTempFile("testScriptWithOutput", ".out"); + runScript(scriptFile, true, outputFile.getAbsolutePath()); + assertFileContains(outputFile, + allOf(containsString("| 223 |"), + containsString("| 353 |"))); + final boolean delete = outputFile.delete(); + assertThat(delete, is(true)); + } + + /** + * Values that contain null. + */ + @Test + public void testNull() { + final String script = "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString( + "+-------------+-------------+-----+\n" + + "| C1 | C2 | C3 |\n" + + "+-------------+-------------+-----+\n" + + "| 1 | null | |\n" + + "+-------------+-------------+-----+\n")); + } + + @Test + public void testScan() { + final String expectedLine0 = "Compliant Version Driver Class"; + final String expectedLine1 = "yes 2.4 org.hsqldb.jdbc.JDBCDriver"; + checkScriptFile("!scan\n", false, + equalTo(SqlLine.Status.OK), + allOf(containsString(expectedLine0), containsString(expectedLine1))); + } + + /** + * Table output without header. + */ + @Test + public void testTableOutputNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set incremental true\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("| 1 | null | |\n")); + } + + /** + * Csv output without header. + */ + @Test + public void testCsvNullWithoutHeader() { + final String script = "!set showHeader false\n" + + "!set outputformat csv\n" + + "values (1, cast(null as integer), cast(null as varchar(3)));\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + containsString("'1','null',''\n")); + } + + /** + * Tests the "close" command, + * [HIVE-5768] + * Beeline connection cannot be closed with '!close' command and + * [SQLLINE-139] + * Look for the exact match if there are multiple matches. + */ + @Test + public void testClose() { + final String expected = "!close\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile("!close\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + /** + * Test case for + * [SQLLINE-32] + * !help set' should print documentation for all variables. + */ + @Test + public void testHelpSet() { + final String expected = "1/1 !help set\n" + + "!set List / set a sqlline variable\n" + + "\n" + + "Variables:\n" + + "\n" + + "Variable Value Description\n" + + "=============== ========== " + + "==================================================\n" + + "autoCommit true/false " + + "Enable/disable automatic transaction commit\n" + + "autoSave true/false Automatically save preferences\n"; + checkScriptFile("!help set\n", false, equalTo(SqlLine.Status.OK), + containsString(expected)); + + // Make sure that each variable (autoCommit, autoSave, color, etc.) has a + // line in the output of '!help set' + final SqlLine sqlLine = new SqlLine(); + String help = sqlLine.loc("help-set") + + sqlLine.loc("variables"); + + final TreeSet propertyNamesMixed = + Arrays.stream(BuiltInProperty.values()) + .map(BuiltInProperty::propertyName) + .collect(Collectors.toCollection(TreeSet::new)); + for (String p : propertyNamesMixed) { + assertThat(help, containsString("\n" + p + " ")); + } + assertThat(propertyNamesMixed.contains("autoCommit"), + is(true)); + assertThat(propertyNamesMixed.contains("autocommit"), + is(false)); + assertThat(propertyNamesMixed.contains("trimScripts"), + is(true)); + + while (help.length() > 0) { + int i = help.indexOf("\n", 1); + if (i < 0) { + break; + } + if (i > 78) { + fail("line exceeds 78 chars: " + i + ": " + help.substring(0, i)); + } + help = help.substring(i); + } + } + + /** + * Test case for + * [SQLLINE-39] + * 'help set' should not break long lines. + * + *

    But it should break 'help all', which consists of a single long line. + */ + @Test + public void testHelpAll() { + // Note that "connections" has been broken onto a new line. + final String expected = "1/1 !help all\n" + + "!all Execute the specified SQL against all the current\n" + + " connections\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help all\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + + /** + * Tests "!go <non-existent connection indexes>". + */ + @Test + public void testGoFailing() { + final String[] connectionIndexes = {"321", "invalid"}; + for (String connectionIndex : connectionIndexes) { + final String script = "!go " + connectionIndex + "\n"; + final String expected = "Invalid connection: " + connectionIndex; + checkScriptFile(script, false, + // Status.OTHER as checking of fail cases + equalTo(SqlLine.Status.OTHER), containsString(expected)); + } + } + + /** + * Tests "!help go". "go" and "#" are synonyms. + */ + @Test + public void testHelpGo() { + for (String c : new String[] {"go", "#"}) { + final String expected = "1/1 !help " + c + "\n" + + "!go Select the current connection\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection\n" + + "sqlline version ???\n"; + checkScriptFile("!help " + c + "\n", false, equalTo(SqlLine.Status.OK), + is(expected)); + } + } + + /** + * Test case for + * !?, !# + * and other one-symbol length commands stopped working + * + *

    '!?' should work in the same way as '!help'. + */ + @Test + public void testHelpAsQuestionMark() { + final String script = "!?\n"; + final String expected = + "!autocommit Set autocommit mode on or off"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + allOf(not(containsString("Unknown command: ?")), + containsString(expected))); + } + + /** + * Test case for + * [SQLLINE-49] + * !manual command fails. + */ + @Test + public void testManual() { + final String expectedLine = "sqlline version"; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + new MockUp() { + @Mock + void less(Terminal terminal, InputStream in, PrintStream out, + PrintStream err, Path currentDir, String[] argv) { + } + }; + + SqlLine beeLine = new SqlLine(); + SqlLine.Status status = + begin(beeLine, baos, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + beeLine.runCommands(new DispatchCallback(), "!manual"); + String output = baos.toString("UTF8"); + + assertThat(output, containsString(expectedLine)); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** Test case for + * [SQLLINE-38] + * Expand ~ to user's home directory. */ + @Test + public void testRunFromHome() { + try { + Path tmpDir = + Files.createTempDirectory( + Paths.get(System.getProperty("user.home")), + "tmpdir" + System.nanoTime()); + tmpDir.toFile().deleteOnExit(); + + File tmpFile = createTempFile("test", ".sql", tmpDir); + try (Writer fw = new OutputStreamWriter( + new FileOutputStream(tmpFile), StandardCharsets.UTF_8)) { + fw.write("!set outputformat csv\n"); + fw.write("values (1, 2, 3, 4, 5);"); + fw.flush(); + checkScriptFile("!run ~" + File.separatorChar + + tmpDir.getFileName() + + File.separatorChar + tmpFile.getName().toString(), + false, + equalTo(SqlLine.Status.OK), + allOf(containsString("!set outputformat csv"), + containsString("values (1, 2, 3, 4, 5);"))); + } + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-26] + * Flush output for each command when using !record command. + */ + @Test + public void testRecord() { + File file = createTempFile("sqlline", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + /** Test case for + * [SQLLINE-62] + * Expand ~ to user's home directory. */ + @Test + public void testRecordHome() { + File home = new File(System.getProperty("user.home")); + File file; + for (int i = 0;; i++) { + file = new File(home, "sqlline" + i + ".log"); + if (!file.exists()) { + break; + } + } + file.deleteOnExit(); + final String s = "Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "2/4 !set outputformat csv\n" + + "3/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "4/4 !record\n"; + checkScriptFile("!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n", + false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/4 !record .*.log\n" + + s + + "Recording stopped.\n" + + ".*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, RegexMatcher.of(s)); + final boolean delete = file.delete(); + assertThat(delete, is(true)); + } + + /** + * As {@link #testRecord()}, but file name is double-quoted and contains a + * space. + */ + @Test + public void testRecordFilenameWithSpace() { + File file = createTempFile("sqlline file with spaces", ".log"); + final String script = "!set incremental true\n" + + "values 1;\n" + + "!record " + file.getAbsolutePath() + "\n" + + "!set outputformat csv\n" + + "values 2;\n" + + "!record\n" + + "!set outputformat csv\n" + + "values 3;\n"; + checkScriptFile(script, false, + equalTo(SqlLine.Status.OK), + RegexMatcher.of("(?s)1/8 !set incremental true\n" + + "2/8 values 1;\n" + + "\\+-------------\\+\n" + + "\\| C1 \\|\n" + + "\\+-------------\\+\n" + + "\\| 1 \\|\n" + + "\\+-------------\\+\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/8 !record .*.log\n" + + "Saving all output to \".*.log\". Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n" + + "Recording stopped.\n" + + "7/8 !set outputformat csv\n" + + "8/8 values 3;\n" + + "'C1'\n" + + "'3'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*")); + + // Now check that the right stuff got into the file. + assertFileContains(file, + RegexMatcher.of("Saving all output to \".*.log\". " + + "Enter \"record\" with no arguments to stop it.\n" + + "4/8 !set outputformat csv\n" + + "5/8 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "6/8 !record\n")); + } + + private static void assertFileContains(File file, Matcher matcher) { + try (BufferedReader br = new BufferedReader( + new InputStreamReader(new FileInputStream(file), + StandardCharsets.UTF_8.name()))) { + final StringWriter stringWriter = new StringWriter(); + for (;;) { + final String line = br.readLine(); + if (line == null) { + break; + } + stringWriter.write(line); + stringWriter.write("\n"); + } + assertThat(toLinux(stringWriter.toString()), matcher); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Test case for + * [SQLLINE-61] + * Add !nickname command. + */ + @Test + public void testNickname() { + final String script = "!set outputformat csv\n" + + "values 1;\n" + + "!nickname foo\n" + + "values 2;\n"; + final String expected = "(?s)1/4 !set outputformat csv\n" + + "2/4 values 1;\n" + + "'C1'\n" + + "'1'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n" + + "3/4 !nickname foo\n" + + "4/4 values 2;\n" + + "'C1'\n" + + "'2'\n" + + "1 row selected \\([0-9.,]+ seconds\\)\n.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + } + + /** + * Attempts to execute a simple script file with the -f option to SqlLine. + * The first command should fail and the second command should not execute. + */ + @Test + public void testBreakOnErrorScriptFile() { + checkScriptFile("select * from abcdefg01;\ncall 100 + 23;\n", + true, + equalTo(SqlLine.Status.OTHER), + not(containsString(" 123 "))); + } + + /** + * Emulation of Apache Hive behavior with throwing exceptions + * while calling {@link DatabaseMetaData#storesUpperCaseIdentifiers()} + * and {@link DatabaseMetaData#supportsTransactionIsolationLevel(int)}. + * + *

    Also please see + * [SQLLINE-183]. + * + * @param meta Mocked JDBCDatabaseMetaData + */ + @Test + public void testExecutionWithNotSupportedMethods( + @Mocked final JDBCDatabaseMetaData meta) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + + // emulate apache hive behavior + meta.supportsTransactionIsolationLevel(4); + result = new SQLException("Method not supported"); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback dc = new DispatchCallback(); + sqlLine.initArgs(args, dc); + os.reset(); + sqlLine.runCommands(dc, + "!set incremental true", + "values 1;"); + final String output = os.toString("UTF8"); + final String line0 = "+-------------+"; + final String line1 = "| C1 |"; + final String line2 = "+-------------+"; + final String line3 = "| 1 |"; + final String line4 = "+-------------+"; + assertThat(output, + CoreMatchers.allOf(containsString(line0), + containsString(line1), + containsString(line2), + containsString(line3), + containsString(line4))); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + @Test + public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, + @Mocked final JDBCResultSet resultSet) { + try { + new Expectations() { + { + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductName(); + result = "hsqldb"; + // prevent calls to functions that also call resultSet.next + meta.getSQLKeywords(); + result = ""; + // prevent calls to functions that also call resultSet.next + meta.getDatabaseProductVersion(); + result = "1.0"; + // Generate an exception on a call to resultSet.next + resultSet.next(); + result = new SQLException("Generated Exception."); + } + }; + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + // If sqlline is not initialized, handleSQLException will print + // the entire stack trace. + // To prevent that, forcibly set init to true. + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "CREATE TABLE rsTest ( a int);", + "insert into rsTest values (1);", + "insert into rsTest values (2);", + "select a from rsTest; "); + String output = os.toString("UTF8"); + assertThat(output, containsString("Generated Exception")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Attempts to execute a missing script file with the -f option to SqlLine. + */ + @Test + public void testNegativeScriptFile() { + // Create and delete a temp file + File scriptFile = createTempFile("sqllinenegative", "temp"); + final boolean delete = scriptFile.delete(); + assertThat(delete, is(true)); + + Pair pair = runScript(scriptFile, true, null); + assertThat(pair.status, equalTo(SqlLine.Status.OTHER)); + assertThat(pair.output, not(containsString(" 123 "))); + } + + /** Displays usage. */ + @Test + public void testUsage() { + Pair pair = run("--help"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + private int countUsage(String output) { + int n = 0; + for (String line : output.split("\n")) { + if (line.contains("Usage")) { + ++n; + } + } + return n; + } + + /** Invalid arguments. */ + @Test + public void testInvalidArguments() { + Pair pair = run("--fuzz"); + assertThat(pair.status, equalTo(SqlLine.Status.ARGS)); + assertThat(pair.output, containsString("-f ")); + assertThat(countUsage(pair.output), equalTo(1)); + } + + /** Result of executing sqlline: status code and output. */ + static class Pair { + final SqlLine.Status status; + final String output; + + Pair(SqlLine.Status status, String output) { + this.status = status; + this.output = output; + } + } + + @Test + public void testIsolationSetting() { + final String script0 = "!isolation TRANSACTION_NONE\n"; + final String expected = "Transaction isolation level TRANSACTION_NONE " + + "is not supported. Default (TRANSACTION_READ_COMMITTED) " + + "will be used instead."; + checkScriptFile(script0, true, equalTo(SqlLine.Status.OTHER), + containsString(expected)); + } + + @Test + public void testDefaultIsolation() { + final String script1 = "!isolation default\n"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + allOf(not(containsString("Transaction isolation level")), + not(containsString("is not supported")))); + } + + /** + * HIVE-4566, "NullPointerException if typeinfo and nativesql commands are + * executed at beeline before a DB connection is established". + */ + @Test + public void testNPE() { + SqlLine sqlLine = new SqlLine(); + + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = getPrintStream(os); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + + try { + sqlLine.runCommands(new DispatchCallback(), "!typeinfo"); + String output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + + sqlLine.runCommands(new DispatchCallback(), "!nativesql"); + output = os.toString("UTF8"); + assertThat( + output, not(containsString("java.lang.NullPointerException"))); + assertThat(output, containsString("No current connection")); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandlerOnStartup() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final String[] args = { + "-e", "!set maxwidth 80", + "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; + begin(sqlLine, os, false, args); + + try { + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!test"); + output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD")); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello test")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testCommandHandler() { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + begin(sqlLine, os, false, "-e", "!set maxwidth 80"); + + try { + final String script = "!commandhandler" + + " sqlline.extensions.HelloWorld2CommandHandler" + + " sqlline.extensions.HelloWorldCommandHandler"; + sqlLine.runCommands(new DispatchCallback(), script); + sqlLine.runCommands(new DispatchCallback(), "!hello"); + String output = os.toString("UTF8"); + assertThat(output, containsString("HELLO WORLD2")); + final String expected = "Could not add command handler " + + "sqlline.extensions.HelloWorldCommandHandler as one of commands " + + "[hello, test] is already present"; + assertThat(output, containsString(expected)); + os.reset(); + sqlLine.runCommands(new DispatchCallback(), "!help hello"); + output = os.toString("UTF8"); + assertThat(output, containsString("help for hello2")); + sqlLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(sqlLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testTablesCsv() { + final String script = "!set outputformat csv\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("'TABLE_CAT','TABLE_SCHEM','TABLE_NAME',"), + containsString("'PUBLIC','SCOTT','SALGRADE','TABLE','',"))); + } + + /** + * java.lang.NullPointerException test case from + * https://github.com/julianhyde/sqlline/pull/86#issuecomment-410868361 + */ + @Test + public void testCsvDelimiterAndQuoteCharacter() { + final String script = "!set outputformat csv\n" + + "!set csvDelimiter null\n" + + "!set csvQuoteCharacter @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!set csvDelimiter ##\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@null@C2@null@C3@null@C4@null@C5@null@C6@"; + final String line2 = + "@#@null@@@#@@@null@1@null@1969-07-20@null@@null@ 1'2\"3\t4@"; + final String line3 = "@C1@##@C2@##@C3@##@C4@##@C5@##@C6@"; + final String line4 = "@#@##@@@#@@@##@1@##@1969-07-20@##@@##@ 1'2\"3\t4@"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testCsvOneLiner() { + final String script = "!outputformat csv \"'\" @\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n" + + "!outputformat csv & default\n" + + "values ('#', '@#@', 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + final String line1 = "@C1@'@C2@'@C3@'@C4@'@C5@'@C6@"; + final String line2 = + "@#@'@@@#@@@'@1@'@1969-07-20@'@@'@ 1'2\"3\t4@"; + final String line3 = "'C1'&'C2'&'C3'&'C4'&'C5'&'C6'"; + final String line4 = + "'#'&'@#@'&'1'&'1969-07-20'&''&' 1''2\"3\t4'"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line1), containsString(line2), + containsString(line3), containsString(line4))); + } + + @Test + public void testSetForNulls() { + final String script = "!set numberFormat null\n" + + "!set\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("numberFormat null")); + } + + @Test + public void testSetNonIntValuesToIntProperties() { + SqlLine sqlLine = new SqlLine(); + final String headerIntervalScript = "!set headerinterval abc\n"; + checkScriptFile(headerIntervalScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "headerinterval", "abc"))); + + final String rowLimitScript = "!set rowlimit xxx\n"; + checkScriptFile(rowLimitScript, false, equalTo(SqlLine.Status.OK), + containsString(sqlLine.loc("not-a-number", "rowlimit", "xxx"))); + } + + @Test + public void testSelectXmlAttributes() { + final String script = "!set outputformat xmlattr\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ']]> 1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString("&4\"/>"))); + } + + @Test + public void testSelectXmlElements() { + final String script = "!set outputformat xmlelements\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' ]]>1''2\"3\t<>&4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(""), + containsString(""), + containsString("1"), + containsString("-1.5"), + containsString("TRUE"), + containsString("1969-07-20"), + containsString("null"), + containsString(" ]]>1'2\"3\t<>&4"), + containsString(""), + containsString(""))); + } + + @Test + public void testTablesJson() { + final String script = "!set outputformat json\n" + + "!tables\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"TABLE_CAT\":\"PUBLIC\"," + + "\"TABLE_SCHEM\":\"SYSTEM_LOBS\",\"TABLE_NAME\":\"BLOCKS\"," + + "\"TABLE_TYPE\":\"SYSTEM TABLE\",\"REMARKS\":null," + + "\"TYPE_CAT\":null,"))); + } + + @Test + public void testSelectJson() { + final String script = "!set outputformat json\n" + + "values (1, -1.5, 1 = 1, date '1969-07-20', null, ' 1''2\"3\t4');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("{\"resultset\":["), + containsString("{\"C1\":1,\"C2\":-1.5,\"C3\":true," + + "\"C4\":\"1969-07-20\",\"C5\":null," + + "\"C6\":\" 1'2\\\"3\\t4\"}"))); + } + + @Test + public void testNullValue() { + final String script = "!set nullValue %%%\n" + + "!set outputformat csv\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue \"'\"\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n" + + "!set nullValue null\n" + + "values (NULL, -1.5, null, date '1969-07-20', null, 'null');\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'%%%','-1.5','%%%','1969-07-20','%%%','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'''','-1.5','''','1969-07-20','''','null'"), + containsString("'C1','C2','C3','C4','C5','C6'"), + containsString("'null','-1.5','null','1969-07-20','null','null'"))); + } + + @Test + public void testTimeFormat() { + // Use System.err as it is used in sqlline.SqlLineOpts#set + final PrintStream originalErr = System.err; + try { + final ByteArrayOutputStream errBaos = new ByteArrayOutputStream(); + System.setErr( + new PrintStream(errBaos, false, StandardCharsets.UTF_8.name())); + + // successful patterns + final String okTimeFormat = "!set timeFormat HH:mm:ss\n"; + final String defaultTimeFormat = "!set timeFormat default\n"; + final String okDateFormat = "!set dateFormat YYYY-MM-dd\n"; + final String defaultDateFormat = "!set dateFormat default\n"; + final String okTimestampFormat = "!set timestampFormat default\n"; + final String defaultTimestampFormat = "!set timestampFormat default\n"; + + // successful cases + final SqlLine sqlLine = new SqlLine(); + sqlLine.runCommands(new DispatchCallback(), okTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimeFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultDateFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), okTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + sqlLine.runCommands(new DispatchCallback(), defaultTimestampFormat); + assertThat(errBaos.toString("UTF8"), + not( + anyOf(containsString("Error setting configuration"), + containsString("Exception")))); + + // failed patterns + final String wrongTimeFormat = "!set timeFormat qwerty\n"; + final String wrongDateFormat = "!set dateFormat ASD\n"; + final String wrongTimestampFormat = + "!set timestampFormat 'YYYY-MM-ddTHH:MI:ss'\n"; + + // failed cases + sqlLine.runCommands(new DispatchCallback(), wrongTimeFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'q'")); + sqlLine.runCommands(new DispatchCallback(), wrongDateFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'A'")); + sqlLine.runCommands(new DispatchCallback(), wrongTimestampFormat); + assertThat(errBaos.toString("UTF8"), + containsString("Illegal pattern character 'T'")); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } finally { + // Set error stream back + System.setErr(originalErr); + } + } + + /** + * Test case for + * [SQLLINE-203] + * !indexes command fails because of Hive bug. + * The bug in question is + * [HIVE-20983] + * HiveResultSetMetaData.getColumnDisplaySize throws for SHORT column. + * + * @param meta Mocked hsqldb {@link JDBCResultSetMetaData} to use in the test + */ + @Test + public void testOutputWithFailingColumnDisplaySize( + @Mocked final JDBCResultSetMetaData meta) { + try { + new Expectations() { + { + meta.getColumnCount(); + result = 3; + + meta.getColumnLabel(1); + result = "TABLE_CAT"; + + meta.getColumnLabel(2); + result = "TABLE_SCHEM"; + + meta.getColumnLabel(3); + result = "TABLE_NAME"; + + meta.getColumnDisplaySize(1); + result = new Exception("getColumnDisplaySize exception"); + } + }; + + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-u", + "jdbc:hsqldb:res:scott", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + FieldReflection.setFieldValue( + sqlLine.getClass().getDeclaredField("initComplete"), sqlLine, true); + sqlLine.getConnection(); + sqlLine.runCommands(callback, + "!set incremental true", + "!set maxwidth 80", + "!set verbose true", + "!indexes"); + assertThat(os.toString("UTF8"), not(containsString("Exception"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests the {@code !connect} command with interactive password submission. + */ + @Test + public void testConnectWithoutPassword() { + new MockUp() { + @Mock + String readPassword(String url) { + return ""; + } + }; + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} property outside of the URL: + * + *

    + * !connect -p PASSWORD_HASH TRUE jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set maxwidth 80", + "!set incremental true"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + final String expected = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing in the password in as a hash, + * and using h2's {@code PASSWORD_HASH} and {@code ALLOW_LITERALS} properties + * outside of the URL: + * + *
    + * !connect -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE + * jdbc:h2:mem sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbPropertyAsParameter2() { + SqlLine beeLine = new SqlLine(); + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!set maxwidth 80"); + String fakeNonEmptyPassword = "nonEmptyPasswd"; + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect " + + " -p PASSWORD_HASH TRUE -p ALLOW_LITERALS NONE " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + StringUtils.convertBytesToHex(bytes)); + beeLine.runCommands(dc, "select 1;"); + String output = os.toString("UTF8"); + final String expected = "Error:"; + assertThat(output, containsString(expected)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Throwable t) { + // fail + throw new RuntimeException(t); + } + } + + /** + * Tests the {@code !connect} command passing the password in as a hash: + * + *
    + * !connect "jdbc:h2:mem; PASSWORD_HASH=TRUE" sa 6e6f6e456d707479506173737764 + *
    + */ + @Test + public void testConnectWithDbProperty() { + SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + try { + beeLine.runCommands(dc, "!set maxwidth 80"); + + // fail attempt + String fakeNonEmptyPassword = "nonEmptyPasswd"; + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE\" " + + ConnectionSpec.H2.username + + " \"" + fakeNonEmptyPassword + "\""); + String output = os.toString("UTF8"); + final String expected0 = "Error:"; + assertThat(output, containsString(expected0)); + os.reset(); + + // success attempt + final byte[] bytes = + fakeNonEmptyPassword.getBytes(StandardCharsets.UTF_8); + beeLine.runCommands(dc, "!connect \"" + + ConnectionSpec.H2.url + + " ;PASSWORD_HASH=TRUE;ALLOW_LITERALS=NONE\" " + + ConnectionSpec.H2.username + " \"" + + StringUtils.convertBytesToHex(bytes) + + "\""); + beeLine.runCommands(dc, "!set incremental true"); + beeLine.runCommands(dc, "!tables"); + output = os.toString("UTF8"); + final String expected1 = "| TABLE_CAT | TABLE_SCHEM | " + + "TABLE_NAME | TABLE_TYPE | REMARKS | TYPE_CAT | TYP |"; + assertThat(output, containsString(expected1)); + + beeLine.runCommands(dc, "select 5;"); + output = os.toString("UTF8"); + final String expected2 = "Error:"; + assertThat(output, containsString(expected2)); + os.reset(); + + beeLine.runCommands(new DispatchCallback(), "!quit"); + output = os.toString("UTF8"); + assertThat(output, + allOf(not(containsString("Error:")), containsString("!quit"))); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + private static PrintStream getPrintStream(OutputStream os) { + try { + return new PrintStream(os, false, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testReconnect() { + final String script = "!reconnect"; + final String expected = "Reconnecting to \"jdbc:hsqldb:res:scott\"...\n" + + "Closing: org.hsqldb.jdbc.JDBCConnection"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(expected)); + } + + @Test + public void testTables() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxcolumnwidth 15\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = + "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME | TABLE_TYPE | |"; + final String line1 = + "| PUBLIC | SYSTEM_LOBS | BLOCKS | SYSTEM TABLE | |"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + @Test + public void testTablesH2() { + connectionSpec = ConnectionSpec.H2; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString(line0), containsString(line1))); + } + + /** + * Test case for + * [SQLLINE-107] + * Script fails if the wrong driver is specified with -d option + * and there is a valid registered driver for the specified url. + * + */ + @Test + public void testTablesH2WithErrorDriver() { + connectionSpec = ConnectionSpec.ERROR_H2_DRIVER; + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true\n" + + "!tables\n"; + final String line0 = "| TABLE_CAT | TABLE_SCHEM | TABLE_NAME |"; + final String line1 = + "| UNNAMED | INFORMATION_SCHEMA | CATALOGS | SYSTEM TABLE"; + final String message = "Could not find driver " + + connectionSpec.driver + + "; using registered driver org.h2.Driver instead"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + CoreMatchers.allOf(containsString(message), + not(containsString("NullPointerException")), + containsString(line0), + containsString(line1))); + } + + @Test + public void testH2TablesWithErrorUrl() { + connectionSpec = ConnectionSpec.ERROR_H2_URL; + final String script = "!tables\n"; + + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + CoreMatchers.allOf(containsString("No suitable driver"), + not(containsString("NullPointerException")))); + } + + @Test + public void testEmptyMetadata() { + final String script = "!metadata\n"; + final String line = "Usage: metadata "; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + /** Tests that methods inherited from Object are not included in the list + * of possible metadata methods. */ + @Test + public void testPossibleMetadataValues() { + final String script = "!metadata 1\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + allOf(containsString("allProceduresAreCallable"), + containsString("getIndexInfo"), + not(containsString("Exception")), + not(containsString("equals")), + not(containsString("notify")), + not(containsString("wait")), + not(containsString("toString")), + not(containsString("hashCode")), + not(containsString("notifyAll")))); + } + + @Test + public void testMetadataForClassHierarchy() { + final SqlLine beeLine = new SqlLine(); + + new MockUp() { + @Mock + public DatabaseMetaData getMetaData() throws SQLException { + return new CustomDatabaseMetadata( + (JDBCConnection) beeLine.getConnection()); + } + }; + + try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { + SqlLine.Status status = + begin(beeLine, os, false, "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, "!connect " + + ConnectionSpec.HSQLDB.url + " \"" + + ConnectionSpec.HSQLDB.username + "\" \"" + + ConnectionSpec.HSQLDB.password + "\""); + os.reset(); + beeLine.runCommands(dc, "!tables"); + String output = os.toString("UTF8"); + assertThat(output, + allOf(containsString("TABLE_CAT"), + not(containsString("No such method \"getTables\"")))); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testEmptyRecord() { + final String line = "Usage: record "; + checkScriptFile("!record", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyRun() { + final String line = "Usage: run "; + checkScriptFile("!run", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEmptyScript() { + final String line = "Usage: script "; + checkScriptFile("!script", true, equalTo(SqlLine.Status.OTHER), + allOf(containsString(line), not(containsString("Exception")))); + } + + @Test + public void testEscapeSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set maxColumnWidth 15\n" + + "!set escapeOutput yes\n" + + "values \n" + + "('\n" + + "multiline\n" + + "value') \n" + + ";\n"; + final String line1 = "" + + "+-----------------+\n" + + "| C1 |\n" + + "+-----------------+\n" + + "| \\nmultiline \\nvalue |\n" + + "+-----------------+\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testSqlMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!sql \n" + + "values \n" + + "(1, 2) \n" + + ";\n"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 1 | 2 |\n" + + "+-------------+-------------+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAllMultiline() { + // Set width so we don't inherit from the current terminal. + final String script = "!set maxwidth 80\n" + + "!set incremental true \n" + + "!all \n" + + "values \n" + + "(1, '2') \n" + + ";\n"; + final String line1 = "" + + "+-------------+----+\n" + + "| C1 | C2 |\n" + + "+-------------+----+\n" + + "| 1 | 2 |\n" + + "+-------------+----+"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + @Test + public void testAppInfoMessage() { + Pair pair = run("-e", "!set maxwidth 80"); + assertThat(pair.status, equalTo(SqlLine.Status.OK)); + assertThat(pair.output, + containsString(Application.DEFAULT_APP_INFO_MESSAGE)); + + String[] args = {"-e", "!set maxwidth 80", "-ac", "INCORRECT_CLASS_NAME"}; + pair = run(args); + assertThat(pair.output, + containsString("Could not initialize INCORRECT_CLASS_NAME")); + assertThat(pair.output, + containsString(CustomApplication.DEFAULT_APP_INFO_MESSAGE)); + + String[] args2 = {"-e", "!set maxwidth 80", + "-ac", "sqlline.extensions.CustomApplication"}; + pair = run(args2); + assertThat(pair.output, + containsString(CustomApplication.CUSTOM_INFO_MESSAGE)); + } + + @Test + public void testCustomOutputFormats() { + // json format was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!set outputformat json\n" + + "values 1;"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("Unknown outputFormat \"json\"")); + } + + @Test + public void testCustomCommands() { + // table command was removed + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Unknown command: tables")); + } + + @Test + public void testAppConfigReset() { + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!appconfig sqlline.Application\n" + + "!tables"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("TABLE_CAT")); + } + + @Test + public void testCustomOpts() { + // nulls are displayed as custom_null + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "values(null)"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("custom_null")); + } + + @Test + public void testScanForEmptyAllowedDrivers() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.emptyList(); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("No driver classes found")); + } + + @Test + public void testScanForOnlyH2Allowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.h2.Driver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 1.4 org.h2.Driver"), + not(containsString("org.hsqldb.jdbc.JDBCDriver")))); + } + + @Test + public void testScanForOnlyHsqldbAllowed() { + new MockUp() { + @Mock + public List allowedDrivers() { + return Collections.singletonList("org.hsqldb.jdbc.JDBCDriver"); + } + }; + + final String script = "!appconfig" + + " sqlline.extensions.CustomApplication\n" + + "!scan"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("yes 2.4 org.hsqldb.jdbc.JDBCDriver"), + not(containsString("org.h2.Driver")))); + } + + @Test + public void testVersion() { + final String script = "!set\n"; + try { + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString(new Application().getVersion())); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSetVersion() { + final String script = "!set version test-version\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("version property is read only")); + } + + @Test + public void testSetPropertySuccess() { + final String script = "!set timeout\n" + + "!set timeout 200\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("timeout -1"), + containsString("timeout 200"))); + } + + @Test + public void testSetPropertyFailure() { + final String script = "!set unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testSetUsage() { + final String script = "!set 1 2 3"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: set [all | []]")); + } + + @Test + public void testSetWrongValueToEnumTypeProperties() { + Collection propertiesWithAvailableValues = + Arrays.stream(BuiltInProperty.values()) + .filter(t -> !t.getAvailableValues().isEmpty()) + .collect(Collectors.toSet()); + final String wrongValue = "wrong_value"; + for (BuiltInProperty property: propertiesWithAvailableValues) { + final String script = + "!set " + property.propertyName() + " " + wrongValue + "\n"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf( + containsString("Unknown " + property.propertyName() + " \"" + + wrongValue + "\""), + not(containsString("Exception")))); + } + } + + @Test + public void testResetSuccess() { + final String script = "!set timeout 200\n" + + "!reset timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + containsString("[timeout] was reset to [-1]")); + } + + @Test + public void testResetFailure() { + final String script = "!reset unk"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Specified property [unk] does not exist." + + " Use !set command to get list of all available properties.")); + } + + @Test + public void testResetAll() { + final String script = "!set timeout 200\n" + + "!reset all\n" + + "!set timeout"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OK), + allOf(containsString("All properties were reset to their defaults."), + containsString("timeout -1"))); + } + + @Test + public void testResetUsage() { + final String script = "!reset"; + checkScriptFile(script, true, equalTo(SqlLine.Status.OTHER), + containsString("Usage: reset (all | )")); + } + + @Test + public void testRerun() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:!/ 4\n" + + "1536743104551:!/ 5\n" + + "1536743104551:!/ 2\n" + + "1536743104551:!/ 7\n" + + "1536743107526:!history\n" + + "1536743115431:!/ 3\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + beeLine.runCommands(dc, + "!set incremental true", + "!set maxcolumnwidth 30", + "!connect " + + ConnectionSpec.H2.url + " " + + ConnectionSpec.H2.username + " " + + "\"\""); + os.reset(); + + beeLine.runCommands(dc, "!/ 1"); + String output = os.toString("UTF8"); + final String expected0 = "+----------------------------+"; + final String expected1 = "| C1 |"; + final String expected2 = "1 row selected"; + assertThat(output, + allOf(containsString(expected0), + containsString(expected1), + containsString(expected2))); + os.reset(); + + beeLine.runCommands(dc, "!/ 4"); + output = os.toString("UTF8"); + String expectedLine3 = "Cycled rerun of commands from history [2, 4]"; + assertThat(output, containsString(expectedLine3)); + os.reset(); + + beeLine.runCommands(dc, "!/ 3"); + output = os.toString("UTF8"); + String expectedLine4 = "Cycled rerun of commands from history [3, 5, 7]"; + assertThat(output, containsString(expectedLine4)); + os.reset(); + + beeLine.runCommands(dc, "!/ 8"); + output = os.toString("UTF8"); + String expectedLine5 = "Cycled rerun of commands from history [8]"; + assertThat(output, containsString(expectedLine5)); + os.reset(); + + beeLine.runCommands(dc, "!rerun " + Integer.MAX_VALUE); + output = os.toString("UTF8"); + String expectedLine6 = + "Usage: rerun , available range of offset is -7..8"; + assertThat(output, containsString(expectedLine6)); + beeLine.runCommands(new DispatchCallback(), "!quit"); + assertTrue(beeLine.isExit()); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testMaxColumnWidthIncremental() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line1 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line2 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line3 = "" + + "+-------------+-------------+\n" + + "| C1 | C2 |\n" + + "+-------------+-------------+\n" + + "| 100 | 200 |\n" + + "+-------------+-------------+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental true\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testMaxColumnWidthBuffered() { + final String script1 = "!set maxcolumnwidth -1\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line1 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + + final String script2 = "!set maxcolumnwidth 0\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line2 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + + final String script3 = "!set maxcolumnwidth 5000\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line3 = "" + + "+-----+-----+\n" + + "| C1 | C2 |\n" + + "+-----+-----+\n" + + "| 100 | 200 |\n" + + "+-----+-----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + + final String script4 = "!set maxcolumnwidth 2\n" + + "!set incremental false\n" + + "values (100, 200)"; + final String line4 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 100 | 200 |\n" + + "+----+----+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + /** Tests with incrementalBufferRows = -1; query stays in non-incremental + * mode. */ + @Test + public void testIncrementalBufferRows() { + final String script1 = "!set incrementalBufferRows -1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line1 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script1, true, equalTo(SqlLine.Status.OK), + containsString(line1)); + } + + /** Tests with incrementalBufferRows = 0; query goes straight into + * incremental mode. */ + @Test + public void testIncrementalBufferRows2() { + final String script2 = "!set incrementalBufferRows 0\n" + + "!set incremental false\n" + + "select * from (values (1, 2), (1, 20), (111, 20), (11, 2222), (1, 22))"; + final String line2 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 1 | 2 |\n" + + "| 1 | 20 |\n" + + "| 111 | 20 |\n" + + "| 11 | 2222 |\n" + + "| 1 | 22 |\n" + + "+----+----+"; + checkScriptFile(script2, true, equalTo(SqlLine.Status.OK), + containsString(line2)); + } + + /** Tests with incrementalBufferRows = 1; query starts in non-incremental mode + * and switches to incremental after 1 row. */ + @Test + public void testIncrementalBufferRows3() { + final String script3 = "!set incrementalBufferRows 1\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222), (111, 2222))"; + final String line3 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "| 111 | 2222 |\n" + + "+----+----+"; + checkScriptFile(script3, true, equalTo(SqlLine.Status.OK), + containsString(line3)); + } + + /** Tests with incrementalBufferRows = 4; query starts in non-incremental mode + * and rows run out before the limit is reached. */ + @Test + public void testIncrementalBufferRows4() { + final String script4 = "!set incrementalBufferRows 4\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2), (111, 2), (11, 2222))"; + final String line4 = "" + + "+-----+------+\n" + + "| C1 | C2 |\n" + + "+-----+------+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "| 111 | 2 |\n" + + "| 11 | 2222 |\n" + + "+-----+------+"; + checkScriptFile(script4, true, equalTo(SqlLine.Status.OK), + containsString(line4)); + } + + @Test + public void testIncrementalBufferRows5() { + // With incrementalBufferRows default (1000), query starts and + // stays in incremental mode. + final String script5 = "!set incrementalBufferRows default\n" + + "!set incremental false\n" + + "select * from (values (10, 20), (1, 2))"; + final String line5 = "" + + "+----+----+\n" + + "| C1 | C2 |\n" + + "+----+----+\n" + + "| 10 | 20 |\n" + + "| 1 | 2 |\n" + + "+----+----+"; + checkScriptFile(script5, true, equalTo(SqlLine.Status.OK), + containsString(line5)); + } + + @Test + public void testMaxHistoryFileRows() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + final File tmpHistoryFile = createTempFile("tmpHistory", "temp"); + try (BufferedWriter bw = + new BufferedWriter( + new OutputStreamWriter( + new FileOutputStream(tmpHistoryFile), + StandardCharsets.UTF_8))) { + bw.write("1536743099591:SELECT \\n CURRENT_TIMESTAMP \\n as \\n c1;\n" + + "1536743104551:SELECT \\n 'asd' as \"sdf\", 4 \\n \\n as \\n c2;\\n\n" + + "1536743104551:SELECT \\n 'asd' \\n as \\n c2;\\n\n" + + "1536743104551:!/ 2\n" + + "1536743104551:SELECT \\n 2123 \\n as \\n c2 from dual;\\n\n" + + "1536743107526:!history\n" + + "1536743115431:SELECT \\n 2 \\n as \\n c2;\n" + + "1536743115431:SELECT \\n '213' \\n as \\n c1;\n" + + "1536743115431:!/ 8\n"); + bw.flush(); + bw.close(); + + SqlLine.Status status = begin(beeLine, os, true, + "--historyfile=" + tmpHistoryFile.getAbsolutePath(), + "-e", "!set maxwidth 80"); + assertThat(status, equalTo(SqlLine.Status.OK)); + DispatchCallback dc = new DispatchCallback(); + + final int maxLines = 3; + beeLine.runCommands(dc, "!set maxHistoryFileRows " + maxLines); + os.reset(); + beeLine.runCommands(dc, "!history"); + assertEquals(maxLines + 1, + os.toString("UTF8").split("\\s+\\d{2}:\\d{2}:\\d{2}\\s+").length); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testSave() { + final SqlLine beeLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + SqlLine.Status status = begin(beeLine, os, false, + "-e", "!save"); + assertThat(status, equalTo(SqlLine.Status.OK)); + final DispatchCallback dc = new DispatchCallback(); + + assertThat(os.toString("UTF8"), + containsString("Saving preferences to")); + os.reset(); + beeLine.runCommands(dc, "!set"); + assertThat(os.toString("UTF8"), + allOf(containsString("autoCommit"), + not(containsString("Unknown property:")))); + os.reset(); + } catch (Exception e) { + // fail + throw new RuntimeException(e); + } + } + + @Test + public void testScript() { + final File file = createTempFile("sqlline", ".script"); + final String script = "!script " + file.getAbsolutePath() + "\n" + + "values (100, 200);\n" + + "!set maxcolumnwidth -1\n" + + "!script\n" + + "values (1, 2);\n"; + final String expected = "(?s)1/5 !script.*" + + "2/5 values \\(100, 200\\);.*" + + "3/5 !set maxcolumnwidth -1.*" + + "4/5 !script.*" + + "5/5 values \\(1, 2\\);.*"; + checkScriptFile(script, false, equalTo(SqlLine.Status.OK), + RegexMatcher.of(expected)); + + final String output = "values \\(100, 200\\);\n" + + "!set maxcolumnwidth -1\n"; + assertFileContains(file, RegexMatcher.of(output)); + } + + @Test + public void testStartupArgsWithoutUrl() { + try { + SqlLine sqlLine = new SqlLine(); + ByteArrayOutputStream os = new ByteArrayOutputStream(); + PrintStream sqllineOutputStream = + new PrintStream(os, false, StandardCharsets.UTF_8.name()); + sqlLine.setOutputStream(sqllineOutputStream); + sqlLine.setErrorStream(sqllineOutputStream); + String[] args = { + "-d", + "org.hsqldb.jdbcDriver", + "-n", + "SCOTT", + "-p", + "TIGER" + }; + DispatchCallback callback = new DispatchCallback(); + sqlLine.initArgs(args, callback); + assertThat(os.toString("UTF8"), containsString(sqlLine.loc("no-url"))); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests setting the "confirm" property. + */ + @Test + public void testConfirmFlag() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + begin(line, os, false, "-e", "!set confirm true"); + assertThat(line.getOpts().getConfirm(), is(true)); + begin(line, os, false, "-e", "!set confirm false"); + assertThat(line.getOpts().getConfirm(), is(false)); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** + * Tests that the "confirm" property works. + */ + @Test + public void testConfirmFlagEffects() { + new MockUp() { + @Mock + int getUserAnswer(String question, int... allowedAnswers) { + return 'n'; + } + }; + + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + assertThat(line.getOpts().getConfirmPattern(), is("default")); + String script = "CREATE TABLE dummy_test(pk int);\n" + + "INSERT INTO dummy_test(pk) VALUES(1);\n" + + "INSERT INTO dummy_test(pk) VALUES(2);\n" + + "INSERT INTO dummy_test(pk) VALUES(3);\n" + + "DELETE FROM dummy_test;\n" + + "DROP TABLE dummy_test;\n"; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OK), + containsString(" ")); + + script = "!set confirm true\n" + script; + checkScriptFile(script, true, + equalTo(SqlLine.Status.OTHER), + containsString(line.loc("abort-action"))); + } + + /** + * Tests that the "confirmPattern" property works. + */ + @Test + public void testConfirmPattern() { + final SqlLine line = new SqlLine(); + assertThat(line.getOpts().getConfirm(), is(false)); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i:(TRUNCATE|ALTER))\""); + assertThat(line.getOpts().getConfirmPattern(), + is("^(?i:(TRUNCATE|ALTER))")); + + begin(line, os, false, "-e", "!set confirmPattern default"); + assertThat(line.getOpts().getConfirmPattern(), + is(line.loc("default-confirm-pattern"))); + } + + /** + * Test for illegal regex in confirmPattern + */ + @Test + public void testExceptionConfirmPattern() { + try { + final SqlLine line = new SqlLine(); + final ByteArrayOutputStream os = new ByteArrayOutputStream(); + assertThat(line.getOpts().getConfirm(), is(false)); + SqlLine.Status status = + begin(line, os, false, "-e", + "!set confirmPattern \"^(?i*:(TRUNCATE|ALTER))\""); + assertThat(status, equalTo(SqlLine.Status.OK)); + assertThat(os.toString("UTF8"), containsString("invalid regex")); + os.reset(); + } catch (Throwable e) { + // fail + throw new RuntimeException(e); + } + } + + /** Information necessary to create a JDBC connection. Specify one to run + * tests against a different database. (hsqldb is the default.) */ + public static class ConnectionSpec { + public final String url; + public final String username; + public final String password; + public final String driver; + + public ConnectionSpec(String url, String username, String password, + String driver) { + this.url = url; + this.username = username; + this.password = password; + this.driver = driver; + } + + public static final ConnectionSpec H2 = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec ERROR_H2_DRIVER = + new ConnectionSpec("jdbc:h2:mem:", "sa", "", "ERROR_DRIVER"); + + public static final ConnectionSpec ERROR_H2_URL = + new ConnectionSpec("ERROR_URL", "sa", "", "org.h2.Driver"); + + public static final ConnectionSpec HSQLDB = + new ConnectionSpec( + ScottHsqldb.URI, ScottHsqldb.USER, ScottHsqldb.PASSWORD, + "org.hsqldb.jdbcDriver"); + + public static final ConnectionSpec MYSQL = + new ConnectionSpec( + "jdbc:mysql://localhost/scott", "scott", "tiger", + "com.mysql.jdbc.Driver"); + } + + /** Regular expression matcher. */ + private static class RegexMatcher extends BaseMatcher { + private final String pattern; + + RegexMatcher(String pattern) { + super(); + this.pattern = pattern; + } + + public static RegexMatcher of(String pattern) { + return new RegexMatcher(pattern); + } + + public boolean matches(Object o) { + return o instanceof String + && ((String) o).matches(pattern); + } + + public void describeTo(Description description) { + description.appendText("regular expression ").appendText(pattern); + } + } + +} + +// End SqlLineArgsTest.java + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PrintStream` acquired by call to `SqlLine()` at line 1077 is not released after line 1082. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testNPE() + +### Procedure Id: +sqlline.SqlLineArgsTest.testNPE():void.f497417622c772629e5984dd5ffe663f + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testNPE|RESOURCE_LEAK + +### Node Key: +83dd0b424ff41162de0c33c9b165340c + +### Hash: +6dc04971d8f703294b357d0ce1729f7a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8151/instruction.md b/inferredbugs-8151/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c3594b7fb99b47b8f51bfb376634e8f8c565e09 --- /dev/null +++ b/inferredbugs-8151/instruction.md @@ -0,0 +1,471 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 15 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.domain; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import de.slackspace.openkeepass.crypto.RandomGenerator; +import de.slackspace.openkeepass.exception.KeePassHeaderUnreadableException; +import de.slackspace.openkeepass.util.ByteUtils; + +public class KeePassHeader { + + private static final int SIZE_OF_FIELD_LENGTH_BUFFER = 3; + + // Header Fields + public static final int CIPHER = 2; + public static final int COMPRESSION = 3; + public static final int MASTER_SEED = 4; + public static final int TRANSFORM_SEED = 5; + public static final int TRANSFORM_ROUNDS = 6; + public static final int ENCRYPTION_IV = 7; + public static final int PROTECTED_STREAM_KEY = 8; + public static final int STREAM_START_BYTES = 9; + public static final int INNER_RANDOM_STREAM_ID = 10; + + // KeePass 2.x signature + private static final byte[] DATABASE_V2_FILE_SIGNATURE_1 = ByteUtils.hexStringToByteArray("03d9a29a"); + private static final byte[] DATABASE_V2_FILE_SIGNATURE_2 = ByteUtils.hexStringToByteArray("67fb4bb5"); + private static final byte[] DATABASE_V2_FILE_VERSION = ByteUtils.hexStringToByteArray("00000300"); + + // KeePass Magic Bytes for AES Cipher + private static final byte[] DATABASE_V2_AES_CIPHER = ByteUtils + .hexStringToByteArray("31C1F2E6BF714350BE5805216AFC5AFF"); + + // KeePass version signature length in bytes + public static final int VERSION_SIGNATURE_LENGTH = 12; + + // KeePass 2.x signature + private static final int DATABASE_V2_FILE_SIGNATURE_1_INT = 0x9AA2D903 & 0xFF; + private static final int DATABASE_V2_FILE_SIGNATURE_2_INT = 0xB54BFB67 & 0xFF; + + // KeePass 1.x signature + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_1_INT = 0x9AA2D903 & 0xFF; + private static final int OLD_DATABASE_V1_FILE_SIGNATURE_2_INT = 0xB54BFB65 & 0xFF; + + private byte[] cipher; + private byte[] encryptionIV; + private byte[] streamStartBytes; + private byte[] masterSeed; + private byte[] transformSeed; + private byte[] protectedStreamKey; + private CompressionAlgorithm compression; + private long transformRounds; + private CrsAlgorithm crsAlgorithm; + + public void setValue(int headerId, byte[] value) { + switch (headerId) { + case CIPHER: + setCipher(value); + break; + case COMPRESSION: + setCompressionFlag(value); + break; + case MASTER_SEED: + setMasterSeed(value); + break; + case TRANSFORM_SEED: + setTransformSeed(value); + break; + case TRANSFORM_ROUNDS: + setTransformRounds(value); + break; + case ENCRYPTION_IV: + setEncryptionIV(value); + break; + case PROTECTED_STREAM_KEY: + setProtectedStreamKey(value); + break; + case STREAM_START_BYTES: + setStreamStartBytes(value); + break; + case INNER_RANDOM_STREAM_ID: + setInnerRandomStreamId(value); + break; + } + } + + public void checkVersionSupport(byte[] keepassFile) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + + byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; + bufferedInputStream.read(signature); + + ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); + signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); + + int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); + + if (signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1_INT && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2_INT) { + return; + } else if (signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1_INT + && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2_INT) { + throw new UnsupportedOperationException( + "The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); + } else { + throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); + } + } + + /** + * Initializes the header values from a given byte array. + * + * @param keepassFile + * the byte array to read from + * @throws IOException + * if the header cannot be read + */ + public void read(byte[] keepassFile) throws IOException { + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); + bufferedInputStream.skip(VERSION_SIGNATURE_LENGTH); // skip version + + while (true) { + try { + int fieldId = bufferedInputStream.read(); + byte[] fieldLength = new byte[2]; + bufferedInputStream.read(fieldLength); + + ByteBuffer fieldLengthBuffer = ByteBuffer.wrap(fieldLength); + fieldLengthBuffer.order(ByteOrder.LITTLE_ENDIAN); + int fieldLengthInt = ByteUtils.toUnsignedInt(fieldLengthBuffer.getShort()); + + if (fieldLengthInt > 0) { + byte[] data = new byte[fieldLengthInt]; + bufferedInputStream.read(data); + setValue(fieldId, data); + } + + if (fieldId == 0) { + break; + } + } catch (IOException e) { + throw new KeePassHeaderUnreadableException("Could not read header input", e); + } + } + } + + /** + * Returns the whole header as byte array. + * + * @return header as byte array + */ + public byte[] getBytes() { + try { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + + stream.write(DATABASE_V2_FILE_SIGNATURE_1); + stream.write(DATABASE_V2_FILE_SIGNATURE_2); + stream.write(DATABASE_V2_FILE_VERSION); + + for (int i = 2; i < 11; i++) { + byte[] headerValue = getValue(i); + + // Write index + stream.write(i); + + // Write length + byte[] length = new byte[] { (byte) headerValue.length, 0 }; + stream.write(length); + + // Write value + stream.write(headerValue); + } + + // Write terminating flag + stream.write(getEndOfHeader()); + + return stream.toByteArray(); + } catch (IOException e) { + throw new KeePassHeaderUnreadableException("Could not write header value to stream", e); + } + } + + private byte[] getEndOfHeader() { + try { + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + stream.write(0); + stream.write(4); + stream.write(0); + stream.write("\r\n\r\n".getBytes()); + + return stream.toByteArray(); + } catch (IOException e) { + throw new KeePassHeaderUnreadableException("Could not write end of header to stream", e); + } + } + + public byte[] getValue(int headerId) { + switch (headerId) { + case CIPHER: + return getCipher(); + case COMPRESSION: + return getCompressionFlag(); + case MASTER_SEED: + return getMasterSeed(); + case TRANSFORM_SEED: + return getTransformSeed(); + case TRANSFORM_ROUNDS: + return getTransformRoundsByte(); + case ENCRYPTION_IV: + return getEncryptionIV(); + case PROTECTED_STREAM_KEY: + return getProtectedStreamKey(); + case STREAM_START_BYTES: + return getStreamStartBytes(); + case INNER_RANDOM_STREAM_ID: + return getInnerRandomStreamId(); + } + + return new byte[0]; + } + + private void setInnerRandomStreamId(byte[] value) { + ByteBuffer buffer = wrapInBuffer(value); + int intValue = buffer.getInt(); + crsAlgorithm = CrsAlgorithm.parseValue(intValue); + } + + private byte[] getInnerRandomStreamId() { + int intValue = CrsAlgorithm.getIntValue(crsAlgorithm); + return wrapInBuffer(intValue); + } + + private void setStreamStartBytes(byte[] value) { + streamStartBytes = value; + } + + private void setProtectedStreamKey(byte[] value) { + protectedStreamKey = value; + } + + private void setEncryptionIV(byte[] value) { + encryptionIV = value; + } + + private void setTransformRounds(byte[] value) { + ByteBuffer buffer = wrapInBuffer(value); + transformRounds = buffer.getLong(); + } + + private void setTransformSeed(byte[] value) { + transformSeed = value; + } + + private void setMasterSeed(byte[] value) { + masterSeed = value; + } + + private void setCompressionFlag(byte[] value) { + ByteBuffer buffer = wrapInBuffer(value); + int intValue = buffer.getInt(); + + compression = CompressionAlgorithm.parseValue(intValue); + } + + public void setCompression(CompressionAlgorithm algorithm) { + compression = algorithm; + } + + private byte[] getCompressionFlag() { + int intValue = CompressionAlgorithm.getIntValue(compression); + return wrapInBuffer(intValue); + } + + private void setCipher(byte[] value) { + if (value == null || value.length != 16) { + throw new IllegalArgumentException("The encryption cipher must contain 16 bytes!"); + } + cipher = value; + } + + public byte[] getCipher() { + return cipher; + } + + public CompressionAlgorithm getCompression() { + return compression; + } + + public long getTransformRounds() { + return transformRounds; + } + + public void setTransformRounds(long rounds) { + transformRounds = rounds; + } + + private byte[] getTransformRoundsByte() { + return wrapInBuffer(transformRounds); + } + + public byte[] getEncryptionIV() { + return encryptionIV; + } + + public byte[] getStreamStartBytes() { + return streamStartBytes; + } + + public CrsAlgorithm getCrsAlgorithm() { + return crsAlgorithm; + } + + public void setCrsAlgorithm(CrsAlgorithm algorithm) { + crsAlgorithm = algorithm; + } + + public byte[] getMasterSeed() { + return masterSeed; + } + + public byte[] getTransformSeed() { + return transformSeed; + } + + public int getHeaderSize() { + int size = 0; + + // Add size of values + for (int i = 2; i < 11; i++) { + byte[] value = getValue(i); + + if (value != null) { + size += value.length + SIZE_OF_FIELD_LENGTH_BUFFER; + } + } + + // Add size of header end + size += getEndOfHeader().length; + + return size; + } + + public byte[] getProtectedStreamKey() { + return protectedStreamKey; + } + + private ByteBuffer wrapInBuffer(byte[] value) { + ByteBuffer buffer = ByteBuffer.wrap(value); + buffer.order(ByteOrder.LITTLE_ENDIAN); + return buffer; + } + + private byte[] wrapInBuffer(int value) { + ByteBuffer buffer = ByteBuffer.allocate(4); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putInt(value); + return buffer.array(); + } + + private byte[] wrapInBuffer(long value) { + ByteBuffer buffer = ByteBuffer.allocate(8); + buffer.order(ByteOrder.LITTLE_ENDIAN); + buffer.putLong(value); + return buffer.array(); + } + + /** + * Initializes the header with default values and creates new random values + * for crypto keys. + *

    + * Default values: + *

      + *
    • Compression: GZIP
    • + *
    • CrsAlgorithm: Salsa20
    • + *
    • TransformRounds: 8000 + *
    • + *
    • Cipher: AES
    • + *
    + */ + public void initialize() { + RandomGenerator random = new RandomGenerator(); + + setCompression(CompressionAlgorithm.Gzip); + setCrsAlgorithm(CrsAlgorithm.Salsa20); + setTransformRounds(8000); + setMasterSeed(random.getRandomBytes(32)); + setTransformSeed(random.getRandomBytes(32)); + setEncryptionIV(random.getRandomBytes(16)); + setProtectedStreamKey(random.getRandomBytes(32)); + setStreamStartBytes(random.getRandomBytes(32)); + setCipher(DATABASE_V2_AES_CIPHER); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedInputStream` acquired to `bufferedInputStream` by call to `new()` at line 92 is not released after line 95. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void KeePassHeader.checkVersionSupport(byte[]) + +### Procedure Id: +de.slackspace.openkeepass.domain.KeePassHeader.checkVersionSupport(byte[]):void.a3f8ba4259968d2049e4950f663bc6c5 + +### File: +src/main/java/de/slackspace/openkeepass/domain/KeePassHeader.java + +### Key: +KeePassHeader.java|checkVersionSupport|RESOURCE_LEAK + +### Node Key: +08038b5f1153a3f1e72ab3f29b05862b + +### Hash: +53d3977b55ccc89f0faa1f171dc21ae9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8156/instruction.md b/inferredbugs-8156/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bffe2803e49e9471c59b5b1daf305bc81fcfcbfa --- /dev/null +++ b/inferredbugs-8156/instruction.md @@ -0,0 +1,169 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.parser; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.TimeZone; + +import junit.framework.Assert; + +import org.junit.BeforeClass; +import org.junit.Test; + +import de.slackspace.openkeepass.crypto.Salsa20; +import de.slackspace.openkeepass.domain.Entry; +import de.slackspace.openkeepass.domain.Group; +import de.slackspace.openkeepass.domain.KeePassFile; +import de.slackspace.openkeepass.util.ByteUtils; + +public class XmlParserTest { + + private byte[] protectedStreamKey = ByteUtils.hexStringToByteArray("ec77a2169769734c5d26e5341401f8d7b11052058f8455d314879075d0b7e257"); + private static SimpleDateFormat dateFormatter; + + @BeforeClass + public static void init() { + // make sure we use UTC time + dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectMetadata() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + Assert.assertEquals("KeePass", keePassFile.getMeta().getGenerator()); + Assert.assertEquals("TestDatabase", keePassFile.getMeta().getDatabaseName()); + Assert.assertEquals("Just a sample db", keePassFile.getMeta().getDatabaseDescription()); + Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseNameChanged().getTime())); + Assert.assertEquals("2014-11-22 18:59:39", dateFormatter.format(keePassFile.getMeta().getDatabaseDescriptionChanged().getTime())); + Assert.assertEquals(365, keePassFile.getMeta().getMaintenanceHistoryDays()); + Assert.assertEquals(true, keePassFile.getMeta().getRecycleBinEnabled()); + Assert.assertEquals("AAAAAAAAAAAAAAAAAAAAAA==", keePassFile.getMeta().getRecycleBinUuid()); + Assert.assertEquals("2014-11-22 18:58:56", dateFormatter.format(keePassFile.getMeta().getRecycleBinChanged().getTime())); + Assert.assertEquals(10, keePassFile.getMeta().getHistoryMaxItems()); + Assert.assertEquals(6291456, keePassFile.getMeta().getHistoryMaxSize()); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + + List groups = keePassFile.getTopGroups(); + Assert.assertNotNull(groups); + + Assert.assertEquals(6, groups.size()); + Assert.assertEquals("General", groups.get(0).getName()); + Assert.assertEquals("FqvMJ8yjlUSAEt9OmNSj2A==", groups.get(0).getUuid()); + + Assert.assertEquals("Windows", groups.get(1).getName()); + Assert.assertEquals("rXt7D+EM/0qW1rgPB4g5nw==", groups.get(1).getUuid()); + + Assert.assertEquals("Network", groups.get(2).getName()); + Assert.assertEquals("DwdAaKn4tEyXFlU56/2UBQ==", groups.get(2).getUuid()); + + Assert.assertEquals("Internet", groups.get(3).getName()); + Assert.assertEquals("COgUrPt5P0676DeyZn/auQ==", groups.get(3).getUuid()); + + Assert.assertEquals("eMail", groups.get(4).getName()); + Assert.assertEquals("/xWfOfnC6ki76sNhrZR7rw==", groups.get(4).getUuid()); + + Assert.assertEquals("Homebanking", groups.get(5).getName()); + Assert.assertEquals("Rdjt21Jla0+E5Q9ElJHw1g==", groups.get(5).getUuid()); + } + + @Test + public void whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectEntries() throws FileNotFoundException { + FileInputStream fileInputStream = new FileInputStream("target/test-classes/testDatabase_decrypted.xml"); + KeePassFile keePassFile = new XmlParser().parse(fileInputStream, Salsa20.createInstance(protectedStreamKey)); + + List entries = keePassFile.getTopEntries(); + Assert.assertNotNull(entries); + + Assert.assertEquals(2, entries.size()); + Assert.assertEquals("libdLW88cU6BvrPQlvKqMA==", entries.get(0).getUuid()); + Assert.assertEquals(5, entries.get(0).getProperties().size()); + Assert.assertEquals("Sample Entry", entries.get(0).getTitle()); + Assert.assertEquals("http://keepass.info/", entries.get(0).getUrl()); + Assert.assertEquals("User Name", entries.get(0).getUsername()); + Assert.assertEquals("Notes", entries.get(0).getNotes()); + Assert.assertEquals("Password", entries.get(0).getPassword()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired to `fileInputStream` by call to `FileInputStream(...)` at line 51 is not released after line 75. +**Note**: potential exception at line 52 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void XmlParserTest.whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups() + +### Procedure Id: +de.slackspace.openkeepass.parser.XmlParserTest.whenInputIsValidKeePassXmlShouldParseFileAndReturnCor.617a6736bea7c780a2909a30ffa315cd + +### File: +src/test/java/de/slackspace/openkeepass/parser/XmlParserTest.java + +### Key: +XmlParserTest.java|whenInputIsValidKeePassXmlShouldParseFileAndReturnCorrectGroups|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +f5472b9598d7295149acecf4966ef394 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8157/instruction.md b/inferredbugs-8157/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a8acd4585d3593cfab5b3f35dbb0b0a72b9476a --- /dev/null +++ b/inferredbugs-8157/instruction.md @@ -0,0 +1,133 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** openkeepass +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.slackspace.openkeepass.crypto; + +import de.slackspace.openkeepass.domain.KeePassHeader; +import de.slackspace.openkeepass.util.StreamUtils; + +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +public class Decrypter { + + public byte[] decryptDatabase(byte[] password, KeePassHeader header, byte[] database) throws IOException { + byte[] aesKey = createAesKey(password, header); + + return processDatabaseEncryption(false, database, header, aesKey); + } + + public byte[] encryptDatabase(byte[] password, KeePassHeader header, byte[] database) throws IOException { + byte[] aesKey = createAesKey(password, header); + + return processDatabaseEncryption(true, database, header, aesKey); + } + + private byte[] processDatabaseEncryption(boolean encrypt, byte[] database, KeePassHeader header, byte[] aesKey) + throws IOException { + byte[] metaData = new byte[KeePassHeader.VERSION_SIGNATURE_LENGTH + header.getHeaderSize()]; + BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(database)); + bufferedInputStream.read(metaData); + + byte[] payload = StreamUtils.toByteArray(bufferedInputStream); + byte[] processedPayload; + if (encrypt) { + processedPayload = Aes.encrypt(aesKey, header.getEncryptionIV(), payload); + } else { + processedPayload = Aes.decrypt(aesKey, header.getEncryptionIV(), payload); + } + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + output.write(metaData); + output.write(processedPayload); + + return output.toByteArray(); + } + + private byte[] createAesKey(byte[] password, KeePassHeader header) { + byte[] hashedPwd = Sha256.hash(password); + + byte[] transformedPwd = Aes.transformKey(header.getTransformSeed(), hashedPwd, header.getTransformRounds()); + byte[] transformedHashedPwd = Sha256.hash(transformedPwd); + + ByteArrayOutputStream stream = new ByteArrayOutputStream(); + stream.write(header.getMasterSeed(), 0, 32); + stream.write(transformedHashedPwd, 0, 32); + + return Sha256.hash(stream.toByteArray()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedInputStream` acquired to `bufferedInputStream` by call to `new()` at line 28 is not released after line 43. +**Note**: potential exception at line 29 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] Decrypter.processDatabaseEncryption(boolean,byte[],KeePassHeader,byte[]) + +### Procedure Id: +de.slackspace.openkeepass.crypto.Decrypter.processDatabaseEncryption(boolean,byte[],de.slackspace.op.1ee10d63f652a7ddffe99dbac07afd71 + +### File: +src/main/java/de/slackspace/openkeepass/crypto/Decrypter.java + +### Key: +Decrypter.java|processDatabaseEncryption|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +274e9e964841a2da2f1fd94047c5a5d0 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8158/instruction.md b/inferredbugs-8158/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3bbaa57f593498dcb019e73ea44da0c8bca74f5e --- /dev/null +++ b/inferredbugs-8158/instruction.md @@ -0,0 +1,253 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** elasticsearch-analysis-dynamic-synonym +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + */ +package com.bellszhu.elasticsearch.plugin.synonym.analysis; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpHead; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.synonym.SolrSynonymParser; +import org.apache.lucene.analysis.synonym.SynonymMap; +import org.apache.lucene.analysis.synonym.WordnetSynonymParser; +import org.elasticsearch.ElasticsearchIllegalArgumentException; +import org.elasticsearch.common.logging.ESLogger; +import org.elasticsearch.common.logging.Loggers; +import org.elasticsearch.env.Environment; + +/** + * @author bells + * + */ +public class RemoteSynonymFile implements SynonymFile { + + public static ESLogger logger = Loggers.getLogger("dynamic-synonym"); + + private CloseableHttpClient httpclient = HttpClients.createDefault(); + + private String format; + + private boolean expand; + + private Analyzer analyzer; + + private Environment env; + + /** 远程url地址 */ + private String location; + + /** 上次更改时间 */ + private String lastModified; + + /** 资源属性 */ + private String eTags; + + public RemoteSynonymFile(Environment env, Analyzer analyzer, + boolean expand, String format, String location) { + this.analyzer = analyzer; + this.expand = expand; + this.format = format; + this.env = env; + this.location = location; + } + + @Override + public SynonymMap reloadSynonymMap() { + try { + Reader rulesReader = getReader(); + SynonymMap.Builder parser = null; + + if ("wordnet".equalsIgnoreCase(format)) { + parser = new WordnetSynonymParser(true, expand, analyzer); + ((WordnetSynonymParser) parser).parse(rulesReader); + } else { + parser = new SolrSynonymParser(true, expand, analyzer); + ((SolrSynonymParser) parser).parse(rulesReader); + } + return parser.build(); + } catch (Exception e) { + logger.error("reload remote synonym {} error!", e, location); + throw new ElasticsearchIllegalArgumentException( + "could not reload remote synonyms file", e); + } + } + + /** + * 从远程服务器上下载自定义词条 + */ + public Reader getReader() { + RequestConfig rc = RequestConfig.custom() + .setConnectionRequestTimeout(10 * 1000) + .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000) + .build(); + CloseableHttpResponse response = null; + BufferedReader in = null; + HttpGet get = new HttpGet(location); + get.setConfig(rc); + try { + response = httpclient.execute(get); + if (response.getStatusLine().getStatusCode() == 200) { + String charset = "UTF-8"; // 获取编码,默认为utf-8 + if (response.getEntity().getContentType().getValue() + .contains("charset=")) { + String contentType = response.getEntity().getContentType() + .getValue(); + charset = contentType.substring(contentType + .lastIndexOf("=") + 1); + } + in = new BufferedReader(new InputStreamReader(response + .getEntity().getContent(), charset)); + } + } catch (IOException e) { + logger.error("get remote synonym reader {} error!", e, location); + throw new ElasticsearchIllegalArgumentException( + "IOException while reading remote synonyms file", e); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return in; + } + + @Override + public boolean isNeedReloadSynonymMap() { + RequestConfig rc = RequestConfig.custom() + .setConnectionRequestTimeout(10 * 1000) + .setConnectTimeout(10 * 1000).setSocketTimeout(15 * 1000) + .build(); + HttpHead head = new HttpHead(location); + head.setConfig(rc); + + // 设置请求头 + if (lastModified != null) { + head.setHeader("If-Modified-Since", lastModified); + } + if (eTags != null) { + head.setHeader("If-None-Match", eTags); + } + + CloseableHttpResponse response = null; + try { + response = httpclient.execute(head); + if (response.getStatusLine().getStatusCode() == 200) { // 返回200 才做操作 + if (!response.getLastHeader("Last-Modified").getValue() + .equalsIgnoreCase(lastModified) + || !response.getLastHeader("ETag").getValue() + .equalsIgnoreCase(eTags)) { + + lastModified = response.getLastHeader("Last-Modified") == null ? null + : response.getLastHeader("Last-Modified") + .getValue(); + eTags = response.getLastHeader("ETag") == null ? null + : response.getLastHeader("ETag").getValue(); + return true; + } + } else if (response.getStatusLine().getStatusCode() == 304) { + return false; + } else { + logger.info("remote synonym {} return bad code {}", location, + response.getStatusLine().getStatusCode()); + } + + } catch (IOException e) { + logger.error("check need reload remote synonym {} error!", e, location); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + + } + } + return false; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `getReader()` at line 65 is not released after line 70. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SynonymMap RemoteSynonymFile.reloadSynonymMap() + +### Procedure Id: +com.bellszhu.elasticsearch.plugin.synonym.analysis.RemoteSynonymFile.reloadSynonymMap():org.apache.l.aa2a07f4a01b27079439b8a681707bcd + +### File: +src/main/java/com/bellszhu/elasticsearch/plugin/synonym/analysis/RemoteSynonymFile.java + +### Key: +RemoteSynonymFile.java|reloadSynonymMap|RESOURCE_LEAK + +### Node Key: +5b3fa5c793240ccb2ff9640dfe8fac58 + +### Hash: +f429d34d4f6bfba5b50b51a11b3d39ac + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8159/instruction.md b/inferredbugs-8159/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bb6e2161c864e52f235e2b02b1c62b1040c0849 --- /dev/null +++ b/inferredbugs-8159/instruction.md @@ -0,0 +1,253 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** elasticsearch-analysis-dynamic-synonym +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + */ +package com.bellszhu.elasticsearch.plugin.synonym.analysis; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.Reader; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpHead; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.lucene.analysis.Analyzer; +import org.apache.lucene.analysis.synonym.SolrSynonymParser; +import org.apache.lucene.analysis.synonym.SynonymMap; +import org.apache.lucene.analysis.synonym.WordnetSynonymParser; +import org.elasticsearch.ElasticsearchIllegalArgumentException; +import org.elasticsearch.common.logging.ESLogger; +import org.elasticsearch.common.logging.Loggers; +import org.elasticsearch.env.Environment; + +/** + * @author bells + * + */ +public class RemoteSynonymFile implements SynonymFile { + + public static ESLogger logger = Loggers.getLogger("dynamic-synonym"); + + private CloseableHttpClient httpclient = HttpClients.createDefault(); + + private String format; + + private boolean expand; + + private Analyzer analyzer; + + private Environment env; + + /** 远程url地址 */ + private String location; + + /** 上次更改时间 */ + private String lastModified; + + /** 资源属性 */ + private String eTags; + + public RemoteSynonymFile(Environment env, Analyzer analyzer, + boolean expand, String format, String location) { + this.analyzer = analyzer; + this.expand = expand; + this.format = format; + this.env = env; + this.location = location; + } + + @Override + public SynonymMap reloadSynonymMap() { + try { + Reader rulesReader = getReader(); + SynonymMap.Builder parser = null; + + if ("wordnet".equalsIgnoreCase(format)) { + parser = new WordnetSynonymParser(true, expand, analyzer); + ((WordnetSynonymParser) parser).parse(rulesReader); + } else { + parser = new SolrSynonymParser(true, expand, analyzer); + ((SolrSynonymParser) parser).parse(rulesReader); + } + return parser.build(); + } catch (Exception e) { + logger.error("reload remote synonym {} error!", e, location); + throw new ElasticsearchIllegalArgumentException( + "could not reload remote synonyms file", e); + } + } + + /** + * 从远程服务器上下载自定义词条 + */ + public Reader getReader() { + RequestConfig rc = RequestConfig.custom() + .setConnectionRequestTimeout(10 * 1000) + .setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000) + .build(); + CloseableHttpResponse response = null; + BufferedReader in = null; + HttpGet get = new HttpGet(location); + get.setConfig(rc); + try { + response = httpclient.execute(get); + if (response.getStatusLine().getStatusCode() == 200) { + String charset = "UTF-8"; // 获取编码,默认为utf-8 + if (response.getEntity().getContentType().getValue() + .contains("charset=")) { + String contentType = response.getEntity().getContentType() + .getValue(); + charset = contentType.substring(contentType + .lastIndexOf("=") + 1); + } + in = new BufferedReader(new InputStreamReader(response + .getEntity().getContent(), charset)); + } + } catch (IOException e) { + logger.error("get remote synonym reader {} error!", e, location); + throw new ElasticsearchIllegalArgumentException( + "IOException while reading remote synonyms file", e); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + return in; + } + + @Override + public boolean isNeedReloadSynonymMap() { + RequestConfig rc = RequestConfig.custom() + .setConnectionRequestTimeout(10 * 1000) + .setConnectTimeout(10 * 1000).setSocketTimeout(15 * 1000) + .build(); + HttpHead head = new HttpHead(location); + head.setConfig(rc); + + // 设置请求头 + if (lastModified != null) { + head.setHeader("If-Modified-Since", lastModified); + } + if (eTags != null) { + head.setHeader("If-None-Match", eTags); + } + + CloseableHttpResponse response = null; + try { + response = httpclient.execute(head); + if (response.getStatusLine().getStatusCode() == 200) { // 返回200 才做操作 + if (!response.getLastHeader("Last-Modified").getValue() + .equalsIgnoreCase(lastModified) + || !response.getLastHeader("ETag").getValue() + .equalsIgnoreCase(eTags)) { + + lastModified = response.getLastHeader("Last-Modified") == null ? null + : response.getLastHeader("Last-Modified") + .getValue(); + eTags = response.getLastHeader("ETag") == null ? null + : response.getLastHeader("ETag").getValue(); + return true; + } + } else if (response.getStatusLine().getStatusCode() == 304) { + return false; + } else { + logger.info("remote synonym {} return bad code {}", location, + response.getStatusLine().getStatusCode()); + } + + } catch (IOException e) { + logger.error("check need reload remote synonym {} error!", e, location); + } finally { + try { + if (response != null) { + response.close(); + } + } catch (IOException e) { + e.printStackTrace(); + + } + } + return false; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `getReader()` at line 65 is not released after line 73. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SynonymMap RemoteSynonymFile.reloadSynonymMap() + +### Procedure Id: +com.bellszhu.elasticsearch.plugin.synonym.analysis.RemoteSynonymFile.reloadSynonymMap():org.apache.l.aa2a07f4a01b27079439b8a681707bcd + +### File: +src/main/java/com/bellszhu/elasticsearch/plugin/synonym/analysis/RemoteSynonymFile.java + +### Key: +RemoteSynonymFile.java|reloadSynonymMap|RESOURCE_LEAK + +### Node Key: +5b3fa5c793240ccb2ff9640dfe8fac58 + +### Hash: +f429d34d4f6bfba5b50b51a11b3d39ac + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8160/instruction.md b/inferredbugs-8160/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f499c0302057239624b8b7384749f39c6de9754 --- /dev/null +++ b/inferredbugs-8160/instruction.md @@ -0,0 +1,148 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** generic-webhook-trigger-plugin +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.jenkinsci.plugins.gwt.whitelist; + +import static org.jenkinsci.plugins.gwt.whitelist.HMACVerifier.hmacVerify; + +import com.google.common.base.Optional; +import java.util.List; +import java.util.Map; +import org.jenkinsci.plugins.gwt.global.CredentialsHelper; +import org.jenkinsci.plugins.gwt.global.Whitelist; +import org.jenkinsci.plugins.gwt.global.WhitelistItem; +import org.jenkinsci.plugins.plaincredentials.StringCredentials; + +public class WhitelistVerifier { + + public static void verifyWhitelist( + final String remoteHost, final Map> headers, final String postContent) + throws WhitelistException { + final Whitelist whitelist = Whitelist.get(); + doVerifyWhitelist(remoteHost, headers, postContent, whitelist); + } + + static void doVerifyWhitelist( + final String remoteHost, + final Map> headers, + final String postContent, + final Whitelist whitelist) + throws WhitelistException { + if (whitelist.getWhitelistItems().isEmpty() || !whitelist.isEnabled()) { + return; + } + final StringBuilder messages = new StringBuilder(); + int i = 0; + for (final WhitelistItem whitelistItem : whitelist.getWhitelistItems()) { + i++; + try { + whitelistVerify(remoteHost, whitelistItem, headers, postContent); + return; + } catch (final WhitelistException e) { + messages.append(i + ") " + e.getMessage() + "\n"); + } + } + final String messagesString = messages.toString(); + throw new WhitelistException("Did not find a matching whitelisted host:\n" + messagesString); + } + + static void whitelistVerify( + final String remoteHost, + final WhitelistItem whitelistItem, + final Map> headers, + final String postContent) + throws WhitelistException { + + String whitelistHost = whitelistItem.getHost(); + + if (HostVerifier.whitelistContains(remoteHost, whitelistHost)) { + if (whitelistItem.isHmacEnabled()) { + final Optional hmacKeyOpt = + CredentialsHelper.findCredentials(whitelistItem.getHmacCredentialId()); + if (!hmacKeyOpt.isPresent()) { + throw new WhitelistException( + "Was unable to find secret text credential " + whitelistItem.getHmacCredentialId()); + } + final String hmacHeader = whitelistItem.getHmacHeader(); + final String hmacKey = hmacKeyOpt.get().getSecret().getPlainText(); + final String hmacAlgorithm = whitelistItem.getHmacAlgorithm(); + hmacVerify(headers, postContent, hmacHeader, hmacKey, hmacAlgorithm); + return; + } + return; + } + throw new WhitelistException( + "Sending host \"" + remoteHost + "\" was not matched by whitelist."); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `whitelistHost` last assigned on line 53 could be null and is dereferenced by call to `whitelistContains(...)` at line 55. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WhitelistVerifier.whitelistVerify(String,WhitelistItem,Map,String) + +### Procedure Id: +org.jenkinsci.plugins.gwt.whitelist.WhitelistVerifier.whitelistVerify(java.lang.String,org.jenkinsci.a3249383b74d0c1e00a75708a8cbe052 + +### File: +src/main/java/org/jenkinsci/plugins/gwt/whitelist/WhitelistVerifier.java + +### Key: +WhitelistVerifier.java|whitelistVerify|NULL_DEREFERENCE + +### Node Key: +18086a76ec6f499138a84f176568ec09 + +### Hash: +37b9c075a6c8cb7a66e3938befaca2da + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8161/instruction.md b/inferredbugs-8161/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af649fe4e15475df2b71c98a388dfab1bf340224 --- /dev/null +++ b/inferredbugs-8161/instruction.md @@ -0,0 +1,1116 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +package org.shredzone.acme4j.connector; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.shredzone.acme4j.toolbox.TestUtils.url; +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URI; +import java.net.URL; +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.jose4j.base64url.Base64Url; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwx.CompactSerializer; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.shredzone.acme4j.Login; +import org.shredzone.acme4j.Session; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.exception.AcmeProtocolException; +import org.shredzone.acme4j.exception.AcmeRateLimitedException; +import org.shredzone.acme4j.exception.AcmeRetryAfterException; +import org.shredzone.acme4j.exception.AcmeServerException; +import org.shredzone.acme4j.exception.AcmeUnauthorizedException; +import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; +import org.shredzone.acme4j.provider.AcmeProvider; +import org.shredzone.acme4j.toolbox.AcmeUtils; +import org.shredzone.acme4j.toolbox.JSON; +import org.shredzone.acme4j.toolbox.JSONBuilder; +import org.shredzone.acme4j.toolbox.TestUtils; + +/** + * Unit tests for {@link DefaultConnection}. + */ +public class DefaultConnectionTest { + + private URL requestUrl = TestUtils.url("http://example.com/acme/"); + private URL accountUrl = TestUtils.url(TestUtils.ACCOUNT_URL); + private HttpURLConnection mockUrlConnection; + private HttpConnector mockHttpConnection; + private Session session; + private Login login; + private KeyPair keyPair; + + @Before + public void setup() throws AcmeException, IOException { + mockUrlConnection = mock(HttpURLConnection.class); + + mockHttpConnection = mock(HttpConnector.class); + when(mockHttpConnection.openConnection(requestUrl, Proxy.NO_PROXY)).thenReturn(mockUrlConnection); + + final AcmeProvider mockProvider = mock(AcmeProvider.class); + when(mockProvider.directory( + ArgumentMatchers.any(Session.class), + ArgumentMatchers.eq(URI.create(TestUtils.ACME_SERVER_URI)))) + .thenReturn(TestUtils.getJSON("directory")); + + session = TestUtils.session(mockProvider); + session.setLocale(Locale.JAPAN); + + keyPair = TestUtils.createKeyPair(); + + login = session.login(accountUrl, keyPair); + } + + /** + * Test that {@link DefaultConnection#getNonce()} returns {@code null} if there is no + * {@code Replay-Nonce} header. + */ + @Test + public void testNoNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(null); + + assertThat(session.getNonce(), is(nullValue())); + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} extracts a {@code Replay-Nonce} + * header correctly. + */ + @Test + public void testGetNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(TestUtils.DUMMY_NONCE)); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} fails on an invalid + * {@code Replay-Nonce} header. + */ + @Test + public void testInvalidNonceFromHeader() { + String badNonce = "#$%&/*+*#'"; + + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(badNonce); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.getNonce(); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), org.hamcrest.Matchers.startsWith("Invalid replay nonce")); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#resetNonce(Session)} fetches a new nonce via + * new-nonce resource and a HEAD request. + */ + @Test + public void testResetNonce() throws AcmeException, IOException { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NO_CONTENT); + + assertThat(session.getNonce(), is(nullValue())); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + fail("missing Replay-Nonce header not detected"); + } catch (AcmeProtocolException ex) { + // expected + } + + assertThat(session.getNonce(), is(nullValue())); + + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + } + + assertThat(session.getNonce(), is(TestUtils.DUMMY_NONCE)); + + verify(mockUrlConnection, atLeastOnce()).setRequestMethod("HEAD"); + verify(mockUrlConnection, atLeastOnce()).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection, atLeastOnce()).connect(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Replay-Nonce"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that an absolute Location header is evaluated. + */ + @Test + public void testGetAbsoluteLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("https://example.com/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.com/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a relative Location header is evaluated. + */ + @Test + public void testGetRelativeLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.org/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that absolute and relative Link headers are evaluated. + */ + @Test + public void testGetLink() throws Exception { + Map> headers = new HashMap<>(); + headers.put("Content-Type", Arrays.asList("application/json")); + headers.put("Location", Arrays.asList("https://example.com/acme/acct/asdf")); + headers.put("Link", Arrays.asList( + ";rel=\"next\"", + ";rel=recover", + "; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("next"), containsInAnyOrder(new URL("https://example.com/acme/new-authz"))); + assertThat(conn.getLinks("recover"), containsInAnyOrder(new URL("https://example.org/recover-acct"))); + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder(new URL("https://example.com/acme/terms"))); + assertThat(conn.getLinks("secret-stuff"), is(empty())); + } + } + + /** + * Test that multiple link headers are evaluated. + */ + @Test + public void testGetMultiLink() { + URL baseUrl = url("https://example.com/acme/request/1234"); + + Map> headers = new HashMap<>(); + headers.put("Link", Arrays.asList( + "; rel=\"terms-of-service\"", + "; rel=\"terms-of-service\"", + "<../terms3>; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(baseUrl); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder( + url("https://example.com/acme/terms1"), + url("https://example.com/acme/terms2"), + url("https://example.com/acme/terms3") + )); + } + } + + /** + * Test that no link headers are properly handled. + */ + @Test + public void testGetNoLink() { + Map> headers = Collections.emptyMap(); + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("something"), is(empty())); + } + } + + /** + * Test that no Location header returns {@code null}. + */ + @Test + public void testNoLocation() { + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test if Retry-After header with absolute date is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDate() throws AcmeException, IOException { + Instant retryDate = Instant.now().plus(Duration.ofHours(10)).truncatedTo(ChronoUnit.MILLIS); + String retryMsg = "absolute date"; + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryDate.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryDate.toEpochMilli()); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(retryDate)); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if Retry-After header with relative timespan is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDelta() throws AcmeException, IOException { + int delta = 10 * 60 * 60; + long now = System.currentTimeMillis(); + String retryMsg = "relative time"; + + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(String.valueOf(delta)); + when(mockUrlConnection.getHeaderFieldDate( + ArgumentMatchers.eq("Date"), + ArgumentMatchers.anyLong())) + .thenReturn(now); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(Instant.ofEpochMilli(now).plusSeconds(delta))); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if no Retry-After header is correctly handled. + */ + @Test + public void testHandleRetryAfterHeaderNull() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(null); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("no header"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if missing retry-after header is correctly handled. + */ + @Test + public void testHandleRetryAfterNotAccepted() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("http ok"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAccept() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + int rc = conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + assertThat(rc, is(HttpURLConnection.HTTP_OK)); + } + + verify(mockUrlConnection).getResponseCode(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:unauthorized\",\"detail\":\"Invalid response: 404\"}"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUnauthorizedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:unauthorized"))); + assertThat(ex.getMessage(), is("Invalid response: 404")); + } catch (AcmeException ex) { + fail("Expected an AcmeUnauthorizedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeUserActionRequiredException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsUserActionRequiredException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:userActionRequired\",\"detail\":\"Accept the TOS\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"terms-of-service\"")); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUserActionRequiredException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:userActionRequired"))); + assertThat(ex.getMessage(), is("Accept the TOS")); + assertThat(ex.getTermsOfServiceUri(), is(URI.create("https://example.com/tos.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeUserActionRequiredException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeRateLimitedException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsRateLimitedException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:rateLimited\",\"detail\":\"Too many invocations\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"urn:ietf:params:acme:documentation\"")); + + Instant retryAfter = Instant.now().plusSeconds(30L).truncatedTo(ChronoUnit.MILLIS); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryAfter.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryAfter.toEpochMilli()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeRateLimitedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:rateLimited"))); + assertThat(ex.getMessage(), is("Too many invocations")); + assertThat(ex.getRetryAfter(), is(retryAfter)); + assertThat(ex.getDocuments(), is(notNullValue())); + assertThat(ex.getDocuments().size(), is(1)); + assertThat(ex.getDocuments().iterator().next(), is(url("https://example.com/rates.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeRateLimitedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + verify(mockUrlConnection).getHeaderFieldDate("Retry-After", 0L); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on another problem. + */ + @Test + public void testAcceptThrowsOtherException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + JSONBuilder result = new JSONBuilder(); + result.put("type", "urn:zombie:error:apocalypse"); + result.put("detail", "Zombie apocalypse in progress"); + return result.toJSON(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeServerException ex) { + assertThat(ex.getType(), is(URI.create("urn:zombie:error:apocalypse"))); + assertThat(ex.getMessage(), is("Zombie apocalypse in progress")); + } catch (AcmeException ex) { + fail("Expected an AcmeServerException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is no error type. + */ + @Test + public void testAcceptThrowsNoTypeException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + return JSON.empty(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), not(isEmptyOrNullString())); + } catch (AcmeException ex) { + fail("Did not expect an AcmeException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is a generic error. + */ + @Test + public void testAcceptThrowsServerException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("text/html"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getResponseMessage()) + .thenReturn("Infernal Server Error"); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeException ex) { + assertThat(ex.getMessage(), is("HTTP 500: Infernal Server Error")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getResponseMessage(); + } + + /** + * Test GET requests. + */ + @Test + public void testSendRequest() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendRequest(requestUrl, session); + } + + verify(mockUrlConnection).setRequestMethod("GET"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setDoOutput(false); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test signed POST requests. + */ + @Test + public void testSendSignedRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); + expectedHeader.append('}'); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST-as-GET requests. + */ + @Test + public void testSendSignedPostAsGetRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + conn.sendSignedPostAsGetRequest(requestUrl, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); + expectedHeader.append('}'); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), is("")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test certificate POST-as-GET requests. + */ + @Test + public void testSendCertificateRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + conn.sendCertificateRequest(requestUrl, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test signed POST requests without KeyIdentifier. + */ + @Test + public void testSendSignedRequestNoKid() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, session, keyPair); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"jwk\":{"); + expectedHeader.append("\"kty\":\"").append(TestUtils.KTY).append("\","); + expectedHeader.append("\"e\":\"").append(TestUtils.E).append("\","); + expectedHeader.append("\"n\":\"").append(TestUtils.N).append("\""); + expectedHeader.append("}}"); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST requests if there is no nonce. + */ + @Test(expected = AcmeException.class) + public void testSendSignedRequestNoNonce() throws Exception { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + JSONBuilder cb = new JSONBuilder(); + conn.sendSignedRequest(requestUrl, cb, DefaultConnectionTest.this.session, DefaultConnectionTest.this.keyPair); + } + } + + /** + * Test getting a JSON response. + */ + @Test + public void testReadJsonResponse() throws Exception { + String jsonData = "{\n\"foo\":123,\n\"bar\":\"a-string\"\n}\n"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + JSON result = conn.readJsonResponse(); + assertThat(result, is(notNullValue())); + assertThat(result.keySet(), hasSize(2)); + assertThat(result.get("foo").asInt(), is(123)); + assertThat(result.get("bar").asString(), is("a-string")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a certificate is downloaded correctly. + */ + @Test + public void testReadCertificate() throws Exception { + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(getClass().getResourceAsStream("/cert.pem")); + + List downloaded; + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + downloaded = conn.readCertificates(); + } + + List original = TestUtils.createCertificate(); + assertThat(original.size(), is(2)); + + assertThat(downloaded, not(nullValue())); + assertThat(downloaded.size(), is(original.size())); + for (int ix = 0; ix < downloaded.size(); ix++) { + assertThat(downloaded.get(ix).getEncoded(), is(original.get(ix).getEncoded())); + }; + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a bad certificate throws an exception. + */ + @Test(expected = AcmeProtocolException.class) + public void testReadBadCertificate() throws Exception { + // Build a broken certificate chain PEM file + byte[] brokenPem; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter w = new OutputStreamWriter(baos)) { + for (X509Certificate cert : TestUtils.createCertificate()) { + byte[] badCert = cert.getEncoded(); + Arrays.sort(badCert); // break it + AcmeUtils.writeToPem(badCert, AcmeUtils.PemLabel.CERTIFICATE, w); + } + w.flush(); + brokenPem = baos.toByteArray(); + } + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(brokenPem)); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.readCertificates(); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.HttpURLConnection` acquired by call to `sendRequest(...)` at line 652 is not released after line 653. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultConnectionTest.testSendRequest() + +### Procedure Id: +org.shredzone.acme4j.connector.DefaultConnectionTest.testSendRequest():void.57115950df0dc37ce3928cda06f0923d + +### File: +acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java + +### Key: +DefaultConnectionTest.java|testSendRequest|RESOURCE_LEAK + +### Node Key: +be34d01a97ade44aabeb9969f5c22e18 + +### Hash: +e35ce667353970de82bd49e2ecdc1f17 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8166/instruction.md b/inferredbugs-8166/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dceed9c6102a42c17b6032f01d7bb8a406dd3c72 --- /dev/null +++ b/inferredbugs-8166/instruction.md @@ -0,0 +1,312 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +package org.shredzone.acme4j; + +import java.net.URI; +import java.security.KeyPair; +import java.time.Duration; +import java.time.Instant; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.ServiceLoader; + +import org.shredzone.acme4j.challenge.Challenge; +import org.shredzone.acme4j.challenge.TokenChallenge; +import org.shredzone.acme4j.connector.Resource; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.provider.AcmeProvider; +import org.shredzone.acme4j.util.JSON; + +/** + * A session stores the ACME server URI and the account's key pair. It also tracks + * communication parameters. + *

    + * Note that {@link Session} objects are not serializable, as they contain a keypair and + * volatile data. + */ +public class Session { + private final Map resourceMap = new EnumMap<>(Resource.class); + private final URI serverUri; + + private KeyPair keyPair; + private AcmeProvider provider; + private byte[] nonce; + private JSON directoryJson; + private Metadata metadata; + private Locale locale = Locale.getDefault(); + protected Instant directoryCacheExpiry; + + /** + * Creates a new {@link Session}. + * + * @param serverUri + * URI string of the ACME server + * @param keyPair + * {@link KeyPair} of the ACME account + */ + public Session(String serverUri, KeyPair keyPair) { + this(URI.create(serverUri), keyPair); + } + + /** + * Creates a new {@link Session}. + * + * @param serverUri + * {@link URI} of the ACME server + * @param keyPair + * {@link KeyPair} of the ACME account + */ + public Session(URI serverUri, KeyPair keyPair) { + this.serverUri = Objects.requireNonNull(serverUri, "serverUri"); + this.keyPair = Objects.requireNonNull(keyPair, "keyPair"); + } + + /** + * Gets the ACME server {@link URI} of this session. + */ + public URI getServerUri() { + return serverUri; + } + + /** + * Gets the {@link KeyPair} of the ACME account. + */ + public KeyPair getKeyPair() { + return keyPair; + } + + /** + * Sets a different {@link KeyPair}. + */ + public void setKeyPair(KeyPair keyPair) { + this.keyPair = keyPair; + } + + /** + * Gets the last nonce, or {@code null} if the session is new. + */ + public byte[] getNonce() { + return nonce; + } + + /** + * Sets the nonce received by the server. + */ + public void setNonce(byte[] nonce) { + this.nonce = nonce; + } + + /** + * Gets the current locale of this session. + */ + public Locale getLocale() { + return locale; + } + + /** + * Sets the locale used in this session. The locale is passed to the server as + * Accept-Language header. The server may respond with localized messages. + */ + public void setLocale(Locale locale) { + this.locale = locale; + } + + /** + * Returns the {@link AcmeProvider} that is used for this session. + *

    + * The {@link AcmeProvider} instance is lazily created and cached. + * + * @return {@link AcmeProvider} + */ + public AcmeProvider provider() { + synchronized (this) { + if (provider == null) { + List candidates = new ArrayList<>(); + for (AcmeProvider acp : ServiceLoader.load(AcmeProvider.class)) { + if (acp.accepts(serverUri)) { + candidates.add(acp); + } + } + + if (candidates.isEmpty()) { + throw new IllegalArgumentException("No ACME provider found for " + serverUri); + } else if (candidates.size() > 1) { + throw new IllegalStateException("There are " + candidates.size() + " " + + AcmeProvider.class.getSimpleName() + " accepting " + serverUri + + ". Please check your classpath."); + } else { + provider = candidates.get(0); + } + } + } + return provider; + } + + /** + * Creates a {@link Challenge} instance for the given challenge data. + * + * @param data + * Challenge JSON data + * @return {@link Challenge} instance + */ + public Challenge createChallenge(JSON data) { + Objects.requireNonNull(data, "data"); + + String type = data.get("type").required().asString(); + + Challenge challenge = provider().createChallenge(this, type); + if (challenge == null) { + if (data.contains("token")) { + challenge = new TokenChallenge(this); + } else { + challenge = new Challenge(this); + } + } + challenge.unmarshall(data); + return challenge; + } + + /** + * Gets the {@link URI} of the given {@link Resource}. This may involve connecting to + * the server and getting a directory. The result is cached. + * + * @param resource + * {@link Resource} to get the {@link URI} of + * @return {@link URI}, or {@code null} if the server does not offer that resource + */ + public URI resourceUri(Resource resource) throws AcmeException { + readDirectory(); + return resourceMap.get(Objects.requireNonNull(resource, "resource")); + } + + /** + * Gets the metadata of the provider's directory. This may involve connecting to the + * server and getting a directory. The result is cached. + * + * @return {@link Metadata}. May contain no data, but is never {@code null}. + */ + public Metadata getMetadata() throws AcmeException { + readDirectory(); + return metadata; + } + + /** + * Reads the provider's directory, then rebuild the resource map. The response is + * cached. + */ + private void readDirectory() throws AcmeException { + synchronized (this) { + Instant now = Instant.now(); + if (directoryJson == null || !directoryCacheExpiry.isAfter(now)) { + directoryJson = provider().directory(this, getServerUri()); + directoryCacheExpiry = now.plus(Duration.ofHours(1)); + + JSON meta = directoryJson.get("meta").asObject(); + if (meta != null) { + metadata = new Metadata(meta); + } else { + metadata = new Metadata(JSON.empty()); + } + + resourceMap.clear(); + for (Resource res : Resource.values()) { + URI uri = directoryJson.get(res.path()).asURI(); + if (uri != null) { + resourceMap.put(res, uri); + } + } + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.shredzone.acme4j.Session.provider` reads without synchronization from `this.org.shredzone.acme4j.Session.provider`. Potentially races with write in method `Session.resourceUri(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +AcmeProvider Session.provider() + +### Procedure Id: +org.shredzone.acme4j.Session.provider():org.shredzone.acme4j.provider.AcmeProvider.ed495ed67087feafb5b450bdeda21489 + +### File: +acme4j-client/src/main/java/org/shredzone/acme4j/Session.java + +### Key: +Session.java|provider|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +673ecaf5b29e859bbeb5edf7f88d7335 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8167/instruction.md b/inferredbugs-8167/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a97737b06e7c1c38d566e3cbd6ab035bdad99d --- /dev/null +++ b/inferredbugs-8167/instruction.md @@ -0,0 +1,1116 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +package org.shredzone.acme4j.connector; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; +import static org.shredzone.acme4j.toolbox.TestUtils.url; +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URI; +import java.net.URL; +import java.security.KeyPair; +import java.security.cert.X509Certificate; +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.jose4j.base64url.Base64Url; +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwx.CompactSerializer; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentMatchers; +import org.shredzone.acme4j.Login; +import org.shredzone.acme4j.Session; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.exception.AcmeProtocolException; +import org.shredzone.acme4j.exception.AcmeRateLimitedException; +import org.shredzone.acme4j.exception.AcmeRetryAfterException; +import org.shredzone.acme4j.exception.AcmeServerException; +import org.shredzone.acme4j.exception.AcmeUnauthorizedException; +import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; +import org.shredzone.acme4j.provider.AcmeProvider; +import org.shredzone.acme4j.toolbox.AcmeUtils; +import org.shredzone.acme4j.toolbox.JSON; +import org.shredzone.acme4j.toolbox.JSONBuilder; +import org.shredzone.acme4j.toolbox.TestUtils; + +/** + * Unit tests for {@link DefaultConnection}. + */ +public class DefaultConnectionTest { + + private URL requestUrl = TestUtils.url("http://example.com/acme/"); + private URL accountUrl = TestUtils.url(TestUtils.ACCOUNT_URL); + private HttpURLConnection mockUrlConnection; + private HttpConnector mockHttpConnection; + private Session session; + private Login login; + private KeyPair keyPair; + + @Before + public void setup() throws AcmeException, IOException { + mockUrlConnection = mock(HttpURLConnection.class); + + mockHttpConnection = mock(HttpConnector.class); + when(mockHttpConnection.openConnection(requestUrl, Proxy.NO_PROXY)).thenReturn(mockUrlConnection); + + final AcmeProvider mockProvider = mock(AcmeProvider.class); + when(mockProvider.directory( + ArgumentMatchers.any(Session.class), + ArgumentMatchers.eq(URI.create(TestUtils.ACME_SERVER_URI)))) + .thenReturn(TestUtils.getJSON("directory")); + + session = TestUtils.session(mockProvider); + session.setLocale(Locale.JAPAN); + + keyPair = TestUtils.createKeyPair(); + + login = session.login(accountUrl, keyPair); + } + + /** + * Test that {@link DefaultConnection#getNonce()} returns {@code null} if there is no + * {@code Replay-Nonce} header. + */ + @Test + public void testNoNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(null); + + assertThat(session.getNonce(), is(nullValue())); + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} extracts a {@code Replay-Nonce} + * header correctly. + */ + @Test + public void testGetNonceFromHeader() { + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getNonce(), is(TestUtils.DUMMY_NONCE)); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#getNonce()} fails on an invalid + * {@code Replay-Nonce} header. + */ + @Test + public void testInvalidNonceFromHeader() { + String badNonce = "#$%&/*+*#'"; + + when(mockUrlConnection.getHeaderField("Replay-Nonce")).thenReturn(badNonce); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.getNonce(); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), org.hamcrest.Matchers.startsWith("Invalid replay nonce")); + } + + verify(mockUrlConnection).getHeaderField("Replay-Nonce"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that {@link DefaultConnection#resetNonce(Session)} fetches a new nonce via + * new-nonce resource and a HEAD request. + */ + @Test + public void testResetNonce() throws AcmeException, IOException { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NO_CONTENT); + + assertThat(session.getNonce(), is(nullValue())); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + fail("missing Replay-Nonce header not detected"); + } catch (AcmeProtocolException ex) { + // expected + } + + assertThat(session.getNonce(), is(nullValue())); + + when(mockUrlConnection.getHeaderField("Replay-Nonce")) + .thenReturn(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.resetNonce(session); + } + + assertThat(session.getNonce(), is(TestUtils.DUMMY_NONCE)); + + verify(mockUrlConnection, atLeastOnce()).setRequestMethod("HEAD"); + verify(mockUrlConnection, atLeastOnce()).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection, atLeastOnce()).connect(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Replay-Nonce"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that an absolute Location header is evaluated. + */ + @Test + public void testGetAbsoluteLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("https://example.com/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.com/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a relative Location header is evaluated. + */ + @Test + public void testGetRelativeLocation() throws Exception { + when(mockUrlConnection.getHeaderField("Location")).thenReturn("/otherlocation"); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(new URL("https://example.org/otherlocation"))); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verify(mockUrlConnection).getURL(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that absolute and relative Link headers are evaluated. + */ + @Test + public void testGetLink() throws Exception { + Map> headers = new HashMap<>(); + headers.put("Content-Type", Arrays.asList("application/json")); + headers.put("Location", Arrays.asList("https://example.com/acme/acct/asdf")); + headers.put("Link", Arrays.asList( + ";rel=\"next\"", + ";rel=recover", + "; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(new URL("https://example.org/acme")); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("next"), containsInAnyOrder(new URL("https://example.com/acme/new-authz"))); + assertThat(conn.getLinks("recover"), containsInAnyOrder(new URL("https://example.org/recover-acct"))); + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder(new URL("https://example.com/acme/terms"))); + assertThat(conn.getLinks("secret-stuff"), is(empty())); + } + } + + /** + * Test that multiple link headers are evaluated. + */ + @Test + public void testGetMultiLink() { + URL baseUrl = url("https://example.com/acme/request/1234"); + + Map> headers = new HashMap<>(); + headers.put("Link", Arrays.asList( + "; rel=\"terms-of-service\"", + "; rel=\"terms-of-service\"", + "<../terms3>; rel=\"terms-of-service\"" + )); + + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + when(mockUrlConnection.getURL()).thenReturn(baseUrl); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("terms-of-service"), containsInAnyOrder( + url("https://example.com/acme/terms1"), + url("https://example.com/acme/terms2"), + url("https://example.com/acme/terms3") + )); + } + } + + /** + * Test that no link headers are properly handled. + */ + @Test + public void testGetNoLink() { + Map> headers = Collections.emptyMap(); + when(mockUrlConnection.getHeaderFields()).thenReturn(headers); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + assertThat(conn.getLinks("something"), is(empty())); + } + } + + /** + * Test that no Location header returns {@code null}. + */ + @Test + public void testNoLocation() { + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + URL location = conn.getLocation(); + assertThat(location, is(nullValue())); + } + + verify(mockUrlConnection).getHeaderField("Location"); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test if Retry-After header with absolute date is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDate() throws AcmeException, IOException { + Instant retryDate = Instant.now().plus(Duration.ofHours(10)).truncatedTo(ChronoUnit.MILLIS); + String retryMsg = "absolute date"; + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryDate.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryDate.toEpochMilli()); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(retryDate)); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if Retry-After header with relative timespan is correctly parsed. + */ + @Test + public void testHandleRetryAfterHeaderDelta() throws AcmeException, IOException { + int delta = 10 * 60 * 60; + long now = System.currentTimeMillis(); + String retryMsg = "relative time"; + + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(String.valueOf(delta)); + when(mockUrlConnection.getHeaderFieldDate( + ArgumentMatchers.eq("Date"), + ArgumentMatchers.anyLong())) + .thenReturn(now); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter(retryMsg); + fail("no AcmeRetryAfterException was thrown"); + } catch (AcmeRetryAfterException ex) { + assertThat(ex.getRetryAfter(), is(Instant.ofEpochMilli(now).plusSeconds(delta))); + assertThat(ex.getMessage(), is(retryMsg)); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if no Retry-After header is correctly handled. + */ + @Test + public void testHandleRetryAfterHeaderNull() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getHeaderField("Retry-After")) + .thenReturn(null); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("no header"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + } + + /** + * Test if missing retry-after header is correctly handled. + */ + @Test + public void testHandleRetryAfterNotAccepted() throws AcmeException, IOException { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.handleRetryAfter("http ok"); + } catch (AcmeRetryAfterException ex) { + fail("an AcmeRetryAfterException was thrown"); + } + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAccept() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + int rc = conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + assertThat(rc, is(HttpURLConnection.HTTP_OK)); + } + + verify(mockUrlConnection).getResponseCode(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:unauthorized\",\"detail\":\"Invalid response: 404\"}"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUnauthorizedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:unauthorized"))); + assertThat(ex.getMessage(), is("Invalid response: 404")); + } catch (AcmeException ex) { + fail("Expected an AcmeUnauthorizedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeUserActionRequiredException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsUserActionRequiredException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:userActionRequired\",\"detail\":\"Accept the TOS\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"terms-of-service\"")); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeUserActionRequiredException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:userActionRequired"))); + assertThat(ex.getMessage(), is("Accept the TOS")); + assertThat(ex.getTermsOfServiceUri(), is(URI.create("https://example.com/tos.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeUserActionRequiredException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeRateLimitedException} is thrown on an acme problem. + */ + @Test + public void testAcceptThrowsRateLimitedException() throws Exception { + String jsonData = "{\"type\":\"urn:ietf:params:acme:error:rateLimited\",\"detail\":\"Too many invocations\"}"; + + Map> linkHeader = new HashMap<>(); + linkHeader.put("Link", Arrays.asList("; rel=\"urn:ietf:params:acme:documentation\"")); + + Instant retryAfter = Instant.now().plusSeconds(30L).truncatedTo(ChronoUnit.MILLIS); + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/problem+json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getHeaderField("Retry-After")).thenReturn(retryAfter.toString()); + when(mockUrlConnection.getHeaderFieldDate("Retry-After", 0L)).thenReturn(retryAfter.toEpochMilli()); + when(mockUrlConnection.getHeaderFields()).thenReturn(linkHeader); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN); + when(mockUrlConnection.getOutputStream()).thenReturn(new ByteArrayOutputStream()); + when(mockUrlConnection.getErrorStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + when(mockUrlConnection.getURL()).thenReturn(url("https://example.com/acme/1")); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeRateLimitedException ex) { + assertThat(ex.getType(), is(URI.create("urn:ietf:params:acme:error:rateLimited"))); + assertThat(ex.getMessage(), is("Too many invocations")); + assertThat(ex.getRetryAfter(), is(retryAfter)); + assertThat(ex.getDocuments(), is(notNullValue())); + assertThat(ex.getDocuments().size(), is(1)); + assertThat(ex.getDocuments().iterator().next(), is(url("https://example.com/rates.pdf"))); + } catch (AcmeException ex) { + fail("Expected an AcmeRateLimitedException"); + } + + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getHeaderField("Retry-After"); + verify(mockUrlConnection).getHeaderFieldDate("Retry-After", 0L); + verify(mockUrlConnection, atLeastOnce()).getHeaderFields(); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getErrorStream(); + verify(mockUrlConnection, atLeastOnce()).getURL(); + } + + /** + * Test if an {@link AcmeServerException} is thrown on another problem. + */ + @Test + public void testAcceptThrowsOtherException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + JSONBuilder result = new JSONBuilder(); + result.put("type", "urn:zombie:error:apocalypse"); + result.put("detail", "Zombie apocalypse in progress"); + return result.toJSON(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeServerException ex) { + assertThat(ex.getType(), is(URI.create("urn:zombie:error:apocalypse"))); + assertThat(ex.getMessage(), is("Zombie apocalypse in progress")); + } catch (AcmeException ex) { + fail("Expected an AcmeServerException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is no error type. + */ + @Test + public void testAcceptThrowsNoTypeException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("application/problem+json"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getURL()) + .thenReturn(url("https://example.com/acme/1")); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public JSON readJsonResponse() { + return JSON.empty(); + } + }) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeProtocolException ex) { + assertThat(ex.getMessage(), not(isEmptyOrNullString())); + } catch (AcmeException ex) { + fail("Did not expect an AcmeException"); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection).getURL(); + } + + /** + * Test if an {@link AcmeException} is thrown if there is a generic error. + */ + @Test + public void testAcceptThrowsServerException() throws IOException { + when(mockUrlConnection.getHeaderField("Content-Type")) + .thenReturn("text/html"); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_INTERNAL_ERROR); + when(mockUrlConnection.getResponseMessage()) + .thenReturn("Infernal Server Error"); + when(mockUrlConnection.getOutputStream()) + .thenReturn(new ByteArrayOutputStream()); + + session.setNonce(TestUtils.DUMMY_NONCE); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendSignedRequest(requestUrl, new JSONBuilder(), login); + fail("Expected to fail"); + } catch (AcmeException ex) { + assertThat(ex.getMessage(), is("HTTP 500: Infernal Server Error")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection, atLeastOnce()).getResponseCode(); + verify(mockUrlConnection, atLeastOnce()).getResponseMessage(); + } + + /** + * Test GET requests. + */ + @Test + public void testSendRequest() throws Exception { + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.sendRequest(requestUrl, session); + } + + verify(mockUrlConnection).setRequestMethod("GET"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setDoOutput(false); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test signed POST requests. + */ + @Test + public void testSendSignedRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); + expectedHeader.append('}'); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST-as-GET requests. + */ + @Test + public void testSendSignedPostAsGetRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + conn.sendSignedPostAsGetRequest(requestUrl, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"kid\":\"").append(accountUrl).append('"'); + expectedHeader.append('}'); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), is("")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test certificate POST-as-GET requests. + */ + @Test + public void testSendCertificateRequest() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + conn.sendCertificateRequest(requestUrl, login); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/pem-certificate-chain"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test signed POST requests without KeyIdentifier. + */ + @Test + public void testSendSignedRequestNoKid() throws Exception { + final String nonce1 = Base64Url.encode("foo-nonce-1-foo".getBytes()); + final String nonce2 = Base64Url.encode("foo-nonce-2-foo".getBytes()); + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getOutputStream()).thenReturn(outputStream); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection) { + @Override + public void resetNonce(Session session) { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == null) { + session.setNonce(nonce1); + } else { + fail("unknown nonce"); + } + } + + @Override + public String getNonce() { + assertThat(session, is(sameInstance(DefaultConnectionTest.this.session))); + if (session.getNonce() == nonce1) { + return nonce2; + } else { + fail("unknown nonce"); + return null; + } + } + }) { + JSONBuilder cb = new JSONBuilder(); + cb.put("foo", 123).put("bar", "a-string"); + conn.sendSignedRequest(requestUrl, cb, session, keyPair); + } + + verify(mockUrlConnection).setRequestMethod("POST"); + verify(mockUrlConnection).setRequestProperty("Accept", "application/json"); + verify(mockUrlConnection).setRequestProperty("Accept-Charset", "utf-8"); + verify(mockUrlConnection).setRequestProperty("Accept-Language", "ja-JP"); + verify(mockUrlConnection).setRequestProperty("Content-Type", "application/jose+json"); + verify(mockUrlConnection).connect(); + verify(mockUrlConnection).setDoOutput(true); + verify(mockUrlConnection).setFixedLengthStreamingMode(outputStream.toByteArray().length); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getOutputStream(); + verify(mockUrlConnection, atLeast(0)).getHeaderFields(); + verifyNoMoreInteractions(mockUrlConnection); + + JSON data = JSON.parse(new String(outputStream.toByteArray(), "utf-8")); + String encodedHeader = data.get("protected").asString(); + String encodedSignature = data.get("signature").asString(); + String encodedPayload = data.get("payload").asString(); + + StringBuilder expectedHeader = new StringBuilder(); + expectedHeader.append('{'); + expectedHeader.append("\"nonce\":\"").append(nonce1).append("\","); + expectedHeader.append("\"url\":\"").append(requestUrl).append("\","); + expectedHeader.append("\"alg\":\"RS256\","); + expectedHeader.append("\"jwk\":{"); + expectedHeader.append("\"kty\":\"").append(TestUtils.KTY).append("\","); + expectedHeader.append("\"e\":\"").append(TestUtils.E).append("\","); + expectedHeader.append("\"n\":\"").append(TestUtils.N).append("\""); + expectedHeader.append("}}"); + + assertThat(Base64Url.decodeToUtf8String(encodedHeader), sameJSONAs(expectedHeader.toString())); + assertThat(Base64Url.decodeToUtf8String(encodedPayload), sameJSONAs("{\"foo\":123,\"bar\":\"a-string\"}")); + assertThat(encodedSignature, not(isEmptyOrNullString())); + + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature)); + jws.setKey(login.getKeyPair().getPublic()); + assertThat(jws.verifySignature(), is(true)); + } + + /** + * Test signed POST requests if there is no nonce. + */ + @Test(expected = AcmeException.class) + public void testSendSignedRequestNoNonce() throws Exception { + when(mockHttpConnection.openConnection(new URL("https://example.com/acme/new-nonce"), Proxy.NO_PROXY)) + .thenReturn(mockUrlConnection); + when(mockUrlConnection.getResponseCode()) + .thenReturn(HttpURLConnection.HTTP_NOT_FOUND); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + JSONBuilder cb = new JSONBuilder(); + conn.sendSignedRequest(requestUrl, cb, DefaultConnectionTest.this.session, DefaultConnectionTest.this.keyPair); + } + } + + /** + * Test getting a JSON response. + */ + @Test + public void testReadJsonResponse() throws Exception { + String jsonData = "{\n\"foo\":123,\n\"bar\":\"a-string\"\n}\n"; + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/json"); + when(mockUrlConnection.getContentLength()).thenReturn(jsonData.length()); + when(mockUrlConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(jsonData.getBytes("utf-8"))); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + JSON result = conn.readJsonResponse(); + assertThat(result, is(notNullValue())); + assertThat(result.keySet(), hasSize(2)); + assertThat(result.get("foo").asInt(), is(123)); + assertThat(result.get("bar").asString(), is("a-string")); + } + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getContentLength(); + verify(mockUrlConnection).getResponseCode(); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a certificate is downloaded correctly. + */ + @Test + public void testReadCertificate() throws Exception { + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(getClass().getResourceAsStream("/cert.pem")); + + List downloaded; + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + downloaded = conn.readCertificates(); + } + + List original = TestUtils.createCertificate(); + assertThat(original.size(), is(2)); + + assertThat(downloaded, not(nullValue())); + assertThat(downloaded.size(), is(original.size())); + for (int ix = 0; ix < downloaded.size(); ix++) { + assertThat(downloaded.get(ix).getEncoded(), is(original.get(ix).getEncoded())); + }; + + verify(mockUrlConnection).getHeaderField("Content-Type"); + verify(mockUrlConnection).getInputStream(); + verifyNoMoreInteractions(mockUrlConnection); + } + + /** + * Test that a bad certificate throws an exception. + */ + @Test(expected = AcmeProtocolException.class) + public void testReadBadCertificate() throws Exception { + // Build a broken certificate chain PEM file + byte[] brokenPem; + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + OutputStreamWriter w = new OutputStreamWriter(baos)) { + for (X509Certificate cert : TestUtils.createCertificate()) { + byte[] badCert = cert.getEncoded(); + Arrays.sort(badCert); // break it + AcmeUtils.writeToPem(badCert, AcmeUtils.PemLabel.CERTIFICATE, w); + } + w.flush(); + brokenPem = baos.toByteArray(); + } + + when(mockUrlConnection.getHeaderField("Content-Type")).thenReturn("application/pem-certificate-chain"); + when(mockUrlConnection.getInputStream()).thenReturn(new ByteArrayInputStream(brokenPem)); + + try (DefaultConnection conn = new DefaultConnection(mockHttpConnection)) { + conn.conn = mockUrlConnection; + conn.readCertificates(); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `javax.net.ssl.HttpsURLConnection` acquired by call to `sendRequest(...)` at line 652 is not released after line 653. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultConnectionTest.testSendRequest() + +### Procedure Id: +org.shredzone.acme4j.connector.DefaultConnectionTest.testSendRequest():void.57115950df0dc37ce3928cda06f0923d + +### File: +acme4j-client/src/test/java/org/shredzone/acme4j/connector/DefaultConnectionTest.java + +### Key: +DefaultConnectionTest.java|testSendRequest|RESOURCE_LEAK + +### Node Key: +be34d01a97ade44aabeb9969f5c22e18 + +### Hash: +f8eb3974ff7953533c42978536057452 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8168/instruction.md b/inferredbugs-8168/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aff02aef072d98cc60be9a6656de6a03913ac9d4 --- /dev/null +++ b/inferredbugs-8168/instruction.md @@ -0,0 +1,509 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +package org.shredzone.acme4j.impl; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.shredzone.acme4j.util.TestUtils.*; +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.shredzone.acme4j.Account; +import org.shredzone.acme4j.Authorization; +import org.shredzone.acme4j.Registration; +import org.shredzone.acme4j.challenge.Challenge; +import org.shredzone.acme4j.challenge.Challenge.Status; +import org.shredzone.acme4j.challenge.DnsChallenge; +import org.shredzone.acme4j.challenge.GenericChallenge; +import org.shredzone.acme4j.challenge.HttpChallenge; +import org.shredzone.acme4j.connector.Connection; +import org.shredzone.acme4j.connector.Resource; +import org.shredzone.acme4j.connector.Session; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.util.ClaimBuilder; +import org.shredzone.acme4j.util.TestUtils; + +/** + * Unit tests for {@link AbstractAcmeClient}. + * + * @author Richard "Shred" Körber + */ +public class AbstractAcmeClientTest { + + private Account testAccount; + private URI resourceUri; + private URI locationUri; + private URI agreementUri; + + @Before + public void setup() throws IOException, URISyntaxException { + resourceUri = new URI("https://example.com/acme/some-resource"); + locationUri = new URI("https://example.com/acme/some-location"); + agreementUri = new URI("http://example.com/agreement.pdf"); + testAccount = new Account(TestUtils.createKeyPair()); + } + + /** + * Test that a new {@link Registration} can be registered. + */ + @Test + public void testNewRegistration() throws AcmeException { + Registration registration = new Registration(); + registration.addContact("mailto:foo@example.com"); + + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(resourceUri)); + assertThat(claims.toString(), sameJSONAs(getJson("newRegistration"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_CREATED; + } + + @Override + public URI getLocation() throws AcmeException { + return locationUri; + } + + @Override + public URI getLink(String relation) throws AcmeException { + switch(relation) { + case "terms-of-service": return agreementUri; + default: return null; + } + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + client.putTestResource(Resource.NEW_REG, resourceUri); + + client.newRegistration(testAccount, registration); + + assertThat(registration.getLocation(), is(locationUri)); + assertThat(registration.getAgreement(), is(agreementUri)); + } + + /** + * Test that a {@link Registration} can be modified. + */ + @Test + public void testModifyRegistration() throws AcmeException { + Registration registration = new Registration(); + registration.setAgreement(agreementUri); + registration.addContact("mailto:foo2@example.com"); + registration.setLocation(locationUri); + + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(locationUri)); + assertThat(claims.toString(), sameJSONAs(getJson("modifyRegistration"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public URI getLocation() throws AcmeException { + return locationUri; + } + + @Override + public URI getLink(String relation) throws AcmeException { + switch(relation) { + case "terms-of-service": return agreementUri; + default: return null; + } + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + + client.modifyRegistration(testAccount, registration); + + assertThat(registration.getLocation(), is(locationUri)); + assertThat(registration.getAgreement(), is(agreementUri)); + } + + /** + * Test that a new {@link Authorization} can be created. + */ + @Test + public void testNewAuthorization() throws AcmeException { + Authorization auth = new Authorization(); + auth.setDomain("example.org"); + + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(resourceUri)); + assertThat(claims.toString(), sameJSONAs(getJson("newAuthorizationRequest"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_CREATED; + } + + @Override + public Map readJsonResponse() throws AcmeException { + return getJsonAsMap("newAuthorizationResponse"); + } + }; + + HttpChallenge httpChallenge = new HttpChallenge(); + DnsChallenge dnsChallenge = new DnsChallenge(); + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + client.putTestResource(Resource.NEW_AUTHZ, resourceUri); + client.putTestChallenge("http-01", httpChallenge); + client.putTestChallenge("dns-01", dnsChallenge); + + client.newAuthorization(testAccount, auth); + + assertThat(auth.getDomain(), is("example.org")); + assertThat(auth.getStatus(), is("pending")); + assertThat(auth.getExpires(), is(nullValue())); + + assertThat(auth.getChallenges(), containsInAnyOrder( + (Challenge) httpChallenge, (Challenge) dnsChallenge)); + + assertThat(auth.getCombinations(), hasSize(2)); + assertThat(auth.getCombinations().get(0), containsInAnyOrder( + (Challenge) httpChallenge)); + assertThat(auth.getCombinations().get(1), containsInAnyOrder( + (Challenge) httpChallenge, (Challenge) dnsChallenge)); + } + + /** + * Test that a {@link Challenge} can be triggered. + */ + @Test + public void testTriggerChallenge() throws AcmeException { + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(resourceUri)); + assertThat(claims.toString(), sameJSONAs(getJson("triggerHttpChallengeRequest"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public Map readJsonResponse() throws AcmeException { + return getJsonAsMap("triggerHttpChallengeResponse"); + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + + Challenge challenge = new HttpChallenge(); + challenge.unmarshall(getJsonAsMap("triggerHttpChallenge")); + challenge.authorize(testAccount); + + client.triggerChallenge(testAccount, challenge); + + assertThat(challenge.getStatus(), is(Status.PENDING)); + assertThat(challenge.getLocation(), is(locationUri)); + } + + /** + * Test that a {@link Challenge} is properly updated. + */ + @Test + public void testUpdateChallenge() throws AcmeException { + Connection connection = new DummyConnection() { + @Override + public int sendRequest(URI uri) throws AcmeException { + assertThat(uri, is(locationUri)); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public Map readJsonResponse() throws AcmeException { + return getJsonAsMap("updateHttpChallengeResponse"); + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + + Challenge challenge = new HttpChallenge(); + challenge.unmarshall(getJsonAsMap("triggerHttpChallengeResponse")); + + client.updateChallenge(challenge); + + assertThat(challenge.getStatus(), is(Status.VALID)); + assertThat(challenge.getLocation(), is(locationUri)); + } + + @Test + public void testRestoreChallenge() throws AcmeException { + Connection connection = new DummyConnection() { + @Override + public int sendRequest(URI uri) throws AcmeException { + assertThat(uri, is(locationUri)); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public Map readJsonResponse() throws AcmeException { + return getJsonAsMap("updateHttpChallengeResponse"); + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + client.putTestChallenge(HttpChallenge.TYPE, new HttpChallenge()); + + Challenge challenge = client.restoreChallenge(locationUri); + + assertThat(challenge.getStatus(), is(Status.VALID)); + assertThat(challenge.getLocation(), is(locationUri)); + } + + /** + * Test that a certificate can be requested. + */ + @Test + public void testRequestCertificate() throws AcmeException, IOException { + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(resourceUri)); + assertThat(claims.toString(), sameJSONAs(getJson("requestCertificateRequest"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_CREATED; + } + + @Override + public URI getLocation() throws AcmeException { + return locationUri; + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + client.putTestResource(Resource.NEW_CERT, resourceUri); + + byte[] csr = TestUtils.getResourceAsByteArray("/csr.der"); + URI certUri = client.requestCertificate(testAccount, csr); + + assertThat(certUri, is(locationUri)); + } + + /** + * Test that a certificate can be downloaded. + */ + @Test + public void testDownloadCertificate() throws AcmeException, IOException { + final X509Certificate originalCert = TestUtils.createCertificate(); + + Connection connection = new DummyConnection() { + @Override + public int sendRequest(URI uri) throws AcmeException { + assertThat(uri, is(locationUri)); + return HttpURLConnection.HTTP_OK; + } + + @Override + public X509Certificate readCertificate() throws AcmeException { + return originalCert; + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + + X509Certificate downloadedCert = client.downloadCertificate(locationUri); + assertThat(downloadedCert, is(sameInstance(originalCert))); + } + + /** + * Test that a certificate can be revoked. + */ + @Test + public void testRevokeCertificate() throws AcmeException, IOException { + final X509Certificate cert = TestUtils.createCertificate(); + + Connection connection = new DummyConnection() { + @Override + public int sendSignedRequest(URI uri, ClaimBuilder claims, Session session, Account account) throws AcmeException { + assertThat(uri, is(resourceUri)); + assertThat(claims.toString(), sameJSONAs(getJson("revokeCertificateRequest"))); + assertThat(session, is(notNullValue())); + assertThat(account, is(sameInstance(testAccount))); + return HttpURLConnection.HTTP_OK; + } + }; + + TestableAbstractAcmeClient client = new TestableAbstractAcmeClient(connection); + client.putTestResource(Resource.REVOKE_CERT, resourceUri); + + client.revokeCertificate(testAccount, cert); + } + + /** + * Extends the {@link AbstractAcmeClient} to be tested, and implements the abstract + * methods with a simple implementation specially made for testing purposes. + */ + public static class TestableAbstractAcmeClient extends AbstractAcmeClient { + private final Map resourceMap = new HashMap<>(); + private final Map challengeMap = new HashMap<>(); + private final Connection connection; + private boolean connected = false; + + public TestableAbstractAcmeClient(Connection connection) { + this.connection = connection; + } + + /** + * Register a {@link Resource} mapping. + * + * @param r + * {@link Resource} to be mapped + * @param u + * {@link URI} to be returned + */ + public void putTestResource(Resource r, URI u) { + resourceMap.put(r, u); + } + + /** + * Register a {@link Challenge}. For the sake of simplicity, + * {@link #createChallenge(String)} will always return the same {@link Challenge} + * instance in this test suite. + * + * @param s + * Challenge type + * @param c + * {@link Challenge} instance. + */ + public void putTestChallenge(String s, Challenge c) { + challengeMap.put(s, c); + } + + @Override + protected URI resourceUri(Resource resource) throws AcmeException { + if (resourceMap.isEmpty()) { + fail("Unexpected invocation of resourceUri()"); + } + URI resUri = resourceMap.get(resource); + if (resUri == null) { + fail("Unexpected invocation of resourceUri() with resource " + resource.name()); + } + return resUri; + } + + @Override + protected Challenge createChallenge(String type) { + if (challengeMap.isEmpty()) { + fail("Unexpected invocation of createChallenge()"); + } + Challenge challenge = challengeMap.get(type); + return (challenge != null ? challenge : new GenericChallenge()); + } + + @Override + protected Connection createConnection() { + if (connected) { + fail("createConnection() invoked twice"); + } + connected = true; + return connection; + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.shredzone.acme4j.impl.AbstractAcmeClientTest$3` acquired by call to `AbstractAcmeClientTest$3(...)` at line 157 is not released after line 181. +**Note**: potential exception at line 181 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractAcmeClientTest.testNewAuthorization() + +### Procedure Id: +org.shredzone.acme4j.impl.AbstractAcmeClientTest.testNewAuthorization():void.86bf8fbeda0c153cd6690800edf9878a + +### File: +acme4j-client/src/test/java/org/shredzone/acme4j/impl/AbstractAcmeClientTest.java + +### Key: +AbstractAcmeClientTest.java|testNewAuthorization|RESOURCE_LEAK + +### Node Key: +93b1bf656f2416dde9dc4ae2fb47c678 + +### Hash: +6fb965f471eb317f5c6de9235869a276 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8169/instruction.md b/inferredbugs-8169/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69635fc084ef0831c70c7f3bef91aad39c2fedbb --- /dev/null +++ b/inferredbugs-8169/instruction.md @@ -0,0 +1,575 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** acme4j +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * acme4j - Java ACME client + * + * Copyright (C) 2015 Richard "Shred" Körber + * http://acme4j.shredzone.org + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ +package org.shredzone.acme4j; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.shredzone.acme4j.util.AcmeUtils.parseTimestamp; +import static org.shredzone.acme4j.util.TestUtils.*; +import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.security.KeyPair; +import java.time.Instant; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.jose4j.jws.JsonWebSignature; +import org.jose4j.jwx.CompactSerializer; +import org.jose4j.lang.JoseException; +import org.junit.Test; +import org.shredzone.acme4j.Registration.EditableRegistration; +import org.shredzone.acme4j.challenge.Challenge; +import org.shredzone.acme4j.challenge.Dns01Challenge; +import org.shredzone.acme4j.challenge.Http01Challenge; +import org.shredzone.acme4j.connector.Resource; +import org.shredzone.acme4j.exception.AcmeException; +import org.shredzone.acme4j.provider.AcmeProvider; +import org.shredzone.acme4j.provider.TestableConnectionProvider; +import org.shredzone.acme4j.util.JSON; +import org.shredzone.acme4j.util.JSONBuilder; +import org.shredzone.acme4j.util.TestUtils; + +/** + * Unit tests for {@link Registration}. + */ +public class RegistrationTest { + + private URL resourceUrl = url("http://example.com/acme/resource"); + private URL locationUrl = url("http://example.com/acme/registration"); + private URI agreementUri = URI.create("http://example.com/agreement.pdf"); + + /** + * Test that a registration can be updated. + */ + @Test + public void testUpdateRegistration() throws AcmeException, IOException, URISyntaxException { + TestableConnectionProvider provider = new TestableConnectionProvider() { + private JSON jsonResponse; + private Integer response; + + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + assertThat(url, is(locationUrl)); + assertThat(claims.toString(), sameJSONAs(getJSON("updateRegistration").toString())); + assertThat(session, is(notNullValue())); + jsonResponse = getJSON("updateRegistrationResponse"); + response = HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public void sendRequest(URL url, Session session) { + if (url("https://example.com/acme/acct/1/orders").equals(url)) { + jsonResponse = new JSONBuilder() + .array("orders", "https://example.com/acme/order/1") + .toJSON(); + response = HttpURLConnection.HTTP_OK; + return; + } + + response = HttpURLConnection.HTTP_NOT_FOUND; + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(response, not(nullValue())); + return response; + } + + @Override + public JSON readJsonResponse() { + return jsonResponse; + } + + @Override + public URL getLocation() { + return locationUrl; + } + + @Override + public URL getLink(String relation) { + return null; + } + + @Override + public Collection getLinks(String relation) { + switch(relation) { + case "terms-of-service": return Arrays.asList(agreementUri); + default: return null; + } + } + }; + + Session session = provider.createSession(); + Registration registration = new Registration(session, locationUrl); + registration.update(); + + assertThat(session.getKeyIdentifier(), is(locationUrl.toString())); + assertThat(registration.getLocation(), is(locationUrl)); + assertThat(registration.getTermsOfServiceAgreed(), is(true)); + assertThat(registration.getContacts(), hasSize(1)); + assertThat(registration.getContacts().get(0), is(URI.create("mailto:foo2@example.com"))); + assertThat(registration.getStatus(), is(Status.VALID)); + + Iterator orderIt = registration.getOrders(); + assertThat(orderIt, not(nullValue())); + assertThat(orderIt.next().getLocation(), is(url("https://example.com/acme/order/1"))); + assertThat(orderIt.hasNext(), is(false)); + + provider.close(); + } + + /** + * Test lazy loading. + */ + @Test + public void testLazyLoading() throws AcmeException, IOException { + final AtomicBoolean requestWasSent = new AtomicBoolean(false); + + TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + requestWasSent.set(true); + assertThat(url, is(locationUrl)); + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder( + HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED)); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public JSON readJsonResponse() { + return getJSON("updateRegistrationResponse"); + } + + @Override + public URL getLocation() { + return locationUrl; + } + + @Override + public URL getLink(String relation) { + return null; + } + + @Override + public Collection getLinks(String relation) { + switch(relation) { + case "terms-of-service": return Arrays.asList(agreementUri); + default: return null; + } + } + }; + + Registration registration = new Registration(provider.createSession(), locationUrl); + + // Lazy loading + assertThat(requestWasSent.get(), is(false)); + assertThat(registration.getTermsOfServiceAgreed(), is(true)); + assertThat(requestWasSent.get(), is(true)); + + // Subsequent queries do not trigger another load + requestWasSent.set(false); + assertThat(registration.getTermsOfServiceAgreed(), is(true)); + assertThat(registration.getStatus(), is(Status.VALID)); + assertThat(requestWasSent.get(), is(false)); + + provider.close(); + } + + /** + * Test that a new {@link Authorization} can be created. + */ + @Test + public void testOrderCertificate() throws Exception { + byte[] csr = TestUtils.getResourceAsByteArray("/csr.der"); + Instant notBefore = parseTimestamp("2016-01-01T00:00:00Z"); + Instant notAfter = parseTimestamp("2016-01-08T00:00:00Z"); + + TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + assertThat(url, is(resourceUrl)); + assertThat(claims.toString(), sameJSONAs(getJSON("requestOrderRequest").toString())); + assertThat(session, is(notNullValue())); + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_CREATED)); + return HttpURLConnection.HTTP_CREATED; + } + + @Override + public JSON readJsonResponse() { + return getJSON("requestOrderResponse"); + } + + @Override + public URL getLocation() { + return locationUrl; + } + }; + + Session session = provider.createSession(); + + provider.putTestResource(Resource.NEW_ORDER, resourceUrl); + + Registration registration = new Registration(session, locationUrl); + Order order = registration.orderCertificate(csr, notBefore, notAfter); + + assertThat(order.getCsr(), is(csr)); + assertThat(order.getNotBefore(), is(parseTimestamp("2016-01-01T00:10:00Z"))); + assertThat(order.getNotAfter(), is(parseTimestamp("2016-01-08T00:10:00Z"))); + assertThat(order.getExpires(), is(parseTimestamp("2016-01-10T00:00:00Z"))); + assertThat(order.getStatus(), is(Status.PENDING)); + assertThat(order.getLocation(), is(locationUrl)); + assertThat(order.getAuthorizations(), is(notNullValue())); + assertThat(order.getAuthorizations().size(), is(2)); + + provider.close(); + } + + /** + * Test that a new {@link Authorization} can be created. + */ + @Test + public void testAuthorizeDomain() throws Exception { + TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + assertThat(url, is(resourceUrl)); + assertThat(claims.toString(), sameJSONAs(getJSON("newAuthorizationRequest").toString())); + assertThat(session, is(notNullValue())); + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_CREATED)); + return HttpURLConnection.HTTP_CREATED; + } + + @Override + public JSON readJsonResponse() { + return getJSON("newAuthorizationResponse"); + } + + @Override + public URL getLocation() { + return locationUrl; + } + }; + + Session session = provider.createSession(); + + Http01Challenge httpChallenge = new Http01Challenge(session); + Dns01Challenge dnsChallenge = new Dns01Challenge(session); + + provider.putTestResource(Resource.NEW_AUTHZ, resourceUrl); + provider.putTestChallenge(Http01Challenge.TYPE, httpChallenge); + provider.putTestChallenge(Dns01Challenge.TYPE, dnsChallenge); + + String domainName = "example.org"; + + Registration registration = new Registration(session, locationUrl); + Authorization auth = registration.authorizeDomain(domainName); + + assertThat(auth.getDomain(), is(domainName)); + assertThat(auth.getStatus(), is(Status.PENDING)); + assertThat(auth.getExpires(), is(nullValue())); + assertThat(auth.getLocation(), is(locationUrl)); + + assertThat(auth.getChallenges(), containsInAnyOrder( + (Challenge) httpChallenge, (Challenge) dnsChallenge)); + + provider.close(); + } + + /** + * Test that a bad domain parameter is not accepted. + */ + @Test + public void testAuthorizeBadDomain() throws Exception { + TestableConnectionProvider provider = new TestableConnectionProvider(); + Session session = provider.createSession(); + Registration registration = Registration.bind(session, locationUrl); + + try { + registration.authorizeDomain(null); + fail("null domain was accepted"); + } catch (NullPointerException ex) { + // expected + } + + try { + registration.authorizeDomain(""); + fail("empty domain string was accepted"); + } catch (IllegalArgumentException ex) { + // expected + } + + provider.close(); + } + + /** + * Test that the account key can be changed. + */ + @Test + public void testChangeKey() throws Exception { + final KeyPair oldKeyPair = TestUtils.createKeyPair(); + final KeyPair newKeyPair = TestUtils.createDomainKeyPair(); + + final TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder payload, Session session) { + try { + assertThat(url, is(locationUrl)); + assertThat(session, is(notNullValue())); + assertThat(session.getKeyPair(), is(sameInstance(oldKeyPair))); + + JSON json = payload.toJSON(); + String encodedHeader = json.get("protected").asString(); + String encodedSignature = json.get("signature").asString(); + String encodedPayload = json.get("payload").asString(); + + String serialized = CompactSerializer.serialize(encodedHeader, encodedPayload, encodedSignature); + JsonWebSignature jws = new JsonWebSignature(); + jws.setCompactSerialization(serialized); + jws.setKey(newKeyPair.getPublic()); + assertThat(jws.verifySignature(), is(true)); + + String decodedPayload = jws.getPayload(); + + StringBuilder expectedPayload = new StringBuilder(); + expectedPayload.append('{'); + expectedPayload.append("\"account\":\"").append(resourceUrl).append("\","); + expectedPayload.append("\"newKey\":{"); + expectedPayload.append("\"kty\":\"").append(TestUtils.D_KTY).append("\","); + expectedPayload.append("\"e\":\"").append(TestUtils.D_E).append("\","); + expectedPayload.append("\"n\":\"").append(TestUtils.D_N).append("\""); + expectedPayload.append("}}"); + assertThat(decodedPayload, sameJSONAs(expectedPayload.toString())); + } catch (JoseException ex) { + fail("decoding inner payload failed"); + } + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_OK)); + return HttpURLConnection.HTTP_OK; + } + + @Override + public URL getLocation() { + return resourceUrl; + } + }; + + provider.putTestResource(Resource.KEY_CHANGE, locationUrl); + + Session session = new Session(new URI(TestUtils.ACME_SERVER_URI), oldKeyPair) { + @Override + public AcmeProvider provider() { + return provider; + }; + }; + + assertThat(session.getKeyPair(), is(sameInstance(oldKeyPair))); + + Registration registration = new Registration(session, resourceUrl); + registration.changeKey(newKeyPair); + + assertThat(session.getKeyPair(), is(sameInstance(newKeyPair))); + } + + /** + * Test that the same account key is not accepted for change. + */ + @Test(expected = IllegalArgumentException.class) + public void testChangeSameKey() throws Exception { + TestableConnectionProvider provider = new TestableConnectionProvider(); + Session session = provider.createSession(); + + Registration registration = new Registration(session, locationUrl); + registration.changeKey(session.getKeyPair()); + + provider.close(); + } + + /** + * Test that a registration can be deactivated. + */ + @Test + public void testDeactivate() throws Exception { + TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + JSON json = claims.toJSON(); + assertThat(json.get("status").asString(), is("deactivated")); + assertThat(url, is(locationUrl)); + assertThat(session, is(notNullValue())); + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_OK)); + return HttpURLConnection.HTTP_OK; + } + + @Override + public JSON readJsonResponse() { + return getJSON("deactivateRegistrationResponse"); + } + }; + + Registration registration = new Registration(provider.createSession(), locationUrl); + registration.deactivate(); + + assertThat(registration.getStatus(), is(Status.DEACTIVATED)); + + provider.close(); + } + + /** + * Test that a registration can be modified. + */ + @Test + public void testModify() throws Exception { + TestableConnectionProvider provider = new TestableConnectionProvider() { + @Override + public void sendSignedRequest(URL url, JSONBuilder claims, Session session) { + assertThat(url, is(locationUrl)); + assertThat(claims.toString(), sameJSONAs(getJSON("modifyRegistration").toString())); + assertThat(session, is(notNullValue())); + } + + @Override + public int accept(int... httpStatus) throws AcmeException { + assertThat(httpStatus, isIntArrayContainingInAnyOrder(HttpURLConnection.HTTP_ACCEPTED)); + return HttpURLConnection.HTTP_ACCEPTED; + } + + @Override + public JSON readJsonResponse() { + return getJSON("modifyRegistrationResponse"); + } + + @Override + public URL getLocation() { + return locationUrl; + } + }; + + Registration registration = new Registration(provider.createSession(), locationUrl); + + EditableRegistration editable = registration.modify(); + assertThat(editable, notNullValue()); + + editable.addContact("mailto:foo2@example.com"); + editable.getContacts().add(URI.create("mailto:foo3@example.com")); + editable.commit(); + + assertThat(registration.getLocation(), is(locationUrl)); + assertThat(registration.getContacts().size(), is(2)); + assertThat(registration.getContacts().get(0), is(URI.create("mailto:foo2@example.com"))); + assertThat(registration.getContacts().get(1), is(URI.create("mailto:foo3@example.com"))); + + provider.close(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `authorizeDomain(...)` at line 318. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RegistrationTest.testAuthorizeBadDomain() + +### Procedure Id: +org.shredzone.acme4j.RegistrationTest.testAuthorizeBadDomain():void.361a384d48245e573338ff681889b83a + +### File: +acme4j-client/src/test/java/org/shredzone/acme4j/RegistrationTest.java + +### Key: +RegistrationTest.java|testAuthorizeBadDomain|NULL_DEREFERENCE + +### Node Key: +2d63b1f68a2299187625b103ef57d3ba + +### Hash: +3f6d274a88aac164c4199a462962fc4d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8192/instruction.md b/inferredbugs-8192/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01b90b254ad8783d3bf68f97de268c10ef602ac0 --- /dev/null +++ b/inferredbugs-8192/instruction.md @@ -0,0 +1,248 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SmartIM +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.github.biezhi.wechat.model; + +import java.io.File; + +import com.google.gson.annotations.Expose; +import com.google.gson.annotations.SerializedName; + +import cn.ieclipse.smartim.model.impl.AbstractMessage; +import cn.ieclipse.util.StringUtils; +import io.github.biezhi.wechat.api.WechatClient; +import io.github.biezhi.wechat.handler.msg.AppMsgXmlHandler; +import io.github.biezhi.wechat.handler.msg.EmojiMsgXmlHandler; +import io.github.biezhi.wechat.handler.msg.ImageMsgXmlHandler; + +public class WechatMessage extends AbstractMessage { + + public static final int MSGTYPE_TEXT = 1; + public static final int MSGTYPE_IMAGE = 3; + /** + * 慎用,并不确定 + */ + public static final int MSGTYPE_FILE = 6; + public static final int MSGTYPE_VOICE = 34; + public static final int MSGTYPE_VERIFYMSG = 37; + public static final int MSGTYPE_POSSIBLEFRIEND_MSG = 40; + public static final int MSGTYPE_SHARECARD = 42; + public static final int MSGTYPE_VIDEO = 43; + public static final int MSGTYPE_EMOTICON = 47; + public static final int MSGTYPE_LOCATION = 48; + public static final int MSGTYPE_APP = 49; + public static final int MSGTYPE_VOIPMSG = 50; + public static final int MSGTYPE_STATUSNOTIFY = 51; + public static final int MSGTYPE_VOIPNOTIFY = 52; + public static final int MSGTYPE_VOIPINVITE = 53; + public static final int MSGTYPE_MICROVIDEO = 62; + public static final int MSGTYPE_SYSNOTICE = 9999; + public static final int MSGTYPE_SYS = 10000; + public static final int MSGTYPE_RECALLED = 10002; + + public static final int APPMSGTYPE_TEXT = 1; + public static final int APPMSGTYPE_IMG = 2; + public static final int APPMSGTYPE_AUDIO = 3; + public static final int APPMSGTYPE_VIDEO = 4; + public static final int APPMSGTYPE_URL = 5; + public static final int APPMSGTYPE_ATTACH = 6; + public static final int APPMSGTYPE_OPEN = 7; + public static final int APPMSGTYPE_EMOJI = 8; + public static final int APPMSGTYPE_VOICE_REMIND = 9; + public static final int APPMSGTYPE_SCAN_GOOD = 10; + public static final int APPMSGTYPE_GOOD = 13; + public static final int APPMSGTYPE_EMOTION = 15; + public static final int APPMSGTYPE_CARD_TICKET = 16; + public static final int APPMSGTYPE_REALTIME_SHARE_LOCATION = 17; + public static final String APPMSGTYPE_TRANSFERS = "2e3"; + public static final int APPMSGTYPE_RED_ENVELOPES = 2001; + public static final int APPMSGTYPE_READER_TYPE = 100001; + public static final int UPLOAD_MEDIA_TYPE_IMAGE = 1; + public static final int UPLOAD_MEDIA_TYPE_VIDEO = 2; + public static final int UPLOAD_MEDIA_TYPE_AUDIO = 3; + public static final int UPLOAD_MEDIA_TYPE_ATTACHMENT = 4; + + public static final String CONTENT_DELIMITER = ":
    "; + + @SerializedName("MsgType") + public int MsgType; + @SerializedName("FromUserName") + public String FromUserName; + @SerializedName("ToUserName") + public String ToUserName; + @SerializedName("Content") + public String Content; + + @SerializedName("MsgId") + public String MsgId; + + @SerializedName("CreateTime") + public long CreateTime; + + @SerializedName("StatusNotifyCode") + public int StatusNotifyCode; + + @SerializedName("StatusNotifyUserName") + public String StatusNotifyUserName; + + @Expose(serialize = false, deserialize = false) + public String text; + public String src; + public String groupId; + public String MediaId; + public int AppMsgType; + public String FileName; + public String EncryFileName; + public int ImgHeight; + public int ImgWidth; + + @Override + public CharSequence getText() { + if (text == null) { + parseContent(); + } + return text; + } + + public void parseContent() { + String temp = StringUtils.decodeXml(Content); + if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { + text = new EmojiMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + else if (MsgType == WechatMessage.MSGTYPE_IMAGE) { + text = new ImageMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + else if (MsgType == WechatMessage.MSGTYPE_APP) { + text = new AppMsgXmlHandler(temp).getHtml(getMediaLink(), this); + } + // else if (MsgType == WechatMessage.MSGTYPE_FILE) { + // text = new FileMsgXmlHandler(temp).getHtml(getMediaLink()); + // } + else if (MsgType == WechatMessage.MSGTYPE_VIDEO) { + text = "视频消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VOICE) { + text = "语音消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_MICROVIDEO) { + text = "小视频(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VERIFYMSG) { + text = "验证消息(请在手机上查看)"; + } + else if (MsgType == WechatMessage.MSGTYPE_VOIPINVITE) { + text = "视频邀请消息(请在手机上查看)"; + } + else { + text = temp; + } + } + + public String getMediaLink() { + if (WechatClient.getInstance() != null) { + File dir = WechatClient.getInstance().getWorkDir("media"); + File f = null; + if (MsgType == WechatMessage.MSGTYPE_IMAGE) { + f = new File(dir, "image_" + MsgId + ".jpg"); + } + else if (MsgType == WechatMessage.MSGTYPE_EMOTICON) { + f = new File(dir, "emotion_" + MsgId + ".gif"); + } + else if (MsgType == WechatMessage.MSGTYPE_APP) { + if (WechatMessage.MSGTYPE_FILE == AppMsgType + && !StringUtils.isEmpty(FileName)) { + f = new File( + WechatClient.getInstance().getWorkDir("attach"), + FileName); + } + } + + String link = WechatClient.getInstance().getMediaLink(this, f); + return link; + } + return null; + } + + @Override + public long getTime() { + // fix #2 wechat timeline error refer to + // https://github.com/Jamling/SmartQQ4IntelliJ/issues/30 + return CreateTime * 1000; + } + + @Override + public String toString() { + return String.format("type:%d, msg:%s", MsgType, text); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `temp` last assigned on line 105 could be null and is dereferenced by call to `EmojiMsgXmlHandler(...)` at line 107. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WechatMessage.parseContent() + +### Procedure Id: +io.github.biezhi.wechat.model.WechatMessage.parseContent():void.3fe963b408dde7ba19ff1177d8df6510 + +### File: +wechat/src/main/java/io/github/biezhi/wechat/model/WechatMessage.java + +### Key: +WechatMessage.java|parseContent|NULL_DEREFERENCE + +### Node Key: +784c4b183b3d42c8e49c891ead93a47b + +### Hash: +dbd7da9bb8602b51c9c9521105b07f01 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8193/instruction.md b/inferredbugs-8193/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3aa5f7932afef9bad5e4901c76327c5d4fb87c63 --- /dev/null +++ b/inferredbugs-8193/instruction.md @@ -0,0 +1,105 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SmartIM +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.github.biezhi.wechat.handler.msg; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import io.github.biezhi.wechat.model.xml.AppMsgInfo; + +public class AppMsgXmlHandlerTest { + AppMsgXmlHandler handler; + + @Before + public void setUp() throws Exception { + String content = File2String.read("appmsg-file.xml"); + handler = new AppMsgXmlHandler(content); + } + + @Test + public void testGetRecents() { + AppMsgInfo info = handler.decode(); + Assert.assertEquals("南京abc.xlsx", info.title); + System.out.println(info); + + handler = new AppMsgXmlHandler( + File2String.read("appmsg-publisher.xml")); + info = handler.decode(); + Assert.assertEquals("谷歌开发者", info.appName); + System.out.println(info); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `content` last assigned on line 14 could be null and is dereferenced by call to `AppMsgXmlHandler(...)` at line 15. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AppMsgXmlHandlerTest.setUp() + +### Procedure Id: +io.github.biezhi.wechat.handler.msg.AppMsgXmlHandlerTest.setUp():void.7c9d848a63a9658df0332c11adfb254e + +### File: +wechat/src/test/java/io/github/biezhi/wechat/handler/msg/AppMsgXmlHandlerTest.java + +### Key: +AppMsgXmlHandlerTest.java|setUp|NULL_DEREFERENCE + +### Node Key: +1ea622e3065de2665c2aef206eac0fa5 + +### Hash: +22ea5bcc639e73de1148804e18d73111 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8194/instruction.md b/inferredbugs-8194/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f35ecbe67e71f48efd40cf16ea9fd7f4f94a594f --- /dev/null +++ b/inferredbugs-8194/instruction.md @@ -0,0 +1,116 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jdonframework +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2003-2009 the original author or authors. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +package com.jdon.sample.test.cqrs; + +import junit.framework.Assert; + +import com.jdon.controller.AppUtil; +import com.jdon.domain.message.DomainMessage; +import com.jdon.sample.test.cqrs.a.AggregateRootA; + +public class TestMain { + + public static void main(String[] args) { + AppUtil appUtil = new AppUtil(); + AService service = (AService) appUtil.getComponentInstance("aService"); + AggregateRootA aggregateRootA = service.getAggregateRootA("11"); + DomainMessage res = service.commandA("11", aggregateRootA, 100); + + long start = System.currentTimeMillis(); + int result = 0; + DomainMessage res1 = (DomainMessage) res.getBlockEventResult(); + if (res1.getBlockEventResult() != null) + result = (Integer) res1.getBlockEventResult(); + + long stop = System.currentTimeMillis(); + Assert.assertEquals(result, 400); + System.out.print("\n ok \n" + result + (stop - start)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `res1` last assigned on line 34 could be null and is dereferenced at line 35. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestMain.main(java.lang.String[]) + +### Procedure Id: +com.jdon.sample.test.cqrs.TestMain.main(java.lang.String[]):void.be3c53f2792c6cbb126312b7ffac8bf9 + +### File: +src/test/java/com/jdon/sample/test/cqrs/TestMain.java + +### Key: +TestMain.java|main|NULL_DEREFERENCE + +### Node Key: +cbf4abef6a7d17d1b80dfb598ec521f3 + +### Hash: +d30d2cf4fd3600ba5145f053e6dec775 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8195/instruction.md b/inferredbugs-8195/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6d6cb27dc20d5c222be154b177ca2b79027164b --- /dev/null +++ b/inferredbugs-8195/instruction.md @@ -0,0 +1,320 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** JavaVerbalExpressions +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +import java.util.regex.Pattern; + +class VerbalExpression { + private String prefixes, source, suffixes, pattern = ""; + private int modifiers = Pattern.MULTILINE; + + private String sanitize(String value) { + if(value == null) + return value; + return Pattern.quote(value); + } + + public VerbalExpression add(String value) { + this.source = this.source != null ? this.source + value : value; + if (this.source != null) { + Pattern p = Pattern.compile(this.prefixes + this.source + this.suffixes, this.modifiers); + this.pattern = p.pattern(); + } + return this; + } + + public VerbalExpression startOfLine(boolean enable) { + this.prefixes = enable ? "^" : ""; + this.add(""); + return this; + } + + public VerbalExpression startOfLine() { + return startOfLine(true); + } + + public VerbalExpression endOfLine(boolean enable) { + this.suffixes = enable ? "$" : ""; + this.add(""); + return this; + } + + public VerbalExpression endOfLine() { + return endOfLine(true); + } + + public VerbalExpression then(String value) { + value = sanitize(value); + this.add("(" + value + ")"); + return this; + } + + public VerbalExpression find(String value) { + this.then(value); + return this; + } + + public VerbalExpression maybe(String value) { + value = sanitize(value); + this.add("(" + value + ")?"); + return this; + } + + public VerbalExpression anything() { + this.add("(.*)"); + return this; + } + + public VerbalExpression anythingBut(String value) { + value = sanitize(value); + this.add("([^" + value + "]*)"); + return this; + } + + public VerbalExpression something() { + this.add("(.+)"); + return this; + } + + public VerbalExpression somethingBut(String value) { + value = sanitize(value); + this.add("([^" + value + "]+)"); + return this; + } + + public VerbalExpression replace(String source, String value) { + this.add(""); + this.source.replaceAll(pattern,value); + return this; + } + + public VerbalExpression lineBreak() { + this.add("(\\n|(\\r\\n))"); + return this; + } + + public VerbalExpression br() { + this.lineBreak(); + return this; + } + + public VerbalExpression tab() { + this.add("\\t"); + return this; + } + + public VerbalExpression word() { + this.add("\\w+"); + return this; + } + + public VerbalExpression anyOf(String value) { + value = sanitize(value); + this.add("[" + value + "]"); + return this; + } + + public VerbalExpression any(String value) { + this.anyOf(value); + return this; + } + + public VerbalExpression range(Object[] args) { + String value = "["; + for(int _from = 0; _from < args.length; _from += 2) { + int _to = _from+1; + if (args.length <= _to) break; + int from = Integer.getInteger(sanitize((String)args[_from])); + int to = Integer.getInteger(sanitize((String)args[_to])); + + value += from + "-" + to; + } + + value += "]"; + + this.add(value); + return this; + } + + public VerbalExpression addModifier(char modifier) { + switch (modifier) { + case 'd': + modifiers |= Pattern.UNIX_LINES; + break; + case 'i': + modifiers |= Pattern.CASE_INSENSITIVE; + break; + case 'x': + modifiers |= Pattern.COMMENTS; + break; + case 'm': + modifiers |= Pattern.MULTILINE; + break; + case 's': + modifiers |= Pattern.DOTALL; + break; + case 'u': + modifiers |= Pattern.UNICODE_CASE; + break; + case 'U': + modifiers |= Pattern.UNICODE_CHARACTER_CLASS; + break; + default: + break; + } + + this.add(""); + return this; + } + + public VerbalExpression removeModifier(char modifier) { + switch (modifier) { + case 'd': + modifiers ^= Pattern.UNIX_LINES; + break; + case 'i': + modifiers ^= Pattern.CASE_INSENSITIVE; + break; + case 'x': + modifiers ^= Pattern.COMMENTS; + break; + case 'm': + modifiers ^= Pattern.MULTILINE; + break; + case 's': + modifiers ^= Pattern.DOTALL; + break; + case 'u': + modifiers ^= Pattern.UNICODE_CASE; + break; + case 'U': + modifiers ^= Pattern.UNICODE_CHARACTER_CLASS; + break; + default: + break; + } + + this.add(""); + return this; + } + + public VerbalExpression withAnyCase(boolean enable) { + if (enable) this.addModifier( 'i' ); + else this.removeModifier( 'i' ); + this.add(""); + return this; + } + + public VerbalExpression withAnyCase() { + return withAnyCase(true); + } + + public VerbalExpression searchOneLine(boolean enable) { + if (enable) this.removeModifier( 'm' ); + else this.addModifier( 'm' ); + this.add(""); + return this; + } + + public VerbalExpression multiple(String value) { + value = this.sanitize(value); + switch (value.charAt(0)) { + case '*': + case '+': + break; + default: + value += '+'; + } + this.add(value); + return this; + } + + public VerbalExpression or(String value) { + if (this.prefixes.indexOf("(") == -1) this.prefixes += "("; + if (this.suffixes.indexOf(")") == -1) this.suffixes = ")" + this.suffixes; + + this.add(")|("); + if (value != null) this.then(value); + return this; + } + + public boolean test(String toTest) { + this.add(""); + return Pattern.matches(this.pattern, toTest); + } + + public String toString() { + this.add(""); + return this.pattern.toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `VerbalExpression.source` last assigned on line 82 could be null and is dereferenced at line 83. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +VerbalExpression VerbalExpression.replace(String,String) + +### Procedure Id: +VerbalExpression.replace(java.lang.String,java.lang.String):VerbalExpression.ee091891566d736960ca296342eeedf1 + +### File: +src/main/java/VerbalExpression.java + +### Key: +VerbalExpression.java|replace|NULL_DEREFERENCE + +### Node Key: +2777f2506d1c1849b67f08d2ed9fe7aa + +### Hash: +be97bbef660e32b6d700b40270ebae87 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8210/instruction.md b/inferredbugs-8210/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7eb67ec9252e7e80593da52c699b9b24893baf50 --- /dev/null +++ b/inferredbugs-8210/instruction.md @@ -0,0 +1,226 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pf4j +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2015 Decebal Suiu + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ro.fortsoft.pf4j; + +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; + +import static org.junit.Assert.*; + +/** + * + * @author Mario Franco + */ +public class DefaultPluginStatusProviderTest { + + @Rule + public TemporaryFolder testFolder = new TemporaryFolder(); + + /** + * Test of isPluginDisabled method, of class DefaultPluginStatusProvider. + */ + @Test + public void testIsPluginDisabled() throws IOException { + createEnabledFile(); + createDisabledFile(); + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertFalse(instance.isPluginDisabled("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-2")); + assertTrue(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of isPluginDisabled method, of class DefaultPluginStatusProvider. + */ + @Test + public void testIsPluginDisabledWithEnableEmpty() throws IOException { + createDisabledFile(); + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertFalse(instance.isPluginDisabled("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-2")); + assertFalse(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of disablePlugin method, of class DefaultPluginStatusProvider. + */ + @Test + public void testDisablePlugin() throws IOException { + createEnabledFile(); + createDisabledFile(); + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertTrue(instance.disablePlugin("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-2")); + assertTrue(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of disablePlugin method, of class DefaultPluginStatusProvider. + */ + @Test + public void testDisablePluginWithEnableEmpty() throws IOException { + createDisabledFile(); + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertTrue(instance.disablePlugin("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-2")); + assertFalse(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of enablePlugin method, of class DefaultPluginStatusProvider. + */ + @Test + public void testEnablePlugin() throws IOException { + createEnabledFile(); + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertTrue(instance.enablePlugin("plugin-2")); + assertFalse(instance.isPluginDisabled("plugin-1")); + assertFalse(instance.isPluginDisabled("plugin-2")); + assertTrue(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of enablePlugin method, of class DefaultPluginStatusProvider. + */ + @Test + public void testEnablePluginWithEnableEmpty() { + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertTrue(instance.enablePlugin("plugin-2")); + assertFalse(instance.isPluginDisabled("plugin-1")); + assertFalse(instance.isPluginDisabled("plugin-2")); + assertFalse(instance.isPluginDisabled("plugin-3")); + } + + /** + * Test of disablePlugin method without a disabled.txt file. + */ + @Test + public void testDisablePluginWithoutDisabledFile() throws IOException { + DefaultPluginStatusProvider instance = new DefaultPluginStatusProvider(testFolder.getRoot()); + + assertFalse(instance.isPluginDisabled("plugin-1")); + assertTrue(instance.disablePlugin("plugin-1")); + assertTrue(instance.isPluginDisabled("plugin-1")); + } + + private void createDisabledFile() throws IOException { + File file = testFolder.newFile("disabled.txt"); + try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) { + writer.write("plugin-2\r\n"); + } + file.createNewFile(); + } + + private void createEnabledFile() throws IOException { + File file = testFolder.newFile("enabled.txt"); + file.createNewFile(); + try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) { + writer.write("plugin-1\r\n"); + writer.write("plugin-2\r\n"); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired by call to `FileOutputStream(...)` at line 146 is not released after line 146. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultPluginStatusProviderTest.createEnabledFile() + +### Procedure Id: +ro.fortsoft.pf4j.DefaultPluginStatusProviderTest.createEnabledFile():void.258af3b7c2cddcf4fd3bc77bfcb58676 + +### File: +pf4j/src/test/java/ro/fortsoft/pf4j/DefaultPluginStatusProviderTest.java + +### Key: +DefaultPluginStatusProviderTest.java|createEnabledFile|RESOURCE_LEAK + +### Node Key: +77c9666e2163e37e098ff5397dda0560 + +### Hash: +3e7e03c1101dbc422f2b82d0a3653e40 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8217/instruction.md b/inferredbugs-8217/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9dda8409d0ca68a7813673a23617d0c7fb53057 --- /dev/null +++ b/inferredbugs-8217/instruction.md @@ -0,0 +1,799 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pf4j +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2012 Decebal Suiu + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with + * the License. You may obtain a copy of the License in the LICENSE file, or at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + */ +package ro.fortsoft.pf4j; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ro.fortsoft.pf4j.util.AndFileFilter; +import ro.fortsoft.pf4j.util.CompoundClassLoader; +import ro.fortsoft.pf4j.util.DirectoryFileFilter; +import ro.fortsoft.pf4j.util.FileUtils; +import ro.fortsoft.pf4j.util.HiddenFilter; +import ro.fortsoft.pf4j.util.NotFileFilter; +import ro.fortsoft.pf4j.util.Unzip; +import ro.fortsoft.pf4j.util.ZipFileFilter; + +/** + * Default implementation of the PluginManager interface. + * + * @author Decebal Suiu + */ +public class DefaultPluginManager implements PluginManager { + + private static final Logger log = LoggerFactory.getLogger(DefaultPluginManager.class); + + public static final String DEFAULT_PLUGINS_DIRECTORY = "plugins"; + public static final String DEVELOPMENT_PLUGINS_DIRECTORY = "../plugins"; + + /** + * The plugins repository. + */ + private File pluginsDirectory; + + private ExtensionFinder extensionFinder; + + private PluginDescriptorFinder pluginDescriptorFinder; + + private PluginClasspath pluginClasspath; + + /** + * A map of plugins this manager is responsible for (the key is the 'pluginId'). + */ + private Map plugins; + + /** + * A map of plugin class loaders (he key is the 'pluginId'). + */ + private Map pluginClassLoaders; + + /** + * A relation between 'pluginPath' and 'pluginId' + */ + private Map pathToIdMap; + + /** + * A list with unresolved plugins (unresolved dependency). + */ + private List unresolvedPlugins; + + /** + * A list with resolved plugins (resolved dependency). + */ + private List resolvedPlugins; + + /** + * A list with started plugins. + */ + private List startedPlugins; + + private List enabledPlugins; + private List disabledPlugins; + + /** + * A compound class loader of resolved plugins. + */ + protected CompoundClassLoader compoundClassLoader; + + /** + * Cache value for the runtime mode. No need to re-read it because it wont change at + * runtime. + */ + private RuntimeMode runtimeMode; + + /** + * The plugins directory is supplied by System.getProperty("pf4j.pluginsDir", "plugins"). + */ + public DefaultPluginManager() { + this.pluginsDirectory = createPluginsDirectory(); + + initialize(); + } + + /** + * Constructs DefaultPluginManager which the given plugins directory. + * + * @param pluginsDirectory + * the directory to search for plugins + */ + public DefaultPluginManager(File pluginsDirectory) { + this.pluginsDirectory = pluginsDirectory; + + initialize(); + } + + @Override + public List getPlugins() { + return new ArrayList(plugins.values()); + } + + @Override + public List getPlugins(PluginState pluginState) { + List plugins= new ArrayList(); + for (PluginWrapper plugin : getPlugins()) { + if (pluginState.equals(plugin.getPluginState())) { + plugins.add(plugin); + } + } + + return plugins; + } + + @Override + public List getResolvedPlugins() { + return resolvedPlugins; + } + + public PluginWrapper getPlugin(String pluginId) { + return plugins.get(pluginId); + } + + @Override + public List getUnresolvedPlugins() { + return unresolvedPlugins; + } + + @Override + public List getStartedPlugins() { + return startedPlugins; + } + + @Override + public String loadPlugin(File pluginArchiveFile) { + if (pluginArchiveFile == null || !pluginArchiveFile.exists()) { + throw new IllegalArgumentException(String.format("Specified plugin %s does not exist!", pluginArchiveFile)); + } + + File pluginDirectory = null; + try { + pluginDirectory = expandPluginArchive(pluginArchiveFile); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + if (pluginDirectory == null || !pluginDirectory.exists()) { + throw new IllegalArgumentException(String.format("Failed to expand %s", pluginArchiveFile)); + } + + try { + PluginWrapper pluginWrapper = loadPluginDirectory(pluginDirectory); + // TODO uninstalled plugin dependencies? + unresolvedPlugins.remove(pluginWrapper); + resolvedPlugins.add(pluginWrapper); + compoundClassLoader.addLoader(pluginWrapper.getPluginClassLoader()); + extensionFinder.reset(); + return pluginWrapper.getDescriptor().getPluginId(); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + return null; + } + + /** + * Start all active plugins. + */ + @Override + public void startPlugins() { + for (PluginWrapper pluginWrapper : resolvedPlugins) { + PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor(); + if (!isPluginDisabled(pluginDescriptor.getPluginId())) { + try { + log.info("Start plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + pluginWrapper.getPlugin().start(); + pluginWrapper.setPluginState(PluginState.STARTED); + startedPlugins.add(pluginWrapper); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + } + } + } + + /** + * Start the specified plugin and it's dependencies. + */ + @Override + public PluginState startPlugin(String pluginId) { + if (!plugins.containsKey(pluginId)) { + throw new IllegalArgumentException(String.format("Unknown pluginId %s", pluginId)); + } + + PluginWrapper pluginWrapper = plugins.get(pluginId); + PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor(); + if (pluginWrapper.getPluginState().equals(PluginState.STARTED)) { + log.debug("Already started plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + return PluginState.STARTED; + } + + // test for disabled plugin + if (isPluginDisabled(pluginDescriptor.getPluginId())) { + // do nothing + return pluginWrapper.getPluginState(); + } + + for (PluginDependency dependency : pluginDescriptor.getDependencies()) { + startPlugin(dependency.getPluginId()); + } + + try { + log.info("Start plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + pluginWrapper.getPlugin().start(); + pluginWrapper.setPluginState(PluginState.STARTED); + startedPlugins.add(pluginWrapper); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + + return pluginWrapper.getPluginState(); + } + + /** + * Stop all active plugins. + */ + @Override + public void stopPlugins() { + // stop started plugins in reverse order + Collections.reverse(startedPlugins); + Iterator itr = startedPlugins.iterator(); + while (itr.hasNext()) { + PluginWrapper pluginWrapper = itr.next(); + PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor(); + if (!isPluginDisabled(pluginDescriptor.getPluginId())) { + try { + log.info("Stop plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + pluginWrapper.getPlugin().stop(); + pluginWrapper.setPluginState(PluginState.STOPPED); + itr.remove(); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + } + } + } + + /** + * Stop the specified plugin and it's dependencies. + */ + @Override + public PluginState stopPlugin(String pluginId) { + if (!plugins.containsKey(pluginId)) { + throw new IllegalArgumentException(String.format("Unknown pluginId %s", pluginId)); + } + + PluginWrapper pluginWrapper = plugins.get(pluginId); + PluginDescriptor pluginDescriptor = pluginWrapper.getDescriptor(); + if (pluginWrapper.getPluginState().equals(PluginState.STOPPED)) { + log.debug("Already stopped plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + return PluginState.STOPPED; + } + + // test for disabled plugin + if (isPluginDisabled(pluginDescriptor.getPluginId())) { + // do nothing + return pluginWrapper.getPluginState(); + } + + for (PluginDependency dependency : pluginDescriptor.getDependencies()) { + stopPlugin(dependency.getPluginId()); + } + + try { + log.info("Stop plugin '{}:{}'", pluginDescriptor.getPluginId(), pluginDescriptor.getVersion()); + pluginWrapper.getPlugin().stop(); + pluginWrapper.setPluginState(PluginState.STOPPED); + startedPlugins.remove(pluginWrapper); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + + return pluginWrapper.getPluginState(); + } + + /** + * Load plugins. + */ + @Override + public void loadPlugins() { + log.debug("Lookup plugins in '{}'", pluginsDirectory.getAbsolutePath()); + // check for plugins directory + if (!pluginsDirectory.exists() || !pluginsDirectory.isDirectory()) { + log.error("No '{}' directory", pluginsDirectory.getAbsolutePath()); + return; + } + + // expand all plugin archives + FileFilter zipFilter = new ZipFileFilter(); + File[] zipFiles = pluginsDirectory.listFiles(zipFilter); + if (zipFiles != null) { + for (File zipFile : zipFiles) { + try { + expandPluginArchive(zipFile); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } + } + + // check for no plugins + List filterList = new ArrayList(); + filterList.add(new DirectoryFileFilter()); + filterList.add(new NotFileFilter(createHiddenPluginFilter())); + FileFilter pluginsFilter = new AndFileFilter(filterList); + File[] directories = pluginsDirectory.listFiles(pluginsFilter); + if (directories == null) { + directories = new File[0]; + } + log.debug("Found possible {} plugins: {}", directories.length, directories); + if (directories.length == 0) { + log.info("No plugins"); + return; + } + + // load any plugin from plugins directory + for (File directory : directories) { + try { + loadPluginDirectory(directory); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + } + + // resolve 'unresolvedPlugins' + try { + resolvePlugins(); + } catch (PluginException e) { + log.error(e.getMessage(), e); + } + } + + @Override + public boolean unloadPlugin(String pluginId) { + try { + PluginState state = stopPlugin(pluginId); + if (!PluginState.STOPPED.equals(state)) { + return false; + } + + PluginWrapper pluginWrapper = plugins.get(pluginId); + PluginDescriptor descriptor = pluginWrapper.getDescriptor(); + List dependencies = descriptor.getDependencies(); + for (PluginDependency dependency : dependencies) { + if (!unloadPlugin(dependency.getPluginId())) { + return false; + } + } + + // remove the plugin + plugins.remove(pluginId); + resolvedPlugins.remove(pluginWrapper); + pathToIdMap.remove(pluginWrapper.getPluginPath()); + extensionFinder.reset(); + + // remove the classloader + if (pluginClassLoaders.containsKey(pluginId)) { + PluginClassLoader classLoader = pluginClassLoaders.remove(pluginId); + compoundClassLoader.removeLoader(classLoader); + try { + classLoader.close(); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } + return true; + } catch (IllegalArgumentException e) { + // ignore not found exceptions because this method is recursive + } + + return false; + } + + @Override + public boolean disablePlugin(String pluginId) { + if (plugins.containsKey(pluginId)) { + log.debug("Unloading plugin {}", pluginId); + unloadPlugin(pluginId); + } + + if (disabledPlugins.add(pluginId)) { + try { + FileUtils.writeLines(disabledPlugins, new File(pluginsDirectory, "disabled.txt")); + return true; + } catch (IOException e) { + log.error("Failed to disable plugin {}", pluginId, e); + } + } + + return false; + } + + @Override + public boolean enablePlugin(String pluginId) { + if (!disabledPlugins.remove(pluginId)) { + log.debug("Plugin {} was not disabled", pluginId); + return true; + } + + try { + FileUtils.writeLines(disabledPlugins, new File(pluginsDirectory, "disabled.txt")); + return true; + } catch (IOException e) { + log.error("Failed to enable plugin {}", pluginId, e); + } + + return false; + } + + @Override + public boolean deletePlugin(String pluginId) { + if (!plugins.containsKey(pluginId)) { + throw new IllegalArgumentException(String.format("Unknown pluginId %s", pluginId)); + } + PluginWrapper pw = getPlugin(pluginId); + PluginState state = stopPlugin(pluginId); + + if (PluginState.STOPPED != state) { + log.error("Failed to stop plugin {} on delete", pluginId); + return false; + } + + if (!unloadPlugin(pluginId)) { + log.error("Failed to unload plugin {} on delete", pluginId); + return false; + } + + File pluginFolder = new File(pluginsDirectory, pw.getPluginPath()); + File pluginZip = null; + + FileFilter zipFilter = new ZipFileFilter(); + File[] zipFiles = pluginsDirectory.listFiles(zipFilter); + if (zipFiles != null) { + // strip prepended / from the plugin path + String dirName = pw.getPluginPath().substring(1); + // find the zip file that matches the plugin path + for (File zipFile : zipFiles) { + String name = zipFile.getName().substring(0, zipFile.getName().lastIndexOf('.')); + if (name.equals(dirName)) { + pluginZip = zipFile; + break; + } + } + } + + if (pluginFolder.exists()) { + FileUtils.delete(pluginFolder); + } + if (pluginZip != null && pluginZip.exists()) { + FileUtils.delete(pluginZip); + } + return true; + } + + /** + * Get plugin class loader for this path. + */ + @Override + public PluginClassLoader getPluginClassLoader(String pluginId) { + return pluginClassLoaders.get(pluginId); + } + + @Override + public List getExtensions(Class type) { + List> extensionsWrapper = extensionFinder.find(type); + List extensions = new ArrayList(extensionsWrapper.size()); + for (ExtensionWrapper extensionWrapper : extensionsWrapper) { + extensions.add(extensionWrapper.getInstance()); + } + + return extensions; + } + + @Override + public RuntimeMode getRuntimeMode() { + if (runtimeMode == null) { + // retrieves the runtime mode from system + String modeAsString = System.getProperty("pf4j.mode", RuntimeMode.DEPLOYMENT.toString()); + runtimeMode = RuntimeMode.byName(modeAsString); + + log.info("PF4J runtime mode is '{}'", runtimeMode); + + } + + return runtimeMode; + } + + /** + * Retrieves the {@link PluginWrapper} that loaded the given class 'clazz'. + */ + public PluginWrapper whichPlugin(Class clazz) { + ClassLoader classLoader = clazz.getClassLoader(); + for (PluginWrapper plugin : resolvedPlugins) { + if (plugin.getPluginClassLoader() == classLoader) { + return plugin; + } + } + log.warn("Failed to find the plugin for {}", clazz); + return null; + } + + /** + * Add the possibility to override the PluginDescriptorFinder. + * By default if getRuntimeMode() returns RuntimeMode.DEVELOPMENT than a + * PropertiesPluginDescriptorFinder is returned else this method returns + * DefaultPluginDescriptorFinder. + */ + protected PluginDescriptorFinder createPluginDescriptorFinder() { + if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { + return new PropertiesPluginDescriptorFinder(); + } + + return new DefaultPluginDescriptorFinder(pluginClasspath); + } + + /** + * Add the possibility to override the ExtensionFinder. + */ + protected ExtensionFinder createExtensionFinder() { + return new DefaultExtensionFinder(compoundClassLoader); + } + + /** + * Add the possibility to override the PluginClassPath. + * By default if getRuntimeMode() returns RuntimeMode.DEVELOPMENT than a + * DevelopmentPluginClasspath is returned else this method returns + * PluginClasspath. + */ + protected PluginClasspath createPluginClasspath() { + if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { + return new DevelopmentPluginClasspath(); + } + + return new PluginClasspath(); + } + + @Override + public boolean isPluginDisabled(String pluginId) { + if (enabledPlugins.isEmpty()) { + return disabledPlugins.contains(pluginId); + } + + return !enabledPlugins.contains(pluginId); + } + + protected FileFilter createHiddenPluginFilter() { + return new HiddenFilter(); + } + + /** + * Add the possibility to override the plugins directory. + * If a "pf4j.pluginsDir" system property is defined than this method returns + * that directory. + * If getRuntimeMode() returns RuntimeMode.DEVELOPMENT than a + * DEVELOPMENT_PLUGINS_DIRECTORY ("../plugins") is returned else this method returns + * DEFAULT_PLUGINS_DIRECTORY ("plugins"). + * @return + */ + protected File createPluginsDirectory() { + String pluginsDir = System.getProperty("pf4j.pluginsDir"); + if (pluginsDir == null) { + if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { + pluginsDir = DEVELOPMENT_PLUGINS_DIRECTORY; + } else { + pluginsDir = DEFAULT_PLUGINS_DIRECTORY; + } + } + + return new File(pluginsDir); + } + + private void initialize() { + plugins = new HashMap(); + pluginClassLoaders = new HashMap(); + pathToIdMap = new HashMap(); + unresolvedPlugins = new ArrayList(); + resolvedPlugins = new ArrayList(); + startedPlugins = new ArrayList(); + disabledPlugins = new ArrayList(); + compoundClassLoader = new CompoundClassLoader(); + + pluginClasspath = createPluginClasspath(); + pluginDescriptorFinder = createPluginDescriptorFinder(); + extensionFinder = createExtensionFinder(); + + try { + // create a list with plugin identifiers that should be only accepted by this manager (whitelist from plugins/enabled.txt file) + enabledPlugins = FileUtils.readLines(new File(pluginsDirectory, "enabled.txt"), true); + log.info("Enabled plugins: {}", enabledPlugins); + + // create a list with plugin identifiers that should not be accepted by this manager (blacklist from plugins/disabled.txt file) + disabledPlugins = FileUtils.readLines(new File(pluginsDirectory, "disabled.txt"), true); + log.info("Disabled plugins: {}", disabledPlugins); + } catch (IOException e) { + log.error(e.getMessage(), e); + } + + System.setProperty("pf4j.pluginsDir", pluginsDirectory.getAbsolutePath()); + } + + private PluginWrapper loadPluginDirectory(File pluginDirectory) throws PluginException { + // try to load the plugin + String pluginName = pluginDirectory.getName(); + String pluginPath = "/".concat(pluginName); + + // test for plugin duplication + if (plugins.get(pathToIdMap.get(pluginPath)) != null) { + return null; + } + + // retrieves the plugin descriptor + log.debug("Find plugin descriptor '{}'", pluginPath); + PluginDescriptor pluginDescriptor = pluginDescriptorFinder.find(pluginDirectory); + log.debug("Descriptor " + pluginDescriptor); + String pluginClassName = pluginDescriptor.getPluginClass(); + log.debug("Class '{}' for plugin '{}'", pluginClassName, pluginPath); + + // load plugin + log.debug("Loading plugin '{}'", pluginPath); + PluginLoader pluginLoader = new PluginLoader(this, pluginDescriptor, pluginDirectory, pluginClasspath); + pluginLoader.load(); + log.debug("Loaded plugin '{}'", pluginPath); + + // create the plugin wrapper + log.debug("Creating wrapper for plugin '{}'", pluginPath); + PluginWrapper pluginWrapper = new PluginWrapper(pluginDescriptor, pluginPath, pluginLoader.getPluginClassLoader()); + pluginWrapper.setRuntimeMode(getRuntimeMode()); + /* + // test for disabled plugin + if (isPluginDisabled(pluginDescriptor.getPluginId())) { + log.info("Plugin '{}' is disabled", pluginPath); + pluginWrapper.setPluginState(PluginState.DISABLED); + } + */ + log.debug("Created wrapper '{}' for plugin '{}'", pluginWrapper, pluginPath); + + String pluginId = pluginDescriptor.getPluginId(); + + // add plugin to the list with plugins + plugins.put(pluginId, pluginWrapper); + unresolvedPlugins.add(pluginWrapper); + + // add plugin class loader to the list with class loaders + PluginClassLoader pluginClassLoader = pluginLoader.getPluginClassLoader(); + pluginClassLoaders.put(pluginId, pluginClassLoader); + + return pluginWrapper; + } + + private File expandPluginArchive(File pluginArchiveFile) throws IOException { + String fileName = pluginArchiveFile.getName(); + long pluginArchiveDate = pluginArchiveFile.lastModified(); + String pluginName = fileName.substring(0, fileName.length() - 4); + File pluginDirectory = new File(pluginsDirectory, pluginName); + // check if exists directory or the '.zip' file is "newer" than directory + if (!pluginDirectory.exists() || (pluginArchiveDate > pluginDirectory.lastModified())) { + log.debug("Expand plugin archive '{}' in '{}'", pluginArchiveFile, pluginDirectory); + + // do not overwrite an old version, remove it + if (pluginDirectory.exists()) { + FileUtils.delete(pluginDirectory); + } + + // create directory for plugin + pluginDirectory.mkdirs(); + + // expand '.zip' file + Unzip unzip = new Unzip(); + unzip.setSource(pluginArchiveFile); + unzip.setDestination(pluginDirectory); + unzip.extract(); + } + return pluginDirectory; + } + + private void resolvePlugins() throws PluginException { + resolveDependencies(); + } + + private void resolveDependencies() throws PluginException { + DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins); + resolvedPlugins = dependencyResolver.getSortedPlugins(); + for (PluginWrapper pluginWrapper : resolvedPlugins) { + unresolvedPlugins.remove(pluginWrapper); + compoundClassLoader.addLoader(pluginWrapper.getPluginClassLoader()); + log.info("Plugin '{}' resolved", pluginWrapper.getDescriptor().getPluginId()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `pluginWrapper` last assigned on line 178 could be null and is dereferenced at line 182. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String DefaultPluginManager.loadPlugin(File) + +### Procedure Id: +ro.fortsoft.pf4j.DefaultPluginManager.loadPlugin(java.io.File):java.lang.String.8feda28667bfef524a83dbcf0e916910 + +### File: +pf4j/src/main/java/ro/fortsoft/pf4j/DefaultPluginManager.java + +### Key: +DefaultPluginManager.java|loadPlugin|NULL_DEREFERENCE + +### Node Key: +e9814c590e26c031348b9b6ea9d992af + +### Hash: +cc309fa50971112fbfe02297fd288c28 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8228/instruction.md b/inferredbugs-8228/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f64fddfd911d1eacae71c1484bcffa5793d6677 --- /dev/null +++ b/inferredbugs-8228/instruction.md @@ -0,0 +1,513 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** Chronicle-Queue +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Higher Frequency Trading + * + * http://www.higherfrequencytrading.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.openhft.chronicle.tcp; + +import net.openhft.chronicle.*; +import net.openhft.lang.io.StopCharTesters; +import net.openhft.lang.model.constraints.NotNull; +import org.junit.Test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.Externalizable; +import java.io.IOException; +import java.io.ObjectInput; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.Assert.assertEquals; + +/** + * @author peter.lawrey + */ +public class StatefulIndexedChronicleTest extends StatefulChronicleTestBase { + + public static final int PORT = 12345; + + @Test + public void testOverTCP() throws IOException, InterruptedException { + final String basePathSource = getIndexedTestPath("-source"); + final String basePathSink = getIndexedTestPath("-sink"); + + // NOTE: the sink and source must have different chronicle files. + // TODO, make more robust. + final int messages = 5 * 1000 * 1000; + + final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 1); + final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 1); + + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { + ExcerptAppender excerpt = source.createAppender(); + for (int i = 1; i <= messages; i++) { + // use a size which will cause mis-alignment. + excerpt.startExcerpt(); + excerpt.writeLong(i); + excerpt.append(' '); + excerpt.append(i); + excerpt.append('\n'); + excerpt.finish(); + } + System.out.println(System.currentTimeMillis() + ": Finished writing messages"); + } catch (Exception e) { + throw new AssertionError(e); + } + } + }); + + long start = System.nanoTime(); + t.start(); + ExcerptTailer excerpt = sink.createTailer(); + int count = 0; + for (int i = 1; i <= messages; i++) { + while (!excerpt.nextIndex()) { + count++; + } + + long n = excerpt.readLong(); + String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); + if (i != n) { + assertEquals('\'' + text + '\'', i, n); + } + + excerpt.finish(); + } + + sink.close(); + System.out.println("There were " + count + " InSynk messages"); + t.join(); + + source.close(); + long time = System.nanoTime() - start; + System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); + + assertIndexedClean(basePathSource); + assertIndexedClean(basePathSink); + } + + @Test + public void testPricePublishing1() throws IOException, InterruptedException { + final String basePathSource = getIndexedTestPath("-source"); + final String basePathSink = getIndexedTestPath("-sink"); + + final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 2); + final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 2); + + final PriceWriter pw = new PriceWriter(source.createAppender()); + final AtomicInteger count = new AtomicInteger(); + final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { + @Override + public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { + count.incrementAndGet(); + } + }); + + pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); + reader.read(); + + long start = System.nanoTime(); + int prices = 12000000; + for (int i = 1; i <= prices; i++) { + pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); + } + + long mid = System.nanoTime(); + while (count.get() < prices) { + reader.read(); + } + + long end = System.nanoTime(); + System.out.printf("Took an average of %.2f us to write and %.2f us to read%n", + (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); + + source.close(); + sink.close(); + + assertIndexedClean(basePathSource); + assertIndexedClean(basePathSink); + } + + @Test + public void testPricePublishing2() throws IOException, InterruptedException { + final String basePathSource = getIndexedTestPath("-source"); + final String basePathSink = getIndexedTestPath("-sink"); + + final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 3); + final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 3); + + final PriceWriter pw = new PriceWriter(source.createAppender()); + final AtomicInteger count = new AtomicInteger(); + final PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { + @Override + public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { + count.incrementAndGet(); + } + }); + + pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); + assertEquals(-1, reader.excerpt.index()); + reader.read(); + assertEquals(0, reader.excerpt.index()); + + long start = System.nanoTime(); + int prices = 2 * 1000 * 1000; + for (int i = 1; i <= prices; i++) { + pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); + } + + long mid = System.nanoTime(); + while (count.get() < prices) { + reader.read(); + } + + long end = System.nanoTime(); + System.out.printf("Took an average of %.2f us to write and %.2f us to read using Excerpt%n", + (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); + + + source.close(); + sink.close(); + + assertIndexedClean(basePathSource); + assertIndexedClean(basePathSink); + } + + @Test + public void testPricePublishing3() throws IOException, InterruptedException { + final String basePathSource = getIndexedTestPath("-source"); + final String basePathSink = getIndexedTestPath("-sink"); + + final Chronicle source = new ChronicleSource(ChronicleQueueBuilder.indexed(basePathSource).build(), PORT + 4); + final Chronicle sink = new ChronicleSink(ChronicleQueueBuilder.indexed(basePathSink).build(), "localhost", PORT + 4); + + final PriceWriter pw = new PriceWriter(source.createAppender()); + final AtomicInteger count = new AtomicInteger(); + PriceReader reader = new PriceReader(sink.createTailer(), new PriceListener() { + @Override + public void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { + count.incrementAndGet(); + } + }); + + pw.onPrice(1, "symbol", 99.9, 1, 100.1, 2); + assertEquals(-1, reader.excerpt.index()); + reader.read(); + assertEquals(0, reader.excerpt.index()); + + long start = System.nanoTime(); + int prices = 2 * 1000 * 1000; + for (int i = 1; i <= prices; i++) { + pw.onPrice(i, "symbol", 99.9, i, 100.1, i + 1); + } + + long mid = System.nanoTime(); + while (count.get() < prices) + reader.read(); + + long end = System.nanoTime(); + System.out.printf("Took an average of %.2f us to write and %.2f us to read using Tailer%n", + (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); + + source.close(); + sink.close(); + + assertIndexedClean(basePathSource); + assertIndexedClean(basePathSink); + } + + // Took an average of 2.8 us to write and 7.6 us to read (Java 7) + @Test + public void testSerializationPerformance() throws IOException, ClassNotFoundException { + List bytes = new ArrayList(); + long start = System.nanoTime(); + int prices = 200 * 1000; + for (int i = 0; i < prices; i++) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + PriceUpdate pu = new PriceUpdate(1 + i, "symbol", 99.9, i + 1, 100.1, i + 2); + oos.writeObject(pu); + oos.close(); + bytes.add(baos.toByteArray()); + } + + long mid = System.nanoTime(); + for (byte[] bs : bytes) { + ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bs)); + PriceUpdate pu = (PriceUpdate) ois.readObject(); + } + + long end = System.nanoTime(); + System.out.printf("Took an average of %.1f us to write and %.1f us to read%n", + (mid - start) / prices / 1e3, (end - mid) / prices / 1e3); + } + + // Took an average of 0.42 us to write and 0.61 us to read (Java 6) + // Took an average of 0.35 us to write and 0.59 us to read (Java 7) + + // ************************************************************************* + // + // ************************************************************************* + + interface PriceListener { + void onPrice(long timeInMicros, String symbol, double bp, int bq, double ap, int aq); + } + + static class PriceWriter implements PriceListener { + private final ExcerptAppender excerpt; + + PriceWriter(ExcerptAppender excerpt) { + this.excerpt = excerpt; + } + + @Override + public void onPrice(long timeInMicros, @NotNull String symbol, double bp, int bq, double ap, int aq) { + excerpt.startExcerpt(); + excerpt.writeByte('P'); // code for a price + excerpt.writeLong(timeInMicros); + excerpt.writeEnum(symbol); + excerpt.writeDouble(bp); + excerpt.writeInt(bq); + excerpt.writeDouble(ap); + excerpt.writeInt(aq); + excerpt.finish(); + } + } + + static class PriceReader { + private final ExcerptTailer excerpt; + private final PriceListener listener; + + PriceReader(ExcerptTailer excerpt, PriceListener listener) { + this.excerpt = excerpt; + this.listener = listener; + } + + public boolean read() { + if (!excerpt.nextIndex()) { + return false; + } + + char ch = (char) excerpt.readByte(); + switch (ch) { + case 'P': { + long timeInMicros = excerpt.readLong(); + String symbol = excerpt.readEnum(String.class); + double bp = excerpt.readDouble(); + int bq = excerpt.readInt(); + double ap = excerpt.readDouble(); + int aq = excerpt.readInt(); + listener.onPrice(timeInMicros, symbol, bp, bq, ap, aq); + break; + } + default: + throw new AssertionError("Unexpected code " + ch); + } + return true; + } + } +/* + + @Test + @Ignore + public void testOverTCPRolling() throws IOException, InterruptedException { + String baseDir = System.getProperty("java.io.tmpdir"); + String srcBasePath = baseDir + "/IPCTR.testOverTCP.source"; + ChronicleTools.deleteDirOnExit(srcBasePath); + // NOTE: the sink and source must have different chronicle files. + // TODO, make more robust. + final int messages = 2 * 1000 * 1000; + ChronicleConfig config = ChronicleConfig.TEST.clone(); + config.indexFileExcerpts(512); +// config.dataBlockSize(4096); +// config.indexBlockSize(4096); + final Chronicle source = new ChronicleSource(new RollingChronicle(srcBasePath, config), PORT + 1); + Thread t = new Thread(new Runnable() { + @Override + public void run() { + try { +// PosixJNAAffinity.INSTANCE.setAffinity(1 << 1); + ExcerptAppender excerpt = source.createAppender(); + for (int i = 1; i <= messages; i++) { + // use a size which will cause mis-alignment. + excerpt.startExcerpt(); + excerpt.writeLong(i); + excerpt.append(' '); + excerpt.append(i); + excerpt.append('\n'); + excerpt.finish(); + } + System.out.println(System.currentTimeMillis() + ": Finished writing messages"); + } catch (Exception e) { + throw new AssertionError(e); + } + } + }); + +// PosixJNAAffinity.INSTANCE.setAffinity(1 << 2); + String snkBasePath = baseDir + "/IPCTR.testOverTCP.sink"; + ChronicleTools.deleteDirOnExit(snkBasePath); + Chronicle sink = new InProcessChronicleSink(new RollingChronicle(snkBasePath, config), "localhost", PORT + 1); + + long start = System.nanoTime(); + t.start(); + ExcerptTailer excerpt = sink.createTailer(); + int count = 0; + for (int i = 1; i <= messages; i++) { + while (!excerpt.nextIndex()) + count++; + long n = excerpt.readLong(); + String text = excerpt.parseUTF(StopCharTesters.CONTROL_STOP); + if (i != n) + assertEquals('\'' + text + '\'', i, n); + excerpt.finish(); + System.out.println(i); + } + sink.close(); + System.out.println("There were " + count + " isSync messages"); + t.join(); + source.close(); + long time = System.nanoTime() - start; + System.out.printf("Messages per second %,d%n", (int) (messages * 1e9 / time)); + } +*/ + + + static class PriceUpdate implements Externalizable, Serializable { + private long timeInMicros; + private String symbol; + private double bp; + private int bq; + private double ap; + private int aq; + + public PriceUpdate() { + } + + PriceUpdate(long timeInMicros, String symbol, double bp, int bq, double ap, int aq) { + this.timeInMicros = timeInMicros; + this.symbol = symbol; + this.bp = bp; + this.bq = bq; + this.ap = ap; + this.aq = aq; + } + + // @Override + public void writeExternal(@NotNull ObjectOutput out) throws IOException { + out.writeLong(timeInMicros); + out.writeUTF(symbol); + out.writeDouble(bp); + out.writeInt(bq); + out.writeDouble(ap); + out.writeInt(aq); + } + + // @Override + public void readExternal(@NotNull ObjectInput in) throws IOException, ClassNotFoundException { + timeInMicros = in.readLong(); + symbol = in.readUTF(); + bp = in.readDouble(); + bq = in.readInt(); + ap = in.readDouble(); + aq = in.readInt(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `net.openhft.chronicle.tcp.ChronicleSink` acquired by call to `ChronicleSink(...)` at line 117 is not released after line 151. +**Note**: potential exception at line 121 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void StatefulIndexedChronicleTest.testPricePublishing1() + +### Procedure Id: +net.openhft.chronicle.tcp.StatefulIndexedChronicleTest.testPricePublishing1():void.4292337631348536475fdd78e12b13cf + +### File: +chronicle/src/test/java/net/openhft/chronicle/tcp/StatefulIndexedChronicleTest.java + +### Key: +StatefulIndexedChronicleTest.java|testPricePublishing1|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +fa910118fbbcbdbc5ce72e74f6cca30a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8300/instruction.md b/inferredbugs-8300/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b906a5d9c94c2752afe0c2334df56e5892b73fb3 --- /dev/null +++ b/inferredbugs-8300/instruction.md @@ -0,0 +1,434 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jimfs +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.jimfs.internal; + +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.jimfs.internal.LinkHandling.FOLLOW_LINKS; +import static com.google.jimfs.internal.LinkHandling.NOFOLLOW_LINKS; +import static java.nio.file.StandardOpenOption.APPEND; +import static java.nio.file.StandardOpenOption.CREATE; +import static java.nio.file.StandardOpenOption.READ; +import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING; +import static java.nio.file.StandardOpenOption.WRITE; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; +import com.google.jimfs.JimfsConfiguration; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.channels.AsynchronousFileChannel; +import java.nio.channels.SeekableByteChannel; +import java.nio.file.AccessMode; +import java.nio.file.CopyOption; +import java.nio.file.DirectoryStream; +import java.nio.file.FileStore; +import java.nio.file.FileSystem; +import java.nio.file.FileSystemAlreadyExistsException; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.FileSystems; +import java.nio.file.LinkOption; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.ProviderMismatchException; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.FileAttributeView; +import java.nio.file.spi.FileSystemProvider; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ExecutorService; + +/** + * @author Colin Decker + */ +public final class JimfsFileSystemProvider extends FileSystemProvider { + + public static final String SCHEME = "jimfs"; + + public static final String CONFIG_KEY = "config"; + + @Override + public String getScheme() { + return SCHEME; + } + + private final ConcurrentMap fileSystems = new ConcurrentHashMap<>(); + + @Override + public JimfsFileSystem newFileSystem(URI uri, Map env) { + checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME), + "uri (%s) scheme must be '%s'", uri, SCHEME); + checkArgument(env.get(CONFIG_KEY) instanceof JimfsConfiguration, + "env map (%s) must contain key '%s' mapped to an instance of JimfsConfiguration", + env, CONFIG_KEY); + JimfsConfiguration config = (JimfsConfiguration) env.get(CONFIG_KEY); + JimfsFileSystem fileSystem = new JimfsFileSystem(this, uri, config); + if (fileSystems.putIfAbsent(uri, fileSystem) != null) { + throw new FileSystemAlreadyExistsException(uri.toString()); + } + return fileSystem; + } + + @Override + public JimfsFileSystem getFileSystem(URI uri) { + JimfsFileSystem fileSystem = fileSystems.get(uri); + if (fileSystem == null) { + throw new FileSystemNotFoundException(uri.toString()); + } + return fileSystem; + } + + @Override + public FileSystem newFileSystem(Path path, Map env) throws IOException { + JimfsPath checkedPath = checkPath(path); + checkNotNull(env); + + URI pathUri = checkedPath.toUri(); + URI jarUri = URI.create("jar:" + pathUri); + + try { + // pass the new jar:jimfs://... URI to be handled by ZipFileSystemProvider + return FileSystems.newFileSystem(jarUri, env); + } catch (Exception e) { + // if any exception occurred, assume the file wasn't a zip file and that we don't support + // viewing it as a file system + throw new UnsupportedOperationException(e); + } + } + + @Override + public Path getPath(URI uri) { + try { + URI withoutPath = new URI(uri.getScheme(), uri.getHost(), null, null); + return getFileSystem(withoutPath).getPath(uri.getPath()); + } catch (URISyntaxException e) { + throw new AssertionError(); + } + } + + private static JimfsPath checkPath(Path path) { + if (path instanceof JimfsPath) { + return (JimfsPath) path; + } + throw new ProviderMismatchException( + "path " + path + " is not associated with a JIMFS file system"); + } + + /** + * Returns the file tree to use for the given path. + */ + private static FileTree getFileTree(JimfsPath path) { + return ((JimfsFileSystem) path.getFileSystem()).getFileTree(path); + } + + private static LookupResult lookup(Path path, LinkHandling linkHandling) throws IOException { + JimfsPath checkedPath = checkPath(path); + FileTree tree = getFileTree(checkedPath); + return tree.lookup(checkedPath, linkHandling); + } + + @Override + public JimfsFileChannel newFileChannel(Path path, Set options, + FileAttribute... attrs) throws IOException { + JimfsPath checkedPath = checkPath(path); + options = getOptionsForChannel(options); + File file = getFileTree(checkedPath).getRegularFile(checkedPath, options, attrs); + return new JimfsFileChannel(file, options); + } + + @Override + public SeekableByteChannel newByteChannel(Path path, Set options, + FileAttribute... attrs) throws IOException { + return newFileChannel(path, options, attrs); + } + + @Override + public AsynchronousFileChannel newAsynchronousFileChannel(Path path, + Set options, ExecutorService executor, FileAttribute... attrs) + throws IOException { + return newFileChannel(path, options, attrs).asAsynchronousFileChannel(executor); + } + + @Override + public InputStream newInputStream(Path path, OpenOption... options) throws IOException { + return newFileChannel(checkPath(path), getOptionsForRead(options)).asInputStream(); + } + + @Override + public OutputStream newOutputStream(Path path, OpenOption... options) throws IOException { + return newFileChannel(checkPath(path), getOptionsForWrite(options)).asOutputStream(); + } + + public static Set getOptionsForChannel(Set options) { + if (!options.contains(READ) && !options.contains(WRITE)) { + OpenOption optionToAdd = options.contains(APPEND) ? WRITE : READ; + return ImmutableSet.builder() + .addAll(options) + .add(optionToAdd) + .build(); + } + return options; + } + + static Set getOptionsForRead(OpenOption... options) { + Set optionsSet = new HashSet<>(Arrays.asList(options)); + if (optionsSet.contains(WRITE)) { + throw new UnsupportedOperationException("WRITE"); + } else { + optionsSet.add(READ); + } + return optionsSet; + } + + static Set getOptionsForWrite(OpenOption... options) { + Set optionsSet = Sets.newHashSet(options); + if (optionsSet.contains(READ)) { + throw new UnsupportedOperationException("READ"); + } else if (optionsSet.isEmpty()) { + optionsSet.addAll(Arrays.asList(CREATE, WRITE, TRUNCATE_EXISTING)); + } else if (!optionsSet.contains(WRITE)) { + optionsSet.add(WRITE); + } + return optionsSet; + } + + @Override + public DirectoryStream newDirectoryStream(Path dir, + DirectoryStream.Filter filter) throws IOException { + JimfsPath checkedPath = checkPath(dir); + return getFileTree(checkedPath) + .newSecureDirectoryStream(checkedPath, filter, LinkHandling.FOLLOW_LINKS, checkedPath); + } + + @Override + public void createDirectory(Path dir, FileAttribute... attrs) throws IOException { + JimfsPath checkedPath = checkPath(dir); + FileTree tree = getFileTree(checkedPath); + tree.createDirectory(checkedPath, attrs); + } + + @Override + public void createLink(Path link, Path existing) throws IOException { + JimfsPath linkPath = checkPath(link); + JimfsPath existingPath = checkPath(existing); + checkArgument(linkPath.getFileSystem().equals(existingPath.getFileSystem()), + "link and existing paths must belong to the same file system instance"); + FileTree tree = getFileTree(linkPath); + tree.link(linkPath, getFileTree(existingPath), existingPath); + } + + @Override + public void createSymbolicLink(Path link, Path target, FileAttribute... attrs) + throws IOException { + JimfsPath linkPath = checkPath(link); + JimfsPath targetPath = checkPath(target); + checkArgument(linkPath.getFileSystem().equals(targetPath.getFileSystem()), + "link and target paths must belong to the same file system instance"); + FileTree tree = getFileTree(linkPath); + tree.createSymbolicLink(linkPath, targetPath, attrs); + } + + @Override + public Path readSymbolicLink(Path link) throws IOException { + File file = lookup(link, NOFOLLOW_LINKS) + .requireSymbolicLink(link) + .file(); + + return file.content(); + } + + @Override + public void delete(Path path) throws IOException { + JimfsPath checkedPath = checkPath(path); + FileTree tree = getFileTree(checkedPath); + tree.deleteFile(checkedPath); + } + + @Override + public void copy(Path source, Path target, CopyOption... options) throws IOException { + JimfsPath sourcePath = checkPath(source); + JimfsPath targetPath = checkPath(target); + + FileTree sourceTree = getFileTree(sourcePath); + FileTree targetTree = getFileTree(targetPath); + sourceTree.copyFile(sourcePath, targetTree, targetPath, ImmutableSet.copyOf(options)); + } + + @Override + public void move(Path source, Path target, CopyOption... options) throws IOException { + JimfsPath sourcePath = checkPath(source); + JimfsPath targetPath = checkPath(target); + + FileTree sourceTree = getFileTree(sourcePath); + FileTree targetTree = getFileTree(targetPath); + sourceTree.moveFile(sourcePath, targetTree, targetPath, ImmutableSet.copyOf(options)); + } + + @Override + public boolean isSameFile(Path path, Path path2) throws IOException { + if (path.equals(path2)) { + return true; + } + + if (!(path instanceof JimfsPath && path2 instanceof JimfsPath)) { + return false; + } + + JimfsPath checkedPath = (JimfsPath) path; + JimfsPath checkedPath2 = (JimfsPath) path2; + + FileTree tree = getFileTree(checkedPath); + FileTree tree2 = getFileTree(checkedPath2); + + return tree.isSameFile(checkedPath, tree2, checkedPath2); + } + + @Override + public boolean isHidden(Path path) throws IOException { + return ((JimfsFileSystem) checkPath(path).getFileSystem()).configuration() + .isHidden(path); + } + + @Override + public FileStore getFileStore(Path path) throws IOException { + // only one FileStore per file system + return Iterables.getOnlyElement(checkPath(path).getFileSystem().getFileStores()); + } + + @Override + public void checkAccess(Path path, AccessMode... modes) throws IOException { + JimfsPath checkedPath = checkPath(path); + lookup(checkedPath, FOLLOW_LINKS).requireFound(path); + } + + @Override + public V getFileAttributeView(Path path, Class type, + LinkOption... options) { + JimfsPath checkedPath = checkPath(path); + return getFileTree(checkedPath) + .getFileAttributeView(checkedPath, type, LinkHandling.fromOptions(options)); + } + + @Override + public A readAttributes(Path path, Class type, + LinkOption... options) throws IOException { + JimfsPath checkedPath = checkPath(path); + return getFileTree(checkedPath) + .readAttributes(checkedPath, type, LinkHandling.fromOptions(options)); + } + + @Override + public Map readAttributes(Path path, String attributes, LinkOption... options) + throws IOException { + JimfsPath checkedPath = checkPath(path); + return getFileTree(checkedPath) + .readAttributes(checkedPath, attributes, LinkHandling.fromOptions(options)); + } + + @Override + public void setAttribute(Path path, String attribute, Object value, LinkOption... options) + throws IOException { + JimfsPath checkedPath = checkPath(path); + getFileTree(checkedPath) + .setAttribute(checkedPath, attribute, value, LinkHandling.fromOptions(options)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.google.jimfs.internal.JimfsFileSystem` acquired by call to `JimfsFileSystem(...)` at line 89 is not released after line 89. +**Note**: potential exception at line 89 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +JimfsFileSystem JimfsFileSystemProvider.newFileSystem(URI,Map) + +### Procedure Id: +com.google.jimfs.internal.JimfsFileSystemProvider.newFileSystem(java.net.URI,java.util.Map):com.goog.e8ec2a02e83d27ef8c2253902ed4849f + +### File: +src/main/java/com/google/jimfs/internal/JimfsFileSystemProvider.java + +### Key: +JimfsFileSystemProvider.java|newFileSystem|RESOURCE_LEAK + +### Node Key: +595a5c3828eea8b43ed0358cbea36a4d + +### Hash: +b7b2c90aa76f4f09ec7e67b6ddf8f14b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8307/instruction.md b/inferredbugs-8307/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd8ff9689b897878a399aec6bcacb619cf77dcad --- /dev/null +++ b/inferredbugs-8307/instruction.md @@ -0,0 +1,656 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jReddit +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.jreddit.user; + +import com.github.jreddit.CommentSort; +import com.github.jreddit.Sort; +import com.github.jreddit.Thing; +import com.github.jreddit.submissions.Submission; +import com.github.jreddit.subreddit.Subreddit; +import com.github.jreddit.utils.ApiEndpointUtils; +import com.github.jreddit.utils.Utils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents a user connected to Reddit. + * + * @author Omer Elnour + * @author Karan Goel + * @author Benjamin Jakobus + * @author Evin Ugur + * @author Andrei Sfat + */ +public class User extends Thing { + + private String username, password; + private String modhash, cookie; + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + /** + * Call this function to connect the user.
    By "connect" I mean + * effectively sending a POST request to reddit and getting the modhash and + * cookie, which are required for most reddit API functions. + * + * @throws Exception If connection fails. + */ + public void connect() throws Exception { + ArrayList hashCookiePair = hashCookiePair(username, password); + this.modhash = hashCookiePair.get(0); + this.cookie = hashCookiePair.get(1); + } + + /** + * This function submits a link to the specified subreddit. + * Requires authentication. + * + * @param title The title of the submission + * @param link The link to the submission + * @param subreddit The subreddit to submit to + * @throws IOException If connection fails + * @throws ParseException If JSON Parsing fails + */ + public void submitLink(String title, String link, String subreddit) + throws IOException, ParseException { + JSONObject object = submit(title, link, false, subreddit); + if (object.toJSONString().contains(".error.USER_REQUIRED")) { + System.err.println("Please login first."); + } else if (object.toJSONString().contains( + ".error.RATELIMIT.field-ratelimit")) { + System.err.println("You are doing that too much."); + } else if (object.toJSONString().contains( + ".error.ALREADY_SUB.field-url")) { + System.err.println("That link has already been submitted."); + } else { + System.out.println("Link submitted to " + + ((JSONArray) ((JSONArray) ((JSONArray) object.get("jquery")).get(16)).get(3)).get(0)); + } + } + + /** + * This function submits a self post to the specified subreddit. + * Requires authentication. + * + * @param title The title of the submission + * @param text The text of the submission + * @param subreddit The subreddit to submit to + * @throws IOException If connection fails + * @throws ParseException If JSON Parsing fails + */ + public void submitSelfPost(String title, String text, String subreddit) + throws IOException, ParseException { + JSONObject object = submit(title, text, true, subreddit); + if (object.toJSONString().contains(".error.USER_REQUIRED")) { + System.err.println("Please login first."); + } else if (object.toJSONString().contains( + ".error.RATELIMIT.field-ratelimit")) { + System.err.println("You are doing that too much."); + } else if (object.toJSONString().contains( + ".error.ALREADY_SUB.field-url")) { + System.err.println("That link has already been submitted."); + } else { + System.out.println("Self post submitted to " + + ((JSONArray) ((JSONArray) ((JSONArray) object.get("jquery")).get(10)).get(3)).get(0)); + } + } + + /** + * This functions returns true if this user has unread mail. + * + * @return This user has mail or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean hasMail() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("has_mail").toString()); + } + + /** + * This function returns the Unix time that the user's account was created. + * + * @return Unix time that the user's account was created + * @throws NumberFormatException If the "created" property isn't a double + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public double created() throws IOException, ParseException { + return Double.parseDouble(info().get("created").toString()); + } + + /** + * This function returns the Unix time (in UTC/Coordinated Universal Time) + * that the user's account was created. + * + * @return Unix time that the user's account was created in UTC + * @throws NumberFormatException If the "created_utc" property isn't a + * double + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public double createdUTC() throws IOException, ParseException { + return Double.parseDouble(info().get("created_utc").toString()); + } + + /** + * This function returns the amount of link karma this user has.
    + * Returns int because I doubt anyone has more than 2,147,483,647 link karma. + * + * @return integer representing the Link Karma + * @throws NumberFormatException If the "link_karma" property isn't an + * integer + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public int linkKarma() throws IOException, ParseException { + return Integer.parseInt(Utils.toString(info().get("link_karma"))); + } + + /** + * This function returns the amount of comment karma this user has.
    Returns int because I doubt anyone has more than 2,147,483,647 comment + * karma. + * + * @return integer representing the Comment Karma + * @throws NumberFormatException If the "comment_karma" property isn't an + * integer + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public int commentKarma() throws IOException, ParseException { + return Integer.parseInt(Utils.toString(info().get("comment_karma"))); + } + + /** + * This functions returns true if this user has a gold account. + * + * @return This user has a gold account or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean isGold() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("is_gold").toString()); + } + + /** + * This functions returns true if this user is a reddit moderator + * (apparently this means a moderator of any subreddit). + * + * @return This user is a moderator or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean isMod() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("is_mod").toString()); + } + + /** + * This function returns the user's ID.
    The user's ID. This is only + * used internally, right? + * + * @return This user's ID + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public String id() throws IOException, ParseException { + return info().get("id").toString(); + } + + /** + * This functions returns true if this user has unread moderator mail. + * + * @return This user has unread moderator mail or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean hasModMail() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("has_mod_mail").toString()); + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getModhash() { + return modhash; + } + + public String getCookie() { + return cookie; + } + + /** + * This function logs in to reddit and returns an ArrayList containing a + * modhash and cookie. + * + * @param username The username + * @param password The password + * @return An array containing a modhash and cookie + * @throws IOException If connection fails + * @throws ParseException If parsing JSON fails + */ + private ArrayList hashCookiePair(String username, String password) + throws IOException, ParseException { + ArrayList values = new ArrayList(); + JSONObject jsonObject = Utils.post("api_type=json&user=" + username + + "&passwd=" + password, String.format(ApiEndpointUtils.USER_LOGIN, username), getCookie()); + JSONObject valuePair = (JSONObject) ((JSONObject) jsonObject.get("json")).get("data"); + + values.add(valuePair.get("modhash").toString()); + values.add(valuePair.get("cookie").toString()); + + return values; + } + + /** + * This function returns a "response" (me.json) JSON data containing info + * about the user.
    + * + * @return JSON data containing info about the user + */ + private JSONObject info() throws IOException, ParseException { + if (cookie == null || modhash == null) { + System.err.printf("Please invoke the \"connect\" function before attempting to " + + "call any other API functions."); + Runtime.getRuntime().exit(-1); + } + + JSONObject jsonObject = (JSONObject) Utils.get(ApiEndpointUtils.USER_INFO, getCookie()); + return (JSONObject) jsonObject.get("data"); + } + + /** + * This function submits a link or self post. + * + * @param title The title of the submission + * @param linkOrText The link of the submission or text + * @param selfPost If this submission is a self post + * @param subreddit Which subreddit to submit this to + * @return A JSONObject + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + private JSONObject submit(String title, String linkOrText, boolean selfPost, String subreddit) throws IOException, ParseException { + return Utils.post("title=" + title + "&" + (selfPost ? "text" : "url") + + "=" + linkOrText + "&sr=" + subreddit + "&kind=" + + (selfPost ? "self" : "link") + "&uh=" + getModhash(), + ApiEndpointUtils.USER_SUBMIT, getCookie()); + } + + /** + * Returns a list of submissions made by this user. + * + * @return List of submissions made by this user. + */ + public List comments() { + return User.comments(username); + } + + /** + * Returns misc info about the user (which consists of comment karma, mod + * mail identifier, created timestamp, gold member identifier, mod + * identifier, link karma and mail identifier). + * + * @param username The username of the user whose account info you want + * to retrieve. + * @return Misc info about the user. + */ + public static UserInfo about(String username) { + UserInfo info = null; + + try { + // Send GET request to get the account overview + JSONObject object = (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null); + JSONObject data = (JSONObject) object.get("data"); + + // Init account info wrapper + info = new UserInfo(Integer.parseInt(Utils.toString(data.get("comment_karma"))), + Integer.parseInt(Utils.toString(data.get("link_karma"))), + Float.parseFloat(Utils.toString(data.get("created_utc"))), + Boolean.parseBoolean(Utils.toString(data.get("is_gold"))), + Boolean.parseBoolean(Utils.toString(data.get("is_mod"))), + Boolean.parseBoolean(Utils.toString(data.get("has_mail"))), + Boolean.parseBoolean(Utils.toString(data.get("has_mod_mail")))); + + } catch (Exception e) { + System.err.println("Error retrieving user information for " + username); + } + + return info; + } + + + public static List comments(String username) { + return comments(username, CommentSort.NEW); + } + + /** + * Returns a list of submissions made by this user. + * + * @param username The username of the user whose comments you want + * to retrieve. + * @return List of top 500 comments made by this user. + */ + public static List comments(String username, CommentSort commentSort) { + // List of submissions made by this user + List comments = new ArrayList(500); + try { + // Send GET request to get the account overview + JSONObject object = + (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_COMMENTS, + username, commentSort.getValue()), null); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + Comment c; + for (Object aChildren : children) { + // Get the object containing the comment + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + + // Create a new comment + c = new Comment(Utils.toString(obj.get("body")), Utils.toString(obj.get("edited")), + Utils.toString(obj.get("created_utc")), Utils.toString(obj.get("replies")), + Integer.parseInt(Utils.toString(obj.get("ups"))), + Integer.parseInt(Utils.toString(obj.get("downs")))); + + // Add it to the submissions list + comments.add(c); + } + } catch (Exception e) { + e.printStackTrace(); + } + // Return the submissions + return comments; + } + + /** + * Returns a list of submissions made by this user. + * + * @param username The username of the user whose submissions you want + * to retrieve. + * @return List of submissions made by this user. + */ + public static List submissions(String username) { + // List of submissions made by this user + List submissions = new ArrayList(500); + try { + // Send GET request to get the account overview + JSONObject object = (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_SUBMISSIONS, username), null); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + + for (Object aChildren : children) { + // Get the object containing the comment + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + //add a new Submission to the list + submissions.add(new Submission(obj)); + } + } catch (Exception e) { + e.printStackTrace(); + } + + // Return the submissions + return submissions; + } + + /** + * Returns a list of submissions that this user liked. + * + * @return List of liked links with default sorting. + */ + public List getLikedSubmissions() { + return getLikedSubmissions(Sort.HOT); + } + + /** + * Returns a list of submissions that this user liked with a Reddit sort + * + * @param sort Which sort you'd like to apply + * @return List of liked submissions with a Reddit sort + */ + public List getLikedSubmissions(Sort sort) { + return getUserSubmissions("liked", sort); + } + + /** + * Returns a list of submissions that this user chose to hide. with the default sorting + * + * @return List of disliked links. + */ + public List getHiddenSubmissions() { + return getHiddenSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that this user chose to hide with a specified sorting + * + * @param sort Which sort you'd like to apply + * @return List of hidden Submissions with a Reddit sort + */ + public List getHiddenSubmissions(Sort sort) { + return getUserSubmissions("hidden", sort); + } + + /** + * Returns a list of Submissions that the user saved with the default sort + * + * @return List of saved links + */ + public List getSavedSubmissions() { + return getSavedSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that the user saved with a specified sorting + * + * @param sort Which sort you'd like to apply + * @return List of saved links with a Reddit sort + */ + public List getSavedSubmissions(Sort sort) { + return getUserSubmissions("saved", sort); + } + + /** + * Returns a list of Submissions that the user submitted with the default Reddit sort + * + * @return List of submitted Submissions + */ + public List getSubmissions() { + return getSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that the user submitted with a specified Reddit sort + * + * @return List of submitted Submissions with a specified Reddit sort + */ + public List getSubmissions(Sort sort) { + return getUserSubmissions("submitted", sort); + } + + /** + * Returns a list of submissions that this user disliked with the default Reddit sort + * + * @return List of disliked links. + */ + public List getDislikedSubmissions() { + return getDislikedSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that this user disliked with a specified Reddit sort + * + * @param sort Which sort you'd like to apply + * @return List of disliked sorts with a specified sort + */ + public List getDislikedSubmissions(Sort sort) { + return getUserSubmissions("disliked", sort); + } + + public List getUserOverview() { + return getUserSubmissions("overview", Sort.HOT); + } + + /** + * private function used to get submissions that a user interacts with on Reddit + * + * @param where place of Submission - see http://www.reddit.com/dev/api#GET_user_{username}_{where} + * @return Submissions from the specified location, null if the location is invalid + */ + private List getUserSubmissions(String where, Sort sort) { + //valid arguments for where the Submission can come from + final String[] LOCATIONS = { + //TODO: not all of these JSONs return something that can be processed purely into a Submission class, until those are taken care of, I commented them out + /*"overview",*/ "submitted", /*"comments",*/ "liked", "disliked", "hidden", "saved" + }; + //check to see if we have a valid location + boolean valid = false; + for (String LOCATION : LOCATIONS) { + valid = where.equals(LOCATION); + if (valid) { + break; + } + + } + if (!valid) { + System.err.println(where + " is an invalid location"); + return null; + } + + //if we got this far, the location is valid + List submissions = new ArrayList(); + try { + JSONObject object = + (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_SUBMISSIONS_INTERACTION, + username, where, sort.getValue()), cookie); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + for (Object aChildren : children) { + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + submissions.add(new Submission(obj)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return submissions; + } + + /** + * Returns a list of Subreddits to which the user is subscribed. + * @return List of Subreddits + */ + public List getSubscribed() { + List subscibed = new ArrayList(1000); + JSONObject object = (JSONObject) Utils.get(ApiEndpointUtils.USER_GET_SUBSCRIBED, cookie); + + JSONObject rawData = (JSONObject) object.get("data"); + JSONArray subreddits = (JSONArray) rawData.get("children"); + + for (Object subreddit : subreddits) { + JSONObject obj = (JSONObject) subreddit; + obj = (JSONObject) obj.get("data"); + Subreddit sub = new Subreddit(obj.get("display_name").toString(), + obj.get("display_name").toString(), obj.get("title").toString(), + obj.get("url").toString(), obj.get("created").toString(), + obj.get("created_utc").toString(), + Boolean.parseBoolean(obj.get("over18").toString()), + Integer.parseInt(obj.get("subscribers").toString()), + obj.get("id").toString(), obj.get("description").toString()); + subscibed.add(sub); + } + + return subscibed; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `info(this)` could be null and is dereferenced at line 190. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean User.isMod() + +### Procedure Id: +com.github.jreddit.user.User.isMod():boolean.a301651637d9bfac2e9efd207a94b364 + +### File: +src/main/java/com/github/jreddit/user/User.java + +### Key: +User.java|isMod|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +ba74e8c4193358e7b16c2a177678ca42 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8309/instruction.md b/inferredbugs-8309/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..208de1778ec7a7a479f9a65f62f8fc262e946ac0 --- /dev/null +++ b/inferredbugs-8309/instruction.md @@ -0,0 +1,656 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jReddit +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.jreddit.user; + +import com.github.jreddit.CommentSort; +import com.github.jreddit.Sort; +import com.github.jreddit.Thing; +import com.github.jreddit.submissions.Submission; +import com.github.jreddit.subreddit.Subreddit; +import com.github.jreddit.utils.ApiEndpointUtils; +import com.github.jreddit.utils.Utils; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import org.json.simple.parser.ParseException; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * This class represents a user connected to Reddit. + * + * @author Omer Elnour + * @author Karan Goel + * @author Benjamin Jakobus + * @author Evin Ugur + * @author Andrei Sfat + */ +public class User extends Thing { + + private String username, password; + private String modhash, cookie; + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + /** + * Call this function to connect the user.
    By "connect" I mean + * effectively sending a POST request to reddit and getting the modhash and + * cookie, which are required for most reddit API functions. + * + * @throws Exception If connection fails. + */ + public void connect() throws Exception { + ArrayList hashCookiePair = hashCookiePair(username, password); + this.modhash = hashCookiePair.get(0); + this.cookie = hashCookiePair.get(1); + } + + /** + * This function submits a link to the specified subreddit. + * Requires authentication. + * + * @param title The title of the submission + * @param link The link to the submission + * @param subreddit The subreddit to submit to + * @throws IOException If connection fails + * @throws ParseException If JSON Parsing fails + */ + public void submitLink(String title, String link, String subreddit) + throws IOException, ParseException { + JSONObject object = submit(title, link, false, subreddit); + if (object.toJSONString().contains(".error.USER_REQUIRED")) { + System.err.println("Please login first."); + } else if (object.toJSONString().contains( + ".error.RATELIMIT.field-ratelimit")) { + System.err.println("You are doing that too much."); + } else if (object.toJSONString().contains( + ".error.ALREADY_SUB.field-url")) { + System.err.println("That link has already been submitted."); + } else { + System.out.println("Link submitted to " + + ((JSONArray) ((JSONArray) ((JSONArray) object.get("jquery")).get(16)).get(3)).get(0)); + } + } + + /** + * This function submits a self post to the specified subreddit. + * Requires authentication. + * + * @param title The title of the submission + * @param text The text of the submission + * @param subreddit The subreddit to submit to + * @throws IOException If connection fails + * @throws ParseException If JSON Parsing fails + */ + public void submitSelfPost(String title, String text, String subreddit) + throws IOException, ParseException { + JSONObject object = submit(title, text, true, subreddit); + if (object.toJSONString().contains(".error.USER_REQUIRED")) { + System.err.println("Please login first."); + } else if (object.toJSONString().contains( + ".error.RATELIMIT.field-ratelimit")) { + System.err.println("You are doing that too much."); + } else if (object.toJSONString().contains( + ".error.ALREADY_SUB.field-url")) { + System.err.println("That link has already been submitted."); + } else { + System.out.println("Self post submitted to " + + ((JSONArray) ((JSONArray) ((JSONArray) object.get("jquery")).get(10)).get(3)).get(0)); + } + } + + /** + * This functions returns true if this user has unread mail. + * + * @return This user has mail or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean hasMail() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("has_mail").toString()); + } + + /** + * This function returns the Unix time that the user's account was created. + * + * @return Unix time that the user's account was created + * @throws NumberFormatException If the "created" property isn't a double + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public double created() throws IOException, ParseException { + return Double.parseDouble(info().get("created").toString()); + } + + /** + * This function returns the Unix time (in UTC/Coordinated Universal Time) + * that the user's account was created. + * + * @return Unix time that the user's account was created in UTC + * @throws NumberFormatException If the "created_utc" property isn't a + * double + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public double createdUTC() throws IOException, ParseException { + return Double.parseDouble(info().get("created_utc").toString()); + } + + /** + * This function returns the amount of link karma this user has.
    + * Returns int because I doubt anyone has more than 2,147,483,647 link karma. + * + * @return integer representing the Link Karma + * @throws NumberFormatException If the "link_karma" property isn't an + * integer + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public int linkKarma() throws IOException, ParseException { + return Integer.parseInt(Utils.toString(info().get("link_karma"))); + } + + /** + * This function returns the amount of comment karma this user has.
    Returns int because I doubt anyone has more than 2,147,483,647 comment + * karma. + * + * @return integer representing the Comment Karma + * @throws NumberFormatException If the "comment_karma" property isn't an + * integer + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public int commentKarma() throws IOException, ParseException { + return Integer.parseInt(Utils.toString(info().get("comment_karma"))); + } + + /** + * This functions returns true if this user has a gold account. + * + * @return This user has a gold account or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean isGold() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("is_gold").toString()); + } + + /** + * This functions returns true if this user is a reddit moderator + * (apparently this means a moderator of any subreddit). + * + * @return This user is a moderator or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean isMod() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("is_mod").toString()); + } + + /** + * This function returns the user's ID.
    The user's ID. This is only + * used internally, right? + * + * @return This user's ID + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + public String id() throws IOException, ParseException { + return info().get("id").toString(); + } + + /** + * This functions returns true if this user has unread moderator mail. + * + * @return This user has unread moderator mail or not + * @throws ParseException If JSON parsing fails + * @throws IOException If connection fails + */ + public boolean hasModMail() throws IOException, ParseException { + return Boolean.parseBoolean(info().get("has_mod_mail").toString()); + } + + public String getUsername() { + return username; + } + + public String getPassword() { + return password; + } + + public String getModhash() { + return modhash; + } + + public String getCookie() { + return cookie; + } + + /** + * This function logs in to reddit and returns an ArrayList containing a + * modhash and cookie. + * + * @param username The username + * @param password The password + * @return An array containing a modhash and cookie + * @throws IOException If connection fails + * @throws ParseException If parsing JSON fails + */ + private ArrayList hashCookiePair(String username, String password) + throws IOException, ParseException { + ArrayList values = new ArrayList(); + JSONObject jsonObject = Utils.post("api_type=json&user=" + username + + "&passwd=" + password, String.format(ApiEndpointUtils.USER_LOGIN, username), getCookie()); + JSONObject valuePair = (JSONObject) ((JSONObject) jsonObject.get("json")).get("data"); + + values.add(valuePair.get("modhash").toString()); + values.add(valuePair.get("cookie").toString()); + + return values; + } + + /** + * This function returns a "response" (me.json) JSON data containing info + * about the user.
    + * + * @return JSON data containing info about the user + */ + private JSONObject info() throws IOException, ParseException { + if (cookie == null || modhash == null) { + System.err.printf("Please invoke the \"connect\" function before attempting to " + + "call any other API functions."); + Runtime.getRuntime().exit(-1); + } + + JSONObject jsonObject = (JSONObject) Utils.get(ApiEndpointUtils.USER_INFO, getCookie()); + return (JSONObject) jsonObject.get("data"); + } + + /** + * This function submits a link or self post. + * + * @param title The title of the submission + * @param linkOrText The link of the submission or text + * @param selfPost If this submission is a self post + * @param subreddit Which subreddit to submit this to + * @return A JSONObject + * @throws IOException If connection fails + * @throws ParseException If JSON parsing fails + */ + private JSONObject submit(String title, String linkOrText, boolean selfPost, String subreddit) throws IOException, ParseException { + return Utils.post("title=" + title + "&" + (selfPost ? "text" : "url") + + "=" + linkOrText + "&sr=" + subreddit + "&kind=" + + (selfPost ? "self" : "link") + "&uh=" + getModhash(), + ApiEndpointUtils.USER_SUBMIT, getCookie()); + } + + /** + * Returns a list of submissions made by this user. + * + * @return List of submissions made by this user. + */ + public List comments() { + return User.comments(username); + } + + /** + * Returns misc info about the user (which consists of comment karma, mod + * mail identifier, created timestamp, gold member identifier, mod + * identifier, link karma and mail identifier). + * + * @param username The username of the user whose account info you want + * to retrieve. + * @return Misc info about the user. + */ + public static UserInfo about(String username) { + UserInfo info = null; + + try { + // Send GET request to get the account overview + JSONObject object = (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_ABOUT, username), null); + JSONObject data = (JSONObject) object.get("data"); + + // Init account info wrapper + info = new UserInfo(Integer.parseInt(Utils.toString(data.get("comment_karma"))), + Integer.parseInt(Utils.toString(data.get("link_karma"))), + Float.parseFloat(Utils.toString(data.get("created_utc"))), + Boolean.parseBoolean(Utils.toString(data.get("is_gold"))), + Boolean.parseBoolean(Utils.toString(data.get("is_mod"))), + Boolean.parseBoolean(Utils.toString(data.get("has_mail"))), + Boolean.parseBoolean(Utils.toString(data.get("has_mod_mail")))); + + } catch (Exception e) { + System.err.println("Error retrieving user information for " + username); + } + + return info; + } + + + public static List comments(String username) { + return comments(username, CommentSort.NEW); + } + + /** + * Returns a list of submissions made by this user. + * + * @param username The username of the user whose comments you want + * to retrieve. + * @return List of top 500 comments made by this user. + */ + public static List comments(String username, CommentSort commentSort) { + // List of submissions made by this user + List comments = new ArrayList(500); + try { + // Send GET request to get the account overview + JSONObject object = + (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_COMMENTS, + username, commentSort.getValue()), null); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + Comment c; + for (Object aChildren : children) { + // Get the object containing the comment + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + + // Create a new comment + c = new Comment(Utils.toString(obj.get("body")), Utils.toString(obj.get("edited")), + Utils.toString(obj.get("created_utc")), Utils.toString(obj.get("replies")), + Integer.parseInt(Utils.toString(obj.get("ups"))), + Integer.parseInt(Utils.toString(obj.get("downs")))); + + // Add it to the submissions list + comments.add(c); + } + } catch (Exception e) { + e.printStackTrace(); + } + // Return the submissions + return comments; + } + + /** + * Returns a list of submissions made by this user. + * + * @param username The username of the user whose submissions you want + * to retrieve. + * @return List of submissions made by this user. + */ + public static List submissions(String username) { + // List of submissions made by this user + List submissions = new ArrayList(500); + try { + // Send GET request to get the account overview + JSONObject object = (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_SUBMISSIONS, username), null); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + + for (Object aChildren : children) { + // Get the object containing the comment + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + //add a new Submission to the list + submissions.add(new Submission(obj)); + } + } catch (Exception e) { + e.printStackTrace(); + } + + // Return the submissions + return submissions; + } + + /** + * Returns a list of submissions that this user liked. + * + * @return List of liked links with default sorting. + */ + public List getLikedSubmissions() { + return getLikedSubmissions(Sort.HOT); + } + + /** + * Returns a list of submissions that this user liked with a Reddit sort + * + * @param sort Which sort you'd like to apply + * @return List of liked submissions with a Reddit sort + */ + public List getLikedSubmissions(Sort sort) { + return getUserSubmissions("liked", sort); + } + + /** + * Returns a list of submissions that this user chose to hide. with the default sorting + * + * @return List of disliked links. + */ + public List getHiddenSubmissions() { + return getHiddenSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that this user chose to hide with a specified sorting + * + * @param sort Which sort you'd like to apply + * @return List of hidden Submissions with a Reddit sort + */ + public List getHiddenSubmissions(Sort sort) { + return getUserSubmissions("hidden", sort); + } + + /** + * Returns a list of Submissions that the user saved with the default sort + * + * @return List of saved links + */ + public List getSavedSubmissions() { + return getSavedSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that the user saved with a specified sorting + * + * @param sort Which sort you'd like to apply + * @return List of saved links with a Reddit sort + */ + public List getSavedSubmissions(Sort sort) { + return getUserSubmissions("saved", sort); + } + + /** + * Returns a list of Submissions that the user submitted with the default Reddit sort + * + * @return List of submitted Submissions + */ + public List getSubmissions() { + return getSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that the user submitted with a specified Reddit sort + * + * @return List of submitted Submissions with a specified Reddit sort + */ + public List getSubmissions(Sort sort) { + return getUserSubmissions("submitted", sort); + } + + /** + * Returns a list of submissions that this user disliked with the default Reddit sort + * + * @return List of disliked links. + */ + public List getDislikedSubmissions() { + return getDislikedSubmissions(Sort.HOT); + } + + /** + * Returns a list of Submissions that this user disliked with a specified Reddit sort + * + * @param sort Which sort you'd like to apply + * @return List of disliked sorts with a specified sort + */ + public List getDislikedSubmissions(Sort sort) { + return getUserSubmissions("disliked", sort); + } + + public List getUserOverview() { + return getUserSubmissions("overview", Sort.HOT); + } + + /** + * private function used to get submissions that a user interacts with on Reddit + * + * @param where place of Submission - see http://www.reddit.com/dev/api#GET_user_{username}_{where} + * @return Submissions from the specified location, null if the location is invalid + */ + private List getUserSubmissions(String where, Sort sort) { + //valid arguments for where the Submission can come from + final String[] LOCATIONS = { + //TODO: not all of these JSONs return something that can be processed purely into a Submission class, until those are taken care of, I commented them out + /*"overview",*/ "submitted", /*"comments",*/ "liked", "disliked", "hidden", "saved" + }; + //check to see if we have a valid location + boolean valid = false; + for (String LOCATION : LOCATIONS) { + valid = where.equals(LOCATION); + if (valid) { + break; + } + + } + if (!valid) { + System.err.println(where + " is an invalid location"); + return null; + } + + //if we got this far, the location is valid + List submissions = new ArrayList(); + try { + JSONObject object = + (JSONObject) Utils.get(String.format(ApiEndpointUtils.USER_SUBMISSIONS_INTERACTION, + username, where, sort.getValue()), cookie); + JSONObject data = (JSONObject) object.get("data"); + JSONArray children = (JSONArray) data.get("children"); + + JSONObject obj; + for (Object aChildren : children) { + obj = (JSONObject) aChildren; + obj = (JSONObject) obj.get("data"); + submissions.add(new Submission(obj)); + } + } catch (Exception e) { + e.printStackTrace(); + } + return submissions; + } + + /** + * Returns a list of Subreddits to which the user is subscribed. + * @return List of Subreddits + */ + public List getSubscribed() { + List subscibed = new ArrayList(1000); + JSONObject object = (JSONObject) Utils.get(ApiEndpointUtils.USER_GET_SUBSCRIBED, cookie); + + JSONObject rawData = (JSONObject) object.get("data"); + JSONArray subreddits = (JSONArray) rawData.get("children"); + + for (Object subreddit : subreddits) { + JSONObject obj = (JSONObject) subreddit; + obj = (JSONObject) obj.get("data"); + Subreddit sub = new Subreddit(obj.get("display_name").toString(), + obj.get("display_name").toString(), obj.get("title").toString(), + obj.get("url").toString(), obj.get("created").toString(), + obj.get("created_utc").toString(), + Boolean.parseBoolean(obj.get("over18").toString()), + Integer.parseInt(obj.get("subscribers").toString()), + obj.get("id").toString(), obj.get("description").toString()); + subscibed.add(sub); + } + + return subscibed; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `info(this).get("has_mod_mail")` could be null and is dereferenced at line 213. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean User.hasModMail() + +### Procedure Id: +com.github.jreddit.user.User.hasModMail():boolean.2fd9587dbbccd43729ca7634c3aaf0ec + +### File: +src/main/java/com/github/jreddit/user/User.java + +### Key: +User.java|hasModMail|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +c35939f447076a708bf2b5fb8219be7a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8336/instruction.md b/inferredbugs-8336/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f851120eeda5b51e9a204ea54aca231e1aa49cb --- /dev/null +++ b/inferredbugs-8336/instruction.md @@ -0,0 +1,313 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** apollo +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.ctrip.apollo.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.when; + + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.runners.MockitoJUnitRunner; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.client.RestTemplate; + +import com.ctrip.apollo.Apollo.Env; +import com.ctrip.apollo.core.Constants; +import com.ctrip.apollo.core.dto.ClusterDTO; +import com.ctrip.apollo.core.dto.ConfigItemDTO; +import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO; +import com.ctrip.apollo.core.dto.VersionDTO; +import com.ctrip.apollo.portal.api.AdminServiceAPI; +import com.ctrip.apollo.portal.constants.PortalConstants; +import com.ctrip.apollo.portal.entity.AppConfigVO; + +import java.util.Arrays; + +@RunWith(MockitoJUnitRunner.class) +public class ConfigServiceTest { + + @Mock + private RestTemplate restTemplate; + + @InjectMocks + private ConfigService configService; + + @Mock + private ServiceLocator serviceLocator; + @Spy + private AdminServiceAPI.VersionAPI versionAPI; + @Spy + private AdminServiceAPI.ClusterAPI clusterAPI; + @Spy + private AdminServiceAPI.ConfigAPI configAPI; + + + + @Before + public void setUp() { + ReflectionTestUtils.setField(versionAPI, "restTemplate", restTemplate); + ReflectionTestUtils.setField(clusterAPI, "restTemplate", restTemplate); + ReflectionTestUtils.setField(configAPI, "restTemplate", restTemplate); + + ReflectionTestUtils.setField(versionAPI, "serviceLocator", serviceLocator); + ReflectionTestUtils.setField(clusterAPI, "serviceLocator", serviceLocator); + ReflectionTestUtils.setField(configAPI, "serviceLocator", serviceLocator); + + String defaultAdminService = "http://localhost:8090"; + Mockito.doReturn(defaultAdminService).when(serviceLocator).getAdminService(Env.DEV); + } + + @Test + public void testLoadReleaseConfig() { + long appId = 6666; + long versionId = 100; + long releaseId = 11111; + + VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId); + ReleaseSnapshotDTO[] someReleaseSnapShots = assembleReleaseSnapShots(); + + when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion); + when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots); + + AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId); + + assertEquals(appConfigVO.getAppId(), appId); + assertEquals(appConfigVO.getVersionId(), versionId); + assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2); + assertEquals(appConfigVO.getOverrideAppConfigs().size(), 2); + assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 2); + } + + @Test + public void testLoadReleaseConfigOnlyDefaultConfigs() { + long appId = 6666; + long versionId = 100; + long releaseId = 11111; + + VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId); + ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1]; + someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME, + "{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}"); + + when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion); + when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots); + + AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId); + + assertEquals(appConfigVO.getAppId(), appId); + assertEquals(appConfigVO.getVersionId(), versionId); + assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2); + assertEquals(appConfigVO.getOverrideAppConfigs().size(), 0); + assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0); + } + + @Test + public void testLoadReleaseConfigDefaultConfigsAndOverrideApp() { + long appId = 6666; + long versionId = 100; + long releaseId = 11111; + VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId); + ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1]; + someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME, + "{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\", \"5555.bar\":\"demo2\", \"22.bar\":\"demo2\"}"); + + when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion); + when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots); + + AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId); + + assertEquals(appConfigVO.getAppId(), appId); + assertEquals(appConfigVO.getVersionId(), versionId); + assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2); + assertEquals(2, appConfigVO.getOverrideAppConfigs().size()); + assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0); + } + + @Test + public void testLoadReleaseConfigDefaultConfigsAndOverrideCluster() { + long appId = 6666; + long versionId = 100; + long releaseId = 11111; + VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId); + ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[2]; + someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME, + "{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}"); + someReleaseSnapShots[1] = assembleReleaseSnapShot(11112, "cluster1", + "{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}"); + + when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion); + when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots); + + AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId); + + assertEquals(appConfigVO.getAppId(), appId); + assertEquals(appConfigVO.getVersionId(), versionId); + assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2); + assertEquals(0, appConfigVO.getOverrideAppConfigs().size()); + assertEquals(1, appConfigVO.getOverrideClusterConfigs().size()); + } + + @Test + public void testLoadLastestConfig() { + long appId = 6666; + ClusterDTO[] someClusters = assembleClusters(); + ConfigItemDTO[] someConfigItem = assembleConfigItems(); + + when(clusterAPI.getClustersByApp(Env.DEV, appId)).thenReturn(someClusters); + when(configAPI.getLatestConfigItemsByClusters(Env.DEV, Arrays + .asList(Long.valueOf(100), Long.valueOf(101)))).thenReturn(someConfigItem); + + AppConfigVO appConfigVO = configService.loadLatestConfig(Env.DEV, appId); + + assertEquals(appConfigVO.getAppId(), 6666); + assertEquals(appConfigVO.getVersionId(), PortalConstants.LASTEST_VERSION_ID); + assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 3); + assertEquals(appConfigVO.getOverrideAppConfigs().size(), 1); + assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 1); + } + + private VersionDTO assembleVersion(long appId, String versionName, long releaseId) { + VersionDTO version = new VersionDTO(); + version.setAppId(appId); + version.setName(versionName); + version.setReleaseId(releaseId); + return version; + } + + private ReleaseSnapshotDTO[] assembleReleaseSnapShots() { + ReleaseSnapshotDTO[] releaseSnapShots = new ReleaseSnapshotDTO[3]; + releaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME, + "{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\",\"3333.foo\":\"1008\",\"4444.bar\":\"99901\"}"); + releaseSnapShots[1] = assembleReleaseSnapShot(11111, "cluster1", "{\"6666.foo\":\"demo1\"}"); + releaseSnapShots[2] = assembleReleaseSnapShot(11111, "cluster2", "{\"6666.bar\":\"bar2222\"}"); + return releaseSnapShots; + } + + private ReleaseSnapshotDTO assembleReleaseSnapShot(long releaseId, String clusterName, + String configurations) { + ReleaseSnapshotDTO releaseSnapShot = new ReleaseSnapshotDTO(); + releaseSnapShot.setReleaseId(releaseId); + releaseSnapShot.setClusterName(clusterName); + releaseSnapShot.setConfigurations(configurations); + return releaseSnapShot; + } + + private ClusterDTO[] assembleClusters() { + ClusterDTO[] clusters = new ClusterDTO[2]; + clusters[0] = assembleCluster(100, 6666, Constants.DEFAULT_CLUSTER_NAME); + clusters[1] = assembleCluster(101, 6666, "cluster1"); + return clusters; + } + + private ClusterDTO assembleCluster(long id, long appId, String name) { + ClusterDTO cluster = new ClusterDTO(); + cluster.setAppId(appId); + cluster.setId(id); + cluster.setName(name); + return cluster; + } + + private ConfigItemDTO[] assembleConfigItems() { + ConfigItemDTO[] configItems = new ConfigItemDTO[5]; + configItems[0] = + assembleConfigItem(100, Constants.DEFAULT_CLUSTER_NAME, 6666, "6666.k1", "6666.v1"); + configItems[1] = + assembleConfigItem(100, Constants.DEFAULT_CLUSTER_NAME, 6666, "6666.k2", "6666.v2"); + configItems[2] = + assembleConfigItem(100, Constants.DEFAULT_CLUSTER_NAME, 6666, "6666.k3", "6666.v3"); + configItems[3] = + assembleConfigItem(100, Constants.DEFAULT_CLUSTER_NAME, 5555, "5555.k1", "5555.v1"); + configItems[4] = assembleConfigItem(101, "cluster1", 6666, "6666.k1", "6666.v1"); + return configItems; + } + + private ConfigItemDTO assembleConfigItem(long clusterId, String clusterName, int appId, + String key, String value) { + ConfigItemDTO configItem = new ConfigItemDTO(); + configItem.setClusterName(clusterName); + configItem.setClusterId(clusterId); + configItem.setAppId(appId); + configItem.setKey(key); + configItem.setValue(value); + return configItem; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `appConfigVO` last assigned on line 145 could be null and is dereferenced at line 147. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ConfigServiceTest.testLoadReleaseConfigDefaultConfigsAndOverrideCluster() + +### Procedure Id: +com.ctrip.apollo.portal.service.ConfigServiceTest.testLoadReleaseConfigDefaultConfigsAndOverrideClus.f9c1528e9b1a1ad9bb76e84d25b27889 + +### File: +apollo-portal/src/test/java/com/ctrip/apollo/portal/service/ConfigServiceTest.java + +### Key: +ConfigServiceTest.java|testLoadReleaseConfigDefaultConfigsAndOverrideCluster|NULL_DEREFERENCE + +### Node Key: +85f6f5d6678fe27e5119d8f5b7885afd + +### Hash: +b65318a5ad4edf2fee254d40f9504c79 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8338/instruction.md b/inferredbugs-8338/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3449bbdb2bf9b87c6dcbb9f4ba23c39df0e4749b --- /dev/null +++ b/inferredbugs-8338/instruction.md @@ -0,0 +1,585 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** apollo +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package io.logz.apollo; + +import io.logz.apollo.clients.ApolloTestAdminClient; +import io.logz.apollo.clients.ApolloTestClient; +import io.logz.apollo.exceptions.ApolloClientException; +import io.logz.apollo.helpers.Common; +import io.logz.apollo.helpers.ModelsGenerator; +import io.logz.apollo.models.BlockerDefinition; +import io.logz.apollo.models.DeployableVersion; +import io.logz.apollo.models.Environment; +import io.logz.apollo.models.Service; +import io.logz.apollo.models.Stack; +import org.junit.Ignore; +import org.junit.Test; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static io.logz.apollo.helpers.ModelsGenerator.createAndSubmitBlocker; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Created by roiravhon on 6/5/17. + */ +public class BlockerTest { + + private final static String APOLLO_REPO_URL = "https://github.com/logzio/apollo"; + private final static String APOLLO_FAILED_STATUS_CHECKS_COMMIT = "63b79a229defab92df685dcc4e47dd35f0518ef0"; + private final static String APOLLO_VALID_STATUS_CHECKS_COMMIT = "7e01c7e4cfddeadd49d4a4e9ed575b24e9210f4b"; + + @Test + public void testEverythingBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + blocker.setActive(false); + apolloTestAdminClient.updateBlocker(blocker); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + } + + @Test + public void testUnconditionalBlockerWithServiceAndEnvironmentException() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + + List exceptionServiceIds = new ArrayList() {{ add(service.getId()); }}; + List exceptionEnvironmentIds = new ArrayList() {{ add(environment.getId()); }}; + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "unconditional", getUnconditionalBlockerConfiguration(exceptionServiceIds, exceptionEnvironmentIds), null, null); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + + blocker.setActive(false); + apolloTestAdminClient.updateBlocker(blocker); + } + + @Test + public void testUnconditionalBlockerWithEnvironmentException() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment exceptionEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + Environment otherEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + + List exceptionEnvironmentIds = new ArrayList() {{ add(exceptionEnvironment.getId()); }}; + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "unconditional", getUnconditionalBlockerConfiguration(null, exceptionEnvironmentIds), null, service); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, otherEnvironment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, exceptionEnvironment, service, deployableVersion); + + blocker.setActive(false); + apolloTestAdminClient.updateBlocker(blocker); + } + + @Test + public void testUnconditionalBlockerWithServiceException() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service exceptionService = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, exceptionService); + Service otherService = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion otherDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, otherService); + + List exceptionServiceIds = new ArrayList() {{ add(exceptionService.getId()); }}; + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "unconditional", getUnconditionalBlockerConfiguration(exceptionServiceIds, null), environment, null); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, otherService, otherDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, exceptionService, deployableVersion); + + blocker.setActive(false); + apolloTestAdminClient.updateBlocker(blocker); + } + + @Test + public void testEnvironmentBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Environment okEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", blockedEnvironment, null); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, okEnvironment, service, deployableVersion); + } + + @Test + public void testServiceBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service okService = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion blockedDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, blockedService); + DeployableVersion okDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, okService); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, blockedService); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, blockedService, blockedDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, okService, okDeployableVersion); + } + + @Test + public void testEnvironmentsStackBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Environment okEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + Stack blockedEnvironmentsStack = ModelsGenerator.createAndSubmitEnvironmentsStack(apolloTestClient, Arrays.asList(blockedEnvironment.getId())); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, blockedEnvironmentsStack); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, okEnvironment, service, deployableVersion); + } + + @Test + public void testServicesStackBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service okService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Stack blockedServicesStack = ModelsGenerator.createAndSubmitServicesStack(apolloTestClient, Arrays.asList(blockedService.getId())); + DeployableVersion blockedDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, blockedService); + DeployableVersion okDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, okService); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, blockedServicesStack); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, blockedService, blockedDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, okService, okDeployableVersion); + } + + @Test + public void testBlockByAvailabilityOnSpecificService() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + String availability = "BLOCK-ME-1"; + Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, blockedService, null, availability); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, blockedService); + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, blockedService, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + } + + @Test + public void testBlockByAvailabilityOnAllServices() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + String availability = "BLOCK-ME-2"; + Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + } + + @Test + public void testNonBlockedDeploymentWithAvailabilityBlockerOnSpecificService() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + String availability = "BLOCK-ME-3"; + Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); //Environment in this availability + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, blockedService, null, availability); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + } + + @Test + public void testNonBlockedDeploymentWithAnotherAvailabilityBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + String availability = "BLOCK-ME-4"; + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); //Random availability + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, blockedService, null, availability); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + } + + @Test + public void testCreatingInvalidAvailabilityBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + String availability = "BLOCK-ME-5"; + Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient); + String errorMessage = String.format("Trying to add invalid blocker. stackId - null, environmentId - %s, serviceId - null, availability - %s", environment.getId(), availability); + + assertThatThrownBy(() -> ModelsGenerator. createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", environment, null, null, availability)) + .isInstanceOf(ApolloClientException.class) + .hasMessageContaining(errorMessage); + } + + @Test + public void testAddingInvalidBlockers() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + Stack servicesStack = ModelsGenerator.createAndSubmitServicesStack(apolloTestClient, Arrays.asList(service.getId())); + + String errorMessage = "Trying to add invalid blocker. "; + + assertThatThrownBy(() -> ModelsGenerator. createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, service, servicesStack)).isInstanceOf(ApolloClientException.class) + .hasMessageContaining(errorMessage + String.format("stackId - %s, environmentId - null, serviceId - %s, availability - null", servicesStack.getId(), service.getId())); + + assertThatThrownBy(() -> ModelsGenerator. createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", environment, null, servicesStack)).isInstanceOf(ApolloClientException.class) + .hasMessageContaining(errorMessage + String.format("stackId - %s, environmentId - %s, serviceId - null", servicesStack.getId(), environment.getId())); + + assertThatThrownBy(() -> ModelsGenerator. createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", environment, service, servicesStack)).isInstanceOf(ApolloClientException.class) + .hasMessageContaining(errorMessage + String.format("stackId - %s, environmentId - %s, serviceId - %s", servicesStack.getId(), environment.getId(), service.getId())); + } + + @Test + public void testSpecificBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Environment okEnvironment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service blockedService = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service okService = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion blockedDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, blockedService); + DeployableVersion okDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, okService); + + createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", blockedEnvironment, blockedService); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, blockedService, blockedDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, okService, okDeployableVersion); + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, okEnvironment, blockedService, blockedDeployableVersion); + } + + @Test + public void testTimeBasedBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); + + int dayOfWeek = LocalDate.now().getDayOfWeek().getValue(); + LocalTime twoMinutesFromNow = LocalTime.now().plusMinutes(2); + LocalTime twoMinutesBeforeNow = LocalTime.now().minusMinutes(2); + LocalTime threeMinutesFromNow = LocalTime.now().plusMinutes(3); + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "timebased", + getTimeBasedBlockerJsonConfiguration(dayOfWeek, twoMinutesBeforeNow, twoMinutesFromNow), + environment, service); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + blocker.setBlockerJsonConfiguration(getTimeBasedBlockerJsonConfiguration(dayOfWeek, twoMinutesFromNow, threeMinutesFromNow)); + apolloTestAdminClient.updateBlocker(blocker); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + } + + @Test + @Ignore + public void testBranchBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + // Create a deployable version from logzio public API repo (small public one) + DeployableVersion deployableVersion = new DeployableVersion(); + deployableVersion.setGithubRepositoryUrl("https://github.com/logzio/public-api"); + deployableVersion.setGitCommitSha("c5265fcc8a73c9d5a79170b668c21c958b53a93e"); + deployableVersion.setServiceId(service.getId()); + + deployableVersion.setId(apolloTestClient.addDeployableVersion(deployableVersion).getId()); + + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "branch", + getBranchBlockerJsonConfiguration("develop"), + environment, service); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + blocker.setBlockerJsonConfiguration(getBranchBlockerJsonConfiguration("master")); + apolloTestAdminClient.updateBlocker(blocker); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); + } + + @Test + public void testConcurrencyBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service serviceA = ModelsGenerator.createAndSubmitService(apolloTestClient); + Service serviceB = ModelsGenerator.createAndSubmitService(apolloTestClient); + + DeployableVersion deployableVersionA = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, serviceA); + DeployableVersion deployableVersionB = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, serviceB); + + List excludedService = new ArrayList<>(); + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "concurrent", + getConcurrencyBlockerJsonConfiguration(1, excludedService), + environment, null); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, serviceA, deployableVersionA); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, serviceB, deployableVersionB)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + excludedService.add(serviceB.getId()); + blocker.setBlockerJsonConfiguration(getConcurrencyBlockerJsonConfiguration(1, excludedService)); + apolloTestAdminClient.updateBlocker(blocker); + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, serviceB, deployableVersionB); + } + + @Test + @Ignore + public void testGHCommitStatusBlocker() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + DeployableVersion failedDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service, + APOLLO_REPO_URL, APOLLO_FAILED_STATUS_CHECKS_COMMIT); + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "githubCommitStatus",null, environment, service); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, failedDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + // Attempt to deploy a valid commit should work + DeployableVersion validDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service, + APOLLO_REPO_URL, APOLLO_VALID_STATUS_CHECKS_COMMIT); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, validDeployableVersion); + } + + @Test + @Ignore + public void testBlockerUserOverride() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + + DeployableVersion failedDeployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service, + APOLLO_REPO_URL, APOLLO_FAILED_STATUS_CHECKS_COMMIT); + + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "githubCommitStatus",null, environment, service); + + assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, failedDeployableVersion)).isInstanceOf(Exception.class) + .hasMessageContaining("Deployment is currently blocked"); + + apolloTestAdminClient.overrideBlockerByUser(apolloTestClient.getTestUser(), blocker); + + ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, failedDeployableVersion); + } + + @Test + public void changeBlockerActiveAttribute() throws Exception { + ApolloTestClient apolloTestClient = Common.signupAndLogin(); + ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient(); + + Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient); + Service service = ModelsGenerator.createAndSubmitService(apolloTestClient); + BlockerDefinition blocker = createAndSubmitBlocker(apolloTestAdminClient, "githubCommitStatus",null, environment, service); + + Boolean beforeActive = blocker.getActive(); + Boolean afterActive = !beforeActive; + + BlockerDefinition updatedBlocker = apolloTestClient.updateBlockerDefinitionActiveness(blocker.getId(), afterActive); + assertThat(updatedBlocker.getActive()).isEqualTo(afterActive); + } + + private String getTimeBasedBlockerJsonConfiguration(int dayOfWeek, LocalTime startDate, LocalTime endDate) { + + return "{\n" + + " \"startTimeUtc\": \"" + startDate.getHour() + ":" + startDate.getMinute() + "\",\n" + + " \"endTimeUtc\": \"" + endDate.getHour() + ":" + endDate.getMinute() + "\",\n" + + " \"daysOfTheWeek\": [\n" + + " " + dayOfWeek + "\n" + + " ]\n" + + "}"; + } + + private String getConcurrencyBlockerJsonConfiguration(int allowedConcurrentDeployment, List excludeServices) { + return "{\n" + + " \"allowedConcurrentDeployment\": \"" + allowedConcurrentDeployment + "\",\n" + + " \"excludeServices\":" + excludeServices.toString() + + "}"; + } + + private String getBranchBlockerJsonConfiguration(String branchesNames) { + return "{\n" + + " \"branchName\": \"" + branchesNames + "\"\n" + + "}"; + } + + private String getUnconditionalBlockerConfiguration(List exceptionServiceIds, List exceptionEnvironmentIds) { + + if (exceptionServiceIds == null && exceptionEnvironmentIds == null) { + return "{}"; + } + + String jsonConfiguration = "{\n"; + + if (exceptionServiceIds != null) { + jsonConfiguration += " \"exceptionServiceIds\":" + exceptionServiceIds.toString(); + if (exceptionEnvironmentIds != null) { + jsonConfiguration += ",\n"; + } + } + + if (exceptionEnvironmentIds != null) { + jsonConfiguration += " \"exceptionEnvironmentIds\":" + exceptionEnvironmentIds.toString(); + } + + return jsonConfiguration += "}"; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `createAndSubmitBlocker(...)` at line 225. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BlockerTest.testBlockByAvailabilityOnAllServices() + +### Procedure Id: +io.logz.apollo.BlockerTest.testBlockByAvailabilityOnAllServices():void.a3e738dba312b922b964201db064bd7d + +### File: +apollo-backend/src/test/java/io/logz/apollo/BlockerTest.java + +### Key: +BlockerTest.java|testBlockByAvailabilityOnAllServices|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +174af46061a4f8dff3bb574f42f20e0d + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8352/instruction.md b/inferredbugs-8352/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57897cf65f28f15158dc3707748f5d33f7187d8f --- /dev/null +++ b/inferredbugs-8352/instruction.md @@ -0,0 +1,389 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.rithms.riot.api.request; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; + +import net.rithms.riot.api.ApiConfig; +import net.rithms.riot.api.ApiMethod; +import net.rithms.riot.api.RiotApi; +import net.rithms.riot.api.RiotApiAsync; +import net.rithms.riot.api.RiotApiException; + +/** + * This class is used to fire asynchronous call at the Riot Api. You should not construct these requests manually. To fire asynchronous + * requests, use a {@link RiotApiAsync} object. + * + * @author Daniel 'Linnun' Figge + * @see RiotApiAsync + */ +public class AsyncRequest extends Request implements Runnable { + + protected final Object signal = new Object(); + + private List listeners = new ArrayList(); + private Thread executionThread = null; + private boolean sent = false; + + /** + * Constructs an asynchronous request + * + * @param config + * Configuration to use + * @param method + * Api method to call + * @see ApiConfig + * @see ApiMethod + */ + public AsyncRequest(ApiConfig config, ApiMethod object) { + super(); + init(config, object); + } + + /** + * Adds a {@link RequestListener} to this request + * + * @param listener + * A request listener + * @see RequestListener + */ + public void addListener(RequestListener listener) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } + + /** + * Adds a given collection of {@link RequestListener} to this request + * + * @param listeners + * A collection of request listeners + * @see RequestListener + */ + public void addListeners(Collection listeners) { + for (RequestListener listener : listeners) { + if (!this.listeners.contains(listener)) { + this.listeners.add(listener); + } + } + } + + /** + * Waits indefinitely until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + */ + public void await() throws InterruptedException { + if (!isDone()) { + synchronized (signal) { + while (!isDone()) { + signal.wait(); + } + } + } + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { + await(timeout, unit, false); + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @param cancelOnTimeout + * Whether or not the request should be cancelled, if the given {@code timeout} is elapsed without the request completing + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit, boolean cancelOnTimeout) throws InterruptedException, TimeoutException { + final long end = System.currentTimeMillis() + unit.toMillis(timeout); + if (!isDone() && System.currentTimeMillis() < end) { + synchronized (signal) { + while (!isDone() && System.currentTimeMillis() < end) { + signal.wait(end - System.currentTimeMillis()); + } + } + } + if (!isDone()) { + if (cancelOnTimeout) { + cancel(); + } + throw new TimeoutException(); + } + } + + @Override + public boolean cancel() { + boolean cancelled = super.cancel(); + if (!cancelled) { + return false; + } + synchronized (signal) { + signal.notifyAll(); + } + // Try to force-quit the connection + if (connection != null) { + setTimeout(1); + connection.disconnect(); + } + return true; + } + + @Override + public synchronized void execute() { + if (isSent()) { + return; + } + sent = true; + executionThread = new Thread(this); + executionThread.setName("AsyncRequest - " + object); + executionThread.start(); + } + + /** + * Retrieves the request's result. If an exception would be thrown, it is swallowed, since you should only call this method, if the + * request succeeded. + * + *

    + * If you want this method to throw exceptions, please use {@link #getDtoAndThrowException()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + */ + @Override + public T getDto() { + try { + return super.getDto(true); + } catch (RiotApiException e) { + RiotApi.log.log(Level.FINE, "Retrieving Dto Failed", e); + } + return null; + } + + /** + * Retrieves the request's result. If an exception occures, it is thrown. + * + *

    + * If you do not want this method to throw exceptions, please use {@link #getDto()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + * @throws RiotApiException + * If an exception occurs while parsing the Riot Api's response + */ + public T getDtoAndThrowException() throws RiotApiException { + return super.getDto(true); + } + + /** + * Returns {@code true} if this request has started execution + * + * @return {@code true} if this request has started execution + */ + public boolean isSent() { + return sent; + } + + /** + * Notifies the listeners about the given {@code state}. + * + * @param state + * The state to notify the listeners about + */ + protected void notifyListeners(RequestState state) { + for (RequestListener listener : listeners) { + if (state == RequestState.Succeeded) { + listener.onRequestSucceeded(this); + } else if (state == RequestState.Failed) { + listener.onRequestFailed(getException()); + } else if (state == RequestState.Timeout) { + listener.onRequestTimeout(this); + } + } + } + + /** + * Removes all listeners from this request + * + * @see RequestListener + */ + public void removeAllListeners() { + listeners.clear(); + } + + /** + * Removes a listener from this request + * + * @param listener + * Listener to remove + * @see RequestListener + */ + public void removeListener(RequestListener listener) { + listeners.remove(listener); + } + + @Override + public void run() { + try { + super.execute(); + } catch (RiotApiException e) { + setException(e); + } + } + + @Override + protected boolean setState(RequestState state) { + if (isDone()) { + return false; + } + notifyListeners(state); + super.setState(state); + if (isDone()) { + synchronized (signal) { + signal.notifyAll(); + } + } + return true; + } + + @Override + protected void setTimeout() { + setTimeout(config.getAsyncRequestTimeout()); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `net.rithms.riot.api.request.AsyncRequest.cancel` indirectly writes to field `this.net.rithms.riot.api.request.Request.state` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean AsyncRequest.cancel() + +### Procedure Id: +net.rithms.riot.api.request.AsyncRequest.cancel():boolean.8289431347cc76ab949972e929f05591 + +### File: +src/main/java/net/rithms/riot/api/request/AsyncRequest.java + +### Key: +AsyncRequest.java|cancel|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +2e3a9fddb4a9ed186a6914417ff2cdfc + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8354/instruction.md b/inferredbugs-8354/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..881e9516bb053268d67fd9a02b8e9886b0e0dd7c --- /dev/null +++ b/inferredbugs-8354/instruction.md @@ -0,0 +1,389 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.rithms.riot.api.request; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.logging.Level; + +import net.rithms.riot.api.ApiConfig; +import net.rithms.riot.api.ApiMethod; +import net.rithms.riot.api.RiotApi; +import net.rithms.riot.api.RiotApiAsync; +import net.rithms.riot.api.RiotApiException; + +/** + * This class is used to fire asynchronous call at the Riot Api. You should not construct these requests manually. To fire asynchronous + * requests, use a {@link RiotApiAsync} object. + * + * @author Daniel 'Linnun' Figge + * @see RiotApiAsync + */ +public class AsyncRequest extends Request implements Runnable { + + protected final Object signal = new Object(); + + private List listeners = new ArrayList(); + private Thread executionThread = null; + private boolean sent = false; + + /** + * Constructs an asynchronous request + * + * @param config + * Configuration to use + * @param method + * Api method to call + * @see ApiConfig + * @see ApiMethod + */ + public AsyncRequest(ApiConfig config, ApiMethod object) { + super(); + init(config, object); + } + + /** + * Adds a {@link RequestListener} to this request + * + * @param listener + * A request listener + * @see RequestListener + */ + public void addListener(RequestListener listener) { + if (!listeners.contains(listener)) { + listeners.add(listener); + } + } + + /** + * Adds a given collection of {@link RequestListener} to this request + * + * @param listeners + * A collection of request listeners + * @see RequestListener + */ + public void addListeners(Collection listeners) { + for (RequestListener listener : listeners) { + if (!this.listeners.contains(listener)) { + this.listeners.add(listener); + } + } + } + + /** + * Waits indefinitely until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + */ + public void await() throws InterruptedException { + if (!isDone()) { + synchronized (signal) { + while (!isDone()) { + signal.wait(); + } + } + } + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException { + await(timeout, unit, false); + } + + /** + * Waits for at most the given time until the request completes. + *

    + * If the thread is interrupted while waiting for the request to complete, this method will throw an {@code InterruptedException} and + * the thread's interrupt flag will be cleared. + *

    + *

    + * Please note that this method is blocking and thus negates the advantage of the asynchronous nature of this class. Consider using a + * {@link RequestListener} instead. + *

    + * + * @param timeout + * The maximum amount of the given time unit to wait + * @param unit + * The time unit of the {@code timeout} argument + * @param cancelOnTimeout + * Whether or not the request should be cancelled, if the given {@code timeout} is elapsed without the request completing + * @throws InterruptedException + * If the method is interrupted by calling {@link Thread#interrupt()}. The interrupt flag will be cleared + * @throws TimeoutException + * If the given time elapsed without the request completing + */ + public void await(long timeout, TimeUnit unit, boolean cancelOnTimeout) throws InterruptedException, TimeoutException { + final long end = System.currentTimeMillis() + unit.toMillis(timeout); + if (!isDone() && System.currentTimeMillis() < end) { + synchronized (signal) { + while (!isDone() && System.currentTimeMillis() < end) { + signal.wait(end - System.currentTimeMillis()); + } + } + } + if (!isDone()) { + if (cancelOnTimeout) { + cancel(); + } + throw new TimeoutException(); + } + } + + @Override + public boolean cancel() { + boolean cancelled = super.cancel(); + if (!cancelled) { + return false; + } + synchronized (signal) { + signal.notifyAll(); + } + // Try to force-quit the connection + if (connection != null) { + setTimeout(1); + connection.disconnect(); + } + return true; + } + + @Override + public synchronized void execute() { + if (isSent()) { + return; + } + sent = true; + executionThread = new Thread(this); + executionThread.setName("AsyncRequest - " + object); + executionThread.start(); + } + + /** + * Retrieves the request's result. If an exception would be thrown, it is swallowed, since you should only call this method, if the + * request succeeded. + * + *

    + * If you want this method to throw exceptions, please use {@link #getDtoAndThrowException()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + */ + @Override + public T getDto() { + try { + return super.getDto(true); + } catch (RiotApiException e) { + RiotApi.log.log(Level.FINE, "Retrieving Dto Failed", e); + } + return null; + } + + /** + * Retrieves the request's result. If an exception occures, it is thrown. + * + *

    + * If you do not want this method to throw exceptions, please use {@link #getDto()} instead. + *

    + * + * @return The object returned by the api call, or {@code null} if the request did not finish yet + * @throws RiotApiException + * If an exception occurs while parsing the Riot Api's response + */ + public T getDtoAndThrowException() throws RiotApiException { + return super.getDto(true); + } + + /** + * Returns {@code true} if this request has started execution + * + * @return {@code true} if this request has started execution + */ + public boolean isSent() { + return sent; + } + + /** + * Notifies the listeners about the given {@code state}. + * + * @param state + * The state to notify the listeners about + */ + protected void notifyListeners(RequestState state) { + for (RequestListener listener : listeners) { + if (state == RequestState.Succeeded) { + listener.onRequestSucceeded(this); + } else if (state == RequestState.Failed) { + listener.onRequestFailed(getException()); + } else if (state == RequestState.Timeout) { + listener.onRequestTimeout(this); + } + } + } + + /** + * Removes all listeners from this request + * + * @see RequestListener + */ + public void removeAllListeners() { + listeners.clear(); + } + + /** + * Removes a listener from this request + * + * @param listener + * Listener to remove + * @see RequestListener + */ + public void removeListener(RequestListener listener) { + listeners.remove(listener); + } + + @Override + public void run() { + try { + super.execute(); + } catch (RiotApiException e) { + setException(e); + } + } + + @Override + protected boolean setState(RequestState state) { + if (isDone()) { + return false; + } + notifyListeners(state); + super.setState(state); + if (isDone()) { + synchronized (signal) { + signal.notifyAll(); + } + } + return true; + } + + @Override + protected void setTimeout() { + setTimeout(config.getAsyncRequestTimeout()); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `net.rithms.riot.api.request.AsyncRequest.cancel` reads without synchronization from `this.net.rithms.riot.api.request.Request.connection`. Potentially races with write in method `AsyncRequest.run()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean AsyncRequest.cancel() + +### Procedure Id: +net.rithms.riot.api.request.AsyncRequest.cancel():boolean.8289431347cc76ab949972e929f05591 + +### File: +src/main/java/net/rithms/riot/api/request/AsyncRequest.java + +### Key: +AsyncRequest.java|cancel|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +45d46ed2a0dc78a99d2800f1059e7864 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8355/instruction.md b/inferredbugs-8355/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6626b81439bfbd2a647ee459d91af749207b8029 --- /dev/null +++ b/inferredbugs-8355/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataSummonerSpell(...)` at line 1609. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SummonerSpell RiotApi.getDataSummonerSpell(int) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataSummonerSpell(int):dto.Static.SummonerSpell.85a3203332765e4d3a30d22ceb7637a8 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataSummonerSpell|NULL_DEREFERENCE + +### Node Key: +71bbd039293bbda847a7c7191bb8b301 + +### Hash: +083142b1ebc3b31fdf96b3e2369526b7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8362/instruction.md b/inferredbugs-8362/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b87b6685b8bbaadc54d32aba3d33fe167c4b673a --- /dev/null +++ b/inferredbugs-8362/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataMastery(...)` at line 1545. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Mastery RiotApi.getDataMastery(int) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataMastery(int):dto.Static.Mastery.509bd5fa5c67f369ca4b99538493b9b6 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataMastery|NULL_DEREFERENCE + +### Node Key: +71bbd039293bbda847a7c7191bb8b301 + +### Hash: +17c1219b56fb53e4a9b87d0c914ab0e2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8363/instruction.md b/inferredbugs-8363/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..56b2ffe3c09e0bae0d72147733ea22e2838022ed --- /dev/null +++ b/inferredbugs-8363/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataItemList(...)` at line 1369. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +ItemList RiotApi.getDataItemList() + +### Procedure Id: +main.java.riotapi.RiotApi.getDataItemList():dto.Static.ItemList.734a7cdb2ccc6d2020b4a97ca6a89ba9 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataItemList|NULL_DEREFERENCE + +### Node Key: +d46e1684de2ca326ba231ad8a5b48143 + +### Hash: +e99bd4c5f6b9ff2f88f3260d9bbd0c15 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8364/instruction.md b/inferredbugs-8364/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ab911ff79d79aa2c90a9ec132d22133d0916c160 --- /dev/null +++ b/inferredbugs-8364/instruction.md @@ -0,0 +1,497 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.rithms.riot.api.request; + +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.lang.reflect.Type; +import java.net.HttpURLConnection; +import java.net.SocketTimeoutException; +import java.net.URL; +import java.util.logging.Level; + +import com.google.gson.Gson; +import com.google.gson.JsonSyntaxException; + +import net.rithms.riot.api.ApiConfig; +import net.rithms.riot.api.ApiMethod; +import net.rithms.riot.api.HttpHeadParameter; +import net.rithms.riot.api.RateLimitException; +import net.rithms.riot.api.RiotApi; +import net.rithms.riot.api.RiotApiException; + +/** + * This class is used to fire synchronous call at the Riot Api. You should not construct these requests manually. To fire synchronous + * requests, use a {@link RiotApi} object. + * + * @author Daniel 'Linnun' Figge + * @see RiotApi + */ +public class Request { + public static final int CODE_SUCCESS_OK = 200; + public static final int CODE_SUCCESS_NO_CONTENT = 204; + public static final int CODE_ERROR_BAD_REQUEST = 400; + public static final int CODE_ERROR_UNAUTHORIZED = 401; + public static final int CODE_ERROR_FORBIDDEN = 403; + public static final int CODE_ERROR_NOT_FOUND = 404; + public static final int CODE_ERROR_UNPROCESSABLE_ENTITY = 422; + public static final int CODE_ERROR_RATE_LIMITED = 429; + public static final int CODE_ERROR_SERVER_ERROR = 500; + public static final int CODE_ERROR_SERVICE_UNAVAILABLE = 503; + + private RequestState state = RequestState.Waiting; + private RequestResponse response = null; + + protected ApiConfig config; + protected ApiMethod method; + protected HttpURLConnection connection = null; + private RiotApiException exception = null; + + /** + * Constructs a synchronous request + * + * @param config + * Configuration to use + * @param method + * Api method to call + * @see ApiConfig + * @see ApiMethod + */ + public Request(ApiConfig config, ApiMethod method) throws RateLimitException, RiotApiException { + init(config, method); + execute(); + } + + /** + * Constructs a synchronous request. This allows child classes to create their own constructor. + */ + protected Request() { + } + + /** + * Attempts to cancel the request. This attempt will fail if the request has already been completed, or could not be cancelled for some + * other reason. If successful, and this request has not started when {@code cancel} is called, this request should never run. + * + * @return {@code false} if the request could not be cancelled, typically because it has already completed normally; {@code true} + * otherwise + */ + public boolean cancel() { + if (isDone()) { + return false; + } + state = RequestState.Cancelled; + return true; + } + + /** + * Executes the request + * + * @throws RiotApiException + * If the Riot Api responds with an error code or parsing the response fails + * @throws RateLimitException + * If a rate limit is exceeded + */ + protected synchronized void execute() throws RiotApiException, RateLimitException { + setState(RequestState.Waiting); + try { + URL url = new URL(method.getUrl()); + connection = (HttpURLConnection) url.openConnection(); + setTimeout(); + connection.setDoInput(true); + connection.setInstanceFollowRedirects(false); + connection.setRequestMethod(method.getMethod().name()); + for (HttpHeadParameter p : method.getHttpHeadParameters()) { + connection.setRequestProperty(p.getKey(), p.getValue()); + } + String body = method.getBody(); + if (body != null) { + connection.setRequestProperty("Content-Type", "application/json"); + connection.setDoOutput(true); + DataOutputStream dos = new DataOutputStream(connection.getOutputStream()); + dos.writeBytes(body); + dos.flush(); + dos.close(); + } + + int responseCode = connection.getResponseCode(); + if (responseCode == CODE_ERROR_RATE_LIMITED) { + String retryAfterString = connection.getHeaderField("Retry-After"); + String rateLimitType = connection.getHeaderField("X-Rate-Limit-Type"); + if (retryAfterString != null) { + int retryAfter = Integer.parseInt(retryAfterString); + throw new RateLimitException(retryAfter, rateLimitType); + } else { + throw new RateLimitException(0, rateLimitType); + } + } else if (responseCode < 200 || responseCode >= 300) { + throw new RiotApiException(responseCode); + } + + StringBuilder responseBodyBuilder = new StringBuilder(); + if (responseCode != CODE_SUCCESS_NO_CONTENT) { + BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); + String line; + while ((line = br.readLine()) != null) { + responseBodyBuilder.append(line).append(System.lineSeparator()); + } + br.close(); + } + setResponse(new RequestResponse(connection.getResponseCode(), responseBodyBuilder.toString(), connection.getHeaderFields())); + setState(RequestState.Succeeded); + } catch (RiotApiException e) { + setException(e); + setState(RequestState.Failed); + throw e; + } catch (SocketTimeoutException e) { + RiotApiException exception = new RiotApiException(RiotApiException.TIMEOUT_EXCEPTION); + setException(exception); + setState(RequestState.TimeOut); + RiotApi.log.log(Level.FINE, "Request Timeout", e); + throw exception; + } catch (IOException e) { + RiotApiException exception = new RiotApiException(RiotApiException.IOEXCEPTION); + setException(exception); + setState(RequestState.Failed); + RiotApi.log.log(Level.SEVERE, "IOException in Request", e); + throw exception; + } finally { + if (connection != null) { + connection.disconnect(); + } + } + } + + /** + * Retrieves the result of the request. + * + * @return The object returned by the api call + * @throws IllegalStateException + * If this request did not complete yet or did not succeed + * @throws RiotApiException + * If parsing the Riot Api's response fails + */ + public T getDto() throws RiotApiException, RateLimitException { + return getDto(false); + } + + /** + * Retrieves the result of the request. + * + * @param overrideStateRequirement + * If set to {@code true}, this method will not check the status of the request, and thus not throw an + * {@code IllegalStateException} + * @return The object returned by the api call + * @throws IllegalStateException + * If this request did not complete yet or did not succeed + * @throws RiotApiException + * If parsing the Riot Api's response fails + */ + @SuppressWarnings("unchecked") + protected T getDto(boolean overrideStateRequirement) throws RiotApiException { + if (!overrideStateRequirement) { + requireSucceededRequestState(); + } + Class clazz = method.getDtoClass(); + if (clazz != null) { + return (T) getDto((Class) clazz); + } + Type type = method.getDtoType(); + if (type != null) { + return getDto(type); + } + throw new NullPointerException( + "The ApiMethod \"" + method.getClass().getName() + "\" has not set a dtoType. If you encounter this issue, please file a bug."); + } + + private T getDto(Class desiredDto) throws RiotApiException { + if (response.getCode() == CODE_SUCCESS_NO_CONTENT) { + // The Riot Api is fine with the request, and explicitly sends no content + return null; + } + T dto = null; + try { + dto = new Gson().fromJson(response.getBody(), desiredDto); + } catch (JsonSyntaxException e) { + RiotApiException exception = new RiotApiException(RiotApiException.PARSE_FAILURE); + setException(exception); + throw exception; + } + if (dto == null) { + RiotApiException exception = new RiotApiException(RiotApiException.PARSE_FAILURE); + setException(exception); + throw exception; + } + return dto; + } + + private T getDto(Type desiredDto) throws RiotApiException { + if (response.getCode() == CODE_SUCCESS_NO_CONTENT) { + // The Riot Api is fine with the request, and explicitly sends no content + return null; + } + T dto = null; + try { + dto = new Gson().fromJson(response.getBody(), desiredDto); + } catch (JsonSyntaxException e) { + RiotApiException exception = new RiotApiException(RiotApiException.PARSE_FAILURE); + setException(exception); + throw exception; + } + if (dto == null) { + RiotApiException exception = new RiotApiException(RiotApiException.PARSE_FAILURE); + setException(exception); + throw exception; + } + return dto; + } + + /** + * Returns the exception that was thrown when calling {@link #execute()}. + * + * @return The exception that was thrown when executing this request + */ + public RiotApiException getException() { + if (!isFailed()) { + return null; + } + return exception; + } + + /** + * Returns the raw response from the Riot Api + * + * @return A {@link RequestResponse} object, providing raw data of the Riot Api's response + * @see RequestResponse + */ + public RequestResponse getResponse() { + return response; + } + + /** + * Initializes the request object. Child classes should call this method instead of the super constructor, if they don't want the + * request to execute automatically. + * + * @param config + * ApiConfig object + * @param method + * ApiMethod object + * @see ApiConfig + * @see ApiMethod + */ + protected void init(ApiConfig config, ApiMethod method) { + this.config = config; + this.method = method; + } + + /** + * Returns {@code true} if this request was cancelled before it completed normally. + * + * @return {@code true} if this request was cancelled before it completed + */ + public boolean isCancelled() { + return state == RequestState.Cancelled; + } + + /** + * Returns {@code true} if this request completed. Completion may be due to normal termination, an exception, cancellation or timing out + * -- in all of these cases, this method will return {@code true}. + * + * @return {@code true} if this request completed + */ + public boolean isDone() { + return state != RequestState.Waiting; + } + + /** + * Returns {@code true} if this request failed. + * + * @return {@code true} if this request failed + */ + public boolean isFailed() { + return state == RequestState.Failed; + } + + /** + * Returns {@code true} if this request is still waiting for a response from the Riot Api. + * + * @return {@code true} if this request is still waiting for a response + */ + public boolean isPending() { + return state == RequestState.Waiting; + } + + /** + * Returns {@code true} if this request completed successfully. + * + * @return {@code true} if this request completed successfully + */ + public boolean isSuccessful() { + return state == RequestState.Succeeded; + } + + /** + * Returns {@code true} if this request timed out before it completed normally. + * + * @return {@code true} if this request timed out before it completed + */ + public boolean isTimeOut() { + return state == RequestState.TimeOut; + } + + /** + * Checks that the current state of this request is succeeded. + * + * @throws IllegalStateException + * If the state of this request is anything other than {@code RequestState.Succeeded}. + */ + protected void requireSucceededRequestState() { + if (state == RequestState.Waiting) { + throw new IllegalStateException("The request has not received a response yet"); + } else if (state == RequestState.Cancelled) { + throw new IllegalStateException("The request has been cancelled"); + } else if (state == RequestState.Failed) { + throw new IllegalStateException("The request has failed"); + } + } + + /** + * Sets the Exception that was thrown when executing this request + * + * @param exception + * Exception + * @see RiotApiException + */ + protected void setException(RiotApiException exception) { + this.exception = exception; + } + + private void setResponse(RequestResponse response) { + this.response = response; + } + + /** + * Sets the state of this request, if the request is not already done. + * + * @param state + * State + * @return {@code true} if the state has been changed + * @see RequestState + */ + protected boolean setState(RequestState state) { + if (isDone()) { + return false; + } + this.state = state; + return true; + } + + /** + * Sets the timeout according to the {@link ApiConfig} object, associated with this request. + */ + protected void setTimeout() { + setTimeout(config.getRequestTimeout()); + } + + /** + * Sets a specified timeout value, in milliseconds, until connecting to or reading from the Riot Api times out. + * + * @param timeout + * Timeout value in milliseconds + */ + protected void setTimeout(int timeout) { + if (connection != null && timeout > 0) { + connection.setConnectTimeout(timeout); + connection.setReadTimeout(timeout); + } + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `net.rithms.riot.api.request.Request.getException` indirectly reads without synchronization from `this.net.rithms.riot.api.request.Request.state`. Potentially races with write in method `Request.execute()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +RiotApiException Request.getException() + +### Procedure Id: +net.rithms.riot.api.request.Request.getException():net.rithms.riot.api.RiotApiException.d0163e0886ae26365f53323f8b8bc3f9 + +### File: +src/net/rithms/riot/api/request/Request.java + +### Key: +Request.java|getException|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +35ec52cf81a69cd558857e257c889b34 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8365/instruction.md b/inferredbugs-8365/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..741d1936c26d4240a15e2d259f1df2d33d42b4c8 --- /dev/null +++ b/inferredbugs-8365/instruction.md @@ -0,0 +1,1906 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riot-api-java +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package main.java.riotapi; + +/** + * Riot Games API Java Library + * riot-api-java + * by Taylor Caldwell - @rithms + * http://rithms.im + */ + +/* + * Copyright 2014 Taylor Caldwell + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import java.util.List; +import java.util.Map; + +import constant.PlatformId; +import constant.QueueType; +import constant.Region; +import constant.Season; +import constant.staticdata.ChampData; +import constant.staticdata.ItemData; +import constant.staticdata.ItemListData; +import constant.staticdata.MasteryData; +import constant.staticdata.MasteryListData; +import constant.staticdata.RuneData; +import constant.staticdata.RuneListData; +import constant.staticdata.SpellData; +import dto.Champion.*; +import dto.CurrentGame.CurrentGameInfo; +import dto.FeaturedGames.FeaturedGames; +import dto.Game.RecentGames; +import dto.League.League; +import dto.Match.MatchDetail; +import dto.MatchHistory.PlayerHistory; +import dto.Team.Team; +import dto.Static.ChampionList; +import dto.Static.GameMapList; +import dto.Static.Item; +import dto.Static.ItemList; +import dto.Static.LanguageStrings; +import dto.Static.Mastery; +import dto.Static.MasteryList; +import dto.Static.Realm; +import dto.Static.Rune; +import dto.Static.RuneList; +import dto.Static.SummonerSpell; +import dto.Static.SummonerSpellList; +import dto.Stats.PlayerStatsSummaryList; +import dto.Stats.RankedStats; +import dto.Status.Shard; +import dto.Status.ShardStatus; +import dto.Summoner.MasteryPages; +import dto.Summoner.RunePages; +import dto.Summoner.Summoner; +import method.*; + +public class RiotApi { + + /** + * The base URL for all API requests + */ + private String endpoint = Region.GLOBAL.getEndpoint(); + + private Region region = Region.NA; // North American region default + private Season season = null; + private String key; + + public RiotApi() { + } + + public RiotApi(String key) { + this.setKey(key); + } + + public RiotApi(String key, Region region) { + this.setKey(key); + this.setRegion(region); + } + + /** + * Get all the champions for a set region + * + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey()); + } + + /** + * Get all the champions for a given region + * + * @param region The desired region + * @return A list of all the champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * Get all the champions for a set region + * + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the set region when + * freeToPlay is true A list of all the champions for the set region when + * freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), freeToPlay); + } + + /** + * Get all champions for a given region + * + * @param region The desired region + * @param freeToPlay Only free to play + * @return A list of all the free to play champions for the given region + * when freeToPlay is true A list of all the champions for the given region + * when freeToPlay is false + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getChampions(Region region, boolean freeToPlay) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), freeToPlay); + } + + /** + * Get all free to play champions for a given region + * + * @param region The desired region + * @return A list of all the free to play champions for the given region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions(Region region) throws RiotApiException { + + return ChampionMethod.getChampions(region.getEndpoint(), region.getName(), getKey(), true); + } + + /** + * Get all free to play champions for a set region + * + * @return A list of all the free to play champions for the set region + * @see ChampionList + * @throws RiotApiException + */ + public dto.Champion.ChampionList getFreeToPlayChampions() throws RiotApiException { + + return ChampionMethod.getChampions(getEndpoint(), getRegion(), getKey(), true); + } + + /** + * Get a champion by id for a given region + * + * @param region The desired region + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(Region region, int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(region.getEndpoint(), region.getName(), getKey(), champId); + } + + /** + * Get a champion by id for a set region + * + * @param champId The ID of the desired champion + * @return The champion of the given ID + * @see ChampionList + * @throws RiotApiException + */ + public Champion getChampionById(int champId) throws RiotApiException { + + return ChampionMethod.getChampionById(getEndpoint(), getRegion(), getKey(), champId); + } + + /** + * Get recent games for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(Region region, long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get recent games for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Recent games of the given summoner + * @see RecentGames + * @throws RiotApiException + */ + public RecentGames getRecentGames(long summonerId) throws RiotApiException { + + return GameMethod.getRecentGames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(long... summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueBySummoners(String summonerIds) throws RiotApiException { + return LeagueMethod.getLeagueBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * + * @param region + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(Region region, String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * + * @param summonerIds + * @throws RiotApiException + */ + public Map> getLeagueEntryBySummoners(String summonerIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryBySummoners(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(long... teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(Region region, String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(region.getEndpoint(), region.getName(), getKey(), teamIds); + } + + /** + * + * @param teamIds + * @throws RiotApiException + */ + public Map> getLeagueEntryByTeams(String teamIds) throws RiotApiException { + + return LeagueMethod.getLeagueEntryByTeams(getEndpoint(), getRegion(), getKey(), teamIds); + } + + /** + * + * @param region + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey()); + } + + /** + * + * @throws RiotApiException + */ + public League getChallengerLeagues() throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey()); + } + + /** + * + * @param region + * @param queueType + * @throws RiotApiException + */ + public League getChallengerLeagues(Region region, QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(region.getEndpoint(), region.getName(), getKey(), queueType); + } + + /** + * + * @param queueType + * @throws RiotApiException + * @return League + */ + public League getChallengerLeagues(QueueType queueType) throws RiotApiException { + + return LeagueMethod.getChallengerLeagues(getEndpoint(), getRegion(), getKey(), queueType); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get a summary of player statistics for a given summoner + * + * @param summonerId The ID of the desired summoner + * @return A summary of player statistics for the given summoner + * @see PlayerStatsSummaryList + * @throws RiotApiException + */ + public PlayerStatsSummaryList getPlayerStatsSummary(long summonerId) throws RiotApiException { + + return StatsMethod.getPlayerStatsSummary(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @param season The desired season + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Season season, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), season.getName(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(Region region, long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(region.getEndpoint(), region.getName(), getSeason(), getKey(), summonerId); + } + + /** + * Get the ranked statistics of a given summoner + * + * @param summonerId The ID of the desired summoner + * @return Ranked statistics of the given summoner + * @see RankedStats + * @throws RiotApiException + */ + public RankedStats getRankedStats(long summonerId) throws RiotApiException { + + return StatsMethod.getRankedStats(getEndpoint(), getRegion(), getSeason(), getKey(), summonerId); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the mastery pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of mastery pages of the given summoners + * @see MasteryPages + * @throws RiotApiException + */ + public Map getMasteryPages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getMasteryPages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(String summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get the rune pages of a given summoner + * + * @param summonerIds The IDs of the desired summoners + * @return A map of rune pages of the given summoners + * @see RunePages + * @throws RiotApiException + */ + public Map getRunePages(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getRunePages(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(Region region, String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerNames); + } + + /** + * Get summoners by names + * + * @param summonerNames The names of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersByName(String summonerNames) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerNames); + } + + /** + * Get summoner by name + * + * @param region The desired region + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(Region region, String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(region.getEndpoint(), region.getName(), getKey(), summonerName); + } + + /** + * Get summoner by name + * + * @param summonerName The name of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerByName(String summonerName) throws RiotApiException { + + return SummonerMethod.getSummonersByName(getEndpoint(), getRegion(), getKey(), summonerName); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonersById(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param region The desired region + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoners by names + * + * @param summonerId The IDs of the desired summoners + * @return A map of desired summoners + * @see Summoner + * @throws RiotApiException + */ + public Map getSummonerById(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonersById(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds The IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(long... summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(Region region, String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param summonerIds A comma separated list of IDs of the desired summoners + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerNames(String summonerIds) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The IDs of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(long summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(Region region, String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(region.getEndpoint(), region.getName(), getKey(), summonerId); + } + + /** + * Get summoner names by IDs + * + * @param summonerId The ID of the desired summoner + * @return A map of desired summoner names + * @throws RiotApiException + */ + public Map getSummonerName(String summonerId) throws RiotApiException { + + return SummonerMethod.getSummonerNames(getEndpoint(), getRegion(), getKey(), summonerId); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds A list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(long... summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param region The desired region + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(Region region, String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(region.getEndpoint(), region.getName(), getKey(), summonerIds); + } + + /** + * Get teams by summonerIDs + * + * @param summonerIds Comma-separated list of summoner IDs + * @return A map of the summoners' teams + * @see Team + * @throws RiotApiException + */ + public Map> getTeamsBySummonerIds(String summonerIds) throws RiotApiException { + + return TeamMethod.getTeamsBySummonerIds(getEndpoint(), getRegion(), getKey(), summonerIds); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId); + } + + /** + * Get match by ID + * + * @param region The desired region + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(Region region, long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(region.getEndpoint(), region.getName(), getKey(), matchId, includeTimeline); + } + + /** + * Get match by ID + * + * @param matchId The ID of the match + * @param includeTimeline Flag indicating whether or not to include match timeline data + * @return A map with match details + * @see MatchDetail + * @throws RiotApiException + */ + public MatchDetail getMatch(long matchId, boolean includeTimeline) throws RiotApiException { + + return MatchMethod.getMatch(getEndpoint(), getRegion(), getKey(), matchId, includeTimeline); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param region The desired region + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(Region region, long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(region.getEndpoint(), region.getName(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param championIds Comma-separated list of champion IDs to use for fetching games. + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String championIds, String rankedQueues) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, championIds, rankedQueues, -1, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param rankedQueues Comma-separated list of ranked queue types to use for fetching games + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, String rankedQueues, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, rankedQueues, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @param endIndex The end index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex, int endIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, endIndex); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @param beginIndex The begin index to use for fetching games + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId, int beginIndex) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, beginIndex, -1); + } + + /** + * Get match history by summonerID + * + * @param summonerId The ID of the desired summoner + * @return A list with matches + * @see PlayerHistory + * @throws RiotApiException + */ + public PlayerHistory getMatchHistory(long summonerId) throws RiotApiException { + + return MatchHistoryMethod.getMatchHistory(getEndpoint(), getRegion(), getKey(), summonerId, null, null, -1, -1); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), locale, version, dataById, champData); + } + + /** + * + */ + public ChampionList getDataChampionList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataChampionList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public ChampionList getDataChampionList() throws RiotApiException { + + return StaticDataMethod.getDataChampionList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id, String locale, String version, boolean dataById, ChampData champData) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, locale, version, dataById, champData); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(region.getName(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public dto.Static.Champion getDataChampion(int id) throws RiotApiException { + + return StaticDataMethod.getDataChampion(getRegion(), getKey(), id, null, null, false, null); + } + + /** + * + */ + public ItemList getDataItemList(Region region, String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(String locale, String version, ItemListData itemListData) throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), locale, version, itemListData); + } + + /** + * + */ + public ItemList getDataItemList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataItemList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public ItemList getDataItemList() throws RiotApiException { + + return StaticDataMethod.getDataItemList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Item getDataItem(Region region, int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(int id, String locale, String version, ItemData itemData) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, locale, version, itemData); + } + + /** + * + */ + public Item getDataItem(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Item getDataItem(int id) throws RiotApiException { + + return StaticDataMethod.getDataItem(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public Realm getDataRealm(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRealm(region.getName(), getKey()); + } + + /** + * + */ + public Realm getDataRealm() throws RiotApiException { + + return StaticDataMethod.getDataRealm(getRegion(), getKey()); + } + + /** + * + */ + public RuneList getDataRuneList(Region region, String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(String locale, String version, RuneListData runeListData) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), locale, version, runeListData); + } + + /** + * + */ + public RuneList getDataRuneList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataRuneList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public RuneList getDataRuneList() throws RiotApiException { + + return StaticDataMethod.getDataRuneList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Rune getDataRune(Region region, int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(int id, String locale, String version, RuneData runeData) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, locale, version, runeData); + } + + /** + * + */ + public Rune getDataRune(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Rune getDataRune(int id) throws RiotApiException { + + return StaticDataMethod.getDataRune(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region, String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(String locale, String version, MasteryListData masteryListData) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), locale, version, masteryListData); + } + + /** + * + */ + public MasteryList getDataMasteryList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(region.getName(), getKey(), null, null, null); + } + + /** + * + */ + public MasteryList getDataMasteryList() throws RiotApiException { + + return StaticDataMethod.getDataMasteryList(getRegion(), getKey(), null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(int id, String locale, String version, MasteryData masteryData) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, locale, version, masteryData); + } + + /** + * + */ + public Mastery getDataMastery(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public Mastery getDataMastery(int id) throws RiotApiException { + + return StaticDataMethod.getDataMastery(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region, String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(String locale, String version, boolean dataById, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), locale, version, dataById, spellData); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(region.getName(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpellList getDataSummonerSpellList() throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpellList(getRegion(), getKey(), null, null, false, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id, String locale, String version, SpellData spellData) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, locale, version, spellData); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(Region region, int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(region.getName(), getKey(), id, null, null, null); + } + + /** + * + */ + public SummonerSpell getDataSummonerSpell(int id) throws RiotApiException { + + return StaticDataMethod.getDataSummonerSpell(getRegion(), getKey(), id, null, null, null); + } + + /** + * + */ + public List getDataVersions(Region region) throws RiotApiException { + + return StaticDataMethod.getDataVersions(region.getName(), getKey()); + } + + /** + * + */ + public List getDataVersions() throws RiotApiException { + + return StaticDataMethod.getDataVersions(getRegion(), getKey()); + } + + /** + * + */ + public List getDataLanguages(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguages(region.getName(), getKey()); + } + + /** + * + */ + public List getDataLanguages() throws RiotApiException { + + return StaticDataMethod.getDataLanguages(getRegion(), getKey()); + } + + /** + * + */ + public List getShards() throws RiotApiException { + + return StatusMethod.getShards(); + } + + /** + * + */ + public ShardStatus getShardStatus(Region region) throws RiotApiException { + + return StatusMethod.getShardStatus(region.getName()); + } + + /** + * + */ + public ShardStatus getShardStatus() throws RiotApiException { + + return StatusMethod.getShardStatus(getRegion()); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public GameMapList getDataGameMapList(Region region) throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(region.getName(), getKey(), null, null); + } + + /** + * + */ + public GameMapList getDataGameMapList() throws RiotApiException { + + return StaticDataMethod.getDataGameMapList(getRegion(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region, String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(String locale, String version) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), locale, version); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings(Region region) throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(region.getName(), getKey(), null, null); + } + + /** + * + */ + public LanguageStrings getDataLanguageStrings() throws RiotApiException { + + return StaticDataMethod.getDataLanguageStrings(getRegion(), getKey(), null, null); + } + + /** + * + */ + public FeaturedGames getFeaturedGames(Region region) throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(region.getName(), getKey()); + } + + /** + * + */ + public FeaturedGames getFeaturedGames() throws RiotApiException { + + return FeaturedGamesMethod.getFeaturedGames(getRegion(), getKey()); + } + + /** + * + */ + public CurrentGameInfo getCurrentGameInfo(PlatformId platformId, long summonerId) throws RiotApiException { + + return CurrentGameMethod.getCurrentGameInfo(platformId, getKey(), summonerId); + } + + /** + * Get the currently set season + * + * @return The currently set season + */ + public String getSeason() { + if(season == null){ + return null; + } + return season.getName(); + } + + /** + * Get the currently set API key + * + * @return The currently set API key + */ + public String getKey() { + return key; + } + + /** + * Get the currently set region + * + * @return The currently set region + * @throws + */ + public String getRegion() { + return region.getName(); + } + + /** + * Set the season + * + * @param season The season to set + */ + public void setSeason(Season season) { + this.season = season; + } + + /** + * Set the API key + * + * @param key The API key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the region + * + * @param region The region to set + */ + public void setRegion(Region region) { + this.region = region; + setEndpoint(); + } + + /** + * Get the base URL for all API requests + * + * @return The base URL for all API requests + */ + public String getEndpoint() { + return endpoint; + } + + private void setEndpoint() { + this.endpoint = region.getEndpoint(); + } + + public RiotApi clone() { + return new RiotApi(this.key, this.region); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `getDataSummonerSpellList(...)` at line 1569. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SummonerSpellList RiotApi.getDataSummonerSpellList(Region) + +### Procedure Id: +main.java.riotapi.RiotApi.getDataSummonerSpellList(constant.Region):dto.Static.SummonerSpellList.3dff58f90a47cfc1a46e56395a8c28c2 + +### File: +src/main/java/riotapi/RiotApi.java + +### Key: +RiotApi.java|getDataSummonerSpellList|NULL_DEREFERENCE + +### Node Key: +d46e1684de2ca326ba231ad8a5b48143 + +### Hash: +19f2a92caa9362375788971929228174 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8390/instruction.md b/inferredbugs-8390/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..efb4b7155c12f66256015c5a52c35bb404fbb684 --- /dev/null +++ b/inferredbugs-8390/instruction.md @@ -0,0 +1,456 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim.model; + +import static org.fim.util.FormatUtil.formatCreationTime; +import static org.fim.util.FormatUtil.formatDate; +import static org.fim.util.FormatUtil.formatLastModified; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.fim.util.Console; + +public class CompareResult +{ + public static final String NOTHING = "[nothing]"; + + private static final Comparator fileNameComparator = new Difference.FileNameComparator(); + + private List added; + private List copied; + private List duplicated; + private List dateModified; + private List contentModified; + private List attributesModified; + private List renamed; + private List deleted; + private List corrupted; + + private Context context; + private State lastState; + private boolean searchForHardwareCorruption; + + public CompareResult(Context context, State lastState) + { + this.context = context; + this.lastState = lastState; + this.searchForHardwareCorruption = false; + + added = new ArrayList<>(); + copied = new ArrayList<>(); + duplicated = new ArrayList<>(); + dateModified = new ArrayList<>(); + contentModified = new ArrayList<>(); + attributesModified = new ArrayList<>(); + renamed = new ArrayList<>(); + deleted = new ArrayList<>(); + corrupted = new ArrayList<>(); + } + + public boolean isSearchForHardwareCorruption() + { + return searchForHardwareCorruption; + } + + public void setSearchForHardwareCorruption(boolean searchForHardwareCorruption) + { + this.searchForHardwareCorruption = searchForHardwareCorruption; + } + + public void sortResults() + { + sortDifferences(added); + sortDifferences(copied); + sortDifferences(duplicated); + sortDifferences(dateModified); + sortDifferences(contentModified); + sortDifferences(attributesModified); + sortDifferences(renamed); + sortDifferences(deleted); + sortDifferences(corrupted); + } + + private void sortDifferences(List differences) + { + Collections.sort(differences, fileNameComparator); + } + + public CompareResult displayChanges() + { + if (lastState != null) + { + System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); + if (lastState.getComment().length() > 0) + { + System.out.println("Comment: " + lastState.getComment()); + } + Console.newLine(); + } + + if (!context.isVerbose()) + { + displayCounts(); + return this; + } + + String stateFormat = "%-17s "; + + for (Difference diff : added) + { + System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName()); + } + + for (Difference diff : copied) + { + System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()); + } + + for (Difference diff : duplicated) + { + System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : dateModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : contentModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : attributesModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : renamed) + { + System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : deleted) + { + System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName()); + } + + for (Difference diff : corrupted) + { + System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + if (somethingModified()) + { + Console.newLine(); + } + + displayCounts(); + + return this; + } + + private String formatModifiedAttributes(Difference diff, boolean nextLine) + { + int modifCount = 0; + StringBuilder modification = new StringBuilder(nextLine ? " " : ""); // Put a white space to force to add a separator + + Map previousFileAttributes = diff.getPreviousFileState().getFileAttributes(); + Map currentFileAttributes = diff.getFileState().getFileAttributes(); + for (FileAttribute attribute : FileAttribute.values()) + { + String key = attribute.name(); + String previousValue = getValue(previousFileAttributes, key); + String currentValue = getValue(currentFileAttributes, key); + + if (false == Objects.equals(previousValue, currentValue)) + { + modifCount++; + addSeparator(diff, modification); + modification.append(key).append(": ").append(previousValue).append(" -> ").append(currentValue); + } + } + + if (diff.isCreationTimeChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("creationTime: ").append(formatCreationTime(diff.getPreviousFileState())).append(" -> ").append(formatCreationTime(diff.getFileState())); + } + + if (diff.isLastModifiedChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("lastModified: ").append(formatLastModified(diff.getPreviousFileState())).append(" -> ").append(formatLastModified(diff.getFileState())); + } + + if (modifCount > 1) + { + modification.append('\n'); + } + + return modification.toString(); + } + + private void addSeparator(Difference diff, StringBuilder modification) + { + if (modification.length() == 0) + { + return; + } + + modification.append("\n"); + int len = 17 + 1 + diff.getFileState().getFileName().length() + 1; + for (int index = 0; index < len; index++) + { + modification.append(' '); + } + modification.append('\t'); + } + + private String getValue(Map attributes, String key) + { + String value = attributes != null ? attributes.get(key) : null; + if (value == null || value.length() == 0) + { + value = NOTHING; + } + return value; + } + + public CompareResult displayCounts() + { + if (somethingModified()) + { + String message = ""; + if (!added.isEmpty()) + { + message += "" + added.size() + " added, "; + } + + if (!copied.isEmpty()) + { + message += "" + copied.size() + " copied, "; + } + + if (!duplicated.isEmpty()) + { + message += "" + duplicated.size() + " duplicated, "; + } + + if (!dateModified.isEmpty()) + { + message += "" + dateModified.size() + " date modified, "; + } + + if (!attributesModified.isEmpty()) + { + message += "" + attributesModified.size() + " attrs. modified, "; + } + + if (!contentModified.isEmpty()) + { + message += "" + contentModified.size() + " content modified, "; + } + + if (!renamed.isEmpty()) + { + message += "" + renamed.size() + " renamed, "; + } + + if (!deleted.isEmpty()) + { + message += "" + deleted.size() + " deleted, "; + } + + if (!corrupted.isEmpty()) + { + message += "" + corrupted.size() + " corrupted, "; + } + + message = message.replaceAll(", $", ""); + System.out.println(message); + } + else + { + if (isSearchForHardwareCorruption()) + { + System.out.println("Nothing corrupted"); + } + else + { + System.out.println("Nothing modified"); + } + } + + return this; + } + + public boolean somethingModified() + { + return modifiedCount() > 0; + } + + public int modifiedCount() + { + return added.size() + copied.size() + duplicated.size() + dateModified.size() + contentModified.size() + + attributesModified.size() + renamed.size() + deleted.size() + corrupted.size(); + } + + public ModificationCounts getModificationCounts() + { + ModificationCounts modificationCounts = new ModificationCounts(); + modificationCounts.setAdded(added.size()); + modificationCounts.setCopied(copied.size()); + modificationCounts.setDuplicated(duplicated.size()); + modificationCounts.setDateModified(dateModified.size()); + modificationCounts.setContentModified(contentModified.size()); + modificationCounts.setAttributesModified(attributesModified.size()); + modificationCounts.setRenamed(renamed.size()); + modificationCounts.setDeleted(deleted.size()); + + return modificationCounts; + } + + public List getAdded() + { + return added; + } + + public List getCopied() + { + return copied; + } + + public List getDuplicated() + { + return duplicated; + } + + public List getDateModified() + { + return dateModified; + } + + public List getContentModified() + { + return contentModified; + } + + public List getAttributesModified() + { + return attributesModified; + } + + public List getRenamed() + { + return renamed; + } + + public List getDeleted() + { + return deleted; + } + + public List getCorrupted() + { + return corrupted; + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CompareResult CompareResult.displayChanges() + +### Procedure Id: +org.fim.model.CompareResult.displayChanges():org.fim.model.CompareResult.a1ae9cd3721eb660a7fec409bf8af966 + +### File: +src/main/java/org/fim/model/CompareResult.java + +### Key: +CompareResult.java|displayChanges|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8f5f91250d216a5d69d5b79057aab607 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8391/instruction.md b/inferredbugs-8391/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69145ce0f336585fd137b6357a76a825899939e0 --- /dev/null +++ b/inferredbugs-8391/instruction.md @@ -0,0 +1,411 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim.internal; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.time.DurationFormatUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.fim.model.FileState; +import org.fim.model.HashMode; +import org.fim.model.Parameters; +import org.fim.model.State; +import org.fim.util.Logger; + +public class StateGenerator +{ + public static final int PROGRESS_DISPLAY_FILE_COUNT = 10; + public static final int FILES_QUEUE_CAPACITY = 500; + + private static final Set ignoredDirectories = new HashSet<>(Arrays.asList(Parameters.DOT_FIM_DIR, ".git", ".svn", ".cvs")); + + private static final Pair[] hashProgress = new Pair[] + { + Pair.of('.', 0), + Pair.of('o', FileState.SIZE_20_MB), + Pair.of('O', FileState.SIZE_50_MB), + Pair.of('@', FileState.SIZE_100_MB), + Pair.of('#', FileState.SIZE_200_MB) + }; + + private static Comparator fileNameComparator = new FileState.FileNameComparator(); + + private final Parameters parameters; + private final ReentrantLock progressLock; + + private ExecutorService executorService; + private long summedFileLength; + private int fileCount; + private long totalFileContentLength; + + private Path fimRepositoryRootDir; + private BlockingDeque filesToHash; + private boolean hashersStarted; + private List hashers; + private long totalBytesHashed; + + public StateGenerator(Parameters parameters) + { + this.parameters = parameters; + this.progressLock = new ReentrantLock(); + } + + public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException + { + this.fimRepositoryRootDir = fimRepositoryRootDir; + + Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount())); + if (displayHashLegend()) + { + System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend()); + } + + State state = new State(); + state.setComment(comment); + + long start = System.currentTimeMillis(); + progressOutputInit(); + + filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY); + InitializeFileHashers(); + + scanFileTree(filesToHash, fimRepositoryRootDir); + + // In case the FileHashers have not been started + startFileHashers(); + + waitAllFilesToBeHashed(); + + for (FileHasher hasher : hashers) + { + state.getFileStates().addAll(hasher.getFileStates()); + totalFileContentLength += hasher.getTotalFileContentLength(); + totalBytesHashed += hasher.getTotalBytesHashed(); + } + + Collections.sort(state.getFileStates(), fileNameComparator); + + progressOutputStop(); + displayStatistics(start, state); + + return state; + } + + private void InitializeFileHashers() + { + hashersStarted = false; + hashers = new ArrayList<>(); + executorService = Executors.newFixedThreadPool(parameters.getThreadCount()); + } + + private void startFileHashers() throws NoSuchAlgorithmException + { + if (!hashersStarted) + { + for (int index = 0; index < parameters.getThreadCount(); index++) + { + FileHasher hasher = new FileHasher(this, filesToHash, fimRepositoryRootDir.toString()); + executorService.submit(hasher); + hashers.add(hasher); + } + hashersStarted = true; + } + } + + private String hashModeToString() + { + switch (parameters.getHashMode()) + { + case DONT_HASH_FILES: + return "retrieving only file attributes"; + + case HASH_ONLY_FIRST_FOUR_KILO: + return "hashing only first four kilo"; + + case HASH_ONLY_FIRST_MEGA: + return "hashing only first mega"; + + case COMPUTE_ALL_HASH: + return "computing all hash"; + } + + throw new IllegalArgumentException("Invalid hash mode " + parameters.getHashMode()); + } + + private void waitAllFilesToBeHashed() + { + try + { + executorService.shutdown(); + executorService.awaitTermination(3, TimeUnit.DAYS); + } + catch (InterruptedException ex) + { + Logger.error(ex); + } + } + + private void displayStatistics(long start, State state) + { + long duration = System.currentTimeMillis() - start; + + String totalFileContentLengthStr = FileUtils.byteCountToDisplaySize(totalFileContentLength); + String totalBytesHashedStr = FileUtils.byteCountToDisplaySize(totalBytesHashed); + String durationStr = DurationFormatUtils.formatDuration(duration, "HH:mm:ss"); + + if (parameters.getHashMode() == HashMode.DONT_HASH_FILES) + { + Logger.info(String.format("Scanned %d files (%s), during %s, using %d thread%n", + state.getFileStates().size(), totalFileContentLengthStr, durationStr, parameters.getThreadCount())); + } + else + { + Logger.info(String.format("Scanned %d files (%s), hashed %s bytes, during %s, using %d thread%n", + state.getFileStates().size(), totalFileContentLengthStr, totalBytesHashedStr, durationStr, parameters.getThreadCount())); + } + } + + private void scanFileTree(BlockingDeque filesToHash, Path directory) throws IOException, NoSuchAlgorithmException + { + try (DirectoryStream stream = Files.newDirectoryStream(directory)) + { + for (Path file : stream) + { + if (!hashersStarted && filesToHash.size() > FILES_QUEUE_CAPACITY / 2) + { + startFileHashers(); + } + + BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attributes.isRegularFile()) + { + try + { + filesToHash.offer(file, 120, TimeUnit.MINUTES); + } + catch (InterruptedException ex) + { + Logger.error(ex); + } + } + else if (attributes.isDirectory()) + { + String fileName = file.getFileName().toString(); + if (ignoredDirectories.contains(fileName)) + { + continue; + } + + scanFileTree(filesToHash, file); + } + } + } + } + + private void progressOutputInit() + { + summedFileLength = 0; + fileCount = 0; + } + + public void updateProgressOutput(long fileSize) throws IOException + { + progressLock.lock(); + try + { + fileCount++; + + if (displayHashLegend()) + { + summedFileLength += fileSize; + + if (fileCount % PROGRESS_DISPLAY_FILE_COUNT == 0) + { + System.out.print(getProgressChar(summedFileLength)); + summedFileLength = 0; + } + } + + if (fileCount % (100 * PROGRESS_DISPLAY_FILE_COUNT) == 0) + { + if (displayHashLegend()) + { + System.out.println(""); + } + } + } + finally + { + progressLock.unlock(); + } + } + + private String hashProgressLegend() + { + StringBuilder sb = new StringBuilder(); + for (int progressIndex = hashProgress.length - 1; progressIndex >= 0; progressIndex--) + { + char marker = hashProgress[progressIndex].getLeft(); + sb.append(marker); + + int fileLength = hashProgress[progressIndex].getRight(); + if (fileLength == 0) + { + sb.append(" otherwise"); + } + else + { + sb.append(" > ").append(FileUtils.byteCountToDisplaySize(fileLength)); + } + sb.append(", "); + } + String legend = sb.toString(); + legend = legend.substring(0, legend.length() - 2); + return legend; + } + + private char getProgressChar(long fileLength) + { + int progressIndex; + for (progressIndex = hashProgress.length - 1; progressIndex >= 0; progressIndex--) + { + if (fileLength > hashProgress[progressIndex].getRight()) + { + break; + } + } + return hashProgress[progressIndex].getLeft(); + } + + private void progressOutputStop() + { + if (displayHashLegend()) + { + if (fileCount > PROGRESS_DISPLAY_FILE_COUNT) + { + System.out.println(""); + } + } + } + + private boolean displayHashLegend() + { + return parameters.isVerbose() && parameters.getHashMode() != HashMode.DONT_HASH_FILES; + } + + public Parameters getParameters() + { + return parameters; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.fim.internal.StateGenerator.generateState` indirectly writes to field `this.org.fim.internal.StateGenerator.fileCount` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +State StateGenerator.generateState(String,Path) + +### Procedure Id: +org.fim.internal.StateGenerator.generateState(java.lang.String,java.nio.file.Path):org.fim.model.Sta.dcefa56923acbef36aa2f70171181cef + +### File: +src/main/java/org/fim/internal/StateGenerator.java + +### Key: +StateGenerator.java|generateState|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +fdab50934677752304e4bc7583e43e51 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8396/instruction.md b/inferredbugs-8396/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37f8560d4a6cb50d8cd876c9f15593ee1321a99b --- /dev/null +++ b/inferredbugs-8396/instruction.md @@ -0,0 +1,456 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 17 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim.model; + +import static org.fim.util.FormatUtil.formatCreationTime; +import static org.fim.util.FormatUtil.formatDate; +import static org.fim.util.FormatUtil.formatLastModified; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.fim.util.Console; + +public class CompareResult +{ + public static final String NOTHING = "[nothing]"; + + private static final Comparator fileNameComparator = new Difference.FileNameComparator(); + + private List added; + private List copied; + private List duplicated; + private List dateModified; + private List contentModified; + private List attributesModified; + private List renamed; + private List deleted; + private List corrupted; + + private Context context; + private State lastState; + private boolean searchForHardwareCorruption; + + public CompareResult(Context context, State lastState) + { + this.context = context; + this.lastState = lastState; + this.searchForHardwareCorruption = false; + + added = new ArrayList<>(); + copied = new ArrayList<>(); + duplicated = new ArrayList<>(); + dateModified = new ArrayList<>(); + contentModified = new ArrayList<>(); + attributesModified = new ArrayList<>(); + renamed = new ArrayList<>(); + deleted = new ArrayList<>(); + corrupted = new ArrayList<>(); + } + + public boolean isSearchForHardwareCorruption() + { + return searchForHardwareCorruption; + } + + public void setSearchForHardwareCorruption(boolean searchForHardwareCorruption) + { + this.searchForHardwareCorruption = searchForHardwareCorruption; + } + + public void sortResults() + { + sortDifferences(added); + sortDifferences(copied); + sortDifferences(duplicated); + sortDifferences(dateModified); + sortDifferences(contentModified); + sortDifferences(attributesModified); + sortDifferences(renamed); + sortDifferences(deleted); + sortDifferences(corrupted); + } + + private void sortDifferences(List differences) + { + Collections.sort(differences, fileNameComparator); + } + + public CompareResult displayChanges() + { + if (lastState != null) + { + System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); + if (lastState.getComment().length() > 0) + { + System.out.println("Comment: " + lastState.getComment()); + } + Console.newLine(); + } + + if (!context.isVerbose()) + { + displayCounts(); + return this; + } + + String stateFormat = "%-17s "; + + for (Difference diff : added) + { + System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName()); + } + + for (Difference diff : copied) + { + System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()); + } + + for (Difference diff : duplicated) + { + System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : dateModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : contentModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : attributesModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : renamed) + { + System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : deleted) + { + System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName()); + } + + for (Difference diff : corrupted) + { + System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + if (somethingModified()) + { + Console.newLine(); + } + + displayCounts(); + + return this; + } + + private String formatModifiedAttributes(Difference diff, boolean nextLine) + { + int modifCount = 0; + StringBuilder modification = new StringBuilder(nextLine ? " " : ""); // Put a white space to force to add a separator + + Map previousFileAttributes = diff.getPreviousFileState().getFileAttributes(); + Map currentFileAttributes = diff.getFileState().getFileAttributes(); + for (FileAttribute attribute : FileAttribute.values()) + { + String key = attribute.name(); + String previousValue = getValue(previousFileAttributes, key); + String currentValue = getValue(currentFileAttributes, key); + + if (false == Objects.equals(previousValue, currentValue)) + { + modifCount++; + addSeparator(diff, modification); + modification.append(key).append(": ").append(previousValue).append(" -> ").append(currentValue); + } + } + + if (diff.isCreationTimeChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("creationTime: ").append(formatCreationTime(diff.getPreviousFileState())).append(" -> ").append(formatCreationTime(diff.getFileState())); + } + + if (diff.isLastModifiedChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("lastModified: ").append(formatLastModified(diff.getPreviousFileState())).append(" -> ").append(formatLastModified(diff.getFileState())); + } + + if (modifCount > 1) + { + modification.append('\n'); + } + + return modification.toString(); + } + + private void addSeparator(Difference diff, StringBuilder modification) + { + if (modification.length() == 0) + { + return; + } + + modification.append("\n"); + int len = 17 + 1 + diff.getFileState().getFileName().length() + 1; + for (int index = 0; index < len; index++) + { + modification.append(' '); + } + modification.append('\t'); + } + + private String getValue(Map attributes, String key) + { + String value = attributes != null ? attributes.get(key) : null; + if (value == null || value.length() == 0) + { + value = NOTHING; + } + return value; + } + + public CompareResult displayCounts() + { + if (somethingModified()) + { + String message = ""; + if (!added.isEmpty()) + { + message += "" + added.size() + " added, "; + } + + if (!copied.isEmpty()) + { + message += "" + copied.size() + " copied, "; + } + + if (!duplicated.isEmpty()) + { + message += "" + duplicated.size() + " duplicated, "; + } + + if (!dateModified.isEmpty()) + { + message += "" + dateModified.size() + " date modified, "; + } + + if (!attributesModified.isEmpty()) + { + message += "" + attributesModified.size() + " attrs. modified, "; + } + + if (!contentModified.isEmpty()) + { + message += "" + contentModified.size() + " content modified, "; + } + + if (!renamed.isEmpty()) + { + message += "" + renamed.size() + " renamed, "; + } + + if (!deleted.isEmpty()) + { + message += "" + deleted.size() + " deleted, "; + } + + if (!corrupted.isEmpty()) + { + message += "" + corrupted.size() + " corrupted, "; + } + + message = message.replaceAll(", $", ""); + System.out.println(message); + } + else + { + if (isSearchForHardwareCorruption()) + { + System.out.println("Nothing corrupted"); + } + else + { + System.out.println("Nothing modified"); + } + } + + return this; + } + + public boolean somethingModified() + { + return modifiedCount() > 0; + } + + public int modifiedCount() + { + return added.size() + copied.size() + duplicated.size() + dateModified.size() + contentModified.size() + + attributesModified.size() + renamed.size() + deleted.size() + corrupted.size(); + } + + public ModificationCounts getModificationCounts() + { + ModificationCounts modificationCounts = new ModificationCounts(); + modificationCounts.setAdded(added.size()); + modificationCounts.setCopied(copied.size()); + modificationCounts.setDuplicated(duplicated.size()); + modificationCounts.setDateModified(dateModified.size()); + modificationCounts.setContentModified(contentModified.size()); + modificationCounts.setAttributesModified(attributesModified.size()); + modificationCounts.setRenamed(renamed.size()); + modificationCounts.setDeleted(deleted.size()); + + return modificationCounts; + } + + public List getAdded() + { + return added; + } + + public List getCopied() + { + return copied; + } + + public List getDuplicated() + { + return duplicated; + } + + public List getDateModified() + { + return dateModified; + } + + public List getContentModified() + { + return contentModified; + } + + public List getAttributesModified() + { + return attributesModified; + } + + public List getRenamed() + { + return renamed; + } + + public List getDeleted() + { + return deleted; + } + + public List getCorrupted() + { + return corrupted; + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CompareResult CompareResult.displayChanges() + +### Procedure Id: +org.fim.model.CompareResult.displayChanges():org.fim.model.CompareResult.a1ae9cd3721eb660a7fec409bf8af966 + +### File: +src/main/java/org/fim/model/CompareResult.java + +### Key: +CompareResult.java|displayChanges|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8f5f91250d216a5d69d5b79057aab607 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8397/instruction.md b/inferredbugs-8397/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9617f6bd64471d04d6feda35c499db24b5939dcb --- /dev/null +++ b/inferredbugs-8397/instruction.md @@ -0,0 +1,357 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Scanner; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.Options; +import org.fim.model.CompareMode; +import org.fim.model.CompareResult; +import org.fim.model.State; + +public class Main +{ + /** + * Construct Options. + */ + public static Options constructOptions() + { + Options options = new Options(); + options.addOption(createOption("q", "quiet", false, "Do not display details", false)); + options.addOption(createOption("f", "fastCompare", false, "Compare only filenames and modification dates", false)); + options.addOption(createOption("m", "message", true, "Message to store with the State", false)); + options.addOption(createOption("t", "threadCount", true, "Number of thread to use to hash files content in parallel", false)); + options.addOption(createOption("l", "useLastState", false, "Use the last committed State", false)); + return options; + } + + public static Option createOption(String opt, String longOpt, boolean hasArg, String description, boolean required) + { + Option option = new Option(opt, longOpt, hasArg, description); + option.setRequired(required); + return option; + } + + public static void main(String[] args) throws IOException + { + String[] filteredArgs = filterEmptyArgs(args); + if (filteredArgs.length < 1) + { + youMustSpecifyACommandToRun(); + } + + Command command = Command.fromName(filteredArgs[0]); + if (command == null) + { + youMustSpecifyACommandToRun(); + } + + CommandLineParser cmdLineGnuParser = new GnuParser(); + + Options options = constructOptions(); + CommandLine commandLine; + + boolean verbose = true; + CompareMode compareMode = CompareMode.FULL; + String message = ""; + boolean useLastState = false; + int threadCount = Runtime.getRuntime().availableProcessors(); + + try + { + String[] actionArgs = Arrays.copyOfRange(filteredArgs, 1, filteredArgs.length); + commandLine = cmdLineGnuParser.parse(options, actionArgs); + if (commandLine.hasOption("h")) + { + printUsage(); + System.exit(0); + } + else + { + verbose = !commandLine.hasOption('q'); + compareMode = commandLine.hasOption('f') ? CompareMode.FAST : CompareMode.FULL; + message = commandLine.getOptionValue('m', message); + threadCount = Integer.parseInt(commandLine.getOptionValue('t', "" + threadCount)); + useLastState = commandLine.hasOption('l'); + } + } + catch (Exception ex) + { + printUsage(); + System.exit(-1); + } + + if (compareMode == CompareMode.FAST) + { + threadCount = 1; + System.out.println("Using fast compare mode. Thread count forced to 1"); + } + + if (threadCount < 1) + { + System.out.println("Thread count must be at least one"); + System.exit(0); + } + + File baseDirectory = new File("."); + File stateDir = new File(StateGenerator.FIC_DIR, "states"); + + if (command == Command.INIT) + { + if (stateDir.exists()) + { + System.out.println("fim repository already exist"); + System.exit(0); + } + } + else + { + if (!stateDir.exists()) + { + System.out.println("fim repository does not exist. Please run 'fim init' before."); + System.exit(-1); + } + } + + State previousState; + State currentState; + + StateGenerator generator = new StateGenerator(threadCount, compareMode); + StateManager manager = new StateManager(stateDir, compareMode); + StateComparator comparator = new StateComparator(compareMode); + DuplicateFinder finder = new DuplicateFinder(); + + switch (command) + { + case INIT: + fastCompareNotSupported(compareMode); + + stateDir.mkdirs(); + currentState = generator.generateState("Initial State", baseDirectory); + comparator.compare(null, currentState).displayChanges(verbose); + manager.createNewState(currentState); + break; + + case COMMIT: + fastCompareNotSupported(compareMode); + + previousState = manager.loadPreviousState(); + currentState = generator.generateState(message, baseDirectory); + CompareResult result = comparator.compare(previousState, currentState).displayChanges(verbose); + if (result.somethingModified()) + { + System.out.println(""); + if (confirmCommand("commit")) + { + manager.createNewState(currentState); + } + else + { + System.out.println("Nothing committed"); + } + } + break; + + case DIFF: + previousState = manager.loadPreviousState(); + currentState = generator.generateState(message, baseDirectory); + comparator.compare(previousState, currentState).displayChanges(verbose); + break; + + case FIND_DUPLICATES: + fastCompareNotSupported(compareMode); + + System.out.println("Searching for duplicated files" + (useLastState ? " from the last committed State" : "")); + System.out.println(""); + State state; + if (useLastState) + { + state = manager.loadPreviousState(); + } + else + { + state = generator.generateState(message, baseDirectory); + } + finder.findDuplicates(state).displayDuplicates(verbose); + break; + + case RESET_DATES: + fastCompareNotSupported(compareMode); + + previousState = manager.loadPreviousState(); + manager.resetDates(previousState); + break; + + case LOG: + manager.displayStatesLog(); + break; + } + } + + private static String[] filterEmptyArgs(String[] args) + { + List filteredArgs = new ArrayList<>(); + for (String arg : args) + { + if (arg.length() > 0) + { + filteredArgs.add(arg); + } + } + return filteredArgs.toArray(new String[0]); + } + + private static void fastCompareNotSupported(CompareMode compareMode) + { + if (compareMode == CompareMode.FAST) + { + System.out.println("Fast compare mode not supported by this command."); + System.exit(-1); + } + } + + private static boolean confirmCommand(String command) + { + Scanner scanner = new Scanner(System.in); + System.out.printf("Do you really want to %s (y/n)? ", command); + String str = scanner.next(); + if (str.equalsIgnoreCase("y")) + { + return true; + } + return false; + } + + private static void youMustSpecifyACommandToRun() + { + System.out.println("You must specify the command to run"); + printUsage(); + System.exit(-1); + } + + public static void printUsage() + { + System.out.println(""); + Options options = constructOptions(); + PrintWriter writer = new PrintWriter(System.out); + HelpFormatter helpFormatter = new HelpFormatter(); + + String usage = "\nAvailable commands:\n"; + for (final Command command : Command.values()) + { + if (command.getShortCmdName() != null && command.getShortCmdName().length() > 0) + { + usage += String.format("- %s / %s: %s\n", command.getShortCmdName(), command.getCmdName(), command.getDescription()); + } + else + { + usage += String.format("- %s: %s\n", command.getCmdName(), command.getDescription()); + } + } + + helpFormatter.printHelp(writer, 110, "fim ", "\nFile Integrity Checker\n", options, 5, 3, usage, true); + writer.flush(); + System.out.println(""); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `previousState.fileStates` last assigned on line 165 could be null and is dereferenced by call to `compare(...)` at line 167. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Main.main(java.lang.String[]) + +### Procedure Id: +org.fim.Main.main(java.lang.String[]):void.fab5e0be07abd28755980a22623edc93 + +### File: +src/main/java/org/fim/Main.java + +### Key: +Main.java|main|NULL_DEREFERENCE + +### Node Key: +d28e6bf92f2bb0eec2b64537f6ae4b13 + +### Hash: +f26a409c4162f5cddeee054fe63fe381 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8398/instruction.md b/inferredbugs-8398/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3265a8c5af419522c8057282f6503685b1360775 --- /dev/null +++ b/inferredbugs-8398/instruction.md @@ -0,0 +1,411 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim.internal; + +import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.time.DurationFormatUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.fim.model.FileState; +import org.fim.model.HashMode; +import org.fim.model.Parameters; +import org.fim.model.State; +import org.fim.util.Logger; + +public class StateGenerator +{ + public static final int PROGRESS_DISPLAY_FILE_COUNT = 10; + public static final int FILES_QUEUE_CAPACITY = 500; + + private static final Set ignoredDirectories = new HashSet<>(Arrays.asList(Parameters.DOT_FIM_DIR, ".git", ".svn", ".cvs")); + + private static final Pair[] hashProgress = new Pair[] + { + Pair.of('.', 0), + Pair.of('o', FileState.SIZE_20_MB), + Pair.of('O', FileState.SIZE_50_MB), + Pair.of('@', FileState.SIZE_100_MB), + Pair.of('#', FileState.SIZE_200_MB) + }; + + private static Comparator fileNameComparator = new FileState.FileNameComparator(); + + private final Parameters parameters; + private final ReentrantLock progressLock; + + private ExecutorService executorService; + private long summedFileLength; + private int fileCount; + private long totalFileContentLength; + + private Path fimRepositoryRootDir; + private BlockingDeque filesToHash; + private boolean hashersStarted; + private List hashers; + private long totalBytesHashed; + + public StateGenerator(Parameters parameters) + { + this.parameters = parameters; + this.progressLock = new ReentrantLock(); + } + + public State generateState(String comment, Path fimRepositoryRootDir) throws IOException, NoSuchAlgorithmException + { + this.fimRepositoryRootDir = fimRepositoryRootDir; + + Logger.info(String.format("Scanning recursively local files, %s, using %d thread", hashModeToString(), parameters.getThreadCount())); + if (displayHashLegend()) + { + System.out.printf(" (Hash progress legend for files grouped %d by %d: %s)%n", PROGRESS_DISPLAY_FILE_COUNT, PROGRESS_DISPLAY_FILE_COUNT, hashProgressLegend()); + } + + State state = new State(); + state.setComment(comment); + + long start = System.currentTimeMillis(); + progressOutputInit(); + + filesToHash = new LinkedBlockingDeque<>(FILES_QUEUE_CAPACITY); + InitializeFileHashers(); + + scanFileTree(filesToHash, fimRepositoryRootDir); + + // In case the FileHashers have not been started + startFileHashers(); + + waitAllFilesToBeHashed(); + + for (FileHasher hasher : hashers) + { + state.getFileStates().addAll(hasher.getFileStates()); + totalFileContentLength += hasher.getTotalFileContentLength(); + totalBytesHashed += hasher.getTotalBytesHashed(); + } + + Collections.sort(state.getFileStates(), fileNameComparator); + + progressOutputStop(); + displayStatistics(start, state); + + return state; + } + + private void InitializeFileHashers() + { + hashersStarted = false; + hashers = new ArrayList<>(); + executorService = Executors.newFixedThreadPool(parameters.getThreadCount()); + } + + private void startFileHashers() throws NoSuchAlgorithmException + { + if (!hashersStarted) + { + for (int index = 0; index < parameters.getThreadCount(); index++) + { + FileHasher hasher = new FileHasher(this, filesToHash, fimRepositoryRootDir.toString()); + executorService.submit(hasher); + hashers.add(hasher); + } + hashersStarted = true; + } + } + + private String hashModeToString() + { + switch (parameters.getHashMode()) + { + case DONT_HASH_FILES: + return "retrieving only file attributes"; + + case HASH_ONLY_FIRST_FOUR_KILO: + return "hashing only first four kilo"; + + case HASH_ONLY_FIRST_MEGA: + return "hashing only first mega"; + + case COMPUTE_ALL_HASH: + return "computing all hash"; + } + + throw new IllegalArgumentException("Invalid hash mode " + parameters.getHashMode()); + } + + private void waitAllFilesToBeHashed() + { + try + { + executorService.shutdown(); + executorService.awaitTermination(3, TimeUnit.DAYS); + } + catch (InterruptedException ex) + { + Logger.error(ex); + } + } + + private void displayStatistics(long start, State state) + { + long duration = System.currentTimeMillis() - start; + + String totalFileContentLengthStr = FileUtils.byteCountToDisplaySize(totalFileContentLength); + String totalBytesHashedStr = FileUtils.byteCountToDisplaySize(totalBytesHashed); + String durationStr = DurationFormatUtils.formatDuration(duration, "HH:mm:ss"); + + if (parameters.getHashMode() == HashMode.DONT_HASH_FILES) + { + Logger.info(String.format("Scanned %d files (%s), during %s, using %d thread%n", + state.getFileStates().size(), totalFileContentLengthStr, durationStr, parameters.getThreadCount())); + } + else + { + Logger.info(String.format("Scanned %d files (%s), hashed %s bytes, during %s, using %d thread%n", + state.getFileStates().size(), totalFileContentLengthStr, totalBytesHashedStr, durationStr, parameters.getThreadCount())); + } + } + + private void scanFileTree(BlockingDeque filesToHash, Path directory) throws IOException, NoSuchAlgorithmException + { + try (DirectoryStream stream = Files.newDirectoryStream(directory)) + { + for (Path file : stream) + { + if (!hashersStarted && filesToHash.size() > FILES_QUEUE_CAPACITY / 2) + { + startFileHashers(); + } + + BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (attributes.isRegularFile()) + { + try + { + filesToHash.offer(file, 120, TimeUnit.MINUTES); + } + catch (InterruptedException ex) + { + Logger.error(ex); + } + } + else if (attributes.isDirectory()) + { + String fileName = file.getFileName().toString(); + if (ignoredDirectories.contains(fileName)) + { + continue; + } + + scanFileTree(filesToHash, file); + } + } + } + } + + private void progressOutputInit() + { + summedFileLength = 0; + fileCount = 0; + } + + public void updateProgressOutput(long fileSize) throws IOException + { + progressLock.lock(); + try + { + fileCount++; + + if (displayHashLegend()) + { + summedFileLength += fileSize; + + if (fileCount % PROGRESS_DISPLAY_FILE_COUNT == 0) + { + System.out.print(getProgressChar(summedFileLength)); + summedFileLength = 0; + } + } + + if (fileCount % (100 * PROGRESS_DISPLAY_FILE_COUNT) == 0) + { + if (displayHashLegend()) + { + System.out.println(""); + } + } + } + finally + { + progressLock.unlock(); + } + } + + private String hashProgressLegend() + { + StringBuilder sb = new StringBuilder(); + for (int progressIndex = hashProgress.length - 1; progressIndex >= 0; progressIndex--) + { + char marker = hashProgress[progressIndex].getLeft(); + sb.append(marker); + + int fileLength = hashProgress[progressIndex].getRight(); + if (fileLength == 0) + { + sb.append(" otherwise"); + } + else + { + sb.append(" > ").append(FileUtils.byteCountToDisplaySize(fileLength)); + } + sb.append(", "); + } + String legend = sb.toString(); + legend = legend.substring(0, legend.length() - 2); + return legend; + } + + private char getProgressChar(long fileLength) + { + int progressIndex; + for (progressIndex = hashProgress.length - 1; progressIndex >= 0; progressIndex--) + { + if (fileLength > hashProgress[progressIndex].getRight()) + { + break; + } + } + return hashProgress[progressIndex].getLeft(); + } + + private void progressOutputStop() + { + if (displayHashLegend()) + { + if (fileCount > PROGRESS_DISPLAY_FILE_COUNT) + { + System.out.println(""); + } + } + } + + private boolean displayHashLegend() + { + return parameters.isVerbose() && parameters.getHashMode() != HashMode.DONT_HASH_FILES; + } + + public Parameters getParameters() + { + return parameters; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.fim.internal.StateGenerator.generateState` indirectly reads without synchronization from `this.org.fim.internal.StateGenerator.fileCount`. Potentially races with write in method `StateGenerator.updateProgressOutput(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +State StateGenerator.generateState(String,Path) + +### Procedure Id: +org.fim.internal.StateGenerator.generateState(java.lang.String,java.nio.file.Path):org.fim.model.Sta.dcefa56923acbef36aa2f70171181cef + +### File: +src/main/java/org/fim/internal/StateGenerator.java + +### Key: +StateGenerator.java|generateState|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +775d1993696adf703b1ee80e66fe9cb8 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8399/instruction.md b/inferredbugs-8399/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f4d2774b96ab4f02bfa9ff1708eb54b84772c4d --- /dev/null +++ b/inferredbugs-8399/instruction.md @@ -0,0 +1,456 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fim +**Bug ID:** 19 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is part of Fim - File Integrity Manager + * + * Copyright (C) 2015 Etienne Vrignaud + * + * Fim is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Fim is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Fim. If not, see . + */ +package org.fim.model; + +import static org.fim.util.FormatUtil.formatCreationTime; +import static org.fim.util.FormatUtil.formatDate; +import static org.fim.util.FormatUtil.formatLastModified; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import org.fim.util.Console; + +public class CompareResult +{ + public static final String NOTHING = "[nothing]"; + + private static final Comparator fileNameComparator = new Difference.FileNameComparator(); + + private List added; + private List copied; + private List duplicated; + private List dateModified; + private List contentModified; + private List attributesModified; + private List renamed; + private List deleted; + private List corrupted; + + private Context context; + private State lastState; + private boolean searchForHardwareCorruption; + + public CompareResult(Context context, State lastState) + { + this.context = context; + this.lastState = lastState; + this.searchForHardwareCorruption = false; + + added = new ArrayList<>(); + copied = new ArrayList<>(); + duplicated = new ArrayList<>(); + dateModified = new ArrayList<>(); + contentModified = new ArrayList<>(); + attributesModified = new ArrayList<>(); + renamed = new ArrayList<>(); + deleted = new ArrayList<>(); + corrupted = new ArrayList<>(); + } + + public boolean isSearchForHardwareCorruption() + { + return searchForHardwareCorruption; + } + + public void setSearchForHardwareCorruption(boolean searchForHardwareCorruption) + { + this.searchForHardwareCorruption = searchForHardwareCorruption; + } + + public void sortResults() + { + sortDifferences(added); + sortDifferences(copied); + sortDifferences(duplicated); + sortDifferences(dateModified); + sortDifferences(contentModified); + sortDifferences(attributesModified); + sortDifferences(renamed); + sortDifferences(deleted); + sortDifferences(corrupted); + } + + private void sortDifferences(List differences) + { + Collections.sort(differences, fileNameComparator); + } + + public CompareResult displayChanges() + { + if (lastState != null) + { + System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); + if (lastState.getComment().length() > 0) + { + System.out.println("Comment: " + lastState.getComment()); + } + Console.newLine(); + } + + if (!context.isVerbose()) + { + displayCounts(); + return this; + } + + String stateFormat = "%-17s "; + + for (Difference diff : added) + { + System.out.printf(stateFormat + "%s%n", "Added:", diff.getFileState().getFileName()); + } + + for (Difference diff : copied) + { + System.out.printf(stateFormat + "%s \t(was %s)%n", "Copied:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName()); + } + + for (Difference diff : duplicated) + { + System.out.printf(stateFormat + "%s = %s%s%n", "Duplicated:", diff.getFileState().getFileName(), diff.getPreviousFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : dateModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Date modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : contentModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Content modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : attributesModified) + { + System.out.printf(stateFormat + "%s \t%s%n", "Attrs. modified:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + for (Difference diff : renamed) + { + System.out.printf(stateFormat + "%s -> %s%s%n", "Renamed:", diff.getPreviousFileState().getFileName(), diff.getFileState().getFileName(), formatModifiedAttributes(diff, true)); + } + + for (Difference diff : deleted) + { + System.out.printf(stateFormat + "%s%n", "Deleted:", diff.getFileState().getFileName()); + } + + for (Difference diff : corrupted) + { + System.out.printf(stateFormat + "%s \t%s%n", "Corrupted?:", diff.getFileState().getFileName(), formatModifiedAttributes(diff, false)); + } + + if (somethingModified()) + { + Console.newLine(); + } + + displayCounts(); + + return this; + } + + private String formatModifiedAttributes(Difference diff, boolean nextLine) + { + int modifCount = 0; + StringBuilder modification = new StringBuilder(nextLine ? " " : ""); // Put a white space to force to add a separator + + Map previousFileAttributes = diff.getPreviousFileState().getFileAttributes(); + Map currentFileAttributes = diff.getFileState().getFileAttributes(); + for (FileAttribute attribute : FileAttribute.values()) + { + String key = attribute.name(); + String previousValue = getValue(previousFileAttributes, key); + String currentValue = getValue(currentFileAttributes, key); + + if (false == Objects.equals(previousValue, currentValue)) + { + modifCount++; + addSeparator(diff, modification); + modification.append(key).append(": ").append(previousValue).append(" -> ").append(currentValue); + } + } + + if (diff.isCreationTimeChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("creationTime: ").append(formatCreationTime(diff.getPreviousFileState())).append(" -> ").append(formatCreationTime(diff.getFileState())); + } + + if (diff.isLastModifiedChanged()) + { + modifCount++; + addSeparator(diff, modification); + modification.append("lastModified: ").append(formatLastModified(diff.getPreviousFileState())).append(" -> ").append(formatLastModified(diff.getFileState())); + } + + if (modifCount > 1) + { + modification.append('\n'); + } + + return modification.toString(); + } + + private void addSeparator(Difference diff, StringBuilder modification) + { + if (modification.length() == 0) + { + return; + } + + modification.append("\n"); + int len = 17 + 1 + diff.getFileState().getFileName().length() + 1; + for (int index = 0; index < len; index++) + { + modification.append(' '); + } + modification.append('\t'); + } + + private String getValue(Map attributes, String key) + { + String value = attributes != null ? attributes.get(key) : null; + if (value == null || value.length() == 0) + { + value = NOTHING; + } + return value; + } + + public CompareResult displayCounts() + { + if (somethingModified()) + { + String message = ""; + if (!added.isEmpty()) + { + message += "" + added.size() + " added, "; + } + + if (!copied.isEmpty()) + { + message += "" + copied.size() + " copied, "; + } + + if (!duplicated.isEmpty()) + { + message += "" + duplicated.size() + " duplicated, "; + } + + if (!dateModified.isEmpty()) + { + message += "" + dateModified.size() + " date modified, "; + } + + if (!attributesModified.isEmpty()) + { + message += "" + attributesModified.size() + " attrs. modified, "; + } + + if (!contentModified.isEmpty()) + { + message += "" + contentModified.size() + " content modified, "; + } + + if (!renamed.isEmpty()) + { + message += "" + renamed.size() + " renamed, "; + } + + if (!deleted.isEmpty()) + { + message += "" + deleted.size() + " deleted, "; + } + + if (!corrupted.isEmpty()) + { + message += "" + corrupted.size() + " corrupted, "; + } + + message = message.replaceAll(", $", ""); + System.out.println(message); + } + else + { + if (isSearchForHardwareCorruption()) + { + System.out.println("Nothing corrupted"); + } + else + { + System.out.println("Nothing modified"); + } + } + + return this; + } + + public boolean somethingModified() + { + return modifiedCount() > 0; + } + + public int modifiedCount() + { + return added.size() + copied.size() + duplicated.size() + dateModified.size() + contentModified.size() + + attributesModified.size() + renamed.size() + deleted.size() + corrupted.size(); + } + + public ModificationCounts getModificationCounts() + { + ModificationCounts modificationCounts = new ModificationCounts(); + modificationCounts.setAdded(added.size()); + modificationCounts.setCopied(copied.size()); + modificationCounts.setDuplicated(duplicated.size()); + modificationCounts.setDateModified(dateModified.size()); + modificationCounts.setContentModified(contentModified.size()); + modificationCounts.setAttributesModified(attributesModified.size()); + modificationCounts.setRenamed(renamed.size()); + modificationCounts.setDeleted(deleted.size()); + + return modificationCounts; + } + + public List getAdded() + { + return added; + } + + public List getCopied() + { + return copied; + } + + public List getDuplicated() + { + return duplicated; + } + + public List getDateModified() + { + return dateModified; + } + + public List getContentModified() + { + return contentModified; + } + + public List getAttributesModified() + { + return attributesModified; + } + + public List getRenamed() + { + return renamed; + } + + public List getDeleted() + { + return deleted; + } + + public List getCorrupted() + { + return corrupted; + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_PRINTF_ARGS + +### Qualifier: +Format string must be string literal. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CompareResult CompareResult.displayChanges() + +### Procedure Id: +org.fim.model.CompareResult.displayChanges():org.fim.model.CompareResult.a1ae9cd3721eb660a7fec409bf8af966 + +### File: +src/main/java/org/fim/model/CompareResult.java + +### Key: +CompareResult.java|displayChanges|CHECKERS_PRINTF_ARGS + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8f5f91250d216a5d69d5b79057aab607 + +### Bug Type Hum: +Checkers Printf Args + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8441/instruction.md b/inferredbugs-8441/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a60af3abcf820c98aa88846ca4a1fa668ad4f454 --- /dev/null +++ b/inferredbugs-8441/instruction.md @@ -0,0 +1,410 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fili +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// Copyright 2016 Yahoo Inc. +// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms. +package com.yahoo.bard.webservice.druid.model.query; + +import com.yahoo.bard.webservice.data.dimension.Dimension; +import com.yahoo.bard.webservice.druid.model.DefaultQueryType; +import com.yahoo.bard.webservice.druid.model.aggregation.Aggregation; +import com.yahoo.bard.webservice.druid.model.datasource.DataSource; +import com.yahoo.bard.webservice.druid.model.datasource.QueryDataSource; +import com.yahoo.bard.webservice.druid.model.filter.Filter; +import com.yahoo.bard.webservice.druid.model.having.Having; +import com.yahoo.bard.webservice.druid.model.orderby.LimitSpec; +import com.yahoo.bard.webservice.druid.model.postaggregation.PostAggregation; +import com.yahoo.bard.webservice.metadata.RequestedIntervalsFunction; +import com.yahoo.bard.webservice.util.SimplifiedIntervalList; +import com.yahoo.bard.webservice.web.ErrorMessageFormat; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import org.joda.time.Interval; +import org.joda.time.Period; +import org.joda.time.base.AbstractPeriod; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Druid lookback query. + */ +public class LookbackQuery extends AbstractDruidAggregationQuery { + + @JsonInclude(JsonInclude.Include.NON_NULL) + private final Having having; + + @JsonInclude(JsonInclude.Include.NON_NULL) + private final LimitSpec limitSpec; + + @JsonInclude(JsonInclude.Include.NON_NULL) + private final Collection lookbackPrefixes; + + private final Collection lookbackOffsets; + + /** + * Constructor. + * + * @param dataSource DataSource for the query + * @param granularity Granularity for the query + * @param filter Filter for the query + * @param aggregations Aggregations for the query + * @param postAggregations Post-aggregation operation trees for the query + * @param context Query context + * @param intervals Query intervals + * @param doFork If the query should track it's forks or not + * @param lookbackOffsets Set of period offsets + * @param lookbackPrefixes Set of prefixes for the lookback queries (should match the lookbackOffsets) + * @param having Having clause to apply to the result query + * @param limitSpec Limit spec to apply to the result query + */ + private LookbackQuery( + DataSource dataSource, + Granularity granularity, + Filter filter, + Collection aggregations, + Collection postAggregations, + Collection intervals, + QueryContext context, + boolean doFork, + Collection lookbackOffsets, + Collection lookbackPrefixes, + Having having, + LimitSpec limitSpec + ) { + super( + DefaultQueryType.LOOKBACK, + dataSource, + granularity, + Collections.emptySet(), + filter, + aggregations, + postAggregations, + intervals, + context, + doFork + ); + + this.having = having; + this.limitSpec = limitSpec; + this.lookbackOffsets = lookbackOffsets != null ? new ArrayList<>(lookbackOffsets) : null; + this.lookbackPrefixes = lookbackPrefixes != null ? new ArrayList<>(lookbackPrefixes) : null; + } + + /** + * Constructor. + * + * @param dataSource DataSource for the query + * @param postAggregations Post-aggregation operation trees for the query + * @param context Query context + * @param lookbackOffsets Set of period offsets + * @param lookbackPrefixes Set of prefixes for the lookback queries (should match the lookbackOffsets) + * @param having Having clause to apply to the result query + * @param limitSpec Limit spec to apply to the result query + */ + public LookbackQuery( + DataSource dataSource, + Collection postAggregations, + QueryContext context, + Collection lookbackOffsets, + Collection lookbackPrefixes, + Having having, + LimitSpec limitSpec + ) { + this( + dataSource, + null, + null, + Collections.emptySet(), + postAggregations, + Collections.emptySet(), + context, + false, + lookbackOffsets, + lookbackPrefixes, + having, + limitSpec + ); + } + + @Override + public DruidAggregationQuery getInnerQuery() { + return (DruidAggregationQuery) this.dataSource.getQuery(); + } + + public Having getHaving() { + return having; + } + + public LimitSpec getLimitSpec() { + return limitSpec; + } + + public Collection getLookbackPrefixes() { + return lookbackPrefixes; + } + + @JsonIgnore + public Collection getLookbackOffsets() { + return lookbackOffsets; + } + + /** + * Get the collection of lookback offsets. + * + * @return The collection of lookback offsets. + */ + @JsonProperty(value = "lookbackOffsets") + public List getlookbackOffsets() { + return lookbackOffsets.stream().map(AbstractPeriod::toString).collect(Collectors.toList()); + } + + @Override + @JsonIgnore + public Granularity getGranularity() { + return getInnerQuery().getGranularity(); + } + + @Override + @JsonIgnore + public Set getAggregations() { + return getInnerQuery().getAggregations(); + } + + @Override + @JsonIgnore + public Filter getFilter() { + return getInnerQuery().getFilter(); + } + + @Override + @JsonIgnore + public List getIntervals() { + return getInnerQuery().getIntervals(); + } + + @Override + @JsonIgnore + public Collection getDimensions() { + return getInnerQuery().getDimensions(); + } + + @JsonProperty(value = "postAggregations") + public Collection getLookbackPostAggregations() { + return new LinkedHashSet<>(postAggregations); + } + + @Override + @JsonIgnore + public Collection getPostAggregations() { + return Stream.concat(getInnerQuery().getPostAggregations().stream(), postAggregations.stream()) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + + // CHECKSTYLE:OFF + + @Override + public LookbackQuery withAggregations(Collection aggregations) { + return withDataSource(new QueryDataSource(getInnerQuery().withAggregations(aggregations))); + } + + @Override + public LookbackQuery withPostAggregations(Collection postAggregations) { + throw new UnsupportedOperationException(ErrorMessageFormat.UNSUPPORTED_LOOKBACKQUERY_OPERATION.format()); + } + + /** + * Update the postAggregations of the nested inner query. The PostAggregations of the LookbackQuery(outer query) + * remain unchanged + * + * @param postAggregations A Collection of PostAggregations + * + * @return A LookbackQuery whose datasource is built using the provided postAggregations + */ + public LookbackQuery withInnerQueryPostAggregations(Collection postAggregations) { + return new LookbackQuery(new QueryDataSource(getInnerQuery().withPostAggregations(postAggregations)), granularity, filter, aggregations, getLookbackPostAggregations(), intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + /** + * Update the postAggregations of the LookbackQuery(outer query). + * + * @param postAggregations A Collection of PostAggregations + * + * @return A LookbackQuery built using the provided postAggregations + */ + public LookbackQuery withLookbackQueryPostAggregations(Collection postAggregations) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + @Override + public LookbackQuery withGranularity(Granularity granularity) { + return withDataSource(new QueryDataSource(getInnerQuery().withGranularity(granularity))); + } + + @Override + public LookbackQuery withFilter(Filter filter) { + return withDataSource(new QueryDataSource(getInnerQuery().withFilter(filter))); + } + + @Override + public LookbackQuery withIntervals(Collection intervals) { + return withDataSource(new QueryDataSource(getInnerQuery().withIntervals(intervals))); + } + + @Override + public LookbackQuery withAllIntervals(Collection intervals) { + DruidFactQuery innerQuery = (DruidFactQuery) this.dataSource.getQuery(); + return (innerQuery == null) ? + withIntervals(intervals) : + withDataSource(new QueryDataSource(innerQuery.withAllIntervals(intervals))).withIntervals(intervals); + } + + @Override + public LookbackQuery withDataSource(DataSource dataSource) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + @Override + public LookbackQuery withInnermostDataSource(DataSource dataSource) { + DruidFactQuery innerQuery = (DruidFactQuery) this.dataSource.getQuery(); + return (innerQuery == null) ? + withDataSource(dataSource) : + withDataSource(new QueryDataSource(innerQuery.withInnermostDataSource(dataSource))); + } + + @Override + public LookbackQuery withContext(QueryContext context) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + public LookbackQuery withOrderBy(LimitSpec limitSpec) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + public LookbackQuery withHaving(Having having) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + public LookbackQuery withLookbackPrefix(List lookbackPrefixes) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + + public LookbackQuery withLookbackOffsets(List lookbackOffsets) { + return new LookbackQuery(dataSource, granularity, filter, aggregations, postAggregations, intervals, context, false, lookbackOffsets, lookbackPrefixes, having, limitSpec); + } + // CHECKSTYLE:ON + + /** + * The function to get requestedIntervals from a LookbackQuery. + */ + public static class LookbackQueryRequestedIntervalsFunction implements RequestedIntervalsFunction { + + @Override + public SimplifiedIntervalList apply(DruidAggregationQuery druidAggregationQuery) { + + LookbackQuery castQuery = (LookbackQuery) druidAggregationQuery; + return Stream.concat( + castQuery.getIntervals().stream(), + castQuery.getIntervals().stream() + .flatMap(interval -> castQuery.getLookbackOffsets().stream() + .map(lookbackOffset -> getCohortInterval(interval, lookbackOffset)) + ) + ).collect(SimplifiedIntervalList.getCollector()); + } + + /** + * Given an interval and a lookbackOffset, calculate the cohortInterval. + * + * @param interval The measurement interval to which the offset is added + * @param lookbackOffset The offset to be added to the given interval + * + * @return Cohort interval calculated using the given interval and lookbackOffset + */ + private Interval getCohortInterval(Interval interval, Period lookbackOffset) { + return new Interval( + interval.getStart().withPeriodAdded(lookbackOffset, 1), + interval.getEnd().withPeriodAdded(lookbackOffset, 1) + ); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getInnerQuery()` could be null and is dereferenced at line 247. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +LookbackQuery LookbackQuery.withGranularity(Granularity) + +### Procedure Id: +com.yahoo.bard.webservice.druid.model.query.LookbackQuery.withGranularity(com.yahoo.bard.webservice..127323f47cfe284433e756f7d7467bab + +### File: +fili-core/src/main/java/com/yahoo/bard/webservice/druid/model/query/LookbackQuery.java + +### Key: +LookbackQuery.java|withGranularity|NULL_DEREFERENCE + +### Node Key: +2cb1d0ccf8074a598a85b7d11f296818 + +### Hash: +17c0f73f73eaa59e4616df4c48839b78 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8502/instruction.md b/inferredbugs-8502/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b41881dec0a171ea103236f73181b01fffe90500 --- /dev/null +++ b/inferredbugs-8502/instruction.md @@ -0,0 +1,189 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** subtitleConverter +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; + +/** + * + * @author J. David + * + * Class that handles reading and writing files or reads from keyboard + * + */ +public class IOClass { + + /** + * Method to get the file name (or path relative to the directory) and file to write to + * in the form of an array of strings where each string represents a line + * + * @param fileName name of the file (or path relative to directory) + * @param totalFile array of strings where each string represents a line in the file + */ + public static void writeFileTxt(String fileName, String[] totalFile){ + FileWriter file = null; + PrintWriter pw = null; + try + { + file = new FileWriter(System.getProperty("user.dir")+"/"+fileName); + pw = new PrintWriter(file); + + for (int i = 0; i < totalFile.length; i++) + pw.println(totalFile[i]); + + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + // Execute the "finally" to make sure the file is closed + if (null != file) + file.close(); + } catch (Exception e2) { + e2.printStackTrace(); + } + } + } + + /** + * Method to get the file name (or path relative to the directory) and file to write to + * in the form of an array of strings where each string represents a line + * + * @param fileName name of the file (or path relative to directory) + * @param s array of strings where each string represents a line in the file + */ + public static String[] readfileTxt(String fileName){ + + String [] s = new String [0]; + String direccion = System.getProperty("user.dir")+"/"+ fileName; + + // Try to load the file (archive) + File archive = null; + FileReader fr = null; + BufferedReader br = null; + try { + // Open the file and create BufferedReader in order to + // reading easier (disposing the method readLine()). + archive = new File (direccion); + fr = new FileReader (archive); + br = new BufferedReader(fr); + + // Reading the file + String line = null; + while((line=br.readLine())!=null){ + int n=0; + String [] s2 = new String[s.length+1]; + for(n=0;nJoerg Wuethrich
    + *

    created on 08.10.2014

    + */ +public class TestDataReaderIBM_J9_R27 { + private static final Logger IMP_LOGGER = Logger.getLogger("com.tagtraum.perf.gcviewer.imp"); + private static final Logger DATA_READER_FACTORY_LOGGER = Logger.getLogger("com.tagtraum.perf.gcviewer.DataReaderFactory"); + + @Test + public void testFullHeaderWithAfGcs() throws Exception { + TestLogHandler handler = new TestLogHandler(); + handler.setLevel(Level.WARNING); + IMP_LOGGER.addHandler(handler); + DATA_READER_FACTORY_LOGGER.addHandler(handler); + + InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_full_header.txt"); + DataReader reader = new DataReaderIBM_J9_R28(in); + GCModel model = reader.read(); + + assertThat("model size", model.size(), is(3)); + + GCEvent event = (GCEvent) model.get(0); + assertThat("pause", event.getPause(), closeTo(0.042303, 0.0000001)); + + assertThat("total before", event.getTotal(), is(toKiloBytes(1073741824))); + assertThat("free before", event.getPreUsed(), is(toKiloBytes(1073741824 - 804158480))); + assertThat("free after", event.getPostUsed(), is(toKiloBytes(1073741824 - 912835672))); + + assertThat("total young before", event.getYoung().getTotal(), is(toKiloBytes(268435456))); + assertThat("young before", event.getYoung().getPreUsed(), is(toKiloBytes(268435456))); + assertThat("young after", event.getYoung().getPostUsed(), is(toKiloBytes(268435456 - 108677192))); + + assertThat("total tenured before", event.getTenured().getTotal(), is(toKiloBytes(805306368))); + assertThat("tenured before", event.getTenured().getPreUsed(), is(toKiloBytes(805306368 - 804158480))); + assertThat("tenured after", event.getTenured().getPostUsed(), is(toKiloBytes(805306368 - 804158480))); + + assertThat("timestamp 1", event.getTimestamp(), closeTo(0.0, 0.0001)); + assertThat("timestamp 2", model.get(1).getTimestamp(), closeTo(1.927, 0.0001)); + assertThat("timestamp 3", model.get(2).getTimestamp(), closeTo(3.982, 0.0001)); + + assertThat("number of errors", handler.getCount(), is(1)); + } + + @Test + public void testSystemGc() throws Exception { + TestLogHandler handler = new TestLogHandler(); + handler.setLevel(Level.WARNING); + IMP_LOGGER.addHandler(handler); + DATA_READER_FACTORY_LOGGER.addHandler(handler); + + InputStream in = UnittestHelper.getResourceAsStream(UnittestHelper.FOLDER_IBM, "SampleIBMJ9_R27_SR1_global.txt"); + DataReader reader = new DataReaderIBM_J9_R28(in); + GCModel model = reader.read(); + + assertThat("model size", model.size(), is(1)); + + GCEvent event = (GCEvent) model.get(0); + assertThat("pause", event.getPause(), closeTo(0.075863, 0.0000001)); + + assertThat("number of errors", handler.getCount(), is(0)); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `event.getYoung()` could be null and is dereferenced at line 45. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestDataReaderIBM_J9_R27.testFullHeaderWithAfGcs() + +### Procedure Id: +com.tagtraum.perf.gcviewer.imp.TestDataReaderIBM_J9_R27.testFullHeaderWithAfGcs():void.c11cb34e714adb0e02c59c423f7c4724 + +### File: +src/test/java/com/tagtraum/perf/gcviewer/imp/TestDataReaderIBM_J9_R27.java + +### Key: +TestDataReaderIBM_J9_R27.java|testFullHeaderWithAfGcs|NULL_DEREFERENCE + +### Node Key: +98e48d8af36063b905de6168fc1ae17c + +### Hash: +3a17e19f8394a1c161a37d87dfdb7dab + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8532/instruction.md b/inferredbugs-8532/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8410cb066217f5d502ffe08a41e0e1287db34ba8 --- /dev/null +++ b/inferredbugs-8532/instruction.md @@ -0,0 +1,3680 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** http-request +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2011 Kevin Sawicki + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ +package com.github.kevinsawicki.http; + +import static com.github.kevinsawicki.http.HttpRequest.CHARSET_UTF8; +import static com.github.kevinsawicki.http.HttpRequest.delete; +import static com.github.kevinsawicki.http.HttpRequest.encode; +import static com.github.kevinsawicki.http.HttpRequest.get; +import static com.github.kevinsawicki.http.HttpRequest.head; +import static com.github.kevinsawicki.http.HttpRequest.options; +import static com.github.kevinsawicki.http.HttpRequest.post; +import static com.github.kevinsawicki.http.HttpRequest.put; +import static com.github.kevinsawicki.http.HttpRequest.trace; +import static java.net.HttpURLConnection.HTTP_BAD_REQUEST; +import static java.net.HttpURLConnection.HTTP_CREATED; +import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR; +import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED; +import static java.net.HttpURLConnection.HTTP_OK; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import com.github.kevinsawicki.http.HttpRequest.HttpRequestException; +import com.github.kevinsawicki.http.HttpRequest.ConnectionFactory; +import com.github.kevinsawicki.http.HttpRequest.ProgressCallback; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintStream; +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.io.Writer; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.zip.GZIPOutputStream; + +import javax.net.ssl.HttpsURLConnection; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.util.B64Code; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +/** + * Unit tests of {@link HttpRequest} + */ +public class HttpRequestTest extends ServerTestCase { + + private static String url; + + private static RequestHandler handler; + + /** + * Set up server + * + * @throws Exception + */ + @BeforeClass + public static void startServer() throws Exception { + url = setUp(new RequestHandler() { + + @Override + public void handle(String target, Request baseRequest, + HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + if (handler != null) + handler.handle(target, baseRequest, request, response); + } + + @Override + public void handle(Request request, HttpServletResponse response) { + if (handler != null) + handler.handle(request, response); + } + }); + } + + /** + * Clear handler + */ + @After + public void clearHandler() { + handler = null; + } + + /** + * Create request with malformed URL + */ + @Test(expected = HttpRequestException.class) + public void malformedStringUrl() { + get("\\m/"); + } + + /** + * Create request with malformed URL + */ + @Test + public void malformedStringUrlCause() { + try { + delete("\\m/"); + fail("Exception not thrown"); + } catch (HttpRequestException e) { + assertNotNull(e.getCause()); + } + } + + /** + * Set request buffer size to negative value + */ + @Test(expected = IllegalArgumentException.class) + public void negativeBufferSize() { + get("http://localhost").bufferSize(-1); + } + + /** + * Make a GET request with an empty body response + * + * @throws Exception + */ + @Test + public void getEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url); + assertNotNull(request.getConnection()); + assertEquals(30000, request.readTimeout(30000).getConnection() + .getReadTimeout()); + assertEquals(50000, request.connectTimeout(50000).getConnection() + .getConnectTimeout()); + assertEquals(2500, request.bufferSize(2500).bufferSize()); + assertFalse(request.ignoreCloseExceptions(false).ignoreCloseExceptions()); + assertFalse(request.useCaches(false).getConnection().getUseCaches()); + int code = request.code(); + assertTrue(request.ok()); + assertFalse(request.created()); + assertFalse(request.badRequest()); + assertFalse(request.serverError()); + assertFalse(request.notFound()); + assertFalse(request.notModified()); + assertEquals("GET", method.get()); + assertEquals("OK", request.message()); + assertEquals(HTTP_OK, code); + assertEquals("", request.body()); + assertNotNull(request.toString()); + assertFalse(request.toString().length() == 0); + assertEquals(request, request.disconnect()); + assertTrue(request.isBodyEmpty()); + assertEquals(request.url().toString(), url); + assertEquals("GET", request.method()); + } + + /** + * Make a GET request with an empty body response + * + * @throws Exception + */ + @Test + public void getUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(new URL(url)); + assertNotNull(request.getConnection()); + int code = request.code(); + assertTrue(request.ok()); + assertFalse(request.created()); + assertFalse(request.badRequest()); + assertFalse(request.serverError()); + assertFalse(request.notFound()); + assertEquals("GET", method.get()); + assertEquals("OK", request.message()); + assertEquals(HTTP_OK, code); + assertEquals("", request.body()); + } + + /** + * Make a GET request with a URL that needs encoding + * + * @throws Exception + */ + @Test + public void getUrlEncodedWithSpace() throws Exception { + String unencoded = "/a resource"; + final AtomicReference path = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + path.set(request.getPathInfo()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(encode(url + unencoded)); + assertTrue(request.ok()); + assertEquals(unencoded, path.get()); + } + + /** + * Make a GET request with a URL that needs encoding + * + * @throws Exception + */ + @Test + public void getUrlEncodedWithUnicode() throws Exception { + String unencoded = "/\u00DF"; + final AtomicReference path = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + path.set(request.getPathInfo()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(encode(url + unencoded)); + assertTrue(request.ok()); + assertEquals(unencoded, path.get()); + } + + /** + * Make a GET request with a URL that needs encoding + * + * @throws Exception + */ + @Test + public void getUrlEncodedWithPercent() throws Exception { + String unencoded = "/%"; + final AtomicReference path = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + path.set(request.getPathInfo()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(encode(url + unencoded)); + assertTrue(request.ok()); + assertEquals(unencoded, path.get()); + } + + /** + * Make a DELETE request with an empty body response + * + * @throws Exception + */ + @Test + public void deleteEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(url); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("DELETE", method.get()); + assertEquals("", request.body()); + assertEquals("DELETE", request.method()); + } + + /** + * Make a DELETE request with an empty body response + * + * @throws Exception + */ + @Test + public void deleteUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(new URL(url)); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("DELETE", method.get()); + assertEquals("", request.body()); + } + + /** + * Make an OPTIONS request with an empty body response + * + * @throws Exception + */ + @Test + public void optionsEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = options(url); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("OPTIONS", method.get()); + assertEquals("", request.body()); + } + + /** + * Make an OPTIONS request with an empty body response + * + * @throws Exception + */ + @Test + public void optionsUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = options(new URL(url)); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("OPTIONS", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a HEAD request with an empty body response + * + * @throws Exception + */ + @Test + public void headEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(url); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("HEAD", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a HEAD request with an empty body response + * + * @throws Exception + */ + @Test + public void headUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(new URL(url)); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("HEAD", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a PUT request with an empty body response + * + * @throws Exception + */ + @Test + public void putEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(url); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("PUT", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a PUT request with an empty body response + * + * @throws Exception + */ + @Test + public void putUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(new URL(url)); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("PUT", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a PUT request with an empty body response + * + * @throws Exception + */ + @Test + public void traceEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = trace(url); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("TRACE", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a TRACE request with an empty body response + * + * @throws Exception + */ + @Test + public void traceUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = trace(new URL(url)); + assertNotNull(request.getConnection()); + assertTrue(request.ok()); + assertFalse(request.notFound()); + assertEquals("TRACE", method.get()); + assertEquals("", request.body()); + } + + /** + * Make a POST request with an empty request body + * + * @throws Exception + */ + @Test + public void postEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_CREATED); + } + }; + HttpRequest request = post(url); + int code = request.code(); + assertEquals("POST", method.get()); + assertFalse(request.ok()); + assertTrue(request.created()); + assertEquals(HTTP_CREATED, code); + } + + /** + * Make a POST request with an empty request body + * + * @throws Exception + */ + @Test + public void postUrlEmpty() throws Exception { + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + response.setStatus(HTTP_CREATED); + } + }; + HttpRequest request = post(new URL(url)); + int code = request.code(); + assertEquals("POST", method.get()); + assertFalse(request.ok()); + assertTrue(request.created()); + assertEquals(HTTP_CREATED, code); + } + + /** + * Make a POST request with a non-empty request body + * + * @throws Exception + */ + @Test + public void postNonEmptyString() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + int code = post(url).send("hello").code(); + assertEquals(HTTP_OK, code); + assertEquals("hello", body.get()); + } + + /** + * Make a POST request with a non-empty request body + * + * @throws Exception + */ + @Test + public void postNonEmptyFile() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + int code = post(url).send(file).code(); + assertEquals(HTTP_OK, code); + assertEquals("hello", body.get()); + } + + /** + * Make a POST request with multiple files in the body + * + * @throws Exception + */ + @Test + public void postMultipleFiles() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + + File file1 = File.createTempFile("post", ".txt"); + new FileWriter(file1).append("hello").close(); + + File file2 = File.createTempFile("post", ".txt"); + new FileWriter(file2).append(" world").close(); + + int code = post(url).send(file1).send(file2).code(); + assertEquals(HTTP_OK, code); + assertEquals("hello world", body.get()); + } + + /** + * Make a POST request with a non-empty request body + * + * @throws Exception + */ + @Test + public void postNonEmptyReader() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + int code = post(url).send(new FileReader(file)).code(); + assertEquals(HTTP_OK, code); + assertEquals("hello", body.get()); + } + + /** + * Make a POST request with a non-empty request body + * + * @throws Exception + */ + @Test + public void postNonEmptyByteArray() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + byte[] bytes = "hello".getBytes(CHARSET_UTF8); + int code = post(url).contentLength(Integer.toString(bytes.length)) + .send(bytes).code(); + assertEquals(HTTP_OK, code); + assertEquals("hello", body.get()); + } + + /** + * Make a post with an explicit set of the content length + * + * @throws Exception + */ + @Test + public void postWithLength() throws Exception { + final AtomicReference body = new AtomicReference(); + final AtomicReference length = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + length.set(request.getContentLength()); + response.setStatus(HTTP_OK); + } + }; + String data = "hello"; + int sent = data.getBytes().length; + int code = post(url).contentLength(sent).send(data).code(); + assertEquals(HTTP_OK, code); + assertEquals(sent, length.get().intValue()); + assertEquals(data, body.get()); + } + + /** + * Make a post of form data + * + * @throws Exception + */ + @Test + public void postForm() throws Exception { + final AtomicReference body = new AtomicReference(); + final AtomicReference contentType = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + contentType.set(request.getContentType()); + response.setStatus(HTTP_OK); + } + }; + Map data = new LinkedHashMap(); + data.put("name", "user"); + data.put("number", "100"); + int code = post(url).form(data).form("zip", "12345").code(); + assertEquals(HTTP_OK, code); + assertEquals("name=user&number=100&zip=12345", body.get()); + assertEquals("application/x-www-form-urlencoded; charset=UTF-8", + contentType.get()); + } + + /** + * Make a post of form data + * + * @throws Exception + */ + @Test + public void postFormWithNoCharset() throws Exception { + final AtomicReference body = new AtomicReference(); + final AtomicReference contentType = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + contentType.set(request.getContentType()); + response.setStatus(HTTP_OK); + } + }; + Map data = new LinkedHashMap(); + data.put("name", "user"); + data.put("number", "100"); + int code = post(url).form(data, null).form("zip", "12345").code(); + assertEquals(HTTP_OK, code); + assertEquals("name=user&number=100&zip=12345", body.get()); + assertEquals("application/x-www-form-urlencoded", contentType.get()); + } + + /** + * Make a post with an empty form data map + * + * @throws Exception + */ + @Test + public void postEmptyForm() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + int code = post(url).form(new HashMap()).code(); + assertEquals(HTTP_OK, code); + assertEquals("", body.get()); + } + + /** + * Make a post in chunked mode + * + * @throws Exception + */ + @Test + public void chunkPost() throws Exception { + final AtomicReference body = new AtomicReference(); + final AtomicReference encoding = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + encoding.set(request.getHeader("Transfer-Encoding")); + } + }; + String data = "hello"; + int code = post(url).chunk(2).send(data).code(); + assertEquals(HTTP_OK, code); + assertEquals(data, body.get()); + assertEquals("chunked", encoding.get()); + } + + /** + * Make a GET request for a non-empty response body + * + * @throws Exception + */ + @Test + public void getNonEmptyString() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + write("hello"); + } + }; + HttpRequest request = get(url); + assertEquals(HTTP_OK, request.code()); + assertEquals("hello", request.body()); + assertEquals("hello".getBytes().length, request.contentLength()); + assertFalse(request.isBodyEmpty()); + } + + /** + * Make a GET request with a response that includes a charset parameter + * + * @throws Exception + */ + @Test + public void getWithResponseCharset() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setContentType("text/html; charset=UTF-8"); + } + }; + HttpRequest request = get(url); + assertEquals(HTTP_OK, request.code()); + assertEquals(CHARSET_UTF8, request.charset()); + } + + /** + * Make a GET request with a response that includes a charset parameter + * + * @throws Exception + */ + @Test + public void getWithResponseCharsetAsSecondParam() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setContentType("text/html; param1=val1; charset=UTF-8"); + } + }; + HttpRequest request = get(url); + assertEquals(HTTP_OK, request.code()); + assertEquals(CHARSET_UTF8, request.charset()); + } + + /** + * Make a GET request with basic authentication specified + * + * @throws Exception + */ + @Test + public void basicAuthentication() throws Exception { + final AtomicReference user = new AtomicReference(); + final AtomicReference password = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + String auth = request.getHeader("Authorization"); + auth = auth.substring(auth.indexOf(' ') + 1); + try { + auth = B64Code.decode(auth, CHARSET_UTF8); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + int colon = auth.indexOf(':'); + user.set(auth.substring(0, colon)); + password.set(auth.substring(colon + 1)); + response.setStatus(HTTP_OK); + } + }; + assertTrue(get(url).basic("user", "p4ssw0rd").ok()); + assertEquals("user", user.get()); + assertEquals("p4ssw0rd", password.get()); + } + + /** + * Make a GET request with basic proxy authentication specified + * + * @throws Exception + */ + @Test + public void basicProxyAuthentication() throws Exception { + final AtomicBoolean finalHostReached = new AtomicBoolean(false); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + finalHostReached.set(true); + response.setStatus(HTTP_OK); + } + }; + assertTrue(get(url).useProxy("localhost", proxyPort).proxyBasic("user", "p4ssw0rd").ok()); + assertEquals("user", proxyUser.get()); + assertEquals("p4ssw0rd", proxyPassword.get()); + assertEquals(true, finalHostReached.get()); + assertEquals(1, proxyHitCount.get()); + } + + /** + * Make a GET and get response as a input stream reader + * + * @throws Exception + */ + @Test + public void getReader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + write("hello"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + BufferedReader reader = new BufferedReader(request.reader()); + assertEquals("hello", reader.readLine()); + reader.close(); + } + + /** + * Make a POST and send request using a writer + * + * @throws Exception + */ + @Test + public void sendWithWriter() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + + HttpRequest request = post(url); + request.writer().append("hello").close(); + assertTrue(request.ok()); + assertEquals("hello", body.get()); + } + + /** + * Make a GET and get response as a buffered reader + * + * @throws Exception + */ + @Test + public void getBufferedReader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + write("hello"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + BufferedReader reader = request.bufferedReader(); + assertEquals("hello", reader.readLine()); + reader.close(); + } + + /** + * Make a GET and get response as a input stream reader + * + * @throws Exception + */ + @Test + public void getReaderWithCharset() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + write("hello"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + BufferedReader reader = new BufferedReader(request.reader(CHARSET_UTF8)); + assertEquals("hello", reader.readLine()); + reader.close(); + } + + /** + * Make a GET and get response body as byte array + * + * @throws Exception + */ + @Test + public void getBytes() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + write("hello"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertTrue(Arrays.equals("hello".getBytes(), request.bytes())); + } + + /** + * Make a GET request that returns an error string + * + * @throws Exception + */ + @Test + public void getError() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HttpServletResponse.SC_NOT_FOUND); + write("error"); + } + }; + HttpRequest request = get(url); + assertTrue(request.notFound()); + assertEquals("error", request.body()); + } + + /** + * Make a GET request that returns an empty error string + * + * @throws Exception + */ + @Test + public void noError() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertEquals("", request.body()); + } + + /** + * Verify 'Server' header + * + * @throws Exception + */ + @Test + public void serverHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("Server", "aserver"); + } + }; + assertEquals("aserver", get(url).server()); + } + + /** + * Verify 'Expires' header + * + * @throws Exception + */ + @Test + public void expiresHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setDateHeader("Expires", 1234000); + } + }; + assertEquals(1234000, get(url).expires()); + } + + /** + * Verify 'Last-Modified' header + * + * @throws Exception + */ + @Test + public void lastModifiedHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setDateHeader("Last-Modified", 555000); + } + }; + assertEquals(555000, get(url).lastModified()); + } + + /** + * Verify 'Date' header + * + * @throws Exception + */ + @Test + public void dateHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setDateHeader("Date", 66000); + } + }; + assertEquals(66000, get(url).date()); + } + + /** + * Verify 'ETag' header + * + * @throws Exception + */ + @Test + public void eTagHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("ETag", "abcd"); + } + }; + assertEquals("abcd", get(url).eTag()); + } + + /** + * Verify 'Location' header + * + * @throws Exception + */ + @Test + public void locationHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("Location", "http://nowhere"); + } + }; + assertEquals("http://nowhere", get(url).location()); + } + + /** + * Verify 'Content-Encoding' header + * + * @throws Exception + */ + @Test + public void contentEncodingHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("Content-Encoding", "gzip"); + } + }; + assertEquals("gzip", get(url).contentEncoding()); + } + + /** + * Verify 'Content-Type' header + * + * @throws Exception + */ + @Test + public void contentTypeHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("Content-Type", "text/html"); + } + }; + assertEquals("text/html", get(url).contentType()); + } + + /** + * Verify 'Content-Type' header + * + * @throws Exception + */ + @Test + public void requestContentType() throws Exception { + final AtomicReference contentType = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + contentType.set(request.getContentType()); + response.setStatus(HTTP_OK); + } + }; + assertTrue(post(url).contentType("text/html", "UTF-8").ok()); + assertEquals("text/html; charset=UTF-8", contentType.get()); + } + + /** + * Verify 'Content-Type' header + * + * @throws Exception + */ + @Test + public void requestContentTypeNullCharset() throws Exception { + final AtomicReference contentType = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + contentType.set(request.getContentType()); + response.setStatus(HTTP_OK); + } + }; + assertTrue(post(url).contentType("text/html", null).ok()); + assertEquals("text/html", contentType.get()); + } + + /** + * Verify 'Content-Type' header + * + * @throws Exception + */ + @Test + public void requestContentTypeEmptyCharset() throws Exception { + final AtomicReference contentType = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + contentType.set(request.getContentType()); + response.setStatus(HTTP_OK); + } + }; + assertTrue(post(url).contentType("text/html", "").ok()); + assertEquals("text/html", contentType.get()); + } + + /** + * Verify 'Cache-Control' header + * + * @throws Exception + */ + @Test + public void cacheControlHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("Cache-Control", "no-cache"); + } + }; + assertEquals("no-cache", get(url).cacheControl()); + } + + /** + * Verify setting headers + * + * @throws Exception + */ + @Test + public void headers() throws Exception { + final AtomicReference h1 = new AtomicReference(); + final AtomicReference h2 = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + h1.set(request.getHeader("h1")); + h2.set(request.getHeader("h2")); + } + }; + Map headers = new HashMap(); + headers.put("h1", "v1"); + headers.put("h2", "v2"); + assertTrue(get(url).headers(headers).ok()); + assertEquals("v1", h1.get()); + assertEquals("v2", h2.get()); + } + + /** + * Verify setting headers + * + * @throws Exception + */ + @Test + public void emptyHeaders() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + assertTrue(get(url).headers(Collections. emptyMap()).ok()); + } + + /** + * Verify getting all headers + * + * @throws Exception + */ + @Test + public void getAllHeaders() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "a"); + response.setHeader("b", "b"); + response.addHeader("a", "another"); + } + }; + Map> headers = get(url).headers(); + assertEquals(headers.size(), 5); + assertEquals(headers.get("a").size(), 2); + assertTrue(headers.get("b").get(0).equals("b")); + } + + /** + * Verify setting number header + * + * @throws Exception + */ + @Test + public void numberHeader() throws Exception { + final AtomicReference h1 = new AtomicReference(); + final AtomicReference h2 = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + h1.set(request.getHeader("h1")); + h2.set(request.getHeader("h2")); + } + }; + assertTrue(get(url).header("h1", 5).header("h2", (Number) null).ok()); + assertEquals("5", h1.get()); + assertEquals("", h2.get()); + } + + /** + * Verify 'User-Agent' request header + * + * @throws Exception + */ + @Test + public void userAgentHeader() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("User-Agent")); + } + }; + assertTrue(get(url).userAgent("browser 1.0").ok()); + assertEquals("browser 1.0", header.get()); + } + + /** + * Verify 'Accept' request header + * + * @throws Exception + */ + @Test + public void acceptHeader() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("Accept")); + } + }; + assertTrue(get(url).accept("application/json").ok()); + assertEquals("application/json", header.get()); + } + + /** + * Verify 'Accept' request header when calling + * {@link HttpRequest#acceptJson()} + * + * @throws Exception + */ + @Test + public void acceptJson() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("Accept")); + } + }; + assertTrue(get(url).acceptJson().ok()); + assertEquals("application/json", header.get()); + } + + /** + * Verify 'If-None-Match' request header + * + * @throws Exception + */ + @Test + public void ifNoneMatchHeader() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("If-None-Match")); + } + }; + assertTrue(get(url).ifNoneMatch("eid").ok()); + assertEquals("eid", header.get()); + } + + /** + * Verify 'Accept-Charset' request header + * + * @throws Exception + */ + @Test + public void acceptCharsetHeader() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("Accept-Charset")); + } + }; + assertTrue(get(url).acceptCharset(CHARSET_UTF8).ok()); + assertEquals(CHARSET_UTF8, header.get()); + } + + /** + * Verify 'Accept-Encoding' request header + * + * @throws Exception + */ + @Test + public void acceptEncodingHeader() throws Exception { + final AtomicReference header = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getHeader("Accept-Encoding")); + } + }; + assertTrue(get(url).acceptEncoding("compress").ok()); + assertEquals("compress", header.get()); + } + + /** + * Verify 'If-Modified-Since' request header + * + * @throws Exception + */ + @Test + public void ifModifiedSinceHeader() throws Exception { + final AtomicLong header = new AtomicLong(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + header.set(request.getDateHeader("If-Modified-Since")); + } + }; + assertTrue(get(url).ifModifiedSince(5000).ok()); + assertEquals(5000, header.get()); + } + + /** + * Verify 'Referer' header + * + * @throws Exception + */ + @Test + public void refererHeader() throws Exception { + final AtomicReference referer = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + referer.set(request.getHeader("Referer")); + response.setStatus(HTTP_OK); + } + }; + assertTrue(post(url).referer("http://heroku.com").ok()); + assertEquals("http://heroku.com", referer.get()); + } + + /** + * Verify multipart with file, stream, number, and string parameters + * + * @throws Exception + */ + @Test + public void postMultipart() throws Exception { + final StringBuilder body = new StringBuilder(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + char[] buffer = new char[8192]; + int read; + try { + while ((read = request.getReader().read(buffer)) != -1) + body.append(buffer, 0, read); + } catch (IOException e) { + fail(); + } + } + }; + File file = File.createTempFile("body", ".txt"); + File file2 = File.createTempFile("body", ".txt"); + new FileWriter(file).append("content1").close(); + new FileWriter(file2).append("content4").close(); + HttpRequest request = post(url); + request.part("description", "content2"); + request.part("size", file.length()); + request.part("body", file.getName(), file); + request.part("file", file2); + request.part("stream", new ByteArrayInputStream("content3".getBytes())); + assertTrue(request.ok()); + assertTrue(body.toString().contains("content1\r\n")); + assertTrue(body.toString().contains("content2\r\n")); + assertTrue(body.toString().contains("content3\r\n")); + assertTrue(body.toString().contains("content4\r\n")); + assertTrue(body.toString().contains(Long.toString(file.length()) + "\r\n")); + } + + /** + * Verify multipart with content type part header + * + * @throws Exception + */ + @Test + public void postMultipartWithContentType() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + body.set(new String(read())); + } + }; + HttpRequest request = post(url); + request.part("body", null, "application/json", "contents"); + assertTrue(request.ok()); + assertTrue(body.toString().contains("Content-Type: application/json")); + assertTrue(body.toString().contains("contents\r\n")); + } + + /** + * Verify response in {@link Appendable} + * + * @throws Exception + */ + @Test + public void receiveAppendable() throws Exception { + final StringBuilder body = new StringBuilder(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + assertTrue(post(url).receive(body).ok()); + assertEquals("content", body.toString()); + } + + /** + * Verify response in {@link Writer} + * + * @throws Exception + */ + @Test + public void receiveWriter() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + StringWriter writer = new StringWriter(); + assertTrue(post(url).receive(writer).ok()); + assertEquals("content", writer.toString()); + } + + /** + * Verify response via a {@link PrintStream} + * + * @throws Exception + */ + @Test + public void receivePrintStream() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + ByteArrayOutputStream output = new ByteArrayOutputStream(); + PrintStream stream = new PrintStream(output, true, CHARSET_UTF8); + assertTrue(post(url).receive(stream).ok()); + stream.close(); + assertEquals("content", output.toString(CHARSET_UTF8)); + } + + /** + * Verify response in {@link File} + * + * @throws Exception + */ + @Test + public void receiveFile() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + File output = File.createTempFile("output", ".txt"); + assertTrue(post(url).receive(output).ok()); + StringBuilder buffer = new StringBuilder(); + BufferedReader reader = new BufferedReader(new FileReader(output)); + int read; + while ((read = reader.read()) != -1) + buffer.append((char) read); + reader.close(); + assertEquals("content", buffer.toString()); + } + + /** + * Verify certificate and host helpers on HTTPS connection + * + * @throws Exception + */ + @Test + public void httpsTrust() throws Exception { + assertNotNull(get("https://localhost").trustAllCerts().trustAllHosts()); + } + + /** + * Verify certificate and host helpers ignore non-HTTPS connection + * + * @throws Exception + */ + @Test + public void httpTrust() throws Exception { + assertNotNull(get("http://localhost").trustAllCerts().trustAllHosts()); + } + + /** + * Verify hostname verifier is set and accepts all + */ + @Test + public void verifierAccepts() { + HttpRequest request = get("https://localhost"); + HttpsURLConnection connection = (HttpsURLConnection) request + .getConnection(); + request.trustAllHosts(); + assertNotNull(connection.getHostnameVerifier()); + assertTrue(connection.getHostnameVerifier().verify(null, null)); + } + + /** + * Verify single hostname verifier is created across all calls + */ + @Test + public void singleVerifier() { + HttpRequest request1 = get("https://localhost").trustAllHosts(); + HttpRequest request2 = get("https://localhost").trustAllHosts(); + assertNotNull(((HttpsURLConnection) request1.getConnection()) + .getHostnameVerifier()); + assertNotNull(((HttpsURLConnection) request2.getConnection()) + .getHostnameVerifier()); + assertEquals( + ((HttpsURLConnection) request1.getConnection()).getHostnameVerifier(), + ((HttpsURLConnection) request2.getConnection()).getHostnameVerifier()); + } + + /** + * Verify single SSL socket factory is created across all calls + */ + @Test + public void singleSslSocketFactory() { + HttpRequest request1 = get("https://localhost").trustAllCerts(); + HttpRequest request2 = get("https://localhost").trustAllCerts(); + assertNotNull(((HttpsURLConnection) request1.getConnection()) + .getSSLSocketFactory()); + assertNotNull(((HttpsURLConnection) request2.getConnection()) + .getSSLSocketFactory()); + assertEquals( + ((HttpsURLConnection) request1.getConnection()).getSSLSocketFactory(), + ((HttpsURLConnection) request2.getConnection()).getSSLSocketFactory()); + } + + /** + * Send a stream that throws an exception when read from + * + * @throws Exception + */ + @Test + public void sendErrorReadStream() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + final IOException readCause = new IOException(); + final IOException closeCause = new IOException(); + InputStream stream = new InputStream() { + + public int read() throws IOException { + throw readCause; + } + + public void close() throws IOException { + throw closeCause; + } + }; + try { + post(url).send(stream); + fail("Exception not thrown"); + } catch (HttpRequestException e) { + assertEquals(readCause, e.getCause()); + } + } + + /** + * Send a stream that throws an exception when read from + * + * @throws Exception + */ + @Test + public void sendErrorCloseStream() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + final IOException closeCause = new IOException(); + InputStream stream = new InputStream() { + + public int read() throws IOException { + return -1; + } + + public void close() throws IOException { + throw closeCause; + } + }; + try { + post(url).ignoreCloseExceptions(false).send(stream); + fail("Exception not thrown"); + } catch (HttpRequestException e) { + assertEquals(closeCause, e.getCause()); + } + } + + /** + * Make a GET request and get the code using an {@link AtomicInteger} + * + * @throws Exception + */ + @Test + public void getToOutputCode() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + AtomicInteger code = new AtomicInteger(0); + get(url).code(code); + assertEquals(HTTP_OK, code.get()); + } + + /** + * Make a GET request and get the body using an {@link AtomicReference} + * + * @throws Exception + */ + @Test + public void getToOutputBody() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("hello world"); + } catch (IOException e) { + fail(); + } + } + }; + AtomicReference body = new AtomicReference(null); + get(url).body(body); + assertEquals("hello world", body.get()); + } + + /** + * Make a GET request and get the body using an {@link AtomicReference} + * + * @throws Exception + */ + @Test + public void getToOutputBodyWithCharset() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("hello world"); + } catch (IOException e) { + fail(); + } + } + }; + AtomicReference body = new AtomicReference(null); + get(url).body(body, CHARSET_UTF8); + assertEquals("hello world", body.get()); + } + + + /** + * Make a GET request that should be compressed + * + * @throws Exception + */ + @Test + public void getGzipped() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + if (!"gzip".equals(request.getHeader("Accept-Encoding"))) + return; + + response.setHeader("Content-Encoding", "gzip"); + GZIPOutputStream output; + try { + output = new GZIPOutputStream(response.getOutputStream()); + } catch (IOException e) { + throw new RuntimeException(e); + } + try { + output.write("hello compressed".getBytes(CHARSET_UTF8)); + } catch (IOException e) { + throw new RuntimeException(e); + } finally { + try { + output.close(); + } catch (IOException ignored) { + // Ignored + } + } + } + }; + HttpRequest request = get(url).acceptGzipEncoding().uncompress(true); + assertTrue(request.ok()); + assertEquals("hello compressed", request.body(CHARSET_UTF8)); + } + + /** + * Make a GET request that should be compressed but isn't + * + * @throws Exception + */ + @Test + public void getNonGzippedWithUncompressEnabled() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + if (!"gzip".equals(request.getHeader("Accept-Encoding"))) + return; + + write("hello not compressed"); + } + }; + HttpRequest request = get(url).acceptGzipEncoding().uncompress(true); + assertTrue(request.ok()); + assertEquals("hello not compressed", request.body(CHARSET_UTF8)); + } + + /** + * Get header with multiple response values + * + * @throws Exception + */ + @Test + public void getHeaders() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.addHeader("a", "1"); + response.addHeader("a", "2"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + String[] values = request.headers("a"); + assertNotNull(values); + assertEquals(2, values.length); + assertTrue(Arrays.asList(values).contains("1")); + assertTrue(Arrays.asList(values).contains("2")); + } + + /** + * Get header values when not set in response + * + * @throws Exception + */ + @Test + public void getEmptyHeaders() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + String[] values = request.headers("a"); + assertNotNull(values); + assertEquals(0, values.length); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getSingleParameter() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=d"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertEquals("d", request.parameter("a", "c")); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getMultipleParameters() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=d;e=f"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertEquals("d", request.parameter("a", "c")); + assertEquals("f", request.parameter("a", "e")); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getSingleParameterQuoted() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=\"d\""); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertEquals("d", request.parameter("a", "c")); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getMultipleParametersQuoted() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=\"d\";e=\"f\""); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertEquals("d", request.parameter("a", "c")); + assertEquals("f", request.parameter("a", "e")); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getMissingParameter() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=d"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertNull(request.parameter("a", "e")); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getParameterFromMissingHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c=d"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertNull(request.parameter("b", "c")); + assertTrue(request.parameters("b").isEmpty()); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getEmptyParameter() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;c="); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertNull(request.parameter("a", "c")); + assertTrue(request.parameters("a").isEmpty()); + } + + /** + * Get header parameter value + * + * @throws Exception + */ + @Test + public void getEmptyParameters() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "b;"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + assertNull(request.parameter("a", "c")); + assertTrue(request.parameters("a").isEmpty()); + } + + /** + * Get header parameter values + * + * @throws Exception + */ + @Test + public void getParameters() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "value;b=c;d=e"); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + Map params = request.parameters("a"); + assertNotNull(params); + assertEquals(2, params.size()); + assertEquals("c", params.get("b")); + assertEquals("e", params.get("d")); + } + + /** + * Get header parameter values + * + * @throws Exception + */ + @Test + public void getQuotedParameters() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "value;b=\"c\";d=\"e\""); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + Map params = request.parameters("a"); + assertNotNull(params); + assertEquals(2, params.size()); + assertEquals("c", params.get("b")); + assertEquals("e", params.get("d")); + } + + /** + * Get header parameter values + * + * @throws Exception + */ + @Test + public void getMixQuotedParameters() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("a", "value; b=c; d=\"e\""); + } + }; + HttpRequest request = get(url); + assertTrue(request.ok()); + Map params = request.parameters("a"); + assertNotNull(params); + assertEquals(2, params.size()); + assertEquals("c", params.get("b")); + assertEquals("e", params.get("d")); + } + + /** + * Verify getting date header with default value + * + * @throws Exception + */ + @Test + public void missingDateHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + assertEquals(1234L, get(url).dateHeader("missing", 1234L)); + } + + /** + * Verify getting date header with default value + * + * @throws Exception + */ + @Test + public void malformedDateHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("malformed", "not a date"); + } + }; + assertEquals(1234L, get(url).dateHeader("malformed", 1234L)); + } + + /** + * Verify getting int header with default value + * + * @throws Exception + */ + @Test + public void missingIntHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + assertEquals(4321, get(url).intHeader("missing", 4321)); + } + + /** + * Verify getting int header with default value + * + * @throws Exception + */ + @Test + public void malformedIntHeader() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + response.setHeader("malformed", "not an integer"); + } + }; + assertEquals(4321, get(url).intHeader("malformed", 4321)); + } + + /** + * Verify sending form data as a sequence of {@link Entry} objects + * + * @throws Exception + */ + @Test + public void postFormAsEntries() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + Map data = new LinkedHashMap(); + data.put("name", "user"); + data.put("number", "100"); + HttpRequest request = post(url); + for (Entry entry : data.entrySet()) + request.form(entry); + int code = request.code(); + assertEquals(HTTP_OK, code); + assertEquals("name=user&number=100", body.get()); + } + + /** + * Verify sending form data where entry value is null + * + * @throws Exception + */ + @Test + public void postFormEntryWithNullValue() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + Map data = new LinkedHashMap(); + data.put("name", null); + HttpRequest request = post(url); + for (Entry entry : data.entrySet()) + request.form(entry); + int code = request.code(); + assertEquals(HTTP_OK, code); + assertEquals("name=", body.get()); + } + + /** + * Verify POST with query parameters + * + * @throws Exception + */ + @Test + public void postWithMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "user"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = post(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("POST", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify POST with query parameters + * + * @throws Exception + */ + @Test + public void postWithVaragsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = post(url, false, "name", "user", "number", "100"); + assertTrue(request.ok()); + assertEquals("POST", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify POST with escaped query parameters + * + * @throws Exception + */ + @Test + public void postWithEscapedMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "us er"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = post(url, inputParams, true); + assertTrue(request.ok()); + assertEquals("POST", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify POST with escaped query parameters + * + * @throws Exception + */ + @Test + public void postWithEscapedVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = post(url, true, "name", "us er", "number", "100"); + assertTrue(request.ok()); + assertEquals("POST", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify POST with numeric query parameters + * + * @throws Exception + */ + @Test + public void postWithNumericQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put(1, 2); + inputParams.put(3, 4); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("1", request.getParameter("1")); + outputParams.put("3", request.getParameter("3")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = post(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("POST", method.get()); + assertEquals("2", outputParams.get("1")); + assertEquals("4", outputParams.get("3")); + } + + /** + * Verify GET with query parameters + * + * @throws Exception + */ + @Test + public void getWithMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "user"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("GET", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify GET with query parameters + * + * @throws Exception + */ + @Test + public void getWithVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url, false, "name", "user", "number", "100"); + assertTrue(request.ok()); + assertEquals("GET", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify GET with escaped query parameters + * + * @throws Exception + */ + @Test + public void getWithEscapedMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "us er"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url, inputParams, true); + assertTrue(request.ok()); + assertEquals("GET", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify GET with escaped query parameters + * + * @throws Exception + */ + @Test + public void getWithEscapedVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = get(url, true, "name", "us er", "number", "100"); + assertTrue(request.ok()); + assertEquals("GET", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify DELETE with query parameters + * + * @throws Exception + */ + @Test + public void deleteWithMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "user"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("DELETE", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify DELETE with query parameters + * + * @throws Exception + */ + @Test + public void deleteWithVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(url, false, "name", "user", "number", "100"); + assertTrue(request.ok()); + assertEquals("DELETE", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify DELETE with escaped query parameters + * + * @throws Exception + */ + @Test + public void deleteWithEscapedMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "us er"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(url, inputParams, true); + assertTrue(request.ok()); + assertEquals("DELETE", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify DELETE with escaped query parameters + * + * @throws Exception + */ + @Test + public void deleteWithEscapedVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = delete(url, true, "name", "us er", "number", "100"); + assertTrue(request.ok()); + assertEquals("DELETE", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify PUT with query parameters + * + * @throws Exception + */ + @Test + public void putWithMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "user"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("PUT", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify PUT with query parameters + * + * @throws Exception + */ + @Test + public void putWithVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(url, false, "name", "user", "number", "100"); + assertTrue(request.ok()); + assertEquals("PUT", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify PUT with escaped query parameters + * + * @throws Exception + */ + @Test + public void putWithEscapedMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "us er"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(url, inputParams, true); + assertTrue(request.ok()); + assertEquals("PUT", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify PUT with escaped query parameters + * + * @throws Exception + */ + @Test + public void putWithEscapedVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = put(url, true, "name", "us er", "number", "100"); + assertTrue(request.ok()); + assertEquals("PUT", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify HEAD with query parameters + * + * @throws Exception + */ + @Test + public void headWithMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "user"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(url, inputParams, false); + assertTrue(request.ok()); + assertEquals("HEAD", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify HEAD with query parameters + * + * @throws Exception + */ + @Test + public void headWithVaragsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(url, false, "name", "user", "number", "100"); + assertTrue(request.ok()); + assertEquals("HEAD", method.get()); + assertEquals("user", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify HEAD with escaped query parameters + * + * @throws Exception + */ + @Test + public void headWithEscapedMappedQueryParams() throws Exception { + Map inputParams = new HashMap(); + inputParams.put("name", "us er"); + inputParams.put("number", "100"); + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(url, inputParams, true); + assertTrue(request.ok()); + assertEquals("HEAD", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Verify HEAD with escaped query parameters + * + * @throws Exception + */ + @Test + public void headWithEscapedVarargsQueryParams() throws Exception { + final Map outputParams = new HashMap(); + final AtomicReference method = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + method.set(request.getMethod()); + outputParams.put("name", request.getParameter("name")); + outputParams.put("number", request.getParameter("number")); + response.setStatus(HTTP_OK); + } + }; + HttpRequest request = head(url, true, "name", "us er", "number", "100"); + assertTrue(request.ok()); + assertEquals("HEAD", method.get()); + assertEquals("us er", outputParams.get("name")); + assertEquals("100", outputParams.get("number")); + } + + /** + * Append with base URL with no path + * + * @throws Exception + */ + @Test + public void appendMappedQueryParamsWithNoPath() throws Exception { + assertEquals( + "http://test.com/?a=b", + HttpRequest.append("http://test.com", + Collections.singletonMap("a", "b"))); + } + + /** + * Append with base URL with no path + * + * @throws Exception + */ + @Test + public void appendVarargsQueryParmasWithNoPath() throws Exception { + assertEquals("http://test.com/?a=b", + HttpRequest.append("http://test.com", "a", "b")); + } + + /** + * Append with base URL with path + * + * @throws Exception + */ + @Test + public void appendMappedQueryParamsWithPath() throws Exception { + assertEquals( + "http://test.com/segment1?a=b", + HttpRequest.append("http://test.com/segment1", + Collections.singletonMap("a", "b"))); + assertEquals( + "http://test.com/?a=b", + HttpRequest.append("http://test.com/", + Collections.singletonMap("a", "b"))); + } + + /** + * Append with base URL with path + * + * @throws Exception + */ + @Test + public void appendVarargsQueryParamsWithPath() throws Exception { + assertEquals("http://test.com/segment1?a=b", + HttpRequest.append("http://test.com/segment1", "a", "b")); + assertEquals("http://test.com/?a=b", + HttpRequest.append("http://test.com/", "a", "b")); + } + + /** + * Append multiple params + * + * @throws Exception + */ + @Test + public void appendMultipleMappedQueryParams() throws Exception { + Map params = new LinkedHashMap(); + params.put("a", "b"); + params.put("c", "d"); + assertEquals("http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1", params)); + } + + /** + * Append multiple params + * + * @throws Exception + */ + @Test + public void appendMultipleVarargsQueryParams() throws Exception { + assertEquals("http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1", "a", "b", "c", "d")); + } + + /** + * Append null params + * + * @throws Exception + */ + @Test + public void appendNullMappedQueryParams() throws Exception { + assertEquals("http://test.com/1", + HttpRequest.append("http://test.com/1", (Map) null)); + } + + /** + * Append null params + * + * @throws Exception + */ + @Test + public void appendNullVaragsQueryParams() throws Exception { + assertEquals("http://test.com/1", + HttpRequest.append("http://test.com/1", (Object[]) null)); + } + + /** + * Append empty params + * + * @throws Exception + */ + @Test + public void appendEmptyMappedQueryParams() throws Exception { + assertEquals( + "http://test.com/1", + HttpRequest.append("http://test.com/1", + Collections. emptyMap())); + } + + /** + * Append empty params + * + * @throws Exception + */ + @Test + public void appendEmptyVarargsQueryParams() throws Exception { + assertEquals("http://test.com/1", + HttpRequest.append("http://test.com/1", new Object[0])); + } + + /** + * Append params with null values + * + * @throws Exception + */ + @Test + public void appendWithNullMappedQueryParamValues() throws Exception { + Map params = new LinkedHashMap(); + params.put("a", null); + params.put("b", null); + assertEquals("http://test.com/1?a=&b=", + HttpRequest.append("http://test.com/1", params)); + } + + /** + * Append params with null values + * + * @throws Exception + */ + @Test + public void appendWithNullVaragsQueryParamValues() throws Exception { + assertEquals("http://test.com/1?a=&b=", + HttpRequest.append("http://test.com/1", "a", null, "b", null)); + } + + /** + * Try to append with wrong number of arguments + */ + @Test(expected = IllegalArgumentException.class) + public void appendOddNumberOfParams() { + HttpRequest.append("http://test.com", "1"); + } + + /** + * Append with base URL already containing a '?' + */ + @Test + public void appendMappedQueryParamsWithExistingQueryStart() { + assertEquals( + "http://test.com/1?a=b", + HttpRequest.append("http://test.com/1?", + Collections.singletonMap("a", "b"))); + } + + /** + * Append with base URL already containing a '?' + */ + @Test + public void appendVarargsQueryParamsWithExistingQueryStart() { + assertEquals("http://test.com/1?a=b", + HttpRequest.append("http://test.com/1?", "a", "b")); + } + + /** + * Append with base URL already containing a '?' + */ + @Test + public void appendMappedQueryParamsWithExistingParams() { + assertEquals( + "http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1?a=b", + Collections.singletonMap("c", "d"))); + assertEquals( + "http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1?a=b&", + Collections.singletonMap("c", "d"))); + + } + + /** + * Append with base URL already containing a '?' + */ + @Test + public void appendWithVarargsQueryParamsWithExistingParams() { + assertEquals("http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1?a=b", "c", "d")); + assertEquals("http://test.com/1?a=b&c=d", + HttpRequest.append("http://test.com/1?a=b&", "c", "d")); + } + + /** + * Get a 500 + * + * @throws Exception + */ + @Test + public void serverErrorCode() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_INTERNAL_ERROR); + } + }; + HttpRequest request = get(url); + assertNotNull(request); + assertTrue(request.serverError()); + } + + /** + * Get a 400 + * + * @throws Exception + */ + @Test + public void badRequestCode() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_BAD_REQUEST); + } + }; + HttpRequest request = get(url); + assertNotNull(request); + assertTrue(request.badRequest()); + } + + /** + * Get a 304 + * + * @throws Exception + */ + @Test + public void notModifiedCode() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_NOT_MODIFIED); + } + }; + HttpRequest request = get(url); + assertNotNull(request); + assertTrue(request.notModified()); + } + + /** + * Verify data is sent when receiving response without first calling + * {@link HttpRequest#code()} + * + * @throws Exception + */ + @Test + public void sendReceiveWithoutCode() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + try { + response.getWriter().write("world"); + } catch (IOException ignored) { + // Ignored + } + response.setStatus(HTTP_OK); + } + }; + + HttpRequest request = post(url).ignoreCloseExceptions(false); + assertEquals("world", request.send("hello").body()); + assertEquals("hello", body.get()); + } + + /** + * Verify data is send when receiving response headers without first calling + * {@link HttpRequest#code()} + * + * @throws Exception + */ + @Test + public void sendHeadersWithoutCode() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setHeader("h1", "v1"); + response.setHeader("h2", "v2"); + response.setStatus(HTTP_OK); + } + }; + + HttpRequest request = post(url).ignoreCloseExceptions(false); + Map> headers = request.send("hello").headers(); + assertEquals("v1", headers.get("h1").get(0)); + assertEquals("v2", headers.get("h2").get(0)); + assertEquals("hello", body.get()); + } + + /** + * Verify data is send when receiving response date header without first + * calling {@link HttpRequest#code()} + * + * @throws Exception + */ + @Test + public void sendDateHeaderWithoutCode() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setDateHeader("Date", 1000); + response.setStatus(HTTP_OK); + } + }; + + HttpRequest request = post(url).ignoreCloseExceptions(false); + assertEquals(1000, request.send("hello").date()); + assertEquals("hello", body.get()); + } + + /** + * Verify data is send when receiving response integer header without first + * calling {@link HttpRequest#code()} + * + * @throws Exception + */ + @Test + public void sendIntHeaderWithoutCode() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setIntHeader("Width", 9876); + response.setStatus(HTTP_OK); + } + }; + + HttpRequest request = post(url).ignoreCloseExceptions(false); + assertEquals(9876, request.send("hello").intHeader("Width")); + assertEquals("hello", body.get()); + } + + /** + * Verify custom connection factory + */ + @Test + public void customConnectionFactory() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + + ConnectionFactory factory = new ConnectionFactory() { + + public HttpURLConnection create(URL otherUrl) throws IOException { + return (HttpURLConnection) new URL(url).openConnection(); + } + + public HttpURLConnection create(URL url, Proxy proxy) throws IOException { + throw new IOException(); + } + }; + + HttpRequest.setConnectionFactory(factory); + int code = get("http://not/a/real/url").code(); + assertEquals(200, code); + } + + /** + * Verify setting a null connection factory restores to the default one + */ + @Test + public void nullConnectionFactory() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + } + }; + + HttpRequest.setConnectionFactory(null); + int code = get(url).code(); + assertEquals(200, code); + } + + /** + * Verify reading response body for empty 200 + * + * @throws Exception + */ + @Test + public void streamOfEmptyOkResponse() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(200); + } + }; + assertEquals("", get(url).body()); + } + + /** + * Verify reading response body for empty 400 + * + * @throws Exception + */ + @Test + public void bodyOfEmptyErrorResponse() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_BAD_REQUEST); + } + }; + assertEquals("", get(url).body()); + } + + /** + * Verify reading response body for non-empty 400 + * + * @throws Exception + */ + @Test + public void bodyOfNonEmptyErrorResponse() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_BAD_REQUEST); + try { + response.getWriter().write("error"); + } catch (IOException ignored) { + // Ignored + } + } + }; + assertEquals("error", get(url).body()); + } + + /** + * Verify progress callback when sending a file + * + * @throws Exception + */ + @Test + public void progressCallbackSend() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + final File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + + final AtomicInteger tx = new AtomicInteger(0); + ProgressCallback progress = new ProgressCallback() { + public void onProgress(int transferred, int total) { + assertEquals(file.length(), total); + assertEquals(tx.incrementAndGet(), transferred); + } + }; + post(url).bufferSize(1).progress(progress).send(file); + assertEquals(file.length(), tx.get()); + } + + /** + * Verify progress callback when sending from an InputStream + * + * @throws Exception + */ + @Test + public void progressCallbackSendInputStream() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + InputStream input = new FileInputStream(file); + final AtomicInteger tx = new AtomicInteger(0); + ProgressCallback progress = new ProgressCallback() { + public void onProgress(int transferred, int total) { + assertEquals(0, total); + assertEquals(tx.incrementAndGet(), transferred); + } + }; + post(url).bufferSize(1).progress(progress).send(input); + assertEquals(file.length(), tx.get()); + } + + /** + * Verify progress callback when sending from a Reader + * + * @throws Exception + */ + @Test + public void progressCallbackSendReader() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + + final AtomicInteger tx = new AtomicInteger(0); + ProgressCallback progress = new ProgressCallback() { + public void onProgress(int transferred, int total) { + assertEquals(-1, total); + assertEquals(tx.incrementAndGet(), transferred); + } + }; + File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + post(url).progress(progress).bufferSize(1).send(new FileReader(file)); + assertEquals(file.length(), tx.get()); + } + + /** + * Verify progress callback when receiving to a Writer + * + * @throws Exception + */ + @Test + public void progressCallbackReceive() throws Exception { + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + response.setStatus(HTTP_OK); + try { + response.getWriter().print("content"); + } catch (IOException e) { + fail(); + } + } + }; + ProgressCallback progress = new ProgressCallback() { + int tx = 1; + + public void onProgress(int transferred, int total) { + assertEquals(-1, total); + assertEquals(tx++, transferred); + } + }; + StringWriter writer = new StringWriter(); + post(url).progress(progress).bufferSize(1).receive(writer); + } + + /** + * Verify progress callback doesn't cause an exception when it's null + * + * @throws Exception + */ + @Test + public void nullProgressCallback() throws Exception { + final AtomicReference body = new AtomicReference(); + handler = new RequestHandler() { + + @Override + public void handle(Request request, HttpServletResponse response) { + body.set(new String(read())); + response.setStatus(HTTP_OK); + } + }; + File file = File.createTempFile("post", ".txt"); + new FileWriter(file).append("hello").close(); + int code = post(url).progress(null).send(file).code(); + assertEquals(HTTP_OK, code); + assertEquals("hello", body.get()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.github.kevinsawicki.http.HttpRequest$RequestOutputStream` acquired by call to `send(...)` at line 3519 is not released after line 3519. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HttpRequestTest.progressCallbackSendInputStream() + +### Procedure Id: +com.github.kevinsawicki.http.HttpRequestTest.progressCallbackSendInputStream():void.dc3195443ce7cac3c65e73671f267f65 + +### File: +lib/src/test/java/com/github/kevinsawicki/http/HttpRequestTest.java + +### Key: +HttpRequestTest.java|progressCallbackSendInputStream|RESOURCE_LEAK + +### Node Key: +85e9fca5019395547dab21ac487d45be + +### Hash: +b0c2385076febde5261fd0a157b45188 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8533/instruction.md b/inferredbugs-8533/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb3f1b945138dfdca6bf5e521b1a5af7a9bdb233 --- /dev/null +++ b/inferredbugs-8533/instruction.md @@ -0,0 +1,163 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fscrawler +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to David Pilato (the "Author") under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Author licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package fr.pilato.elasticsearch.crawler.fs.fileabstractor; + +import fr.pilato.elasticsearch.crawler.fs.meta.settings.FsSettings; +import fr.pilato.elasticsearch.crawler.fs.util.FsCrawlerUtil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Collection; + +public class FileAbstractorFile extends FileAbstractor { + public FileAbstractorFile(FsSettings fsSettings) { + super(fsSettings); + } + + @Override + public FileAbstractModel toFileAbstractModel(String path, File file) { + FileAbstractModel model = new FileAbstractModel(); + model.name = file.getName(); + model.file = file.isFile(); + model.directory = !model.file; + model.lastModifiedDate = Instant.ofEpochMilli(file.lastModified()); + model.creationDate = FsCrawlerUtil.getCreationTime(file); + model.path = path; + model.fullpath = file.getAbsolutePath(); + model.size = file.length(); + model.owner = FsCrawlerUtil.getOwnerName(file); + model.group = FsCrawlerUtil.getGroupName(file); + + return model; + } + + @Override + public InputStream getInputStream(FileAbstractModel file) throws Exception { + return new FileInputStream(new File(file.fullpath)); + } + + @Override + public Collection getFiles(String dir) { + if (logger.isDebugEnabled()) logger.debug("Listing local files from {}", dir); + File[] files = new File(dir).listFiles(); + + Collection result = new ArrayList<>(files.length); + + // Iterate other files + for (File file : files) { + result.add(toFileAbstractModel(dir, file)); + } + + if (logger.isDebugEnabled()) logger.debug("{} local files found", result.size()); + return result; + } + + @Override + public boolean exists(String dir) throws Exception { + return new File(dir).exists(); + } + + @Override + public void open() throws Exception { + + } + + @Override + public void close() throws Exception { + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `files` last assigned on line 62 could be null and is dereferenced at line 64. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Collection FileAbstractorFile.getFiles(String) + +### Procedure Id: +fr.pilato.elasticsearch.crawler.fs.fileabstractor.FileAbstractorFile.getFiles(java.lang.String):java.82be8905275237c22c29c313d58adb61 + +### File: +src/main/java/fr/pilato/elasticsearch/crawler/fs/fileabstractor/FileAbstractorFile.java + +### Key: +FileAbstractorFile.java|getFiles|NULL_DEREFERENCE + +### Node Key: +95b6990c60ada383dc3db02b59d65f16 + +### Hash: +d7e311f95c7f10e4109fea0f13e38a38 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8534/instruction.md b/inferredbugs-8534/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5fe5b326cd491c06737c968923352fda393b12f6 --- /dev/null +++ b/inferredbugs-8534/instruction.md @@ -0,0 +1,590 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fscrawler +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to David Pilato (the "Author") under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Author licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package fr.pilato.elasticsearch.crawler.fs.test.integration; + +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters; +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering; +import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; +import fr.pilato.elasticsearch.containers.ElasticsearchContainer; +import fr.pilato.elasticsearch.crawler.fs.client.ElasticsearchClient; +import fr.pilato.elasticsearch.crawler.fs.framework.TimeValue; +import fr.pilato.elasticsearch.crawler.fs.rest.RestJsonProvider; +import fr.pilato.elasticsearch.crawler.fs.settings.Elasticsearch; +import fr.pilato.elasticsearch.crawler.fs.settings.Rest; +import fr.pilato.elasticsearch.crawler.fs.test.framework.AbstractFSCrawlerTestCase; +import fr.pilato.elasticsearch.crawler.fs.test.framework.TestContainerThreadFilter; +import org.apache.http.HttpHost; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.logging.log4j.Level; +import org.elasticsearch.Version; +import org.elasticsearch.action.main.MainResponse; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.client.RestClient; +import org.elasticsearch.client.RestClientBuilder; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataMultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; +import org.hamcrest.Matcher; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.testcontainers.containers.wait.HttpWaitStrategy; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.MediaType; +import java.io.File; +import java.io.IOException; +import java.net.ConnectException; +import java.net.URISyntaxException; +import java.net.URL; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.time.Duration; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.copyDefaultResources; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.copyDirs; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.unzip; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThan; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.fail; +import static org.junit.Assume.assumeThat; + +/** + * Integration tests are using Docker behind the scene to start an elasticsearch instance + * running by default locally on 127.0.0.1:9200 + * + * Note that all existing data in this cluster might be removed + * + * If you want to run tests against a remote cluster, please launch tests using + * tests.cluster.host and tests.cluster.port properties: + * + * mvn clean install -Dtests.cluster.host=127.0.0.1 -Dtests.cluster.port=9400 + * + * When tests.cluster.host is set, the internal Docker container is not ran anymore. + * + * You can choose running against http or https with tests.cluster.scheme (defaults to HTTP): + * + * mvn clean install -Dtests.cluster.scheme=HTTPS + * + * If the cluster is running with x-pack and using the default username and passwords + * of x-pack, tests can be run as well. You can overwrite default username and password + * with tests.cluster.user and tests.cluster.password + * + * mvn clean install -Dtests.cluster.user=elastic -Dtests.cluster.pass=changeme + * + * All integration tests might be skipped if the cluster is not running + */ +@ThreadLeakFilters(filters = {TestContainerThreadFilter.class}) +@ThreadLeakScope(ThreadLeakScope.Scope.SUITE) +@ThreadLeakLingering(linger = 5000) // 5 sec lingering +public abstract class AbstractITCase extends AbstractFSCrawlerTestCase { + + static Path metadataDir = null; + + private static ElasticsearchContainer container; + private static RestClient esRestClient; + + @BeforeClass + public static void createFsCrawlerJobDir() throws IOException, URISyntaxException { + // We also need to create default mapping files + metadataDir = rootTmpDir.resolve(".fscrawler"); + if (Files.notExists(metadataDir)) { + Files.createDirectory(metadataDir); + } + copyDefaultResources(metadataDir); + staticLogger.debug(" --> Test metadata dir ready in [{}]", metadataDir); + } + + @AfterClass + public static void printMetadataDirContent() throws IOException { + // If something goes wrong while initializing, we might have no metadataDir at all. + if (metadataDir != null) { + staticLogger.debug("ls -l {}", metadataDir); + Files.list(metadataDir).forEach(path -> staticLogger.debug("{}", path)); + } + } + + private final static Integer DEFAULT_TEST_CLUSTER_PORT = 9200; + private final static String DEFAULT_USERNAME = "elastic"; + private final static String DEFAULT_PASSWORD = "changeme"; + private final static Integer DEFAULT_TEST_REST_PORT = 8080; + + static ElasticsearchClient elasticsearchClient; + + private static String testClusterHost; + private static int testClusterPort; + private final static String testClusterUser = System.getProperty("tests.cluster.user", DEFAULT_USERNAME); + private final static String testClusterPass = System.getProperty("tests.cluster.pass", DEFAULT_PASSWORD); + private final static Elasticsearch.Node.Scheme testClusterScheme = Elasticsearch.Node.Scheme.parse(System.getProperty("tests.cluster.scheme", Elasticsearch.Node.Scheme.HTTP.toString())); + final static int testRestPort = Integer.parseInt(System.getProperty("tests.rest.port", DEFAULT_TEST_REST_PORT.toString())); + static Elasticsearch elasticsearchWithSecurity; + + private static WebTarget target; + private static Client client; + + @BeforeClass + public static void copyResourcesToTestDir() throws IOException { + Path testResourceTarget = rootTmpDir.resolve("resources"); + if (Files.notExists(testResourceTarget)) { + staticLogger.debug(" --> Creating test resources dir in [{}]", testResourceTarget); + Files.createDirectory(testResourceTarget); + } + + // We copy files from the src dir to the temp dir + copyTestDocumentsToTargetDir(testResourceTarget, "documents", "/fscrawler-test-documents-marker.txt"); + + staticLogger.debug(" --> Test resources ready in [{}]:", testResourceTarget); + } + + /** + * Copy test documents to the test dir so we will be able to run tests against them + * @param target target directory. + * @param sourceDirName source subdir name where files will be copied or extracted to. + * @param marker one of the filename which is available in the classpath which contains + * the test documents or within a jar + * @throws IOException In case of IO problem + */ + private static void copyTestDocumentsToTargetDir(Path target, String sourceDirName, String marker) throws IOException { + URL resource = AbstractFSCrawlerTestCase.class.getResource(marker); + + switch (resource.getProtocol()) { + case "file": { + Path finalTarget = target.resolve(sourceDirName); + if (Files.notExists(finalTarget)) { + staticLogger.debug(" --> Creating test dir named [{}]", finalTarget); + Files.createDirectory(finalTarget); + } + // We are running our tests from the IDE most likely and documents are directly available in the classpath + Path source = Paths.get(resource.getPath()).getParent().resolve(sourceDirName); + if (Files.notExists(source)) { + staticLogger.error("directory [{}] should be copied to [{}]", source, target); + throw new RuntimeException(source + " doesn't seem to exist. Check your JUnit tests."); + } + + staticLogger.info("-> Copying test documents from [{}] to [{}]", source, finalTarget); + copyDirs(source, finalTarget); + break; + } + case "jar": { + if (Files.notExists(target)) { + staticLogger.debug(" --> Creating test dir named [{}]", target); + Files.createDirectory(target); + } + // We are running our tests from the CLI most likely and documents are provided within a JAR as a dependency + String fileInJar = resource.getPath(); + int i = fileInJar.indexOf("!/"); + String jarFile = fileInJar.substring(0, i); + + staticLogger.info("-> Unzipping test documents from [{}] to [{}]", jarFile, target); + unzip(jarFile, target); + break; + } + default: + fail("Unknown protocol for IT document sources: " + resource.getProtocol()); + break; + } + } + + @BeforeClass + public static void startElasticsearchRestClient() throws IOException { + testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString())); + testClusterHost = System.getProperty("tests.cluster.host"); + + if (testClusterHost == null) { + // We start an elasticsearch Docker instance + Properties props = new Properties(); + props.load(AbstractITCase.class.getResourceAsStream("/elasticsearch.version.properties")); + container = new ElasticsearchContainer().withVersion(props.getProperty("version")); + container.withEnv("ELASTIC_PASSWORD", testClusterPass); + container.setWaitStrategy( + new HttpWaitStrategy() + .forStatusCode(200) + .withBasicCredentials(testClusterUser, testClusterPass) + .withStartupTimeout(Duration.ofSeconds(90))); + container.start(); + + testClusterHost = container.getHost().getHostName(); + testClusterPort = container.getFirstMappedPort(); + } else { + testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString())); + } + + if (testClusterHost == null) { + Thread.dumpStack(); + } + + // We build the elasticsearch High Level Client based on the parameters + elasticsearchClient = new ElasticsearchClient(getClientBuilder( + new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass)); + elasticsearchWithSecurity = Elasticsearch.builder() + .addNode(Elasticsearch.Node.builder() + .setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build()) + .setUsername(testClusterUser) + .setPassword(testClusterPass) + .build(); + + // We make sure the cluster is running + testClusterRunning(); + + // We set what will be elasticsearch behavior as it depends on the cluster version + elasticsearchClient.setElasticsearchBehavior(); + } + + @BeforeClass + public static void startRestClient() { + // create the client + client = ClientBuilder.newBuilder() + .register(MultiPartFeature.class) + .register(RestJsonProvider.class) + .register(JacksonFeature.class) + .build(); + + target = client.target(Rest.builder().setPort(testRestPort).build().url()); + } + + @AfterClass + public static void stopRestClient() throws IOException { + if (client != null) { + client.close(); + client = null; + } + + if (esRestClient != null) { + esRestClient.close(); + esRestClient = null; + } + + if (container != null) { + container.close(); + container = null; + } + } + + private static RestClientBuilder getClientBuilder(HttpHost host, String username, String password) { + final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, + new UsernamePasswordCredentials(username, password)); + + return RestClient.builder(host) + .setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)); + } + + private static void testClusterRunning() throws IOException { + try { + MainResponse info = elasticsearchClient.info(); + staticLogger.info("Starting integration tests against an external cluster running elasticsearch [{}]", info.getVersion()); + } catch (ConnectException e) { + // If we have an exception here, let's ignore the test + staticLogger.warn("Integration tests are skipped: [{}]", e.getMessage()); + assumeThat("Integration tests are skipped", e.getMessage(), not(containsString("Connection refused"))); + } + } + + @AfterClass + public static void stopElasticsearchClient() throws IOException { + staticLogger.info("Stopping integration tests against an external cluster"); + if (elasticsearchClient != null) { + elasticsearchClient.shutdown(); + elasticsearchClient = null; + staticLogger.info("Elasticsearch client stopped"); + } + } + + private static final String testCrawlerPrefix = "fscrawler_"; + + static Elasticsearch generateElasticsearchConfig(String indexName, String indexFolderName, int bulkSize, + TimeValue timeValue) { + Elasticsearch.Builder builder = Elasticsearch.builder() + .addNode(Elasticsearch.Node.builder().setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build()) + .setBulkSize(bulkSize); + + if (indexName != null) { + builder.setIndex(indexName); + } + if (indexFolderName != null) { + builder.setIndexFolder(indexFolderName); + } + + if (timeValue != null) { + builder.setFlushInterval(timeValue); + } + + builder.setUsername(testClusterUser); + builder.setPassword(testClusterPass); + + return builder.build(); + } + + protected static void refresh() throws IOException { + elasticsearchClient.refresh(null); + } + + /** + * Check that we have the expected number of docs or at least one if expected is null + * + * @param request Elasticsearch request to run. + * @param expected expected number of docs. Null if at least 1. + * @param path Path we are supposed to scan. If we have not accurate results, we display its content + * @return the search response if further tests are needed + * @throws Exception in case of error + */ + public static SearchResponse countTestHelper(final SearchRequest request, final Long expected, final Path path) throws Exception { + return countTestHelper(request, expected, path, TimeValue.timeValueSeconds(20)); + } + + /** + * Check that we have the expected number of docs or at least one if expected is null + * + * @param request Elasticsearch request to run. + * @param expected expected number of docs. Null if at least 1. + * @param path Path we are supposed to scan. If we have not accurate results, we display its content + * @param timeout Time before we declare a failure + * @return the search response if further tests are needed + * @throws Exception in case of error + */ + public static SearchResponse countTestHelper(final SearchRequest request, final Long expected, final Path path, final TimeValue timeout) throws Exception { + + final SearchResponse[] response = new SearchResponse[1]; + + // We wait before considering a failing test + staticLogger.info(" ---> Waiting up to {} for {} documents in {}", timeout.toString(), + expected == null ? "some" : expected, request.indices()); + long hits = awaitBusy(() -> { + long totalHits; + + // Let's search for entries + try { + response[0] = elasticsearchClient.search(request); + } catch (IOException e) { + staticLogger.warn("error caught", e); + return -1; + } + staticLogger.trace("result {}", response[0].toString()); + totalHits = response[0].getHits().getTotalHits(); + + staticLogger.debug("got so far [{}] hits on expected [{}]", totalHits, expected); + + return totalHits; + }, expected, timeout.millis(), TimeUnit.MILLISECONDS); + + Matcher matcher; + if (expected == null) { + matcher = greaterThan(0L); + } else { + matcher = equalTo(expected); + } + + if (matcher.matches(hits)) { + staticLogger.debug(" ---> expecting [{}] and got [{}] documents in {}", expected, hits, request.indices()); + logContentOfDir(path, Level.DEBUG); + } else { + staticLogger.warn(" ---> expecting [{}] but got [{}] documents in {}", expected, hits, request.indices()); + logContentOfDir(path, Level.WARN); + } + assertThat(hits, matcher); + + return response[0]; + } + + static void logContentOfDir(Path path, Level level) { + if (path != null) { + try (Stream stream = Files.walk(path)) { + stream.forEach(file -> { + try { + if (Files.isDirectory(file)) { + staticLogger.log(level, " * in dir [{}] [{}]", + path.relativize(file).toString(), + Files.getLastModifiedTime(file)); + } else { + staticLogger.log(level, " - [{}] [{}]", + file.getFileName().toString(), + Files.getLastModifiedTime(file)); + } + } catch (IOException ignored) { + } + }); + } catch (IOException ex) { + staticLogger.error("can not read content of [{}]:", path); + } + } + } + + public static String getUrl(String... subdirs) { + URL resource = AbstractITCase.class.getResource("/fscrawler-integration-tests-marker.txt"); + File dir = URLtoFile(resource).getParentFile(); + + for (String subdir : subdirs) { + dir = new File(dir, subdir); + } + + return dir.getAbsoluteFile().getAbsolutePath(); + } + + String getCrawlerName() { + String testName = testCrawlerPrefix.concat(getCurrentTestName()); + return testName.contains(" ") ? split(testName, " ")[0] : testName; + } + + /** + * Split a String at the first occurrence of the delimiter. + * Does not include the delimiter in the result. + * + * @param toSplit the string to split + * @param delimiter to split the string up with + * @return a two element array with index 0 being before the delimiter, and + * index 1 being after the delimiter (neither element includes the delimiter); + * or null if the delimiter wasn't found in the given input String + */ + public static String[] split(String toSplit, String delimiter) { + int offset = toSplit.indexOf(delimiter); + String beforeDelimiter = toSplit.substring(0, offset); + String afterDelimiter = toSplit.substring(offset + delimiter.length()); + return new String[]{beforeDelimiter, afterDelimiter}; + } + + public static T restCall(String path, Class clazz) { + if (staticLogger.isDebugEnabled()) { + String response = target.path(path).request().get(String.class); + staticLogger.debug("Rest response: {}", response); + } + return target.path(path).request().get(clazz); + } + + public static T restCall(String path, FormDataMultiPart mp, Class clazz, Map params) { + WebTarget targetPath = target.path(path); + params.forEach(targetPath::queryParam); + + return targetPath.request(MediaType.MULTIPART_FORM_DATA) + .accept(MediaType.APPLICATION_JSON) + .post(Entity.entity(mp, mp.getMediaType()), clazz); + } + + public static void deleteRecursively(Path root) throws IOException { + Files.walkFileTree(root, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + Files.delete(file); + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { + Files.delete(dir); + return FileVisitResult.CONTINUE; + } + }); + } + + protected void assumeVersion6AtLeast() throws IOException { + assumeThat("Sadly the HL Rest Client 6.x can not always be used with 5.x versions", elasticsearchClient.info().getVersion().onOrAfter(Version.V_6_0_0), is(true)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `fr.pilato.elasticsearch.containers.ElasticsearchContainer` acquired by call to `new()` at line 232 is not released after line 232. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractITCase.startElasticsearchRestClient() + +### Procedure Id: +fr.pilato.elasticsearch.crawler.fs.test.integration.AbstractITCase.startElasticsearchRestClient():vo.6071bfa4d972b7962e7460cc91ce2c54 + +### File: +integration-tests/src/test/java/fr/pilato/elasticsearch/crawler/fs/test/integration/AbstractITCase.java + +### Key: +AbstractITCase.java|startElasticsearchRestClient|RESOURCE_LEAK + +### Node Key: +71bbd039293bbda847a7c7191bb8b301 + +### Hash: +913566a3e09563808dc9b32d2cd87499 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8535/instruction.md b/inferredbugs-8535/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5c5ed2249b0d4202e11e9f5b743568fa7d45803 --- /dev/null +++ b/inferredbugs-8535/instruction.md @@ -0,0 +1,897 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fscrawler +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to David Pilato (the "Author") under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Author licenses this + * file to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package fr.pilato.elasticsearch.crawler.fs; + +import fr.pilato.elasticsearch.crawler.fs.beans.Attributes; +import fr.pilato.elasticsearch.crawler.fs.beans.Doc; +import fr.pilato.elasticsearch.crawler.fs.beans.DocParser; +import fr.pilato.elasticsearch.crawler.fs.beans.PathParser; +import fr.pilato.elasticsearch.crawler.fs.client.ElasticsearchClientManager; +import fr.pilato.elasticsearch.crawler.fs.crawler.FileAbstractModel; +import fr.pilato.elasticsearch.crawler.fs.crawler.FileAbstractor; +import fr.pilato.elasticsearch.crawler.fs.crawler.fs.FileAbstractorFile; +import fr.pilato.elasticsearch.crawler.fs.crawler.ssh.FileAbstractorSSH; +import fr.pilato.elasticsearch.crawler.fs.framework.TimeValue; +import fr.pilato.elasticsearch.crawler.fs.meta.job.FsJob; +import fr.pilato.elasticsearch.crawler.fs.meta.job.FsJobFileHandler; +import fr.pilato.elasticsearch.crawler.fs.rest.RestServer; +import fr.pilato.elasticsearch.crawler.fs.settings.FsSettings; +import fr.pilato.elasticsearch.crawler.fs.settings.FsSettingsFileHandler; +import fr.pilato.elasticsearch.crawler.fs.tika.XmlDocParser; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.elasticsearch.action.bulk.BulkProcessor; +import org.elasticsearch.action.delete.DeleteRequest; +import org.elasticsearch.action.index.IndexRequest; +import org.elasticsearch.action.search.SearchRequest; +import org.elasticsearch.action.search.SearchResponse; +import org.elasticsearch.common.xcontent.XContentType; +import org.elasticsearch.index.query.QueryBuilders; +import org.elasticsearch.search.SearchHit; +import org.elasticsearch.search.builder.SearchSourceBuilder; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.file.Files; +import java.nio.file.NoSuchFileException; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +import static fr.pilato.elasticsearch.crawler.fs.FsCrawlerValidator.validateSettings; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.computeVirtualPathName; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.isExcluded; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.isIndexable; +import static fr.pilato.elasticsearch.crawler.fs.framework.FsCrawlerUtil.localDateTimeToDate; +import static fr.pilato.elasticsearch.crawler.fs.tika.TikaDocParser.generate; + +/** + * @author dadoonet (David Pilato) + */ +public class FsCrawlerImpl { + + @Deprecated + public static final String INDEX_TYPE_FOLDER = "folder"; + @Deprecated + public static final String INDEX_TYPE_DOC = "doc"; + + public static final class PROTOCOL { + public static final String LOCAL = "local"; + public static final String SSH = "ssh"; + public static final int SSH_PORT = 22; + } + + private static final Logger logger = LogManager.getLogger(FsCrawlerImpl.class); + + private static final String PATH_ROOT = Doc.FIELD_NAMES.PATH + "." + fr.pilato.elasticsearch.crawler.fs.beans.Path.FIELD_NAMES.ROOT; + private static final String FILE_FILENAME = Doc.FIELD_NAMES.FILE + "." + fr.pilato.elasticsearch.crawler.fs.beans.File.FIELD_NAMES.FILENAME; + + private final AtomicInteger runNumber = new AtomicInteger(0); + + private final static String FSCRAWLER_PROPERTIES = "fscrawler.properties"; + public static final Properties properties; + + static { + properties = new Properties(); + try { + properties.load(FsCrawlerImpl.class.getClassLoader().getResourceAsStream(FSCRAWLER_PROPERTIES)); + } catch (IOException e) { + logger.error("Can not find [{}] resource in the class loader", FSCRAWLER_PROPERTIES); + throw new RuntimeException(e); + } + } + + private static final int REQUEST_SIZE = 10000; + public static final int LOOP_INFINITE = -1; + public static final long MAX_SLEEP_RETRY_TIME = TimeValue.timeValueSeconds(30).millis(); + + private volatile boolean closed = false; + private final Object semaphore = new Object(); + + private final FsSettings settings; + private final FsJobFileHandler fsJobFileHandler; + private final Integer loop; + private final boolean rest; + private MessageDigest messageDigest = null; + + private Thread fsCrawlerThread; + + private final ElasticsearchClientManager esClientManager; + + public FsCrawlerImpl(Path config, FsSettings settings) { + this(config, settings, LOOP_INFINITE, false); + } + + public FsCrawlerImpl(Path config, FsSettings settings, Integer loop, boolean rest) { + /* + * We store config files here... + * Default to ~/.fscrawler + * The dir will be created if needed by calling the following CTOR + */ + new FsSettingsFileHandler(config); + this.fsJobFileHandler = new FsJobFileHandler(config); + this.settings = settings; + this.loop = loop; + this.rest = rest; + this.esClientManager = new ElasticsearchClientManager(config, settings); + + closed = validateSettings(logger, settings, rest); + if (closed) { + // We don't go further as we have critical errors + return; + } + + // Generate the directory where we write status and other files + Path jobSettingsFolder = config.resolve(settings.getName()); + try { + Files.createDirectories(jobSettingsFolder); + } catch (IOException e) { + throw new RuntimeException("Can not create the job config directory", e); + } + + // Create MessageDigest instance + if (settings.getFs().getChecksum() != null) { + try { + messageDigest = MessageDigest.getInstance(settings.getFs().getChecksum()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException("This should never happen as we checked that previously"); + } + } + } + + public ElasticsearchClientManager getEsClientManager() { + return esClientManager; + } + + /** + * Upgrade FSCrawler indices + * @return true if done successfully + * @throws Exception In case of error + */ + @SuppressWarnings("deprecation") + public boolean upgrade() throws Exception { + // We need to start a client so we can send requests to elasticsearch + esClientManager.start(); + + // The upgrade script is for now a bit dumb. It assumes that you had an old version of FSCrawler (< 2.3) and it will + // simply move data from index/folder to index_folder + String index = settings.getElasticsearch().getIndex(); + + // Check that the old index actually exists + if (esClientManager.client().isExistingIndex(index)) { + // We check that the new indices don't exist yet or are empty + String indexFolder = settings.getElasticsearch().getIndexFolder(); + boolean indexExists = esClientManager.client().isExistingIndex(indexFolder); + long numberOfDocs = 0; + if (indexExists) { + SearchResponse responseFolder = esClientManager.client().search(new SearchRequest(indexFolder)); + numberOfDocs = responseFolder.getHits().getTotalHits(); + } + if (numberOfDocs > 0) { + logger.warn("[{}] already exists and is not empty. No upgrade needed.", indexFolder); + } else { + logger.debug("[{}] can be upgraded.", index); + + // Create the new indices with the right mappings (well, we don't read existing user configuration) + if (!indexExists) { + esClientManager.createIndices(settings); + logger.info("[{}] has been created.", indexFolder); + } + + // Run reindex task for folders + logger.info("Starting reindex folders..."); + int folders = esClientManager.client().reindex(index, INDEX_TYPE_FOLDER, indexFolder); + logger.info("Done reindexing [{}] folders...", folders); + + // Run delete by query task for folders + logger.info("Starting removing folders from [{}]...", index); + esClientManager.client().deleteByQuery(index, INDEX_TYPE_FOLDER); + logger.info("Done removing folders from [{}]", index); + + logger.info("You can now upgrade your elasticsearch cluster to >=6.0.0!"); + return true; + } + } else { + logger.info("[{}] does not exist. No upgrade needed.", index); + } + + return false; + } + + public void start() throws Exception { + logger.info("Starting FS crawler"); + if (loop < 0) { + logger.info("FS crawler started in watch mode. It will run unless you stop it with CTRL+C."); + } + + if (loop == 0 && !rest) { + closed = true; + } + + if (closed) { + logger.info("Fs crawler is closed. Exiting"); + return; + } + + esClientManager.start(); + esClientManager.createIndices(settings); + + // Start the REST Server if needed + if (rest) { + RestServer.start(settings, esClientManager); + logger.info("FS crawler Rest service started on [{}]", settings.getRest().url()); + } + + // Start the crawler thread - but not if only in rest mode + if (loop != 0) { + fsCrawlerThread = new Thread(new FSParser(settings), "fs-crawler"); + fsCrawlerThread.start(); + } + } + + public void close() throws InterruptedException { + logger.debug("Closing FS crawler [{}]", settings.getName()); + + closed = true; + + synchronized(semaphore) { + semaphore.notifyAll(); + } + + if (this.fsCrawlerThread != null) { + while (fsCrawlerThread.isAlive()) { + // We check that the crawler has been closed effectively + logger.debug("FS crawler thread is still running"); + Thread.sleep(500); + } + logger.debug("FS crawler thread is now stopped"); + } + + // Stop the REST Server if needed + RestServer.close(); + logger.debug("FS crawler Rest service stopped"); + + esClientManager.close(); + logger.debug("ES Client Manager stopped"); + + logger.info("FS crawler [{}] stopped", settings.getName()); + } + + public boolean isClosed() { + return closed; + } + + private class FSParser implements Runnable { + private final FsSettings fsSettings; + + private ScanStatistic stats; + + public FSParser(FsSettings fsSettings) { + this.fsSettings = fsSettings; + logger.debug("creating fs crawler thread [{}] for [{}] every [{}]", fsSettings.getName(), + fsSettings.getFs().getUrl(), + fsSettings.getFs().getUpdateRate()); + } + + @Override + public void run() { + logger.info("FS crawler started for [{}] for [{}] every [{}]", fsSettings.getName(), + fsSettings.getFs().getUrl(), + fsSettings.getFs().getUpdateRate()); + while (true) { + if (closed) { + logger.debug("FS crawler thread [{}] is now marked as closed...", fsSettings.getName()); + return; + } + + int run = runNumber.incrementAndGet(); + FileAbstractor path = null; + + try { + logger.debug("Fs crawler thread [{}] is now running. Run #{}...", fsSettings.getName(), run); + stats = new ScanStatistic(fsSettings.getFs().getUrl()); + + path = buildFileAbstractor(); + path.open(); + + if (!path.exists(fsSettings.getFs().getUrl())) { + throw new RuntimeException(fsSettings.getFs().getUrl() + " doesn't exists."); + } + + String rootPathId = SignTool.sign(fsSettings.getFs().getUrl()); + stats.setRootPathId(rootPathId); + + LocalDateTime scanDatenew = LocalDateTime.now(); + LocalDateTime scanDate = getLastDateFromMeta(fsSettings.getName()); + + // We only index the root directory once (first run) + // That means that we don't have a scanDate yet + if (scanDate == null && fsSettings.getFs().isIndexFolders()) { + indexDirectory(fsSettings.getFs().getUrl()); + } + + if (scanDate == null) { + scanDate = LocalDateTime.MIN; + } + + addFilesRecursively(path, fsSettings.getFs().getUrl(), scanDate); + + updateFsJob(fsSettings.getName(), scanDatenew); + } catch (Exception e) { + logger.warn("Error while crawling {}: {}", fsSettings.getFs().getUrl(), e.getMessage()); + if (logger.isDebugEnabled()) { + logger.warn("Full stacktrace", e); + } + } finally { + if (path != null) { + try { + path.close(); + } catch (Exception e) { + logger.warn("Error while closing the connection: {}", e, e.getMessage()); + } + } + } + + if (loop > 0 && run >= loop) { + logger.info("FS crawler is stopping after {} run{}", run, run > 1 ? "s" : ""); + closed = true; + return; + } + + try { + logger.debug("Fs crawler is going to sleep for {}", fsSettings.getFs().getUpdateRate()); + + // The problem here is that there is no wait to close the thread while we are sleeping. + // Which leads to Zombie threads in our tests + + synchronized (semaphore) { + semaphore.wait(fsSettings.getFs().getUpdateRate().millis()); + logger.debug("Fs crawler is now waking up again..."); + } + } catch (InterruptedException e) { + logger.debug("Fs crawler thread has been interrupted: [{}]", e.getMessage()); + Thread.currentThread().interrupt(); + } + } + } + + @SuppressWarnings("unchecked") + private LocalDateTime getLastDateFromMeta(String jobName) throws IOException { + try { + FsJob fsJob = fsJobFileHandler.read(jobName); + return fsJob.getLastrun(); + } catch (NoSuchFileException e) { + // The file does not exist yet + } + return null; + } + + /** + * Update the job metadata + * @param jobName job name + * @param scanDate last date we scan the dirs + * @throws Exception In case of error + */ + private void updateFsJob(String jobName, LocalDateTime scanDate) throws Exception { + // We need to round that latest date to the lower second and + // remove 2 seconds. + // See #82: https://github.com/dadoonet/fscrawler/issues/82 + scanDate = scanDate.minus(2, ChronoUnit.SECONDS); + FsJob fsJob = FsJob.builder() + .setName(jobName) + .setLastrun(scanDate) + .setIndexed(stats.getNbDocScan()) + .setDeleted(stats.getNbDocDeleted()) + .build(); + fsJobFileHandler.write(jobName, fsJob); + } + + private FileAbstractor buildFileAbstractor() { + // What is the protocol used? + if (fsSettings.getServer() == null || PROTOCOL.LOCAL.equals(fsSettings.getServer().getProtocol())) { + // Local FS + return new FileAbstractorFile(fsSettings); + } else if (PROTOCOL.SSH.equals(fsSettings.getServer().getProtocol())) { + // Remote SSH FS + return new FileAbstractorSSH(fsSettings); + } + + // Non supported protocol + throw new RuntimeException(fsSettings.getServer().getProtocol() + " is not supported yet. Please use " + + PROTOCOL.LOCAL + " or " + PROTOCOL.SSH); + } + + private void addFilesRecursively(FileAbstractor path, String filepath, LocalDateTime lastScanDate) + throws Exception { + + logger.debug("indexing [{}] content", filepath); + + final Collection children = path.getFiles(filepath); + Collection fsFiles = new ArrayList<>(); + Collection fsFolders = new ArrayList<>(); + + if (children != null) { + for (FileAbstractModel child : children) { + String filename = child.name; + + // https://github.com/dadoonet/fscrawler/issues/1 : Filter documents + boolean isIndexable = isIndexable(filename, fsSettings.getFs().getIncludes(), fsSettings.getFs().getExcludes()); + + // It can happen that we a dir "foo" which does not match the include name like "*.txt" + // We need to go in it unless it has been explicitly excluded by the user + if (child.directory && !isExcluded(filename, fsSettings.getFs().getExcludes())) { + isIndexable = true; + } + + logger.debug("[{}] can be indexed: [{}]", filename, isIndexable); + if (isIndexable) { + if (child.file) { + logger.debug(" - file: {}", filename); + fsFiles.add(filename); + if (child.lastModifiedDate.isAfter(lastScanDate) || + (child.creationDate != null && child.creationDate.isAfter(lastScanDate))) { + try { + indexFile(child, stats, filepath, + fsSettings.getFs().isIndexContent() ? path.getInputStream(child) : null, child.size); + stats.addFile(); + } catch (java.io.FileNotFoundException e) { + if (fsSettings.getFs().isContinueOnError()) { + logger.warn("Unable to open Input Stream for {}, skipping...", e.getMessage()); + } else { + throw e; + } + } + } else { + logger.debug(" - not modified: creation date {} , file date {}, last scan date {}", + child.creationDate, child.lastModifiedDate, lastScanDate); + } + } else if (child.directory) { + logger.debug(" - folder: {}", filename); + if (settings.getFs().isIndexFolders()) { + fsFolders.add(child.fullpath); + indexDirectory(child.fullpath); + } + addFilesRecursively(path, child.fullpath, lastScanDate); + } else { + logger.debug(" - other: {}", filename); + logger.debug("Not a file nor a dir. Skipping {}", child.fullpath); + } + } else { + logger.debug(" - ignored file/dir: {}", filename); + } + } + } + + // TODO Optimize + // if (path.isDirectory() && path.lastModified() > lastScanDate + // && lastScanDate != 0) { + + if (fsSettings.getFs().isRemoveDeleted()) { + logger.debug("Looking for removed files in [{}]...", filepath); + Collection esFiles = getFileDirectory(filepath); + + // for the delete files + for (String esfile : esFiles) { + logger.trace("Checking file [{}]", esfile); + + if (isIndexable(esfile, fsSettings.getFs().getIncludes(), fsSettings.getFs().getExcludes()) + && !fsFiles.contains(esfile)) { + logger.trace("Removing file [{}] in elasticsearch", esfile); + esDelete(fsSettings.getElasticsearch().getIndex(), generateIdFromFilename(esfile, filepath)); + stats.removeFile(); + } + } + + if (settings.getFs().isIndexFolders()) { + logger.debug("Looking for removed directories in [{}]...", filepath); + Collection esFolders = getFolderDirectory(filepath); + + // for the delete folder + for (String esfolder : esFolders) { + if (isIndexable(esfolder, fsSettings.getFs().getIncludes(), fsSettings.getFs().getExcludes())) { + logger.trace("Checking directory [{}]", esfolder); + if (!fsFolders.contains(esfolder)) { + logger.trace("Removing recursively directory [{}] in elasticsearch", esfolder); + removeEsDirectoryRecursively(esfolder); + } + } + } + } + } + } + + // TODO Optimize it. We can probably use a search for a big array of filenames instead of + // Searching fo 10000 files (which is somehow limited). + private Collection getFileDirectory(String path) + throws Exception { + + // If the crawler is being closed, we return + if (closed) { + return Collections.emptyList(); + } + + logger.trace("Querying elasticsearch for files in dir [{}:{}]", PATH_ROOT, SignTool.sign(path)); + Collection files; + // Hack because the High Level Client is not compatible with versions < 5.0 + if (esClientManager.client().isIngestSupported()) { + files = new ArrayList<>(); + SearchResponse response = esClientManager.client().search( + new SearchRequest(fsSettings.getElasticsearch().getIndex()).source( + new SearchSourceBuilder() + .size(REQUEST_SIZE) // TODO: WHAT? DID I REALLY WROTE THAT? :p + .storedField(FILE_FILENAME) + .query(QueryBuilders.termQuery(PATH_ROOT, SignTool.sign(path))))); + + logger.trace("Response [{}]", response.toString()); + if (response.getHits() != null && response.getHits().getHits() != null) { + for (SearchHit hit : response.getHits().getHits()) { + String name; + if (hit.getFields() != null + && hit.getFields().get(FILE_FILENAME) != null) { + // In case someone disabled _source which is not recommended + name = hit.getFields().get(FILE_FILENAME).getValue(); + } else { + // Houston, we have a problem ! We can't get the old files from ES + logger.warn("Can't find stored field name to check existing filenames in path [{}]. " + + "Please set store: true on field [{}]", path, FILE_FILENAME); + throw new RuntimeException("Mapping is incorrect: please set stored: true on field [" + + FILE_FILENAME + "]."); + } + files.add(name); + } + } + } else { + files = esClientManager.client().getFromStoredFieldsV2( + fsSettings.getElasticsearch().getIndex(), + REQUEST_SIZE, // TODO: WHAT? DID I REALLY WROTE THAT? :p + FILE_FILENAME, + path, + QueryBuilders.termQuery(PATH_ROOT, SignTool.sign(path))); + } + + logger.trace("We found: {}", files); + + return files; + } + + private Collection getFolderDirectory(String path) throws Exception { + Collection files = new ArrayList<>(); + + // If the crawler is being closed, we return + if (closed) { + return files; + } + + SearchResponse response = esClientManager.client().search( + new SearchRequest(fsSettings.getElasticsearch().getIndexFolder()).source( + new SearchSourceBuilder() + .size(REQUEST_SIZE) // TODO: WHAT? DID I REALLY WROTE THAT? :p + .query(QueryBuilders.termQuery(fr.pilato.elasticsearch.crawler.fs.beans.Path.FIELD_NAMES.ROOT, SignTool.sign(path))))); + + if (response.getHits() != null && response.getHits().getHits() != null) { + for (SearchHit hit : response.getHits().getHits()) { + String name = hit.getSourceAsMap().get(fr.pilato.elasticsearch.crawler.fs.beans.Path.FIELD_NAMES.REAL).toString(); + files.add(name); + } + } + + return files; + } + + /** + * Index a file + */ + private void indexFile(FileAbstractModel fileAbstractModel, ScanStatistic stats, String dirname, InputStream inputStream, + long filesize) throws Exception { + final String filename = fileAbstractModel.name; + final LocalDateTime lastmodified = fileAbstractModel.lastModifiedDate; + final String extension = fileAbstractModel.extension; + final long size = fileAbstractModel.size; + + logger.debug("fetching content from [{}],[{}]", dirname, filename); + + try { + // Create the Doc object (only needed when we have add_as_inner_object: true (default) or when we don't index json or xml) + if (fsSettings.getFs().isAddAsInnerObject() || (!fsSettings.getFs().isJsonSupport() && !fsSettings.getFs().isXmlSupport())) { + + String fullFilename = new File(dirname, filename).toString(); + + Doc doc = new Doc(); + + // File + doc.getFile().setFilename(filename); + doc.getFile().setLastModified(localDateTimeToDate(lastmodified)); + doc.getFile().setIndexingDate(localDateTimeToDate(LocalDateTime.now())); + doc.getFile().setUrl("file://" + fullFilename); + doc.getFile().setExtension(extension); + if (fsSettings.getFs().isAddFilesize()) { + doc.getFile().setFilesize(size); + } + // File + + // Path + // Encoded version of the dir this file belongs to + doc.getPath().setRoot(SignTool.sign(dirname)); + // The virtual URL (not including the initial root dir) + doc.getPath().setVirtual(computeVirtualPathName(stats.getRootPath(), fullFilename)); + // The real and complete filename + doc.getPath().setReal(fullFilename); + // Path + + // Attributes + if (fsSettings.getFs().isAttributesSupport()) { + doc.setAttributes(new Attributes()); + doc.getAttributes().setOwner(fileAbstractModel.owner); + doc.getAttributes().setGroup(fileAbstractModel.group); + } + // Attributes + + if (fsSettings.getFs().isIndexContent()) { + // If needed, we generate the content in addition to metadata + if (fsSettings.getFs().isJsonSupport()) { + // https://github.com/dadoonet/fscrawler/issues/5 : Support JSon files + doc.setObject(DocParser.asMap(read(inputStream))); + } else if (fsSettings.getFs().isXmlSupport()) { + // https://github.com/dadoonet/fscrawler/issues/185 : Support Xml files + doc.setObject(XmlDocParser.generateMap(inputStream)); + } else { + // Extracting content with Tika + generate(fsSettings, inputStream, filename, doc, messageDigest, filesize); + } + } + + // We index the data structure + esIndex(esClientManager.bulkProcessorDoc(), fsSettings.getElasticsearch().getIndex(), + generateIdFromFilename(filename, dirname), + DocParser.toJson(doc), + fsSettings.getElasticsearch().getPipeline()); + } else if (fsSettings.getFs().isIndexContent()) { + if (fsSettings.getFs().isJsonSupport()) { + // We index the json content directly + esIndex(esClientManager.bulkProcessorDoc(), fsSettings.getElasticsearch().getIndex(), + generateIdFromFilename(filename, dirname), + read(inputStream), + fsSettings.getElasticsearch().getPipeline()); + } else if (fsSettings.getFs().isXmlSupport()) { + // We index the xml content directly + esIndex(esClientManager.bulkProcessorDoc(), fsSettings.getElasticsearch().getIndex(), + generateIdFromFilename(filename, dirname), + XmlDocParser.generate(inputStream), + fsSettings.getElasticsearch().getPipeline()); + } + } + } finally { + // Let's close the stream + if (inputStream != null) { + inputStream.close(); + } + } + } + + private String generateIdFromFilename(String filename, String filepath) throws NoSuchAlgorithmException { + return fsSettings.getFs().isFilenameAsId() ? filename : SignTool.sign((new File(filepath, filename)).toString()); + } + + private String read(InputStream input) throws IOException { + try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input, "UTF-8"))) { + return buffer.lines().collect(Collectors.joining("\n")); + } + } + + /** + * Index a Path object (AKA a folder) in elasticsearch + * @param id id of the path + * @param path path object + * @throws Exception in case of error + */ + private void indexDirectory(String id, fr.pilato.elasticsearch.crawler.fs.beans.Path path) throws Exception { + esIndex(esClientManager.bulkProcessorFolder(), fsSettings.getElasticsearch().getIndexFolder(), + id, + PathParser.toJson(path), + null); + } + + /** + * Index a directory + * @param path complete path like /path/to/subdir + */ + private void indexDirectory(String path) throws Exception { + fr.pilato.elasticsearch.crawler.fs.beans.Path pathObject = new fr.pilato.elasticsearch.crawler.fs.beans.Path(); + // The real and complete path + pathObject.setReal(path); + String rootdir = path.substring(0, path.lastIndexOf(File.separator)); + // Encoded version of the parent dir + pathObject.setRoot(SignTool.sign(rootdir)); + // The virtual URL (not including the initial root dir) + pathObject.setVirtual(computeVirtualPathName(stats.getRootPath(), path)); + + indexDirectory(SignTool.sign(path), pathObject); + } + + /** + * Remove a full directory and sub dirs recursively + */ + private void removeEsDirectoryRecursively(final String path) throws Exception { + logger.debug("Delete folder [{}]", path); + Collection listFile = getFileDirectory(path); + + for (String esfile : listFile) { + esDelete(fsSettings.getElasticsearch().getIndex(), SignTool.sign(path.concat(File.separator).concat(esfile))); + } + + Collection listFolder = getFolderDirectory(path); + for (String esfolder : listFolder) { + removeEsDirectoryRecursively(esfolder); + } + + esDelete(fsSettings.getElasticsearch().getIndexFolder(), SignTool.sign(path)); + } + + /** + * Add to bulk an IndexRequest in JSon format + */ + void esIndex(BulkProcessor bulkProcessor, String index, String id, String json, String pipeline) { + logger.debug("Indexing {}/doc/{}?pipeline={}", index, id, pipeline); + logger.trace("JSon indexed : {}", json); + + if (!closed) { + bulkProcessor.add(new IndexRequest(index, "doc", id).source(json, XContentType.JSON).setPipeline(pipeline)); + } else { + logger.warn("trying to add new file while closing crawler. Document [{}]/[doc]/[{}] has been ignored", index, id); + } + } + + /** + * Add to bulk a DeleteRequest + */ + void esDelete(String index, String id) { + logger.debug("Deleting {}/doc/{}", index, id); + if (!closed) { + esClientManager.bulkProcessorDoc().add(new DeleteRequest(index, "doc", id)); + } else { + logger.warn("trying to remove a file while closing crawler. Document [{}]/[doc]/[{}] has been ignored", index, id); + } + } + } + + /** + * Check whether the given CharSequence has actual text. + * More specifically, returns true if the string not null, + * its length is greater than 0, and it contains at least one non-whitespace character. + *

    +     * StringUtils.hasText(null) = false
    +     * StringUtils.hasText("") = false
    +     * StringUtils.hasText(" ") = false
    +     * StringUtils.hasText("12345") = true
    +     * StringUtils.hasText(" 12345 ") = true
    +     * 
    + * + * @param str the CharSequence to check (may be null) + * @return true if the CharSequence is not null, + * its length is greater than 0, and it does not contain whitespace only + * @see java.lang.Character#isWhitespace + */ + public static boolean hasText(CharSequence str) { + if (!hasLength(str)) { + return false; + } + int strLen = str.length(); + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(str.charAt(i))) { + return true; + } + } + return false; + } + + private static boolean hasLength(CharSequence str) { + return str != null && str.length() > 0; + } + + public int getRunNumber() { + return runNumber.get(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `fr.pilato.elasticsearch.crawler.fs.FsCrawlerImpl.start` indirectly writes to field `rest.RestServer.fr.pilato.elasticsearch.crawler.fs.rest.RestServer.httpServer` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FsCrawlerImpl.start() + +### Procedure Id: +fr.pilato.elasticsearch.crawler.fs.FsCrawlerImpl.start():void.9db512bc716ea5abf40b7d0335c0e9da + +### File: +core/src/main/java/fr/pilato/elasticsearch/crawler/fs/FsCrawlerImpl.java + +### Key: +FsCrawlerImpl.java|start|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +46350f5cb6ba0c549e070102b740a30b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8551/instruction.md b/inferredbugs-8551/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..faa00cffd994df86bf590446622cc064f147b92b --- /dev/null +++ b/inferredbugs-8551/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = newReader("[{},{\"a\":5}]"); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void readerUnquotedIntegerValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedLongValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedDoubleValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextDouble()).isEqualTo(5d); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + private JsonReader newReader(String s) { + return JsonReader.of(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.BufferedSourceJsonReader` acquired by call to `newReader(...)` at line 163 is not released after line 170. +**Note**: potential exception at line 165 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerUnquotedIntegerValue() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerUnquotedIntegerValue():void.a71a1173c42447b4e98706eb161565d8 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerUnquotedIntegerValue|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +ebde9d9f18e147f0439a2a03c5858074 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8560/instruction.md b/inferredbugs-8560/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39d3afa20f023712d99a966f7726854f6daa0855 --- /dev/null +++ b/inferredbugs-8560/instruction.md @@ -0,0 +1,408 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 15 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2015 Square, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import okio.Buffer; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class PromoteNameToValueTest { + @Test public void readerStringValue() throws Exception { + JsonReader reader = newReader("{\"a\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.getPath()).isEqualTo("$.a"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.a"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerIntegerValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerDoubleValue() throws Exception { + JsonReader reader = newReader("{\"5.5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(5.5d); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerBooleanValue() throws Exception { + JsonReader reader = newReader("{\"true\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true"); + } + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextString()).isEqualTo("true"); + assertThat(reader.getPath()).isEqualTo("$.true"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerLongValue() throws Exception { + JsonReader reader = newReader("{\"5\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.getPath()).isEqualTo("$.5"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.5"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerNullValue() throws Exception { + JsonReader reader = newReader("{\"null\":1}"); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException e) { + assertThat(e).hasMessage("Expected null but was STRING at path $.null"); + } + assertThat(reader.nextString()).isEqualTo("null"); + assertThat(reader.getPath()).isEqualTo("$.null"); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.getPath()).isEqualTo("$.null"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerMultipleValueObject() throws Exception { + JsonReader reader = newReader("{\"a\":1,\"b\":2}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextInt()).isEqualTo(1); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo("b"); + assertThat(reader.getPath()).isEqualTo("$.b"); + assertThat(reader.nextInt()).isEqualTo(2); + assertThat(reader.getPath()).isEqualTo("$.b"); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerEmptyValueObject() throws Exception { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.promoteNameToValue(); + assertThat(reader.getPath()).isEqualTo("$."); + reader.endObject(); + assertThat(reader.getPath()).isEqualTo("$"); + } + + @Test public void readerUnusedPromotionDoesntPersist() throws Exception { + JsonReader reader = newReader("[{},{\"a\":5}]"); + reader.beginArray(); + reader.beginObject(); + reader.promoteNameToValue(); + reader.endObject(); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void readerUnquotedIntegerValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextInt()).isEqualTo(5); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedLongValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextLong()).isEqualTo(5L); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + @Test public void readerUnquotedDoubleValue() throws Exception { + JsonReader reader = newReader("{5:1}"); + reader.setLenient(true); + reader.beginObject(); + reader.promoteNameToValue(); + assertThat(reader.nextDouble()).isEqualTo(5d); + assertThat(reader.nextInt()).isEqualTo(1); + reader.endObject(); + } + + private JsonReader newReader(String s) { + return JsonReader.of(new Buffer().writeUtf8(s)); + } + + @Test public void writerStringValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value("a"); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.a"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1}"); + } + + @Test public void writerIntegerValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerDoubleValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5.5d); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5.5\":1}"); + } + + @Test public void writerBooleanValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.value(true); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("true"); + assertThat(writer.getPath()).isEqualTo("$.true"); + writer.value(1); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"true\":1}"); + } + + @Test public void writerLongValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + writer.value(5L); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.5"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"5\":1}"); + } + + @Test public void writerNullValue() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + try { + writer.nullValue(); + fail(); + } catch (IllegalStateException e) { + assertThat(e).hasMessage("Nesting problem."); + } + writer.value("null"); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.value(1); + assertThat(writer.getPath()).isEqualTo("$.null"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"null\":1}"); + } + + @Test public void writerMultipleValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.name("a"); + writer.value(1); + writer.promoteNameToValue(); + writer.value("b"); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.value(2); + assertThat(writer.getPath()).isEqualTo("$.b"); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{\"a\":1,\"b\":2}"); + } + + @Test public void writerEmptyValueObject() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginObject(); + writer.promoteNameToValue(); + assertThat(writer.getPath()).isEqualTo("$."); + writer.endObject(); + assertThat(writer.getPath()).isEqualTo("$"); + assertThat(buffer.readUtf8()).isEqualTo("{}"); + } + + @Test public void writerUnusedPromotionDoesntPersist() throws Exception { + Buffer buffer = new Buffer(); + JsonWriter writer = JsonWriter.of(buffer); + writer.beginArray(); + writer.beginObject(); + writer.promoteNameToValue(); + writer.endObject(); + writer.beginObject(); + try { + writer.value("a"); + fail(); + } catch (IllegalStateException expected) { + } + writer.name("a"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.BufferedSourceJsonReader` acquired by call to `newReader(...)` at line 148 is not released after line 160. +**Note**: potential exception at line 149 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PromoteNameToValueTest.readerUnusedPromotionDoesntPersist() + +### Procedure Id: +com.squareup.moshi.PromoteNameToValueTest.readerUnusedPromotionDoesntPersist():void.ff9fbfdc887aa33c33d792718d5dbda4 + +### File: +moshi/src/test/java/com/squareup/moshi/PromoteNameToValueTest.java + +### Key: +PromoteNameToValueTest.java|readerUnusedPromotionDoesntPersist|RESOURCE_LEAK + +### Node Key: +95ced91ca0473a6646194f1eb482b307 + +### Hash: +3c7da46e2ec07b25ab558e83be21bf90 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8561/instruction.md b/inferredbugs-8561/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31ee5a72925e839353f2e24b487c62edd6806cc2 --- /dev/null +++ b/inferredbugs-8561/instruction.md @@ -0,0 +1,1897 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** moshi +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2010 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.squareup.moshi; + +import java.io.EOFException; +import java.io.IOException; +import java.util.Arrays; +import okio.Buffer; +import org.junit.Ignore; +import org.junit.Test; + +import static com.squareup.moshi.JsonReader.Token.BEGIN_ARRAY; +import static com.squareup.moshi.JsonReader.Token.BEGIN_OBJECT; +import static com.squareup.moshi.JsonReader.Token.BOOLEAN; +import static com.squareup.moshi.JsonReader.Token.END_ARRAY; +import static com.squareup.moshi.JsonReader.Token.END_OBJECT; +import static com.squareup.moshi.JsonReader.Token.NAME; +import static com.squareup.moshi.JsonReader.Token.NULL; +import static com.squareup.moshi.JsonReader.Token.NUMBER; +import static com.squareup.moshi.JsonReader.Token.STRING; +import static com.squareup.moshi.TestUtil.newReader; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.fail; + +public final class JsonReaderTest { + @Test public void readingDoesNotBuffer() throws IOException { + Buffer buffer = new Buffer().writeUtf8("{}{}"); + + JsonReader reader1 = new JsonReader(buffer); + reader1.beginObject(); + reader1.endObject(); + assertThat(buffer.size()).isEqualTo(2); + + JsonReader reader2 = new JsonReader(buffer); + reader2.beginObject(); + reader2.endObject(); + assertThat(buffer.size()).isEqualTo(0); + } + + @Test public void readArray() throws IOException { + JsonReader reader = newReader("[true, true]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void readEmptyArray() throws IOException { + JsonReader reader = newReader("[]"); + reader.beginArray(); + assertThat(reader.hasNext()).isFalse(); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void readObject() throws IOException { + JsonReader reader = newReader("{\"a\": \"android\", \"b\": \"banana\"}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextString()).isEqualTo("banana"); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void readObjectBuffer() throws IOException { + Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}"); + JsonReader reader = new JsonReader(buffer); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextString()).isEqualTo("banana"); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void readObjectSource() throws IOException { + Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}"); + JsonReader reader = new JsonReader(buffer); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextString()).isEqualTo("banana"); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void readEmptyObject() throws IOException { + JsonReader reader = newReader("{}"); + reader.beginObject(); + assertThat(reader.hasNext()).isFalse(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipArray() throws IOException { + JsonReader reader = newReader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextInt()).isEqualTo(123); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipArrayAfterPeek() throws Exception { + JsonReader reader = newReader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.peek()).isEqualTo(BEGIN_ARRAY); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("b"); + assertThat(reader.nextInt()).isEqualTo(123); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipTopLevelObject() throws Exception { + JsonReader reader = newReader("{\"a\": [\"one\", \"two\", \"three\"], \"b\": 123}"); + reader.skipValue(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipObject() throws IOException { + JsonReader reader = newReader( + "{\"a\": { \"c\": [], \"d\": [true, true, {}] }, \"b\": \"banana\"}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("b"); + reader.skipValue(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipObjectAfterPeek() throws Exception { + String json = "{" + " \"one\": { \"num\": 1 }" + + ", \"two\": { \"num\": 2 }" + ", \"three\": { \"num\": 3 }" + "}"; + JsonReader reader = newReader(json); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("one"); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("two"); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("three"); + reader.skipValue(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipInteger() throws IOException { + JsonReader reader = newReader("{\"a\":123456789,\"b\":-123456789}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("b"); + reader.skipValue(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipDouble() throws IOException { + JsonReader reader = newReader("{\"a\":-123.456e-789,\"b\":123456789.0}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + reader.skipValue(); + assertThat(reader.nextName()).isEqualTo("b"); + reader.skipValue(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void failOnUnknownFailsOnUnknownObjectValue() throws IOException { + JsonReader reader = newReader("{\"a\": 123}"); + reader.setFailOnUnknown(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.skipValue(); + fail(); + } catch (JsonDataException expected) { + assertThat(expected).hasMessage("Cannot skip unexpected NUMBER at $.a"); + } + // Confirm that the reader is left in a consistent state after the exception. + reader.setFailOnUnknown(false); + assertThat(reader.nextInt()).isEqualTo(123); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void failOnUnknownFailsOnUnknownArrayElement() throws IOException { + JsonReader reader = newReader("[\"a\", 123]"); + reader.setFailOnUnknown(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("a"); + try { + reader.skipValue(); + fail(); + } catch (JsonDataException expected) { + assertThat(expected).hasMessage("Cannot skip unexpected NUMBER at $[1]"); + } + // Confirm that the reader is left in a consistent state after the exception. + reader.setFailOnUnknown(false); + assertThat(reader.nextInt()).isEqualTo(123); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void helloWorld() throws IOException { + String json = "{\n" + + " \"hello\": true,\n" + + " \"foo\": [\"world\"]\n" + + "}"; + JsonReader reader = newReader(json); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("hello"); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextName()).isEqualTo("foo"); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("world"); + reader.endArray(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void nullSource() { + try { + new JsonReader(null); + fail(); + } catch (NullPointerException expected) { + } + } + + @Test public void emptyString() throws Exception { + try { + newReader("").beginArray(); + fail(); + } catch (EOFException expected) { + } + try { + newReader("").beginObject(); + fail(); + } catch (EOFException expected) { + } + } + + @Test public void noTopLevelObject() { + try { + newReader("true").nextBoolean(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void characterUnescaping() throws IOException { + String json = "[\"a\"," + + "\"a\\\"\"," + + "\"\\\"\"," + + "\":\"," + + "\",\"," + + "\"\\b\"," + + "\"\\f\"," + + "\"\\n\"," + + "\"\\r\"," + + "\"\\t\"," + + "\" \"," + + "\"\\\\\"," + + "\"{\"," + + "\"}\"," + + "\"[\"," + + "\"]\"," + + "\"\\u0000\"," + + "\"\\u0019\"," + + "\"\\u20AC\"" + + "]"; + JsonReader reader = newReader(json); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("a\""); + assertThat(reader.nextString()).isEqualTo("\""); + assertThat(reader.nextString()).isEqualTo(":"); + assertThat(reader.nextString()).isEqualTo(","); + assertThat(reader.nextString()).isEqualTo("\b"); + assertThat(reader.nextString()).isEqualTo("\f"); + assertThat(reader.nextString()).isEqualTo("\n"); + assertThat(reader.nextString()).isEqualTo("\r"); + assertThat(reader.nextString()).isEqualTo("\t"); + assertThat(reader.nextString()).isEqualTo(" "); + assertThat(reader.nextString()).isEqualTo("\\"); + assertThat(reader.nextString()).isEqualTo("{"); + assertThat(reader.nextString()).isEqualTo("}"); + assertThat(reader.nextString()).isEqualTo("["); + assertThat(reader.nextString()).isEqualTo("]"); + assertThat(reader.nextString()).isEqualTo("\0"); + assertThat(reader.nextString()).isEqualTo("\u0019"); + assertThat(reader.nextString()).isEqualTo("\u20AC"); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void unescapingInvalidCharacters() throws IOException { + String json = "[\"\\u000g\"]"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void unescapingTruncatedCharacters() throws IOException { + String json = "[\"\\u000"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (EOFException expected) { + } + } + + @Test public void unescapingTruncatedSequence() throws IOException { + String json = "[\"\\"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void integersWithFractionalPartSpecified() throws IOException { + JsonReader reader = newReader("[1.0,1.0,1.0]"); + reader.beginArray(); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextLong()).isEqualTo(1L); + } + + @Test public void doubles() throws IOException { + String json = "[-0.0," + + "1.0," + + "1.7976931348623157E308," + + "4.9E-324," + + "0.0," + + "-0.5," + + "2.2250738585072014E-308," + + "3.141592653589793," + + "2.718281828459045]"; + JsonReader reader = newReader(json); + reader.beginArray(); + assertThat(reader.nextDouble()).isEqualTo(-0.0); + assertThat(reader.nextDouble()).isEqualTo(1.0); + assertThat(reader.nextDouble()).isEqualTo(1.7976931348623157E308); + assertThat(reader.nextDouble()).isEqualTo(4.9E-324); + assertThat(reader.nextDouble()).isEqualTo(0.0); + assertThat(reader.nextDouble()).isEqualTo(-0.5); + assertThat(reader.nextDouble()).isEqualTo(2.2250738585072014E-308); + assertThat(reader.nextDouble()).isEqualTo(3.141592653589793); + assertThat(reader.nextDouble()).isEqualTo(2.718281828459045); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictNonFiniteDoubles() throws IOException { + String json = "[NaN]"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.nextDouble(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictQuotedNonFiniteDoubles() throws IOException { + String json = "[\"NaN\"]"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.nextDouble(); + fail(); + } catch (IOException expected) { + assertThat(expected).hasMessageContaining("NaN"); + } + } + + @Test public void lenientNonFiniteDoubles() throws IOException { + String json = "[NaN, -Infinity, Infinity]"; + JsonReader reader = newReader(json); + reader.setLenient(true); + reader.beginArray(); + assertThat(Double.isNaN(reader.nextDouble())).isTrue(); + assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); + reader.endArray(); + } + + @Test public void lenientQuotedNonFiniteDoubles() throws IOException { + String json = "[\"NaN\", \"-Infinity\", \"Infinity\"]"; + JsonReader reader = newReader(json); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextDouble()).isNaN(); + assertThat(reader.nextDouble()).isEqualTo(Double.NEGATIVE_INFINITY); + assertThat(reader.nextDouble()).isEqualTo(Double.POSITIVE_INFINITY); + reader.endArray(); + } + + @Test public void strictNonFiniteDoublesWithSkipValue() throws IOException { + String json = "[NaN]"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void longs() throws IOException { + String json = "[0,0,0," + + "1,1,1," + + "-1,-1,-1," + + "-9223372036854775808," + + "9223372036854775807]"; + JsonReader reader = newReader(json); + reader.beginArray(); + assertThat(reader.nextLong()).isEqualTo(0L); + assertThat(reader.nextInt()).isEqualTo(0); + assertThat(reader.nextDouble()).isEqualTo(0.0d); + assertThat(reader.nextLong()).isEqualTo(1L); + assertThat(reader.nextInt()).isEqualTo(1); + assertThat(reader.nextDouble()).isEqualTo(1.0d); + assertThat(reader.nextLong()).isEqualTo(-1L); + assertThat(reader.nextInt()).isEqualTo(-1); + assertThat(reader.nextDouble()).isEqualTo(-1.0d); + try { + reader.nextInt(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextLong()).isEqualTo(Long.MIN_VALUE); + try { + reader.nextInt(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextLong()).isEqualTo(Long.MAX_VALUE); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test @Ignore public void numberWithOctalPrefix() throws IOException { + String json = "[01]"; + JsonReader reader = newReader(json); + reader.beginArray(); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + try { + reader.nextInt(); + fail(); + } catch (IOException expected) { + } + try { + reader.nextLong(); + fail(); + } catch (IOException expected) { + } + try { + reader.nextDouble(); + fail(); + } catch (IOException expected) { + } + assertThat(reader.nextString()).isEqualTo("01"); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void booleans() throws IOException { + JsonReader reader = newReader("[true,false]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isFalse(); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void peekingUnquotedStringsPrefixedWithBooleans() throws IOException { + JsonReader reader = newReader("[truey]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + try { + reader.nextBoolean(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextString()).isEqualTo("truey"); + reader.endArray(); + } + + @Test public void malformedNumbers() throws IOException { + assertNotANumber("-"); + assertNotANumber("."); + + // exponent lacks digit + assertNotANumber("e"); + assertNotANumber("0e"); + assertNotANumber(".e"); + assertNotANumber("0.e"); + assertNotANumber("-.0e"); + + // no integer + assertNotANumber("e1"); + assertNotANumber(".e1"); + assertNotANumber("-e1"); + + // trailing characters + assertNotANumber("1x"); + assertNotANumber("1.1x"); + assertNotANumber("1e1x"); + assertNotANumber("1ex"); + assertNotANumber("1.1ex"); + assertNotANumber("1.1e1x"); + + // fraction has no digit + assertNotANumber("0."); + assertNotANumber("-0."); + assertNotANumber("0.e1"); + assertNotANumber("-0.e1"); + + // no leading digit + assertNotANumber(".0"); + assertNotANumber("-.0"); + assertNotANumber(".0e1"); + assertNotANumber("-.0e1"); + } + + private void assertNotANumber(String s) throws IOException { + JsonReader reader = newReader("[" + s + "]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextString()).isEqualTo(s); + reader.endArray(); + } + + @Test public void peekingUnquotedStringsPrefixedWithIntegers() throws IOException { + JsonReader reader = newReader("[12.34e5x]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + try { + reader.nextInt(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextString()).isEqualTo("12.34e5x"); + } + + @Test public void peekLongMinValue() throws IOException { + JsonReader reader = newReader("[-9223372036854775808]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + assertThat(reader.nextLong()).isEqualTo(-9223372036854775808L); + } + + @Test public void peekLongMaxValue() throws IOException { + JsonReader reader = newReader("[9223372036854775807]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + assertThat(reader.nextLong()).isEqualTo(9223372036854775807L); + } + + @Test public void longLargerThanMaxLongThatWrapsAround() throws IOException { + JsonReader reader = newReader("[22233720368547758070]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + } + + @Test public void longLargerThanMinLongThatWrapsAround() throws IOException { + JsonReader reader = newReader("[-22233720368547758070]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + } + + /** + * This test fails because there's no double for 9223372036854775808, and our + * long parsing uses Double.parseDouble() for fractional values. + */ + @Test @Ignore public void peekLargerThanLongMaxValue() throws IOException { + JsonReader reader = newReader("[9223372036854775808]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + } + + /** + * This test fails because there's no double for -9223372036854775809, and our + * long parsing uses Double.parseDouble() for fractional values. + */ + @Test @Ignore public void peekLargerThanLongMinValue() throws IOException { + JsonReader reader = newReader("[-9223372036854775809]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextDouble()).isEqualTo(-9223372036854775809d); + } + + /** + * This test fails because there's no double for 9223372036854775806, and + * our long parsing uses Double.parseDouble() for fractional values. + */ + @Test @Ignore public void highPrecisionLong() throws IOException { + String json = "[9223372036854775806.000]"; + JsonReader reader = newReader(json); + reader.beginArray(); + assertThat(reader.nextLong()).isEqualTo(9223372036854775806L); + reader.endArray(); + } + + @Test public void peekMuchLargerThanLongMinValue() throws IOException { + JsonReader reader = newReader("[-92233720368547758080]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(NUMBER); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextDouble()).isEqualTo(-92233720368547758080d); + } + + @Test public void quotedNumberWithEscape() throws IOException { + JsonReader reader = newReader("[\"12\u00334\"]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + assertThat(reader.nextInt()).isEqualTo(1234); + } + + @Test public void mixedCaseLiterals() throws IOException { + JsonReader reader = newReader("[True,TruE,False,FALSE,NULL,nulL]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isFalse(); + assertThat(reader.nextBoolean()).isFalse(); + reader.nextNull(); + reader.nextNull(); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void missingValue() throws IOException { + JsonReader reader = newReader("{\"a\":}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void prematureEndOfInput() throws IOException { + JsonReader reader = newReader("{\"a\":true,"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.nextName(); + fail(); + } catch (EOFException expected) { + } + } + + @Test public void prematurelyClosed() throws IOException { + try { + JsonReader reader = newReader("{\"a\":[]}"); + reader.beginObject(); + reader.close(); + reader.nextName(); + fail(); + } catch (IllegalStateException expected) { + } + + try { + JsonReader reader = newReader("{\"a\":[]}"); + reader.close(); + reader.beginObject(); + fail(); + } catch (IllegalStateException expected) { + } + + try { + JsonReader reader = newReader("{\"a\":true}"); + reader.beginObject(); + reader.nextName(); + reader.peek(); + reader.close(); + reader.nextBoolean(); + fail(); + } catch (IllegalStateException expected) { + } + } + + @Test public void nextFailuresDoNotAdvance() throws IOException { + JsonReader reader = newReader("{\"a\":true}"); + reader.beginObject(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.nextName(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.beginArray(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.endArray(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.beginObject(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.endObject(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.nextName(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.beginArray(); + fail(); + } catch (JsonDataException expected) { + } + try { + reader.endArray(); + fail(); + } catch (JsonDataException expected) { + } + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + reader.close(); + } + + @Test public void integerMismatchWithDoubleDoesNotAdvance() throws IOException { + JsonReader reader = newReader("[1.5]"); + reader.beginArray(); + try { + reader.nextInt(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextDouble()).isEqualTo(1.5d); + reader.endArray(); + } + + @Test public void integerMismatchWithLongDoesNotAdvance() throws IOException { + JsonReader reader = newReader("[9223372036854775807]"); + reader.beginArray(); + try { + reader.nextInt(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextLong()).isEqualTo(9223372036854775807L); + reader.endArray(); + } + + @Test public void longMismatchWithDoubleDoesNotAdvance() throws IOException { + JsonReader reader = newReader("[1.5]"); + reader.beginArray(); + try { + reader.nextLong(); + fail(); + } catch (JsonDataException expected) { + } + assertThat(reader.nextDouble()).isEqualTo(1.5d); + reader.endArray(); + } + + @Test public void stringNullIsNotNull() throws IOException { + JsonReader reader = newReader("[\"null\"]"); + reader.beginArray(); + try { + reader.nextNull(); + fail(); + } catch (JsonDataException expected) { + } + } + + @Test public void nullLiteralIsNotAString() throws IOException { + JsonReader reader = newReader("[null]"); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (JsonDataException expected) { + } + } + + @Test public void strictNameValueSeparator() throws IOException { + JsonReader reader = newReader("{\"a\"=true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("{\"a\"=>true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientNameValueSeparator() throws IOException { + JsonReader reader = newReader("{\"a\"=true}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); + + reader = newReader("{\"a\"=>true}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); + } + + @Test public void strictNameValueSeparatorWithSkipValue() throws IOException { + JsonReader reader = newReader("{\"a\"=true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("{\"a\"=>true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void commentsInStringValue() throws Exception { + JsonReader reader = newReader("[\"// comment\"]"); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("// comment"); + reader.endArray(); + + reader = newReader("{\"a\":\"#someComment\"}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("#someComment"); + reader.endObject(); + + reader = newReader("{\"#//a\":\"#some //Comment\"}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("#//a"); + assertThat(reader.nextString()).isEqualTo("#some //Comment"); + reader.endObject(); + } + + @Test public void strictComments() throws IOException { + JsonReader reader = newReader("[// comment \n true]"); + reader.beginArray(); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[# comment \n true]"); + reader.beginArray(); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[/* comment */ true]"); + reader.beginArray(); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientComments() throws IOException { + JsonReader reader = newReader("[// comment \n true]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + + reader = newReader("[# comment \n true]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + + reader = newReader("[/* comment */ true]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + + reader = newReader("a//"); + reader.setLenient(true); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictCommentsWithSkipValue() throws IOException { + JsonReader reader = newReader("[// comment \n true]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[# comment \n true]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[/* comment */ true]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictUnquotedNames() throws IOException { + JsonReader reader = newReader("{a:true}"); + reader.beginObject(); + try { + reader.nextName(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientUnquotedNames() throws IOException { + JsonReader reader = newReader("{a:true}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void jsonIsSingleUnquotedString() throws IOException { + JsonReader reader = newReader("abc"); + reader.setLenient(true); + assertThat(reader.nextString()).isEqualTo("abc"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictUnquotedNamesWithSkipValue() throws IOException { + JsonReader reader = newReader("{a:true}"); + reader.beginObject(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictSingleQuotedNames() throws IOException { + JsonReader reader = newReader("{'a':true}"); + reader.beginObject(); + try { + reader.nextName(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientSingleQuotedNames() throws IOException { + JsonReader reader = newReader("{'a':true}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + } + + @Test public void strictSingleQuotedNamesWithSkipValue() throws IOException { + JsonReader reader = newReader("{'a':true}"); + reader.beginObject(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictUnquotedStrings() throws IOException { + JsonReader reader = newReader("[a]"); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictUnquotedStringsWithSkipValue() throws IOException { + JsonReader reader = newReader("[a]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientUnquotedStrings() throws IOException { + JsonReader reader = newReader("[a]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("a"); + } + + @Test public void lenientUnquotedStringsDelimitedByComment() throws IOException { + JsonReader reader = newReader("[a#comment\n]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("a"); + reader.endArray(); + } + + @Test public void strictSingleQuotedStrings() throws IOException { + JsonReader reader = newReader("['a']"); + reader.beginArray(); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientSingleQuotedStrings() throws IOException { + JsonReader reader = newReader("['a']"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo("a"); + } + + @Test public void strictSingleQuotedStringsWithSkipValue() throws IOException { + JsonReader reader = newReader("['a']"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictSemicolonDelimitedArray() throws IOException { + JsonReader reader = newReader("[true;true]"); + reader.beginArray(); + try { + reader.nextBoolean(); + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientSemicolonDelimitedArray() throws IOException { + JsonReader reader = newReader("[true;true]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextBoolean()).isTrue(); + } + + @Test public void strictSemicolonDelimitedArrayWithSkipValue() throws IOException { + JsonReader reader = newReader("[true;true]"); + reader.beginArray(); + try { + reader.skipValue(); + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictSemicolonDelimitedNameValuePair() throws IOException { + JsonReader reader = newReader("{\"a\":true;\"b\":true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.nextBoolean(); + reader.nextName(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientSemicolonDelimitedNameValuePair() throws IOException { + JsonReader reader = newReader("{\"a\":true;\"b\":true}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.nextName()).isEqualTo("b"); + } + + @Test public void strictSemicolonDelimitedNameValuePairWithSkipValue() throws IOException { + JsonReader reader = newReader("{\"a\":true;\"b\":true}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + try { + reader.skipValue(); + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictUnnecessaryArraySeparators() throws IOException { + JsonReader reader = newReader("[true,,true]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.nextNull(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[,true]"); + reader.beginArray(); + try { + reader.nextNull(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[true,]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.nextNull(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[,]"); + reader.beginArray(); + try { + reader.nextNull(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientUnnecessaryArraySeparators() throws IOException { + JsonReader reader = newReader("[true,,true]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + reader.nextNull(); + assertThat(reader.nextBoolean()).isTrue(); + reader.endArray(); + + reader = newReader("[,true]"); + reader.setLenient(true); + reader.beginArray(); + reader.nextNull(); + assertThat(reader.nextBoolean()).isTrue(); + reader.endArray(); + + reader = newReader("[true,]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + reader.nextNull(); + reader.endArray(); + + reader = newReader("[,]"); + reader.setLenient(true); + reader.beginArray(); + reader.nextNull(); + reader.nextNull(); + reader.endArray(); + } + + @Test public void strictUnnecessaryArraySeparatorsWithSkipValue() throws IOException { + JsonReader reader = newReader("[true,,true]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[,true]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[true,]"); + reader.beginArray(); + assertThat(reader.nextBoolean()).isTrue(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + + reader = newReader("[,]"); + reader.beginArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictMultipleTopLevelValues() throws IOException { + JsonReader reader = newReader("[] []"); + reader.beginArray(); + reader.endArray(); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientMultipleTopLevelValues() throws IOException { + JsonReader reader = newReader("[] true {}"); + reader.setLenient(true); + reader.beginArray(); + reader.endArray(); + assertThat(reader.nextBoolean()).isTrue(); + reader.beginObject(); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictMultipleTopLevelValuesWithSkipValue() throws IOException { + JsonReader reader = newReader("[] []"); + reader.beginArray(); + reader.endArray(); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void strictTopLevelString() { + JsonReader reader = newReader("\"a\""); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientTopLevelString() throws IOException { + JsonReader reader = newReader("\"a\""); + reader.setLenient(true); + assertThat(reader.nextString()).isEqualTo("a"); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictTopLevelValueType() { + JsonReader reader = newReader("true"); + try { + reader.nextBoolean(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientTopLevelValueType() throws IOException { + JsonReader reader = newReader("true"); + reader.setLenient(true); + assertThat(reader.nextBoolean()).isTrue(); + } + + @Test public void strictTopLevelValueTypeWithSkipValue() { + JsonReader reader = newReader("true"); + try { + reader.skipValue(); + fail(); + } catch (IOException expected) { + } + } + + @Test @Ignore public void bomIgnoredAsFirstCharacterOfDocument() throws IOException { + JsonReader reader = newReader("\ufeff[]"); + reader.beginArray(); + reader.endArray(); + } + + @Test public void bomForbiddenAsOtherCharacterInDocument() throws IOException { + JsonReader reader = newReader("[\ufeff]"); + reader.beginArray(); + try { + reader.endArray(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void failWithPosition() throws IOException { + testFailWithPosition("Expected value at path $[1]", + "[\n\n\n\n\n\"a\",}]"); + } + + @Test public void failWithPositionGreaterThanBufferSize() throws IOException { + String spaces = repeat(' ', 8192); + testFailWithPosition("Expected value at path $[1]", + "[\n\n" + spaces + "\n\n\n\"a\",}]"); + } + + @Test public void failWithPositionOverSlashSlashEndOfLineComment() throws IOException { + testFailWithPosition("Expected value at path $[1]", + "\n// foo\n\n//bar\r\n[\"a\",}"); + } + + @Test public void failWithPositionOverHashEndOfLineComment() throws IOException { + testFailWithPosition("Expected value at path $[1]", + "\n# foo\n\n#bar\r\n[\"a\",}"); + } + + @Test public void failWithPositionOverCStyleComment() throws IOException { + testFailWithPosition("Expected value at path $[1]", + "\n\n/* foo\n*\n*\r\nbar */[\"a\",}"); + } + + @Test public void failWithPositionOverQuotedString() throws IOException { + testFailWithPosition("Expected value at path $[1]", + "[\"foo\nbar\r\nbaz\n\",\n }"); + } + + @Test public void failWithPositionOverUnquotedString() throws IOException { + testFailWithPosition("Expected value at path $[1]", "[\n\nabcd\n\n,}"); + } + + @Test public void failWithEscapedNewlineCharacter() throws IOException { + testFailWithPosition("Expected value at path $[1]", "[\n\n\"\\\n\n\",}"); + } + + @Test @Ignore public void failWithPositionIsOffsetByBom() throws IOException { + testFailWithPosition("Expected value at path $[1]", "\ufeff[\"a\",}]"); + } + + private void testFailWithPosition(String message, String json) throws IOException { + // Validate that it works reading the string normally. + JsonReader reader1 = newReader(json); + reader1.setLenient(true); + reader1.beginArray(); + reader1.nextString(); + try { + reader1.peek(); + fail(); + } catch (IOException expected) { + assertThat(expected).hasMessage(message); + } + + // Also validate that it works when skipping. + JsonReader reader2 = newReader(json); + reader2.setLenient(true); + reader2.beginArray(); + reader2.skipValue(); + try { + reader2.peek(); + fail(); + } catch (IOException expected) { + assertThat(expected).hasMessage(message); + } + } + + @Test public void failWithPositionDeepPath() throws IOException { + JsonReader reader = newReader("[1,{\"a\":[2,3,}"); + reader.beginArray(); + reader.nextInt(); + reader.beginObject(); + reader.nextName(); + reader.beginArray(); + reader.nextInt(); + reader.nextInt(); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + assertThat(expected).hasMessage("Expected value at path $[1].a[2]"); + } + } + + @Test @Ignore public void strictVeryLongNumber() throws IOException { + JsonReader reader = newReader("[0." + repeat('9', 8192) + "]"); + reader.beginArray(); + try { + assertThat(reader.nextDouble()).isEqualTo(1d); + fail(); + } catch (IOException expected) { + } + } + + @Test @Ignore public void lenientVeryLongNumber() throws IOException { + JsonReader reader = newReader("[0." + repeat('9', 8192) + "]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + assertThat(reader.nextDouble()).isEqualTo(1d); + reader.endArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void veryLongUnquotedLiteral() throws IOException { + String literal = "a" + repeat('b', 8192) + "c"; + JsonReader reader = newReader("[" + literal + "]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo(literal); + reader.endArray(); + } + + @Test public void deeplyNestedArrays() throws IOException { + // this is nested 40 levels deep; Gson is tuned for nesting is 30 levels deep or fewer + JsonReader reader = newReader( + "[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"); + for (int i = 0; i < 40; i++) { + reader.beginArray(); + } + assertThat(reader.getPath()).isEqualTo( + "$[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]" + + "[0][0][0][0][0][0][0][0][0][0][0][0][0][0]"); + for (int i = 0; i < 40; i++) { + reader.endArray(); + } + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void deeplyNestedObjects() throws IOException { + // Build a JSON document structured like {"a":{"a":{"a":{"a":true}}}}, but 40 levels deep + String array = "{\"a\":%s}"; + String json = "true"; + for (int i = 0; i < 40; i++) { + json = String.format(array, json); + } + + JsonReader reader = newReader(json); + for (int i = 0; i < 40; i++) { + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + } + assertThat(reader.getPath()).isEqualTo("$.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a" + + ".a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a"); + assertThat(reader.nextBoolean()).isTrue(); + for (int i = 0; i < 40; i++) { + reader.endObject(); + } + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + // http://code.google.com/p/google-gson/issues/detail?id=409 + @Test public void stringEndingInSlash() throws IOException { + JsonReader reader = newReader("/"); + reader.setLenient(true); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void documentWithCommentEndingInSlash() throws IOException { + JsonReader reader = newReader("/* foo *//"); + reader.setLenient(true); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void stringWithLeadingSlash() throws IOException { + JsonReader reader = newReader("/x"); + reader.setLenient(true); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void unterminatedObject() throws IOException { + JsonReader reader = newReader("{\"a\":\"android\"x"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("android"); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void veryLongQuotedString() throws IOException { + char[] stringChars = new char[1024 * 16]; + Arrays.fill(stringChars, 'x'); + String string = new String(stringChars); + String json = "[\"" + string + "\"]"; + JsonReader reader = newReader(json); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo(string); + reader.endArray(); + } + + @Test public void veryLongUnquotedString() throws IOException { + char[] stringChars = new char[1024 * 16]; + Arrays.fill(stringChars, 'x'); + String string = new String(stringChars); + String json = "[" + string + "]"; + JsonReader reader = newReader(json); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo(string); + reader.endArray(); + } + + @Test public void veryLongUnterminatedString() throws IOException { + char[] stringChars = new char[1024 * 16]; + Arrays.fill(stringChars, 'x'); + String string = new String(stringChars); + String json = "[" + string; + JsonReader reader = newReader(json); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.nextString()).isEqualTo(string); + try { + reader.peek(); + fail(); + } catch (EOFException expected) { + } + } + + @Test public void skipVeryLongUnquotedString() throws IOException { + JsonReader reader = newReader("[" + repeat('x', 8192) + "]"); + reader.setLenient(true); + reader.beginArray(); + reader.skipValue(); + reader.endArray(); + } + + @Test public void skipTopLevelUnquotedString() throws IOException { + JsonReader reader = newReader(repeat('x', 8192)); + reader.setLenient(true); + reader.skipValue(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void skipVeryLongQuotedString() throws IOException { + JsonReader reader = newReader("[\"" + repeat('x', 8192) + "\"]"); + reader.beginArray(); + reader.skipValue(); + reader.endArray(); + } + + @Test public void skipTopLevelQuotedString() throws IOException { + JsonReader reader = newReader("\"" + repeat('x', 8192) + "\""); + reader.setLenient(true); + reader.skipValue(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void stringAsNumberWithTruncatedExponent() throws IOException { + JsonReader reader = newReader("[123e]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + } + + @Test public void stringAsNumberWithDigitAndNonDigitExponent() throws IOException { + JsonReader reader = newReader("[123e4b]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + } + + @Test public void stringAsNumberWithNonDigitExponent() throws IOException { + JsonReader reader = newReader("[123eb]"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(STRING); + } + + @Test public void emptyStringName() throws IOException { + JsonReader reader = newReader("{\"\":true}"); + reader.setLenient(true); + assertThat(reader.peek()).isEqualTo(BEGIN_OBJECT); + reader.beginObject(); + assertThat(reader.peek()).isEqualTo(NAME); + assertThat(reader.nextName()).isEqualTo(""); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.BOOLEAN); + assertThat(reader.nextBoolean()).isTrue(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT); + reader.endObject(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT); + } + + @Test public void strictExtraCommasInMaps() throws IOException { + JsonReader reader = newReader("{\"a\":\"b\",}"); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("b"); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + @Test public void lenientExtraCommasInMaps() throws IOException { + JsonReader reader = newReader("{\"a\":\"b\",}"); + reader.setLenient(true); + reader.beginObject(); + assertThat(reader.nextName()).isEqualTo("a"); + assertThat(reader.nextString()).isEqualTo("b"); + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } + + private String repeat(char c, int count) { + char[] array = new char[count]; + Arrays.fill(array, c); + return new String(array); + } + + @Test public void malformedDocuments() throws IOException { + assertDocument("{]", BEGIN_OBJECT, IOException.class); + assertDocument("{,", BEGIN_OBJECT, IOException.class); + assertDocument("{{", BEGIN_OBJECT, IOException.class); + assertDocument("{[", BEGIN_OBJECT, IOException.class); + assertDocument("{:", BEGIN_OBJECT, IOException.class); + assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\":}", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\"::", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\":,", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\"=}", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\"=>}", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\"=>\"string\":", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\"=>\"string\"=", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\"=>\"string\"=>", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\"=>\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\"=>\"string\",\"name\"", BEGIN_OBJECT, NAME, STRING, NAME); + assertDocument("[}", BEGIN_ARRAY, IOException.class); + assertDocument("[,]", BEGIN_ARRAY, NULL, NULL, END_ARRAY); + assertDocument("{", BEGIN_OBJECT, IOException.class); + assertDocument("{\"name\"", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{\"name\",", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{'name'", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{'name',", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("{name", BEGIN_OBJECT, NAME, IOException.class); + assertDocument("[", BEGIN_ARRAY, IOException.class); + assertDocument("[string", BEGIN_ARRAY, STRING, IOException.class); + assertDocument("[\"string\"", BEGIN_ARRAY, STRING, IOException.class); + assertDocument("['string'", BEGIN_ARRAY, STRING, IOException.class); + assertDocument("[123", BEGIN_ARRAY, NUMBER, IOException.class); + assertDocument("[123,", BEGIN_ARRAY, NUMBER, IOException.class); + assertDocument("{\"name\":123", BEGIN_OBJECT, NAME, NUMBER, IOException.class); + assertDocument("{\"name\":123,", BEGIN_OBJECT, NAME, NUMBER, IOException.class); + assertDocument("{\"name\":\"string\"", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\":\"string\",", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\":'string'", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\":'string',", BEGIN_OBJECT, NAME, STRING, IOException.class); + assertDocument("{\"name\":false", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class); + assertDocument("{\"name\":false,,", BEGIN_OBJECT, NAME, BOOLEAN, IOException.class); + } + + /** + * This test behave slightly differently in Gson 2.2 and earlier. It fails + * during peek rather than during nextString(). + */ + @Test public void unterminatedStringFailure() throws IOException { + JsonReader reader = newReader("[\"string"); + reader.setLenient(true); + reader.beginArray(); + assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING); + try { + reader.nextString(); + fail(); + } catch (IOException expected) { + } + } + + private void assertDocument(String document, Object... expectations) throws IOException { + JsonReader reader = newReader(document); + reader.setLenient(true); + for (Object expectation : expectations) { + if (expectation == BEGIN_OBJECT) { + reader.beginObject(); + } else if (expectation == BEGIN_ARRAY) { + reader.beginArray(); + } else if (expectation == END_OBJECT) { + reader.endObject(); + } else if (expectation == END_ARRAY) { + reader.endArray(); + } else if (expectation == NAME) { + assertThat(reader.nextName()).isEqualTo("name"); + } else if (expectation == BOOLEAN) { + assertThat(reader.nextBoolean()).isFalse(); + } else if (expectation == STRING) { + assertThat(reader.nextString()).isEqualTo("string"); + } else if (expectation == NUMBER) { + assertThat(reader.nextInt()).isEqualTo(123); + } else if (expectation == NULL) { + reader.nextNull(); + } else if (expectation == IOException.class) { + try { + reader.peek(); + fail(); + } catch (IOException expected) { + } + } else { + throw new AssertionError(); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.squareup.moshi.JsonReader` acquired to `reader1` by call to `new()` at line 42 is not released after line 51. +**Note**: potential exception at line 43 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JsonReaderTest.readingDoesNotBuffer() + +### Procedure Id: +com.squareup.moshi.JsonReaderTest.readingDoesNotBuffer():void.be1fa5c53950d20e3251a8bdcf5a3b7c + +### File: +moshi/src/test/java/com/squareup/moshi/JsonReaderTest.java + +### Key: +JsonReaderTest.java|readingDoesNotBuffer|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +1a031283fad8edf41f923834ce15eaf9 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8569/instruction.md b/inferredbugs-8569/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2212da08058f692166ceefa290682be0edd4692 --- /dev/null +++ b/inferredbugs-8569/instruction.md @@ -0,0 +1,383 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** dynamodb-janusgraph-storage-backend +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ +package com.amazon.janusgraph.example; + +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URL; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; + +import org.apache.commons.lang.exception.ExceptionUtils; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.janusgraph.core.JanusGraph; +import org.janusgraph.core.Multiplicity; +import org.janusgraph.core.PropertyKey; +import org.janusgraph.core.schema.JanusGraphManagement; +import org.janusgraph.util.stats.MetricManager; + +import com.codahale.metrics.ConsoleReporter; +import com.codahale.metrics.MetricRegistry; +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.opencsv.CSVReader; + +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; + +/** + * + * @author Matthew Sowders + * @author Alexander Patrikalakis + * + */ +@Slf4j +public final class MarvelGraphFactory { + private static final SecureRandom RANDOM = new SecureRandom(); + private static final int BATCH_SIZE = 10; + public static final String APPEARED = "appeared"; + public static final String COMIC_BOOK = "comic-book"; + public static final String CHARACTER = "character"; + public static final String WEAPON = "weapon"; + public static final MetricRegistry REGISTRY = MetricManager.INSTANCE.getRegistry(); + private static final ConsoleReporter REPORTER = ConsoleReporter.forRegistry(REGISTRY).build(); + private static final String TIMER_LINE = "MarvelGraph.line"; + private static final String TIMER_CREATE = "MarvelGraph.create_"; + private static final String COUNTER_GET = "MarvelGraph.get_"; + private static final List WEAPONS = Lists.newArrayList("claws", "ring", "shield", "robotic suit", "cards", "surf board", "glider", "gun", "swords", "lasso"); + private static final AtomicInteger COMPLETED_TASK_COUNT = new AtomicInteger(0); + private static final int POOL_SIZE = 10; + private static final int TIMEOUT_SIXTY_SECONDS = 60; + + private MarvelGraphFactory() { + } + + /** + * Loads a graph with part or all of the marvel data. + * @param graph the graph object to load with marvel data. + * @param rowsToLoad the number of rows to load with data + * @param report whether to report statistics or not + * @throws IOException if there was a problem loading the marvel file + * @throws InterruptedException if the JanusGraph loading was interrupted + */ + public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) + throws IOException, InterruptedException { + + final JanusGraphManagement mgmt = graph.openManagement(); + if (mgmt.getGraphIndex(CHARACTER) == null) { + final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make(); + mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex(); + } + if (mgmt.getGraphIndex(COMIC_BOOK) == null) { + final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make(); + mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex(); + mgmt.makePropertyKey(WEAPON).dataType(String.class).make(); + mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make(); + } + mgmt.commit(); + + final ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader(); + final URL resource = classLoader.getResource("META-INF/marvel.csv"); + Preconditions.checkNotNull(resource); + final Map> comicToCharacter = new HashMap<>(); + final Map> characterToComic = new HashMap<>(); + final Set characters = new HashSet<>(); + final BlockingQueue creationQueue = new LinkedBlockingQueue<>(); + try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) { + reader.readAll().subList(0, rowsToLoad).forEach(nextLine -> { + final String comicBook = nextLine[1]; + final String[] characterNames = nextLine[0].split("/"); + if (!comicToCharacter.containsKey(comicBook)) { + comicToCharacter.put(comicBook, new HashSet<>()); + } + final List comicCharacters = Arrays.asList(characterNames); + comicToCharacter.get(comicBook).addAll(comicCharacters); + characters.addAll(comicCharacters); + }); + } + creationQueue.addAll(characters.stream().map(character -> new CharacterCreationCommand(character, graph)) + .collect(Collectors.toList())); + + final BlockingQueue appearedQueue = new LinkedBlockingQueue<>(); + for (String comicBook : comicToCharacter.keySet()) { + creationQueue.add(new ComicBookCreationCommand(comicBook, graph)); + final Set comicCharacters = comicToCharacter.get(comicBook); + for (String character : comicCharacters) { + final AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook)); + appearedQueue.add(lineCommand); + if (!characterToComic.containsKey(character)) { + characterToComic.put(character, new HashSet()); + } + characterToComic.get(character).add(comicBook); + } + REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size()); + } + + int maxAppearances = 0; + String maxCharacter = ""; + for (String character : characterToComic.keySet()) { + final Set comicBookSet = characterToComic.get(character); + final int numberOfAppearances = comicBookSet.size(); + REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances); + if (numberOfAppearances > maxAppearances) { + maxCharacter = character; + maxAppearances = numberOfAppearances; + } + } + log.info("Character {} has most appearances at {}", maxCharacter, maxAppearances); + + ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE); + for (int i = 0; i < POOL_SIZE; i++) { + executor.execute(new BatchCommand(graph, creationQueue)); + } + executor.shutdown(); + while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) { + log.info("Awaiting:" + creationQueue.size()); + if (report) { + REPORTER.report(); + } + } + + executor = Executors.newSingleThreadExecutor(); + executor.execute(new BatchCommand(graph, appearedQueue)); + + executor.shutdown(); + while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) { + log.info("Awaiting:" + appearedQueue.size()); + if (report) { + REPORTER.report(); + } + } + log.info("MarvelGraph.load complete"); + } + + @RequiredArgsConstructor + @Getter + private static class Appeared { + private final String character; + private final String comicBook; + } + + @RequiredArgsConstructor + private static class BatchCommand implements Runnable { + private final JanusGraph graph; + private final BlockingQueue commands; + + @Override + public void run() { + int i = 0; + Runnable command = null; + while ((command = commands.poll()) != null) { + try { + command.run(); + } catch (Throwable e) { + final Throwable rootCause = ExceptionUtils.getRootCause(e); + final String rootCauseMessage = Optional.ofNullable(rootCause.getMessage()).orElse(""); + log.error("Error processing comic book {} {}", e.getMessage(), rootCauseMessage, e); + } + if (i++ % BATCH_SIZE == 0) { + try { + graph.tx().commit(); + } catch (Throwable e) { + log.error("error processing commit {} {}", e.getMessage(), ExceptionUtils.getRootCause(e).getMessage()); + } + } + + } + try { + graph.tx().commit(); + } catch (Throwable e) { + log.error("error processing commit {} {}", e.getMessage(), ExceptionUtils.getRootCause(e).getMessage()); + } + } + + } + + @RequiredArgsConstructor + private static class ComicBookCreationCommand implements Runnable { + private final String comicBook; + private final JanusGraph graph; + + @Override + public void run() { + final long start = System.currentTimeMillis(); + final Vertex vertex = graph.addVertex(); + vertex.property(COMIC_BOOK, comicBook); + REGISTRY.counter(COUNTER_GET + COMIC_BOOK).inc(); + final long end = System.currentTimeMillis(); + final long time = end - start; + REGISTRY.timer(TIMER_CREATE + COMIC_BOOK).update(time, TimeUnit.MILLISECONDS); + } + } + + @RequiredArgsConstructor + private static class CharacterCreationCommand implements Runnable { + private final String character; + private final JanusGraph graph; + + @Override + public void run() { + final long start = System.currentTimeMillis(); + final Vertex vertex = graph.addVertex(); + vertex.property(CHARACTER, character); + // only sets weapon on character vertex on initial creation. + vertex.property(WEAPON, WEAPONS.get(RANDOM.nextInt(WEAPONS.size()))); + REGISTRY.counter(COUNTER_GET + CHARACTER).inc(); + final long end = System.currentTimeMillis(); + final long time = end - start; + REGISTRY.timer(TIMER_CREATE + CHARACTER).update(time, TimeUnit.MILLISECONDS); + } + } + + @RequiredArgsConstructor + private static class AppearedCommand implements Runnable { + private final JanusGraph graph; + private final Appeared appeared; + + @Override + public void run() { + try { + final long start = System.currentTimeMillis(); + process(graph, appeared); + final long end = System.currentTimeMillis(); + final long time = end - start; + REGISTRY.timer(TIMER_LINE).update(time, TimeUnit.MILLISECONDS); + } catch (Throwable e) { + final Throwable rootCause = ExceptionUtils.getRootCause(e); + final String rootCauseMessage = Optional.ofNullable(rootCause.getMessage()).orElse(""); + log.error("Error processing line {} {}", e.getMessage(), rootCauseMessage, e); + } finally { + COMPLETED_TASK_COUNT.incrementAndGet(); + } + } + + } + + private static void process(final JanusGraph graph, final Appeared appeared) { + Vertex comicBookVertex = get(graph, COMIC_BOOK, appeared.getComicBook()); + if (null == comicBookVertex) { + REGISTRY.counter("error.missingComicBook." + appeared.getComicBook()).inc(); + comicBookVertex = graph.addVertex(); + comicBookVertex.property(COMIC_BOOK, appeared.getComicBook()); + } + Vertex characterVertex = get(graph, CHARACTER, appeared.getCharacter()); + if (null == characterVertex) { + REGISTRY.counter("error.missingCharacter." + appeared.getCharacter()).inc(); + characterVertex = graph.addVertex(); + characterVertex.property(CHARACTER, appeared.getCharacter()); + characterVertex.property(WEAPON, WEAPONS.get(RANDOM.nextInt(WEAPONS.size()))); + } + characterVertex.addEdge(APPEARED, comicBookVertex); + } + + private static Vertex get(final JanusGraph graph, final String key, final String value) { + final GraphTraversalSource g = graph.traversal(); + final Iterator it = g.V().has(key, value); + if (it.hasNext()) { + return it.next(); + } + return null; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `comicCharacters` last assigned on line 132 could be null and is dereferenced at line 133. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MarvelGraphFactory.load(JanusGraph,int,boolean) + +### Procedure Id: +com.amazon.janusgraph.example.MarvelGraphFactory.load(org.janusgraph.core.JanusGraph,int,boolean):vo.961a7e190cdc63763992b88dabd6b715 + +### File: +src/main/java/com/amazon/janusgraph/example/MarvelGraphFactory.java + +### Key: +MarvelGraphFactory.java|load|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +958695a4ff460f946867a237f32f3592 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8593/instruction.md b/inferredbugs-8593/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8605e476846bc956787a7dcde75dcb0f74b68e46 --- /dev/null +++ b/inferredbugs-8593/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 76 is not released after line 76. +**Note**: potential exception at line 76 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_Integer_Exception_NotTerminated() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_Integer_Exception_NotTerminated():void.2f4c3431eda8fcb0834e327607e22e87 + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_Integer_Exception_NotTerminated|RESOURCE_LEAK + +### Node Key: +f5c23f66aa0be60f5260b2bec3c2ccc6 + +### Hash: +bc82cdf038fba749adf208d3064afd11 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8594/instruction.md b/inferredbugs-8594/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a41ae55fadbe524eb5afbbee980e9f4eccf28b99 --- /dev/null +++ b/inferredbugs-8594/instruction.md @@ -0,0 +1,193 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** bt +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package bt.bencoding; + +import org.junit.Test; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +public class BEParserTest { + + @Test + public void testParse_String1() { + BEParser parser = new BEParser("1:s"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("s", parser.readString()); + } + + @Test + public void testParse_String2() { + BEParser parser = new BEParser("11:!@#$%^&*()_"); + assertEquals(BEType.STRING, parser.readType()); + assertEquals("!@#$%^&*()_", parser.readString()); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_EmptyString() { + new BEParser(""); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_LengthStartsWithZero() { + new BEParser("0:").readString(); + } + + @Test(expected = Exception.class) + public void testParse_String_Exception_InsufficientContent() { + new BEParser("7:abcdef").readString(); + } + + @Test + public void testParse_Integer1() { + BEParser parser = new BEParser("i1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE, parser.readInteger()); + } + + @Test + public void testParse_Integer_Negative() { + BEParser parser = new BEParser("i-1e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ONE.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_ZeroLength() { + BEParser parser = new BEParser("ie"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test//(expected = Exception.class) + public void testParse_Integer_Exception_NegativeZero() { + // not sure why the protocol spec forbids negative zeroes, + // so let it be for now + BEParser parser = new BEParser("i-0e"); + assertEquals(BEType.INTEGER, parser.readType()); + assertEquals(BigInteger.ZERO.negate(), parser.readInteger()); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_NotTerminated() { + BEParser parser = new BEParser("i1"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test(expected = Exception.class) + public void testParse_Integer_Exception_UnexpectedTokens() { + BEParser parser = new BEParser("i-1-e"); + assertEquals(BEType.INTEGER, parser.readType()); + parser.readInteger(); + } + + @Test + public void testParse_List1() { + BEParser parser = new BEParser("l4:spam4:eggsi1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", "eggs", BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_List_ListOfLists() { + BEParser parser = new BEParser("l4:spaml4:spam4:eggsi1eei1ee"); + assertEquals(BEType.LIST, parser.readType()); + assertArrayEquals( + new Object[] {"spam", Arrays.asList("spam", "eggs", BigInteger.ONE), BigInteger.ONE}, + parser.readList().toArray() + ); + } + + @Test + public void testParse_Map1() { + BEParser parser = new BEParser("d4:spaml1:a1:bee"); + assertEquals(BEType.MAP, parser.readType()); + + Map expected = new HashMap<>(); + expected.put("spam", Arrays.asList("a", "b")); + + assertEquals(expected, parser.readMap()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.PushbackReader` acquired by call to `BEParser(...)` at line 36 is not released after line 36. +**Note**: potential exception at line 36 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BEParserTest.testParse_String_Exception_LengthStartsWithZero() + +### Procedure Id: +bt.bencoding.BEParserTest.testParse_String_Exception_LengthStartsWithZero():void.6e173fe832760b07b55fcbff0ee2a595 + +### File: +src/test/java/bt/bencoding/BEParserTest.java + +### Key: +BEParserTest.java|testParse_String_Exception_LengthStartsWithZero|RESOURCE_LEAK + +### Node Key: +34a7f3dc3959865c4e6123ffbf530c11 + +### Hash: +adb349dfb785cd6a37c027545389fd61 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8673/instruction.md b/inferredbugs-8673/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ffa70cd0a0f9fc58a1e8d74224a04c67155562d --- /dev/null +++ b/inferredbugs-8673/instruction.md @@ -0,0 +1,302 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** spatial-framework-for-hadoop +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.esri.json.hadoop; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.LongWritable; +import org.apache.hadoop.io.Text; +import org.apache.hadoop.mapred.FileSplit; +import org.apache.hadoop.mapred.JobConf; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +public class TestUnenclosedJsonRecordReader { + private UnenclosedJsonRecordReader getReaderFor(String resource, int start, int end) throws IOException { + Path path = new Path(this.getClass().getResource(resource).getFile()); + + JobConf conf = new JobConf(); + + FileSplit split = new FileSplit(path, start, end - start, new String[0]); + + return new UnenclosedJsonRecordReader(split, conf); + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader) throws IOException { + return getRecordIndexesInReader(reader, false); + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader, boolean flag) throws IOException { + List linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i clazz = + Class.forName("org.apache.hadoop.mapreduce.task.TaskAttemptContextImpl"); + return (TaskAttemptContext)clazz.getConstructor(Configuration.class, TaskAttemptID.class). + newInstance(conf, taid); + } + } + + private UnenclosedJsonRecordReader getReaderFor(String resource, int start, int end) throws Exception { + Path path = new Path(this.getClass().getResource(resource).getFile()); + + FileSplit split = new FileSplit(path, start, end - start, new String[0]); + + UnenclosedJsonRecordReader rr = new UnenclosedJsonRecordReader(); + try { + TaskAttemptContext tac = + createTaskAttemptContext(new Configuration(), new TaskAttemptID()); + rr.initialize(split, tac); + } catch (InterruptedException ie) { + Thread.currentThread().interrupt(); + } + + return rr; + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader) throws IOException { + return getRecordIndexesInReader(reader, false); + } + + int [] getRecordIndexesInReader(UnenclosedJsonRecordReader reader, boolean flag) throws IOException { + List linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + //System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i linesList = new LinkedList(); + + LongWritable key = reader.createKey(); + Text value = reader.createValue(); + + while (reader.next(key, value)) { + int line = flag ? (int)(key.get()) : value.toString().charAt(23) - '0'; + linesList.add(line); + System.out.println(key.get() + " - " + value.toString()); + } + + int [] lines = new int[linesList.size()]; + for (int i=0;i + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *

    + */ + +package com.vip.pallas.console.httpproxy; + +import java.io.Closeable; +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpCookie; +import java.net.URI; +import java.util.Arrays; +import java.util.BitSet; +import java.util.Enumeration; +import java.util.Formatter; +import java.util.List; +import java.util.stream.Stream; + +import javax.servlet.ServletException; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.http.Header; +import org.apache.http.HttpEntity; +import org.apache.http.HttpEntityEnclosingRequest; +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.AbortableHttpRequest; +import org.apache.http.client.utils.URIUtils; +import org.apache.http.entity.InputStreamEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHeader; +import org.apache.http.message.BasicHttpEntityEnclosingRequest; +import org.apache.http.message.BasicHttpRequest; +import org.apache.http.message.HeaderGroup; +import org.apache.http.util.EntityUtils; + +/** + * An HTTP reverse proxy/gateway servlet. It is designed to be extended for customization + * if desired. Most of the work is handled by + * Apache HttpClient. + *

    + * There are alternatives to a servlet based proxy such as Apache mod_proxy if that is available to you. However + * this servlet is easily customizable by Java, secure-able by your web application's security (e.g. spring-security), + * portable across servlet engines, and is embeddable into another web application. + *

    + *

    + * Inspiration: http://httpd.apache.org/docs/2.0/mod/mod_proxy.html + *

    + * + * @author David Smiley dsmiley@mitre.org + */ +@SuppressWarnings({ "deprecation", "serial" }) +public class ProxyServlet extends HttpServlet { + + /* INIT PARAMETER NAME CONSTANTS */ + + /** A boolean parameter name to enable logging of input and target URLs to the servlet log. */ + public static final String P_LOG = "log"; + + /** A boolean parameter name to enable forwarding of the client IP */ + public static final String P_FORWARDEDFOR = "forwardip"; + + /** A boolean parameter name to keep HOST parameter as-is */ + public static final String P_PRESERVEHOST = "preserveHost"; + + /** A boolean parameter name to keep COOKIES as-is */ + public static final String P_PRESERVECOOKIES = "preserveCookies"; + + /** A boolean parameter name to have auto-handle redirects */ + public static final String P_HANDLEREDIRECTS = "http.protocol.handle-redirects"; // ClientPNames.HANDLE_REDIRECTS + + /** A integer parameter name to set the socket connection timeout (millis) */ + public static final String P_CONNECTTIMEOUT = "http.socket.timeout"; // CoreConnectionPNames.SO_TIMEOUT + + /** The parameter name for the target (destination) URI to proxy to. */ + protected static final String P_TARGET_URI = "targetUri"; + protected static final String ATTR_TARGET_URI = + ProxyServlet.class.getSimpleName() + ".targetUri"; + protected static final String ATTR_TARGET_HOST = + ProxyServlet.class.getSimpleName() + ".targetHost"; + + /* MISC */ + + protected boolean doLog = false; + protected boolean doForwardIP = true; + /** User agents shouldn't send the url fragment but what if it does? */ + protected boolean doSendUrlFragment = true; + protected boolean doPreserveHost = false; + protected boolean doPreserveCookies = false; + protected boolean doHandleRedirects = false; + protected int connectTimeout = -1; + + //These next 3 are cached here, and should only be referred to in initialization logic. See the + // ATTR_* parameters. + /** From the configured parameter "targetUri". */ + protected String targetUri; + protected URI targetUriObj;//new URI(targetUri) + protected HttpHost targetHost;//URIUtils.extractHost(targetUriObj); + + private HttpClient proxyClient; + + @Override + public String getServletInfo() { + return "A proxy servlet by David Smiley, dsmiley@apache.org"; + } + + + protected String getTargetUri(HttpServletRequest servletRequest) { + return (String) servletRequest.getAttribute(ATTR_TARGET_URI); + } + + protected HttpHost getTargetHost(HttpServletRequest servletRequest) { + return (HttpHost) servletRequest.getAttribute(ATTR_TARGET_HOST); + } + + /** + * Reads a configuration parameter. By default it reads servlet init parameters but + * it can be overridden. + */ + protected String getConfigParam(String key) { + return getServletConfig().getInitParameter(key); + } + + @Override + public void init() throws ServletException { + String doLogStr = getConfigParam(P_LOG); + if (doLogStr != null) { + this.doLog = Boolean.parseBoolean(doLogStr); + } + + String doForwardIPString = getConfigParam(P_FORWARDEDFOR); + if (doForwardIPString != null) { + this.doForwardIP = Boolean.parseBoolean(doForwardIPString); + } + + String preserveHostString = getConfigParam(P_PRESERVEHOST); + if (preserveHostString != null) { + this.doPreserveHost = Boolean.parseBoolean(preserveHostString); + } + + String preserveCookiesString = getConfigParam(P_PRESERVECOOKIES); + if (preserveCookiesString != null) { + this.doPreserveCookies = Boolean.parseBoolean(preserveCookiesString); + } + + String handleRedirectsString = getConfigParam(P_HANDLEREDIRECTS); + if (handleRedirectsString != null) { + this.doHandleRedirects = Boolean.parseBoolean(handleRedirectsString); + } + + String connectTimeoutString = getConfigParam(P_CONNECTTIMEOUT); + if (connectTimeoutString != null) { + this.connectTimeout = Integer.parseInt(connectTimeoutString); + } + + initTarget();//sets target* + + proxyClient = createHttpClient(buildRequestConfig()); + } + + /** + * Sub-classes can override specific behaviour of {@link org.apache.http.client.config.RequestConfig}. + */ + protected RequestConfig buildRequestConfig() { + RequestConfig.Builder builder = RequestConfig.custom() + .setRedirectsEnabled(doHandleRedirects) + .setCookieSpec(CookieSpecs.IGNORE_COOKIES) // we handle them in the servlet instead + .setConnectTimeout(connectTimeout); + return builder.build(); + } + + protected void initTarget() throws ServletException { + targetUri = getConfigParam(P_TARGET_URI); + if (targetUri == null) + throw new ServletException(P_TARGET_URI+" is required."); + //test it's valid + try { + targetUriObj = new URI(targetUri); + } catch (Exception e) { + throw new ServletException("Trying to process targetUri init parameter: "+e,e); + } + targetHost = URIUtils.extractHost(targetUriObj); + } + + /** Called from {@link #init(javax.servlet.ServletConfig)}. + * HttpClient offers many opportunities for customization. + * In any case, it should be thread-safe. + **/ + protected HttpClient createHttpClient(final RequestConfig requestConfig) { + return HttpClientBuilder.create().setMaxConnPerRoute(50) + .setDefaultRequestConfig(requestConfig).build(); + } + + /** The http client used. + * @see #createHttpClient(RequestConfig) */ + protected HttpClient getProxyClient() { + return proxyClient; + } + + @Override + public void destroy() { + //Usually, clients implement Closeable: + if (proxyClient instanceof Closeable) { + try { + ((Closeable) proxyClient).close(); + } catch (IOException e) { + log("While destroying servlet, shutting down HttpClient: "+e, e); + } + } else { + //Older releases require we do this: + if (proxyClient != null) + proxyClient.getConnectionManager().shutdown(); + } + super.destroy(); + } + + @Override + protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) + throws ServletException, IOException { + //initialize request attributes from caches if unset by a subclass by this point + if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { + servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); + } + if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { + servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); + } + + // Make the Request + //note: we won't transfer the protocol version because I'm not sure it would truly be compatible + String method = servletRequest.getMethod(); + String proxyRequestUri = rewriteUrlFromRequest(servletRequest); + HttpRequest proxyRequest; + //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. + if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || + servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { + proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest); + } else { + proxyRequest = new BasicHttpRequest(method, proxyRequestUri); + } + + copyRequestHeaders(servletRequest, proxyRequest); + + setXForwardedForHeader(servletRequest, proxyRequest); + + HttpResponse proxyResponse = null; + try { + // Execute the request + proxyResponse = doExecute(servletRequest, servletResponse, proxyRequest); + + // Process the response: + + // Pass the response code. This method with the "reason phrase" is deprecated but it's the + // only way to pass the reason along too. + int statusCode = proxyResponse.getStatusLine().getStatusCode(); + //noinspection deprecation + servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); + + // Copying response headers to make sure SESSIONID or other Cookie which comes from the remote + // server will be saved in client when the proxied url was redirected to another one. + // See issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) + copyResponseHeaders(proxyResponse, servletRequest, servletResponse); + + if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { + // 304 needs special handling. See: + // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 + // Don't send body entity/content! + servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); + } else { + // Send the content to the client + copyResponseEntity(proxyResponse, servletResponse, proxyRequest, servletRequest); + } + + } catch (Exception e) { + //abort request, according to best practice with HttpClient + if (proxyRequest instanceof AbortableHttpRequest) { + AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; + abortableHttpRequest.abort(); + } + if (e instanceof RuntimeException) + throw (RuntimeException)e; + if (e instanceof ServletException) + throw (ServletException)e; + //noinspection ConstantConditions + if (e instanceof IOException) + throw (IOException) e; + throw new RuntimeException(e); + + } finally { + // make sure the entire entity was consumed, so the connection is released + if (proxyResponse != null) + consumeQuietly(proxyResponse.getEntity()); + //Note: Don't need to close servlet outputStream: + // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter + } + } + + protected HttpResponse doExecute(HttpServletRequest servletRequest, HttpServletResponse servletResponse, + HttpRequest proxyRequest) throws IOException { + if (doLog) { + log("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + + proxyRequest.getRequestLine().getUri()); + } + return proxyClient.execute(getTargetHost(servletRequest), proxyRequest); + } + + protected HttpRequest newProxyRequestWithEntity(String method, String proxyRequestUri, + HttpServletRequest servletRequest) + throws IOException { + HttpEntityEnclosingRequest eProxyRequest = + new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); + // Add the input entity (streamed) + // note: we don't bother ensuring we close the servletInputStream since the container handles it + eProxyRequest.setEntity( + new InputStreamEntity(servletRequest.getInputStream(), getContentLength(servletRequest))); + return eProxyRequest; + } + + // Get the header value as a long in order to more correctly proxy very large requests + private long getContentLength(HttpServletRequest request) { + String contentLengthHeader = request.getHeader("Content-Length"); + if (contentLengthHeader != null) { + return Long.parseLong(contentLengthHeader); + } + return -1L; + } + + protected void closeQuietly(Closeable closeable) { + try { + closeable.close(); + } catch (IOException e) { + log(e.getMessage(), e); + } + } + + /** HttpClient v4.1 doesn't have the + * {@link org.apache.http.util.EntityUtils#consumeQuietly(org.apache.http.HttpEntity)} method. */ + protected void consumeQuietly(HttpEntity entity) { + try { + EntityUtils.consume(entity); + } catch (IOException e) {//ignore + log(e.getMessage(), e); + } + } + + /** These are the "hop-by-hop" headers that should not be copied. + * http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html + * I use an HttpClient HeaderGroup class instead of Set<String> because this + * approach does case insensitive lookup faster. + */ + protected static final HeaderGroup hopByHopHeaders; + static { + hopByHopHeaders = new HeaderGroup(); + String[] headers = new String[] { + "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", + "TE", "Trailers", "Transfer-Encoding", "Upgrade" }; + for (String header : headers) { + hopByHopHeaders.addHeader(new BasicHeader(header, null)); + } + } + + /** Copy request headers from the servlet client to the proxy request. */ + protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { + // Get an Enumeration of all of the header names sent by the client + @SuppressWarnings("unchecked") + Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); + while (enumerationOfHeaderNames.hasMoreElements()) { + String headerName = enumerationOfHeaderNames.nextElement(); + copyRequestHeader(servletRequest, proxyRequest, headerName); + } + } + + /** + * Copy a request header from the servlet client to the proxy request. + * This is easily overwritten to filter out certain headers if desired. + */ + protected void copyRequestHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest, + String headerName) { + //Instead the content-length is effectively set via InputStreamEntity + if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) + return; + if (hopByHopHeaders.containsHeader(headerName)) + return; + + @SuppressWarnings("unchecked") + Enumeration headers = servletRequest.getHeaders(headerName); + while (headers.hasMoreElements()) {//sometimes more than one value + String headerValue = headers.nextElement(); + // In case the proxy host is running multiple virtual servers, + // rewrite the Host header to ensure that we get content from + // the correct virtual server + if (!doPreserveHost && headerName.equalsIgnoreCase(HttpHeaders.HOST)) { + HttpHost host = getTargetHost(servletRequest); + headerValue = host.getHostName(); + if (host.getPort() != -1) + headerValue += ":"+host.getPort(); + } else if (!doPreserveCookies && headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { + headerValue = getRealCookie(headerValue); + } + proxyRequest.addHeader(headerName, headerValue); + } + } + + private void setXForwardedForHeader(HttpServletRequest servletRequest, + HttpRequest proxyRequest) { + if (doForwardIP) { + String forHeaderName = "X-Forwarded-For"; + String forHeader = servletRequest.getRemoteAddr(); + String existingForHeader = servletRequest.getHeader(forHeaderName); + if (existingForHeader != null) { + forHeader = existingForHeader + ", " + forHeader; + } + proxyRequest.setHeader(forHeaderName, forHeader); + + String protoHeaderName = "X-Forwarded-Proto"; + String protoHeader = servletRequest.getScheme(); + proxyRequest.setHeader(protoHeaderName, protoHeader); + } + } + + /** Copy proxied response headers back to the servlet client. */ + protected void copyResponseHeaders(HttpResponse proxyResponse, HttpServletRequest servletRequest, + HttpServletResponse servletResponse) { + for (Header header : proxyResponse.getAllHeaders()) { + copyResponseHeader(servletRequest, servletResponse, header); + } + } + + /** Copy a proxied response header back to the servlet client. + * This is easily overwritten to filter out certain headers if desired. + */ + protected void copyResponseHeader(HttpServletRequest servletRequest, + HttpServletResponse servletResponse, Header header) { + String headerName = header.getName(); + if (hopByHopHeaders.containsHeader(headerName)) + return; + String headerValue = header.getValue(); + if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE) || + headerName.equalsIgnoreCase(org.apache.http.cookie.SM.SET_COOKIE2)) { + copyProxyCookie(servletRequest, servletResponse, headerValue); + } else if (headerName.equalsIgnoreCase(HttpHeaders.LOCATION)) { + // LOCATION Header may have to be rewritten. + servletResponse.addHeader(headerName, rewriteUrlFromResponse(servletRequest, headerValue)); + } else { + servletResponse.addHeader(headerName, headerValue); + } + } + + /** Copy cookie from the proxy to the servlet client. + * Replaces cookie path to local path and renames cookie to avoid collisions. + */ + protected void copyProxyCookie(HttpServletRequest servletRequest, + HttpServletResponse servletResponse, String headerValue) { + List cookies = HttpCookie.parse(headerValue); + String path = servletRequest.getContextPath(); // path starts with / or is empty string + path += servletRequest.getServletPath(); // servlet path starts with / or is empty string + if(path.isEmpty()){ + path = "/"; + } + + for (HttpCookie cookie : cookies) { + //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies + String proxyCookieName = doPreserveCookies ? cookie.getName() : getCookieNamePrefix(cookie.getName()) + cookie.getName(); + Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); + servletCookie.setComment(cookie.getComment()); + servletCookie.setMaxAge((int) cookie.getMaxAge()); + servletCookie.setPath(path); //set to the path of the proxy servlet + // don't set cookie domain + servletCookie.setSecure(cookie.getSecure()); + servletCookie.setVersion(cookie.getVersion()); + servletResponse.addCookie(servletCookie); + } + } + + public static void main(String[] args) { + /**获取单词,并且去重**/ + List list = Arrays.asList("hello welcome", "world hello", "hello world", + "hello world welcome"); + + //map和flatmap的区别 + list.stream().map(item -> Arrays.stream(item.split(" "))).distinct().forEach(System.out::println); + System.out.println("---------- "); + list.stream().flatMap(item -> Arrays.stream(item.split(" "))).distinct().forEach(System.out::println); +} + + /** Take any client cookies that were originally from the proxy and prepare them to send to the + * proxy. This relies on cookie headers being set correctly according to RFC 6265 Sec 5.4. + * This also blocks any local cookies from being sent to the proxy. + */ + protected String getRealCookie(String cookieValue) { + StringBuilder escapedCookie = new StringBuilder(); + String cookies[] = cookieValue.split("[;,]"); + + Stream.of(cookies).map(cookie -> cookie.split("=")).filter(cookieSplit -> cookieSplit.length == 2).forEach(cookieSplit -> { + String cookieName = cookieSplit[0].trim(); + if (cookieName.startsWith(getCookieNamePrefix(cookieName))) { + cookieName = cookieName.substring(getCookieNamePrefix(cookieName).length()); + if (escapedCookie.length() > 0) { + escapedCookie.append("; "); + } + escapedCookie.append(cookieName).append("=").append(cookieSplit[1].trim()); + } + }); + return escapedCookie.toString(); + } + + /** The string prefixing rewritten cookies. */ + protected String getCookieNamePrefix(String name) { + return "!Proxy!" + getServletConfig().getServletName(); + } + + /** Copy response body data (the entity) from the proxy to the servlet client. */ + protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse, + HttpRequest proxyRequest, HttpServletRequest servletRequest) + throws IOException { + HttpEntity entity = proxyResponse.getEntity(); + if (entity != null) { + OutputStream servletOutputStream = servletResponse.getOutputStream(); + entity.writeTo(servletOutputStream); + } + } + + /** Reads the request URI from {@code servletRequest} and rewrites it, considering targetUri. + * It's used to make the new request. + */ + protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) { + StringBuilder uri = new StringBuilder(500); + uri.append(getTargetUri(servletRequest)); + // Handle the path given to the servlet + if (servletRequest.getPathInfo() != null) {//ex: /my/path.html + uri.append(encodeUriQuery(servletRequest.getPathInfo())); + } + // Handle the query string & fragment + String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment + String fragment = null; + //split off fragment from queryString, updating queryString if found + if (queryString != null) { + int fragIdx = queryString.indexOf('#'); + if (fragIdx >= 0) { + fragment = queryString.substring(fragIdx + 1); + queryString = queryString.substring(0,fragIdx); + } + } + + queryString = rewriteQueryStringFromRequest(servletRequest, queryString); + if (queryString != null && queryString.length() > 0) { + uri.append('?'); + uri.append(encodeUriQuery(queryString)); + } + + if (doSendUrlFragment && fragment != null) { + uri.append('#'); + uri.append(encodeUriQuery(fragment)); + } + return uri.toString(); + } + + protected String rewriteQueryStringFromRequest(HttpServletRequest servletRequest, String queryString) { + return queryString; + } + + /** For a redirect response from the target server, this translates {@code theUrl} to redirect to + * and translates it to one the original client can use. */ + protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) { + //TODO document example paths + final String targetUri = getTargetUri(servletRequest); + if (theUrl.startsWith(targetUri)) { + /*- + * The URL points back to the back-end server. + * Instead of returning it verbatim we replace the target path with our + * source path in a way that should instruct the original client to + * request the URL pointed through this Proxy. + * We do this by taking the current request and rewriting the path part + * using this servlet's absolute path and the path from the returned URL + * after the base target URL. + */ + StringBuffer curUrl = servletRequest.getRequestURL();//no query + int pos; + // Skip the protocol part + if ((pos = curUrl.indexOf("://"))>=0) { + // Skip the authority part + // + 3 to skip the separator between protocol and authority + if ((pos = curUrl.indexOf("/", pos + 3)) >=0) { + // Trim everything after the authority part. + curUrl.setLength(pos); + } + } + // Context path starts with a / if it is not blank + curUrl.append(servletRequest.getContextPath()); + // Servlet path starts with a / if it is not blank + curUrl.append(servletRequest.getServletPath()); + curUrl.append(theUrl, targetUri.length(), theUrl.length()); + theUrl = curUrl.toString(); + } + return theUrl; + } + + /** The target URI as configured. Not null. */ + public String getTargetUri() { return targetUri; } + + /** + * Encodes characters in the query or fragment part of the URI. + * + *

    Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient + * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}. + * To be more forgiving, we must escape the problematic characters. See the URI class for the + * spec. + * + * @param in example: name=value&foo=bar#fragment + */ + protected static CharSequence encodeUriQuery(CharSequence in) { + //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things. + StringBuilder outBuf = null; + Formatter formatter = null; + for(int i = 0; i < in.length(); i++) { + char c = in.charAt(i); + boolean escape = true; + if (c < 128) { + if (asciiQueryChars.get((int)c)) { + escape = false; + } + } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii + escape = false; + } + if (!escape) { + if (outBuf != null) + outBuf.append(c); + } else { + //escape + if (outBuf == null) { + outBuf = new StringBuilder(in.length() + 5*3); + outBuf.append(in,0,i); + formatter = new Formatter(outBuf); + } + //leading %, 0 padded, width 2, capital hex + formatter.format("%%%02X",(int)c);//TODO + } + } + return outBuf != null ? outBuf : in; + } + + protected static final BitSet asciiQueryChars; + static { + char[] c_unreserved = "_-!.~'()*".toCharArray();//plus alphanum + char[] c_punct = ",;:$&+=".toCharArray(); + char[] c_reserved = "?/[]@".toCharArray();//plus punct + + asciiQueryChars = new BitSet(128); + for(char c = 'a'; c <= 'z'; c++) asciiQueryChars.set((int)c); + for(char c = 'A'; c <= 'Z'; c++) asciiQueryChars.set((int)c); + for(char c = '0'; c <= '9'; c++) asciiQueryChars.set((int)c); + for(char c : c_unreserved) asciiQueryChars.set((int)c); + for(char c : c_punct) asciiQueryChars.set((int)c); + for(char c : c_reserved) asciiQueryChars.set((int)c); + + asciiQueryChars.set((int)'%');//leave existing percent escapes in place + } + +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.Formatter` acquired by call to `new()` at line 653 is not released after line 659. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +CharSequence ProxyServlet.encodeUriQuery(CharSequence) + +### Procedure Id: +com.vip.pallas.console.httpproxy.ProxyServlet.encodeUriQuery(java.lang.CharSequence):java.lang.CharS.ce5c05867d89bca3af7ce3e1b4402dd7 + +### File: +pallas-console/src/main/java/com/vip/pallas/console/httpproxy/ProxyServlet.java + +### Key: +ProxyServlet.java|encodeUriQuery|RESOURCE_LEAK + +### Node Key: +3eaf16b7e8904b2a5602aec15d348bb8 + +### Hash: +95d6b5926da8a5c2a317bf3efe752c9f + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8753/instruction.md b/inferredbugs-8753/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c73d1b64dac62aff11d2820e6db5ddfe093e56f4 --- /dev/null +++ b/inferredbugs-8753/instruction.md @@ -0,0 +1,349 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** litemall +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.linlinjava.litemall.admin.web; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.linlinjava.litemall.admin.annotation.LoginAdmin; +import org.linlinjava.litemall.core.util.JacksonUtil; +import org.linlinjava.litemall.db.domain.*; +import org.linlinjava.litemall.db.service.LitemallOrderGoodsService; +import org.linlinjava.litemall.db.service.LitemallOrderService; +import org.linlinjava.litemall.db.service.LitemallProductService; +import org.linlinjava.litemall.db.service.LitemallUserService; +import org.linlinjava.litemall.db.util.OrderHandleOption; +import org.linlinjava.litemall.db.util.OrderUtil; +import org.linlinjava.litemall.core.util.ResponseUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.web.bind.annotation.*; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/admin/order") +public class AdminOrderController { + private final Log logger = LogFactory.getLog(AdminOrderController.class); + + @Autowired + private PlatformTransactionManager txManager; + + @Autowired + private LitemallOrderGoodsService orderGoodsService; + @Autowired + private LitemallOrderService orderService; + @Autowired + private LitemallProductService productService; + @Autowired + private LitemallUserService userService; + + @GetMapping("/list") + public Object list(@LoginAdmin Integer adminId, + Integer userId, String orderSn, @RequestParam(required = false, value = "orderStatusArray[]")List orderStatusArray, + @RequestParam(value = "page", defaultValue = "1") Integer page, + @RequestParam(value = "limit", defaultValue = "10") Integer limit, + String sort, String order){ + if(adminId == null){ + return ResponseUtil.unlogin(); + } + List orderList = orderService.querySelective(userId, orderSn,orderStatusArray, page, limit, sort, order); + int total = orderService.countSelective(userId, orderSn, orderStatusArray, page, limit, sort, order); + + Map data = new HashMap<>(); + data.put("total", total); + data.put("items", orderList); + + return ResponseUtil.ok(data); + } + + @GetMapping("/detail") + public Object detail(@LoginAdmin Integer adminId, Integer id) { + if(adminId == null){ + return ResponseUtil.unlogin(); + } + + LitemallOrder order = orderService.findById(id); + List orderGoods = orderGoodsService.queryByOid(id); + UserVo user = userService.findUserVoById(order.getUserId()); + Map data = new HashMap<>(); + data.put("order", order); + data.put("orderGoods", orderGoods); + data.put("user", user); + + return ResponseUtil.ok(data); + } + + /** + * 订单退款确认 + * 1. 检测当前订单是否能够退款确认 + * 2. 设置订单退款确认状态 + * 3. 订单商品恢复 + * + * @param adminId 管理员ID + * @param body 订单信息,{ orderId:xxx } + * @return 订单操作结果 + * 成功则 { errno: 0, errmsg: '成功' } + * 失败则 { errno: XXX, errmsg: XXX } + */ + @PostMapping("refund") + public Object refund(@LoginAdmin Integer adminId, @RequestBody String body) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + Integer orderId = JacksonUtil.parseInteger(body, "orderId"); + Integer refundMoney = JacksonUtil.parseInteger(body, "refundMoney"); + if (orderId == null) { + return ResponseUtil.badArgument(); + } + + LitemallOrder order = orderService.findById(orderId); + if (order == null) { + return ResponseUtil.badArgument(); + } + + if(order.getActualPrice().compareTo(new BigDecimal(refundMoney)) != 0){ + return ResponseUtil.badArgumentValue(); + } + + // 如果订单不是退款状态,则不能退款 + if (!order.getOrderStatus().equals(OrderUtil.STATUS_REFUND)) { + return ResponseUtil.fail(403, "订单不能确认收货"); + } + + // 开启事务管理 + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + TransactionStatus status = txManager.getTransaction(def); + try { + // 设置订单取消状态 + order.setOrderStatus(OrderUtil.STATUS_REFUND_CONFIRM); + orderService.update(order); + + // 商品货品数量增加 + List orderGoodsList = orderGoodsService.queryByOid(orderId); + for (LitemallOrderGoods orderGoods : orderGoodsList) { + Integer productId = orderGoods.getProductId(); + LitemallProduct product = productService.findById(productId); + Integer number = product.getNumber() + orderGoods.getNumber(); + product.setNumber(number); + productService.updateById(product); + } + } catch (Exception ex) { + txManager.rollback(status); + logger.error("系统内部错误", ex); + return ResponseUtil.fail(403, "订单退款失败"); + } + txManager.commit(status); + + return ResponseUtil.ok(); + } + + /** + * 发货 + * 1. 检测当前订单是否能够发货 + * 2. 设置订单发货状态 + * + * @param adminId 管理员ID + * @param body 订单信息,{ orderId:xxx, shipSn: xxx, shipChannel: xxx } + * @return 订单操作结果 + * 成功则 { errno: 0, errmsg: '成功' } + * 失败则 { errno: XXX, errmsg: XXX } + */ + @PostMapping("ship") + public Object ship(@LoginAdmin Integer adminId, @RequestBody String body) { + if (adminId == null) { + return ResponseUtil.unlogin(); + } + Integer orderId = JacksonUtil.parseInteger(body, "orderId"); + String shipSn = JacksonUtil.parseString(body, "shipSn"); + String shipChannel = JacksonUtil.parseString(body, "shipChannel"); + if (orderId == null || shipSn == null || shipChannel == null) { + return ResponseUtil.badArgument(); + } + + LitemallOrder order = orderService.findById(orderId); + if (order == null) { + return ResponseUtil.badArgument(); + } + + // 如果订单不是已付款状态,则不能发货 + if (!order.getOrderStatus().equals(OrderUtil.STATUS_PAY)) { + return ResponseUtil.fail(403, "订单不能确认收货"); + } + + order.setOrderStatus(OrderUtil.STATUS_SHIP); + order.setShipSn(shipSn); + order.setShipChannel(shipChannel); + order.setShipTime(LocalDateTime.now()); + orderService.update(order); + + return ResponseUtil.ok(); + } + + /** + * 自动取消订单 + * + * 定时检查订单未付款情况,如果超时半个小时则自动取消订单 + * 定时时间是每次相隔半个小时。 + * + * 注意,因为是相隔半小时检查,因此导致有订单是超时一个小时以后才设置取消状态。 + * TODO + * 这里可以进一步地配合用户订单查询时订单未付款检查,如果订单超时半小时则取消。 + */ + @Scheduled(fixedDelay = 30*60*1000) + public void checkOrderUnpaid() { + logger.debug(LocalDateTime.now()); + + List orderList = orderService.queryUnpaid(); + for(LitemallOrder order : orderList){ + LocalDateTime add = order.getAddTime(); + LocalDateTime now = LocalDateTime.now(); + LocalDateTime expired = add.plusMinutes(30); + if(expired.isAfter(now)){ + continue; + } + + // 开启事务管理 + DefaultTransactionDefinition def = new DefaultTransactionDefinition(); + def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + TransactionStatus status = txManager.getTransaction(def); + try { + // 设置订单已取消状态 + order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL); + order.setEndTime(LocalDateTime.now()); + orderService.updateById(order); + + // 商品货品数量增加 + Integer orderId = order.getId(); + List orderGoodsList = orderGoodsService.queryByOid(orderId); + for (LitemallOrderGoods orderGoods : orderGoodsList) { + Integer productId = orderGoods.getProductId(); + LitemallProduct product = productService.findById(productId); + Integer number = product.getNumber() + orderGoods.getNumber(); + product.setNumber(number); + productService.updateById(product); + } + } catch (Exception ex) { + txManager.rollback(status); + logger.error("系统内部错误", ex); + } + txManager.commit(status); + } + } + + /** + * 自动确认订单 + * + * 定时检查订单未确认情况,如果超时七天则自动确认订单 + * 定时时间是每天凌晨3点。 + * + * 注意,因为是相隔一天检查,因此导致有订单是超时八天以后才设置自动确认。 + * 这里可以进一步地配合用户订单查询时订单未确认检查,如果订单超时7天则自动确认。 + * 但是,这里可能不是非常必要。相比订单未付款检查中存在商品资源有限所以应该 + * 早点清理未付款情况,这里八天再确认是可以的。 + * + * TODO + * 目前自动确认是基于管理后台管理员所设置的商品快递时间,见orderService.queryUnconfirm。 + * 那么在实际业务上有可能存在商品寄出以后商品因为一些原因快递最终没有到达, + * 也就是商品快递失败而shipEndTime一直是空的情况,因此这里业务可能需要扩展,以防止订单一直 + * 处于发货状态。 + */ + @Scheduled(cron = "0 0 3 * * ?") + public void checkOrderUnconfirm() { + logger.debug(LocalDateTime.now()); + + List orderList = orderService.queryUnconfirm(); + for(LitemallOrder order : orderList){ + LocalDateTime ship = order.getShipTime(); + LocalDateTime now = LocalDateTime.now(); + LocalDateTime expired = ship.plusDays(7); + if(expired.isAfter(now)){ + continue; + } + // 设置订单已取消状态 + order.setOrderStatus(OrderUtil.STATUS_AUTO_CONFIRM); + order.setConfirmTime(now); + orderService.updateById(order); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `refundMoney` last assigned on line 100 could be null and is dereferenced at line 110. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object AdminOrderController.refund(Integer,String) + +### Procedure Id: +org.linlinjava.litemall.admin.web.AdminOrderController.refund(java.lang.Integer,java.lang.String):ja.4fa8003333199f765cdff6c2af50d995 + +### File: +litemall-admin-api/src/main/java/org/linlinjava/litemall/admin/web/AdminOrderController.java + +### Key: +AdminOrderController.java|refund|NULL_DEREFERENCE + +### Node Key: +4ca352405b7b88367bd1ea08956d3411 + +### Hash: +2b5eaab9601c6ac53be576bd74d37482 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8764/instruction.md b/inferredbugs-8764/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0273a19e598ac71324355514eaad58efc312f716 --- /dev/null +++ b/inferredbugs-8764/instruction.md @@ -0,0 +1,171 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** blockchain-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package one.wangwei.blockchain.util; + +import one.wangwei.blockchain.block.Block; +import org.rocksdb.Options; +import org.rocksdb.RocksDB; +import org.rocksdb.RocksDBException; + +/** + * RocksDB 工具类 + * + * @author wangwei + * @date 2018/02/27 + */ +public class RocksDBUtils { + + /** + * 区块链数据文件 + */ + private static final String DB_FILE = "blockchain.db"; + /** + * 区块桶前缀 + */ + private static final String BLOCKS_BUCKET_PREFIX = "blocks_"; + + private volatile static RocksDBUtils instance; + + public static RocksDBUtils getInstance() { + if (instance == null) { + synchronized (RocksDBUtils.class) { + if (instance == null) { + instance = new RocksDBUtils(); + } + } + } + return instance; + } + + private static RocksDB rocksDB; + + private RocksDBUtils() { + initRocksDB(); + } + + /** + * 初始化RocksDB + */ + private void initRocksDB() { + try { + rocksDB = RocksDB.open(new Options().setCreateIfMissing(true), DB_FILE); + } catch (RocksDBException e) { + e.printStackTrace(); + } + } + + /** + * 保存最新一个区块的Hash值 + * + * @param tipBlockHash + */ + public void putLastBlockHash(String tipBlockHash) throws Exception { + rocksDB.put((BLOCKS_BUCKET_PREFIX + "l").getBytes(), tipBlockHash.getBytes()); + } + + /** + * 查询最新一个区块的Hash值 + * + * @return + */ + public String getLastBlockHash() throws Exception { + byte[] lastBlockHashBytes = rocksDB.get((BLOCKS_BUCKET_PREFIX + "l").getBytes()); + if (lastBlockHashBytes != null) { + return new String(lastBlockHashBytes); + } + return ""; + } + + /** + * 保存区块 + * + * @param block + */ + public void putBlock(Block block) throws Exception { + rocksDB.put((BLOCKS_BUCKET_PREFIX + block.getHash()).getBytes(), SerializeUtils.serialize(block)); + } + + /** + * 查询区块 + * + * @param blockHash + * @return + */ + public Block getBlock(String blockHash) throws Exception { + return (Block) SerializeUtils.deserialize(rocksDB.get((BLOCKS_BUCKET_PREFIX + blockHash).getBytes())); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `one.wangwei.blockchain.util.RocksDBUtils.putBlock` reads without synchronization from `util.RocksDBUtils.one.wangwei.blockchain.util.RocksDBUtils.rocksDB`. Potentially races with write in method `RocksDBUtils.getInstance()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RocksDBUtils.putBlock(Block) + +### Procedure Id: +one.wangwei.blockchain.util.RocksDBUtils.putBlock(one.wangwei.blockchain.block.Block):void.6f8b8244948e53ac7f3427bff4961d12 + +### File: +src/main/java/one/wangwei/blockchain/util/RocksDBUtils.java + +### Key: +RocksDBUtils.java|putBlock|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +7a1810bd2a99861b437a3712759b2312 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8797/instruction.md b/inferredbugs-8797/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c30ab2d8b5475d26676325856fb181acfab0ae3 --- /dev/null +++ b/inferredbugs-8797/instruction.md @@ -0,0 +1,261 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** failsafe +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package net.jodah.recurrent; + +import static net.jodah.recurrent.Asserts.assertThrows; +import static net.jodah.recurrent.Asserts.getThrowable; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertTrue; + +import java.net.SocketException; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +@Test +public class RecurrentTest { + private ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); + private RetryPolicy retryTwice = new RetryPolicy().withMaxRetries(2); + private Service service = mock(Service.class); + + public interface Service { + boolean connect(); + } + + @BeforeMethod + protected void beforeMethod() { + reset(service); + } + + @SuppressWarnings("unchecked") + private Class[] failures(int numFailures, Class failureType) { + Class[] failures = new Class[numFailures]; + for (int i = 0; i < numFailures; i++) + failures[i] = failureType; + return failures; + } + + private void assertRunWithExecutor(Object runnable) throws Throwable { + // Fail twice then succeed + when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); + if (runnable instanceof Runnable) + Recurrent.run((Runnable) runnable, new RetryPolicy(), executor).get(); + else + Recurrent.run((ContextualRunnable) runnable, new RetryPolicy(), executor).get(); + verify(service, times(3)).connect(); + + // Fail three times + reset(service); + when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); + if (runnable instanceof Runnable) + assertThrows(SocketException.class, () -> Recurrent.run((Runnable) runnable, retryTwice, executor).get()); + else + assertThrows(SocketException.class, + () -> Recurrent.run((ContextualRunnable) runnable, retryTwice, executor).get()); + verify(service, times(3)).connect(); + } + + public void shouldRun() throws Throwable { + Runnable runnable = () -> service.connect(); + + // Fail twice then succeed + when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); + Recurrent.run(runnable, new RetryPolicy()); + verify(service, times(3)).connect(); + + // Fail three times + reset(service); + when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); + assertThrows(SocketException.class, () -> Recurrent.run(runnable, retryTwice)); + verify(service, times(3)).connect(); + } + + public void shouldRunWithExecutor() throws Throwable { + assertRunWithExecutor((Runnable) () -> service.connect()); + } + + public void shouldRunContextualWithExecutor() throws Throwable { + assertRunWithExecutor((ContextualRunnable) (ctx) -> { + try { + service.connect(); + } catch (Exception failure) { + if (ctx.getRetryCount() % 2 == 0) + throw failure; + if (!ctx.retry(failure)) + throw failure; + } + }); + } + + public void shouldGet() throws Throwable { + Callable callable = () -> service.connect(); + + // Fail twice then succeed + when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); + assertEquals(Recurrent.get(callable, new RetryPolicy()), Boolean.TRUE); + verify(service, times(3)).connect(); + + // Fail three times + reset(service); + when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); + assertThrows(SocketException.class, () -> Recurrent.get(callable, retryTwice)); + verify(service, times(3)).connect(); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void assertGetWithExecutor(Object callable) throws Throwable { + // Fail twice then succeed + when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); + boolean result = callable instanceof Callable + ? Recurrent.get((Callable) callable, new RetryPolicy(), executor).get() + : Recurrent.get((ContextualCallable) callable, new RetryPolicy(), executor).get(); + assertEquals(result, true); + verify(service, times(3)).connect(); + + // Fail three times + reset(service); + when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); + Throwable failure = callable instanceof Callable + ? getThrowable(() -> Recurrent.get((Callable) callable, retryTwice, executor).get()) + : getThrowable(() -> Recurrent.get((ContextualCallable) callable, retryTwice, executor).get()); + assertTrue(SocketException.class.isAssignableFrom(failure.getClass())); + verify(service, times(3)).connect(); + } + + public void shouldGetWithExecutor() throws Throwable { + assertGetWithExecutor((Callable) () -> service.connect()); + } + + public void shouldGetContextualWithExecutor() throws Throwable { + assertGetWithExecutor((ContextualCallable) (ctx) -> { + try { + return service.connect(); + } catch (Exception failure) { + if (ctx.getRetryCount() % 2 == 0) + throw failure; + if (!ctx.retry(failure)) + throw failure; + return null; + } + }); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void assertGetFuture(Object callable) throws Throwable { + // Fail twice then succeed + when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); + boolean result = (boolean) (callable instanceof Callable + ? Recurrent.future((Callable) callable, new RetryPolicy(), executor).get() + : Recurrent.future((ContextualCallable) callable, new RetryPolicy(), executor).get()); + assertEquals(result, true); + verify(service, times(3)).connect(); + + // Fail three times + reset(service); + when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); + Throwable failure = callable instanceof Callable + ? getThrowable(() -> Recurrent.future((Callable) callable, retryTwice, executor).get()) + : getThrowable(() -> Recurrent.future((ContextualCallable) callable, retryTwice, executor).get()); + assertTrue(SocketException.class.isAssignableFrom(failure.getClass())); + verify(service, times(3)).connect(); + } + + public void testFuture() throws Throwable { + assertGetFuture((Callable) () -> CompletableFuture.supplyAsync(() -> service.connect())); + } + + public void testFutureContextual() throws Throwable { + assertGetFuture((ContextualCallable) (ctx) -> CompletableFuture.supplyAsync(() -> { + try { + return service.connect(); + } catch (Exception failure) { + if (ctx.getRetryCount() % 2 == 0) + throw failure; + if (!ctx.retry(failure)) + throw failure; + return null; + } + })); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `failure` last assigned on line 165 could be null and is dereferenced at line 166. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RecurrentTest.assertGetFuture(Object) + +### Procedure Id: +net.jodah.recurrent.RecurrentTest.assertGetFuture(java.lang.Object):void.85987327e104a449ad897a280497bfdc + +### File: +src/test/java/net/jodah/recurrent/RecurrentTest.java + +### Key: +RecurrentTest.java|assertGetFuture|NULL_DEREFERENCE + +### Node Key: +674867e9afbd12d31e7532be4794afdf + +### Hash: +059e0cadeb81d318d9f34c216c26871a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8799/instruction.md b/inferredbugs-8799/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e0c32176275a2ed229e2dc6e5672684f54b283b4 --- /dev/null +++ b/inferredbugs-8799/instruction.md @@ -0,0 +1,297 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** failsafe +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package net.jodah.recurrent; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.*; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; + +import java.net.ConnectException; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import net.jodah.recurrent.util.concurrent.Scheduler; + +@Test +public class AsyncExecutionTest { + ConnectException e = new ConnectException(); + AsyncExecution inv; + RecurrentFuture future; + AsyncContextualCallable callable; + Scheduler scheduler; + + @BeforeMethod + @SuppressWarnings("unchecked") + void beforeMethod() { + scheduler = mock(Scheduler.class); + future = mock(RecurrentFuture.class); + callable = mock(AsyncContextualCallable.class); + } + + public void testComplete() { + // Given + inv = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); + + // When + inv.complete(); + + // Then + assertEquals(inv.getExecutions(), 1); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertNull(inv.getLastFailure()); + verify(future).complete(null, null, true); + } + + public void testCompleteForResult() { + // Given + inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); + + // When / Then + assertFalse(inv.complete(null)); + assertTrue(inv.complete(true)); + + // Then + assertEquals(inv.getExecutions(), 1); + assertTrue(inv.isComplete()); + assertEquals(inv.getLastResult(), Boolean.TRUE); + assertNull(inv.getLastFailure()); + verify(future).complete(true, null, true); + } + + public void testGetAttemptCount() { + inv = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); + inv.retryOn(e); + inv.prepare(); + inv.retryOn(e); + assertEquals(inv.getExecutions(), 2); + } + + public void testRetryForResult() { + // Given retry for null + inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); + + // When / Then + assertFalse(inv.complete(null)); + assertTrue(inv.retryFor(null)); + inv.prepare(); + assertFalse(inv.retryFor(1)); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertEquals(inv.getLastResult(), Integer.valueOf(1)); + assertNull(inv.getLastFailure()); + verifyScheduler(1); + verify(future).complete(1, null, true); + + // Given 2 max retries + inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); + + // When / Then + resetMocks(); + assertFalse(inv.complete(null)); + inv.prepare(); + assertTrue(inv.retryFor(null)); + inv.prepare(); + assertFalse(inv.retryFor(null)); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertNull(inv.getLastFailure()); + verifyScheduler(1); + verify(future).complete(null, null, false); + } + + public void testRetryForResultAndThrowable() { + // Given retry for null + inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); + + // When / Then + assertFalse(inv.complete(null)); + assertTrue(inv.retryFor(null, null)); + inv.prepare(); + assertTrue(inv.retryFor(1, new IllegalArgumentException())); + inv.prepare(); + assertFalse(inv.retryFor(1, null)); + + // Then + assertEquals(inv.getExecutions(), 3); + assertTrue(inv.isComplete()); + assertEquals(inv.getLastResult(), Integer.valueOf(1)); + assertNull(inv.getLastFailure()); + verifyScheduler(2); + verify(future).complete(1, null, true); + + // Given 2 max retries + inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); + + // When / Then + resetMocks(); + assertFalse(inv.complete(null)); + assertTrue(inv.retryFor(null, e)); + inv.prepare(); + assertFalse(inv.retryFor(null, e)); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertEquals(inv.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, false); + } + + @SuppressWarnings("unchecked") + public void testRetryOn() { + // Given retry on IllegalArgumentException + inv = new AsyncExecution(callable, new RetryPolicy().retryOn(IllegalArgumentException.class), scheduler, future, + null); + + // When / Then + assertTrue(inv.retryOn(new IllegalArgumentException())); + inv.prepare(); + assertFalse(inv.retryOn(e)); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertEquals(inv.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, false); + + // Given 2 max retries + inv = new AsyncExecution(callable, new RetryPolicy().withMaxRetries(1), scheduler, future, null); + + // When / Then + resetMocks(); + assertTrue(inv.retryOn(e)); + inv.prepare(); + assertFalse(inv.retryOn(e)); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertEquals(inv.getLastFailure(), e); + verifyScheduler(1); + verify(future).complete(null, e, false); + } + + @Test(expectedExceptions = IllegalStateException.class) + public void shouldThrowOnRetryWhenAlreadyComplete() { + inv = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); + inv.complete(); + inv.retryOn(e); + } + + public void testCompleteOrRetry() { + // Given retry on IllegalArgumentException + inv = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); + + // When / Then + inv.completeOrRetry(null, e); + assertFalse(inv.isComplete()); + inv.completeOrRetry(null, null); + + // Then + assertEquals(inv.getExecutions(), 2); + assertTrue(inv.isComplete()); + assertNull(inv.getLastResult()); + assertNull(inv.getLastFailure()); + verifyScheduler(1); + verify(future).complete(null, null, true); + } + + @SuppressWarnings("unchecked") + private void resetMocks() { + reset(scheduler); + reset(future); + reset(callable); + } + + private void verifyScheduler(int executions) { + verify(scheduler, times(executions)).schedule(any(Callable.class), any(Long.class), any(TimeUnit.class)); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `AsyncExecutionTest.inv.listeners` last assigned on line 76 could be null and is dereferenced by call to `prepare()` at line 81. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AsyncExecutionTest.testRetryForResult() + +### Procedure Id: +net.jodah.recurrent.AsyncExecutionTest.testRetryForResult():void.854b0ab46aa979ed5a36629454fea20c + +### File: +src/test/java/net/jodah/recurrent/AsyncExecutionTest.java + +### Key: +AsyncExecutionTest.java|testRetryForResult|NULL_DEREFERENCE + +### Node Key: +c4736613d68023e91e74719fe7f11fcf + +### Hash: +4c27d487a407109b4975b3b1a6d8dd61 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8819/instruction.md b/inferredbugs-8819/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9d20d1b5e02100059af65fb8c23b877bfc5919d --- /dev/null +++ b/inferredbugs-8819/instruction.md @@ -0,0 +1,333 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fluent-logger-java +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// +// A Structured Logger for Fluent +// +// Copyright (C) 2011 - 2012 Muga Nishizawa +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +package org.fluentd.logger.sender; + +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.util.LinkedList; +import java.util.Map; +import java.util.logging.Level; + +import org.msgpack.MessagePack; + +public class RawSocketSender implements Sender { + private static final java.util.logging.Logger LOG = + java.util.logging.Logger.getLogger(RawSocketSender.class.getName()); + + /** + * Calcurate exponential delay for reconnecting + */ + private static class ExponentialDelayReconnector { + private double wait = 0.5; + + private double waitIncrRate = 1.5; + + private double waitMax = 60; + + private int waitMaxCount; + + private LinkedList errorHistory; + + public ExponentialDelayReconnector() { + waitMaxCount = getWaitMaxCount(); + errorHistory = new LinkedList(); + } + + private int getWaitMaxCount() { + double r = waitMax / wait; + for (int j = 1; j <= 100; j++) { + if (r < waitIncrRate) { + return j + 1; + } + r = r / waitIncrRate; + } + return 100; + } + + public void addErrorHistory(long timestamp) { + errorHistory.addLast(timestamp); + if (errorHistory.size() > waitMaxCount) { + errorHistory.removeFirst(); + } + } + + public void clearErrorHistory() { + errorHistory.clear(); + } + + public boolean enableReconnection(long timestamp) { + int size = errorHistory.size(); + if (size == 0) { + return true; + } + + double suppressSec; + if (size < waitMaxCount) { + suppressSec = wait * Math.pow(waitIncrRate, size - 1); + } else { + suppressSec = waitMax; + } + + return (!(timestamp - errorHistory.getLast() < suppressSec)); + } + } + + private MessagePack msgpack; + + private SocketAddress server; + + private Socket socket; + + private String name; + + private int timeout; + + private BufferedOutputStream out; + + private ByteBuffer pendings; + + private ExponentialDelayReconnector reconnector; + + public RawSocketSender() { + this("localhost", 24224); + } + + public RawSocketSender(String host, int port) { + this(host, port, 3 * 1000, 8 * 1024 * 1024); + } + + public RawSocketSender(String host, int port, int timeout, int bufferCapacity) { + msgpack = new MessagePack(); + msgpack.register(Event.class, EventTemplate.INSTANCE); + pendings = ByteBuffer.allocate(bufferCapacity); + server = new InetSocketAddress(host, port); + name = String.format("%s{host=%s,port=%d,timeout=%d,bufCap=%d}", + new Object[] { this.getClass().getName(), host, port, timeout, + bufferCapacity }); + reconnector = new ExponentialDelayReconnector(); + open(); + } + + private void open() { + try { + connect(); + } catch (IOException e) { + LOG.severe("Failed to connect fluentd: " + server.toString()); + LOG.severe("Connection will be retried"); + e.printStackTrace(); + close(); + } + } + + private void connect() throws IOException { + try { + socket = new Socket(); + socket.connect(server); + // the timeout value to be used in milliseconds + socket.setSoTimeout(timeout); + out = new BufferedOutputStream(socket.getOutputStream()); + reconnector.clearErrorHistory(); + } catch (IOException e) { + reconnector.addErrorHistory(System.currentTimeMillis()); + throw e; + } + } + + private void reconnect() throws IOException { + if (socket == null) { + connect(); + } else if (socket.isClosed() || (!socket.isConnected())) { + close(); + connect(); + } + } + + public void close() { + // close output stream + if (out != null) { + try { + out.close(); + } catch (IOException e) { // ignore + } finally { + out = null; + } + } + + // close socket + if (socket != null) { + try { + socket.close(); + } catch (IOException e) { // ignore + } finally { + socket = null; + } + } + } + + public boolean emit(String tag, Map data) { + return emit(tag, System.currentTimeMillis() / 1000, data); + } + + public boolean emit(String tag, long timestamp, Map data) { + return emit(new Event(tag, timestamp, data)); + } + + protected boolean emit(Event event) { + if (LOG.isLoggable(Level.FINE)) { + LOG.fine(String.format("Created %s", new Object[] { event })); + } + + byte[] bytes = null; + try { + // serialize tag, timestamp and data + bytes = msgpack.write(event); + } catch (IOException e) { + LOG.severe("Cannot serialize event: " + event); + e.printStackTrace(); + return false; + } + + // send serialized data + return send(bytes); + } + + private synchronized boolean send(byte[] bytes) { + // buffering + if (pendings.position() + bytes.length > pendings.capacity()) { + LOG.severe("Cannot send logs to " + server.toString()); + return false; + } + pendings.put(bytes); + + try { + // suppress reconnection burst + if (!reconnector.enableReconnection(System.currentTimeMillis())) { + return true; + } + + // check whether connection is established or not + reconnect(); + + // write data + out.write(getBuffer()); + out.flush(); + + clearBuffer(); + } catch (IOException e) { + // close socket + close(); + } + return true; + } + + public byte[] getBuffer() { + int len = pendings.position(); + pendings.position(0); + byte[] ret = new byte[len]; + pendings.get(ret, 0, len); + return ret; + } + + void clearBuffer() { + pendings.clear(); + } + + @Override + public String toString() { + return name; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStream` acquired by call to `reconnect()` at line 228 is not released after line 237. +**Note**: potential exception at line 231 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean RawSocketSender.send(byte[]) + +### Procedure Id: +org.fluentd.logger.sender.RawSocketSender.send(byte[]):boolean.279d9e40c9e85c6e6a8bb46f9effe9d2 + +### File: +src/main/java/org/fluentd/logger/sender/RawSocketSender.java + +### Key: +RawSocketSender.java|send|RESOURCE_LEAK + +### Node Key: +1359f8e76071fbb66843860f5f06e006 + +### Hash: +379dee21c10f1efae257bd2a5bb7bd47 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8826/instruction.md b/inferredbugs-8826/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7afaf68b11f6000fa7a5d930bee086b989faf49 --- /dev/null +++ b/inferredbugs-8826/instruction.md @@ -0,0 +1,203 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** closure-stylesheets +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2013 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.common.css.compiler.passes; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableListMultimap; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.LinkedListMultimap; +import com.google.common.collect.ListMultimap; +import com.google.common.collect.Maps; +import com.google.common.css.compiler.ast.CssCompilerPass; +import com.google.common.css.compiler.ast.CssDefinitionNode; +import com.google.common.css.compiler.ast.CssMixinDefinitionNode; +import com.google.common.css.compiler.ast.CssProvideNode; +import com.google.common.css.compiler.ast.CssRequireNode; +import com.google.common.css.compiler.ast.DefaultTreeVisitor; +import com.google.common.css.compiler.ast.VisitController; + +import java.util.Map; + +/** + * A compiler pass to help find missing {@code @require} lines for def constant references + * and mixins. + * This pass simply collects namespaces that correpond to constant definitions and mixins. + * Also see the CheckMissingRequire pass that is used in conjunction with this one. + * + */ +public final class CollectProvideNamespaces extends DefaultTreeVisitor implements CssCompilerPass { + private final VisitController visitController; + + // Key: filename; Value: provide namespace + private final Map filenameProvideMap = Maps.newHashMap(); + // Key: filename; Value: require namespace + private final ListMultimap filenameRequireMap = LinkedListMultimap.create(); + + // Multiple namespaces can contain the same defs due to duplicate defs (or mods). + // Key: def name; Value: provide namespace + private final ListMultimap defProvideMap = LinkedListMultimap.create(); + // Key: defmixin name; Value: provide namespace + private final ListMultimap defmixinProvideMap = LinkedListMultimap.create(); + + public Map getFilenameProvideMap() { + return ImmutableMap.copyOf(filenameProvideMap); + } + + public ListMultimap getFilenameRequireMap() { + return ImmutableListMultimap.copyOf(filenameRequireMap); + } + + public ListMultimap getDefProvideMap() { + return ImmutableListMultimap.copyOf(defProvideMap); + } + + public ListMultimap getDefmixinProvideMap() { + return ImmutableListMultimap.copyOf(defmixinProvideMap); + } + + public CollectProvideNamespaces(VisitController visitController) { + this.visitController = visitController; + } + + @Override + public boolean enterProvideNode(CssProvideNode node) { + Preconditions.checkState(node.getSourceCodeLocation() != null); + String filename = node.getSourceCodeLocation().getSourceCode().getFileName(); + filenameProvideMap.put(filename, node.getProvide()); + return true; + } + + @Override + public boolean enterRequireNode(CssRequireNode node) { + Preconditions.checkState(node.getSourceCodeLocation() != null); + String filename = node.getSourceCodeLocation().getSourceCode().getFileName(); + filenameRequireMap.put(filename, node.getRequire()); + return true; + } + + @Override + public boolean enterDefinition(CssDefinitionNode node) { + if (node.getSourceCodeLocation() == null) { + // Cannot enforce provide / require for generated GSS components. + return true; + } + String filename = node.getSourceCodeLocation().getSourceCode().getFileName(); + String provideNamespace = filenameProvideMap.get(filename); + // Remove this after switching to the new syntax. + if (provideNamespace == null) { // ignore old format @provide + return true; + } + defProvideMap.put(node.getName().getValue(), provideNamespace); + return true; + } + + @Override + public boolean enterMixinDefinition(CssMixinDefinitionNode node) { + if (node.getSourceCodeLocation() == null) { + // Cannot enforce provide / require for generated GSS components. + return true; + } + String filename = node.getSourceCodeLocation().getSourceCode().getFileName(); + String provideNamespace = filenameProvideMap.get(filename); + // Remove this after switching to the new syntax. + if (provideNamespace == null) { // ignore old format @provide + return true; + } + Preconditions.checkArgument(provideNamespace != null); + defmixinProvideMap.put(node.getDefinitionName(), provideNamespace); + return true; + } + + @Override + public void runPass() { + visitController.startVisit(this); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +CHECKERS_IMMUTABLE_CAST + +### Qualifier: +Method getFilenameProvideMap() returns class com.google.common.collect.ImmutableMap but the return type is class java.util.Map. Make sure that users of this method do not try to modify the collection. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map CollectProvideNamespaces.getFilenameProvideMap() + +### Procedure Id: +com.google.common.css.compiler.passes.CollectProvideNamespaces.getFilenameProvideMap():java.util.Map.79ca9581aa91a009c4405b4f87f1d21c + +### File: +src/com/google/common/css/compiler/passes/CollectProvideNamespaces.java + +### Key: +CollectProvideNamespaces.java|getFilenameProvideMap|CHECKERS_IMMUTABLE_CAST + +### Node Key: +a6910ae797b71d863caed85a9357701b + +### Hash: +5bb59bebf1436772f137ddac44a4d189 + +### Bug Type Hum: +Checkers Immutable Cast + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8900/instruction.md b/inferredbugs-8900/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..be343b638ef6f5c64d7b809ea5151598f100245e --- /dev/null +++ b/inferredbugs-8900/instruction.md @@ -0,0 +1,286 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jkcp +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * 维护kcp状态的线程 + */ +package org.beykery.jkcp; + +import io.netty.channel.socket.DatagramPacket; +import java.net.InetSocketAddress; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author beykery + */ +public class KcpThread extends Thread +{ + + private final Output out; + private final LinkedBlockingQueue inputs; + private boolean running; + private final Map kcps; + private final KcpListerner listerner; + private int nodelay; + private int interval = Kcp.IKCP_INTERVAL; + private int resend; + private int nc; + private int sndwnd = Kcp.IKCP_WND_SND; + private int rcvwnd = Kcp.IKCP_WND_RCV; + private int mtu = Kcp.IKCP_MTU_DEF; + private long timeout;//idle + + + private Object wakeup = new Object(); + public void threadNotify() { + synchronized(wakeup) { + this.wakeup.notify(); + } + } + private Queue pqueue; + private Comparator cmp = new Comparator() { + @Override + public int compare(KcpOnUdp e1, KcpOnUdp e2) { + return (int) (e2.getTimeout() - e1.getTimeout()); + } + }; + /** + * fastest: ikcp_nodelay(kcp, 1, 20, 2, 1) nodelay: 0:disable(default), + * 1:enable interval: internal update timer interval in millisec, default is + * 100ms resend: 0:disable fast resend(default), 1:enable fast resend nc: + * 0:normal congestion control(default), 1:disable congestion control + * + * @param nodelay + * @param interval + * @param resend + * @param nc + */ + public void noDelay(int nodelay, int interval, int resend, int nc) + { + this.nodelay = nodelay; + this.interval = interval; + this.resend = resend; + this.nc = nc; + } + + /** + * set maximum window size: sndwnd=32, rcvwnd=32 by default + * + * @param sndwnd + * @param rcvwnd + */ + public void wndSize(int sndwnd, int rcvwnd) + { + this.sndwnd = sndwnd; + this.rcvwnd = rcvwnd; + } + + /** + * change MTU size, default is 1400 + * + * @param mtu + */ + public void setMtu(int mtu) + { + this.mtu = mtu; + } + + /** + * kcp工作线程 + * + * @param out + * @param listerner + */ + public KcpThread(Output out, KcpListerner listerner) + { + this.out = out; + this.listerner = listerner; + inputs = new LinkedBlockingQueue<>(); + kcps = new HashMap<>(); + pqueue = new PriorityQueue<>(10, cmp); + } + + /** + * 开启线程 + */ + @Override + public synchronized void start() + { + if (!this.running) + { + this.running = true; + super.start(); + } + } + + /** + * 关闭线程 + */ + public void close() + { + this.running = false; + } + + @Override + public void run() + { + while (this.running) + { + //input + while (!this.inputs.isEmpty()) + { + DatagramPacket dp = this.inputs.remove(); + KcpOnUdp ku = this.kcps.get(dp.sender()); + if (ku == null) + { + ku = new KcpOnUdp(this.out, dp.sender(), this.listerner);//初始化 + ku.noDelay(nodelay, interval, resend, nc); + ku.wndSize(sndwnd, rcvwnd); + ku.setMtu(mtu); + ku.setTimeout(timeout); + this.kcps.put(dp.sender(), ku); + pqueue.add(ku); + } + ku.input(dp.content()); + } + + //选出第一个kcp更新状态 + KcpOnUdp first = pqueue.poll(); + if(first != null && first.getTimeout() < System.currentTimeMillis()) { + first.update(); + if(!first.isClosed()) { + pqueue.add(first); + } else { + this.kcps.remove((InetSocketAddress) first.getKcp().getUser()); + } + } + + //每30s,更新一遍所有的kcp状态 + if(System.currentTimeMillis()%(1000*30) == 0) { + //update + KcpOnUdp temp = null; + for (KcpOnUdp ku : this.kcps.values()) + { + ku.update(); + if (ku.isClosed()) {//删掉过时的kcp + this.kcps.remove((InetSocketAddress) temp.getKcp().getUser()); + pqueue.remove(ku); + } + } + } + + //等待 + try { + synchronized(wakeup){ + wakeup.wait(5*60*1000); + } + } catch (InterruptedException ex) { + Logger.getLogger(KcpThread.class.getName()).log(Level.SEVERE, null, ex); + } + + } + } + + /** + * 收到输入 + * + * @param addr + * @param content + */ + void input(DatagramPacket dp) + { + this.inputs.add(dp); + this.threadNotify(); + } + + public void setTimeout(long timeout) + { + this.timeout = timeout; + } + + public long getTimeout() + { + return timeout; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.beykery.jkcp.KcpThread.run` reads without synchronization from `this.org.beykery.jkcp.KcpThread.interval`. Potentially races with write in method `KcpThread.noDelay(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void KcpThread.run() + +### Procedure Id: +org.beykery.jkcp.KcpThread.run():void.bed5863ed90560ead425a16199a3e750 + +### File: +src/main/java/org/beykery/jkcp/KcpThread.java + +### Key: +KcpThread.java|run|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +aa76283207b735de5b9b5e993949a387 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8907/instruction.md b/inferredbugs-8907/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ad068b094476e74bd2fb3c1b7e4d3269c7e7eea --- /dev/null +++ b/inferredbugs-8907/instruction.md @@ -0,0 +1,135 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** word +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * + * APDPlat - Application Product Development Platform + * Copyright (c) 2013, 杨尚川, yang-shangchuan@qq.com + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package org.apdplat.word.util; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +/** + * + * @author 杨尚川 + */ +public class GenericTrieTest { + private final GenericTrie trie = new GenericTrie<>(); + @Before + public void setUp() { + trie.put("杨尚川", 100); + trie.put("杨尚喜", 99); + trie.put("杨尚丽", 98); + trie.put("中华人民共和国", 1); + } + @After + public void tearDown() { + trie.clear(); + } + @Test + public void testClear() { + Assert.assertEquals(100, trie.get("杨尚川"), 0); + Assert.assertEquals(1, trie.get("中华人民共和国"), 0); + trie.clear(); + Assert.assertEquals(null, trie.get("杨尚川")); + Assert.assertEquals(null, trie.get("中华人民共和国")); + } + @Test + public void testGet() { + Assert.assertEquals(100, trie.get("杨尚川"), 0); + Assert.assertEquals(99, trie.get("杨尚喜"), 0); + Assert.assertEquals(98, trie.get("杨尚丽"), 0); + Assert.assertEquals(1, trie.get("中华人民共和国"), 0); + Assert.assertEquals(null, trie.get("杨")); + Assert.assertEquals(null, trie.get("杨尚")); + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `GenericTrieTest.trie.get("\\230\\157\\168\\229\\176\\154\\229\\183\\157")` could be null and is dereferenced at line 55. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericTrieTest.testGet() + +### Procedure Id: +org.apdplat.word.util.GenericTrieTest.testGet():void.16d91a2f852d30acf036645ee7a06b43 + +### File: +src/test/java/org/apdplat/word/util/GenericTrieTest.java + +### Key: +GenericTrieTest.java|testGet|NULL_DEREFERENCE + +### Node Key: +3392ddd9e7af3710d0647e5067e4a3e1 + +### Hash: +6a90b22580a2fedcd8496647ad03224b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8909/instruction.md b/inferredbugs-8909/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8480773cbbbcbfc00cf4b71983be8fcda9cce394 --- /dev/null +++ b/inferredbugs-8909/instruction.md @@ -0,0 +1,113 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** GlobalWarming +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package net.porillo.effect.negative.formation; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; +import net.porillo.effect.api.ListenerClimateEffect; +import net.porillo.engine.ClimateEngine; +import net.porillo.util.MapUtil; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.block.BlockFormEvent; + +import java.util.TreeMap; + +public class SnowForm extends ListenerClimateEffect { + + private TreeMap heightMap; + + @EventHandler + public void blockFormEvent(BlockFormEvent event) { + if (event.getBlock().getType() == Material.ICE) { + double temp = ClimateEngine.getInstance().getClimateEngine(event.getBlock().getWorld().getName()).getTemperature(); + + if (event.getBlock().getY() < MapUtil.searchTreeMap(heightMap, temp)) { + event.setCancelled(true); + } + } + } + + @Override + public void setJsonModel(JsonObject jsonModel) { + super.setJsonModel(jsonModel); + this.heightMap = new Gson().fromJson(jsonModel, new TypeToken>(){}.getType()); + if (this.heightMap == null) { + unregister(); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `searchTreeMap(SnowForm.heightMap,valueOf(temp))` could be null and is dereferenced at line 24. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SnowForm.blockFormEvent(BlockFormEvent) + +### Procedure Id: +net.porillo.effect.negative.formation.SnowForm.blockFormEvent(org.bukkit.event.block.BlockFormEvent).1d2d6dcb62dac8af0d9c7c46d9f7dc78 + +### File: +src/main/java/net/porillo/effect/negative/formation/SnowForm.java + +### Key: +SnowForm.java|blockFormEvent|NULL_DEREFERENCE + +### Node Key: +4e1c2c26c3ac0b39dda101e4d445ea98 + +### Hash: +99fe8b8ac50bb392f35f9c2c5ef9ba81 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8931/instruction.md b/inferredbugs-8931/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e22ca3f9ed3457ad6bbb675298bd2612d17cacb --- /dev/null +++ b/inferredbugs-8931/instruction.md @@ -0,0 +1,147 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +package mediathek.tool; + +import java.io.File; +import java.security.CodeSource; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.ResourceBundle; +import mediathek.Main; + +public class Funktionen { + + public static String getPathJar() { + String pFilePath = "pFile"; + File propFile = new File(pFilePath); + if (!propFile.exists()) { + try { + CodeSource cS = Main.class.getProtectionDomain().getCodeSource(); + File jarFile = new File(cS.getLocation().toURI().getPath()); + String jarDir = jarFile.getParentFile().getPath(); + propFile = new File(jarDir + File.separator + pFilePath); + } catch (Exception ex) { + } + } + return propFile.getAbsolutePath().replace(pFilePath, ""); + } + + public static String getCompileDate() { + String ret = ""; + try { + Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified()); + ret = Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION + " [Buildnummer: " + getBuildNr() + "] - Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d); + } catch (Exception ex) { + Log.fehlerMeldung(569614756, "Log.getCompileDate: ", ex); + } + return ret; + } + + public static String getBuildNr() { + final ResourceBundle rb; + String propToken = "BUILD"; + String msg = ""; + try { + ResourceBundle.clearCache(); + rb = ResourceBundle.getBundle("version"); + msg = rb.getString(propToken); + } catch (Exception e) { + System.err.println(e.getMessage()); + System.err.println("Token " + propToken + " not in Propertyfile!"); + } + return msg; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `javax.net.ssl.HttpsURLConnection` acquired by call to `openConnection()` at line 50 is not released after line 50. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String Funktionen.getCompileDate() + +### Procedure Id: +mediathek.tool.Funktionen.getCompileDate():java.lang.String.90d55639c9f63fe0c20e6328262be471 + +### File: +src/mediathek/tool/Funktionen.java + +### Key: +Funktionen.java|getCompileDate|RESOURCE_LEAK + +### Node Key: +4ca352405b7b88367bd1ea08956d3411 + +### Hash: +de2c48ae06a56194cf3733dfb6a74135 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8936/instruction.md b/inferredbugs-8936/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eba1e47a70230757fb103b4a4afb7607dbbe3ec5 --- /dev/null +++ b/inferredbugs-8936/instruction.md @@ -0,0 +1,233 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek; + +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.Date; +import javax.swing.event.EventListenerList; +import mediathek.controller.filme.filmeImportieren.MediathekListener; +import mediathek.tool.GuiFunktionenProgramme; + +public class Log { + + public static boolean playerMeldungenAus = false; + public static final String LOG_FEHLER = "fehler"; + public static final String LOG_SYSTEM = "system"; + public static final String LOG_PLAYER = "player"; + private static EventListenerList listeners = new EventListenerList(); + private static boolean prog = false; + + public static void addAdListener(MediathekListener listener) { + listeners.add(MediathekListener.class, listener); + } + + public static synchronized void startMeldungen(String classname) { + Log.systemMeldung("###########################################################"); + try { + //Version + Log.systemMeldung(Konstanten.PROGRAMMNAME + " " + Konstanten.VERSION); + Date d = new Date(Main.class.getResource("Main.class").openConnection().getLastModified()); + Log.systemMeldung("Compiled: " + new SimpleDateFormat("dd.MM.yyyy, HH:mm").format(d)); + } catch (IOException ex) { + } + Log.systemMeldung("Klassenname: " + classname); + Log.systemMeldung(""); + Log.systemMeldung("Programmpfad: " + GuiFunktionenProgramme.getPathJar()); + Log.systemMeldung("Verzeichnis Einstellungen: " + Daten.getBasisVerzeichnis()); + Log.systemMeldung("Useragent: " + Daten.getUserAgent()); + Log.systemMeldung(""); + long totalMem = Runtime.getRuntime().totalMemory(); + Log.systemMeldung("totalMemory: " + totalMem / (1024L * 1024L) + " MB"); + long maxMem = Runtime.getRuntime().maxMemory(); + Log.systemMeldung("maxMemory: " + maxMem / (1024L * 1024L) + " MB"); + long freeMem = Runtime.getRuntime().freeMemory(); + Log.systemMeldung("freeMemory: " + freeMem / (1024L * 1024L) + " MB"); + Log.systemMeldung("###########################################################"); + } + + public static synchronized void fehlerMeldung(String klasse, Exception ex) { + fehlermeldung(klasse, new String[]{ex.getMessage(), ""}); + } + + public static synchronized void fehlerMeldung(String klasse, Exception ex, String text) { + String[] str = new String[2]; + str[0] = ex.getLocalizedMessage(); + str[1] = text; + fehlermeldung(klasse, str); + } + + public static synchronized void fehlerMeldung(String klasse, String text) { + fehlermeldung(klasse, new String[]{text}); + } + + public static synchronized void fehlerMeldung(String klasse, String[] text) { + fehlermeldung(klasse, text); + } + + public static synchronized void systemMeldung(String[] text) { + meldung(text); + } + + public static synchronized void systemMeldung(String text) { + meldung(new String[]{text}); + } + + public static synchronized void playerMeldung(String text) { + if (!playerMeldungenAus) { + playermeldung(new String[]{text}); + } + } + + public static synchronized void progress(String texte) { + prog = true; + texte += "\r"; + System.out.print(texte); + } + + private static void fehlermeldung(String klasse, String[] texte) { + if (prog) { + // dann brauchen wir erst eine Leerzeite um die Progresszeile zu löschen + System.out.print(" \r"); + prog = false; + } + final String FEHLER = "Fehler: "; + final String z = "*"; + System.out.println(z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z); + System.out.println(z + " " + FEHLER + klasse); + notifyMediathekListener(LOG_FEHLER, FEHLER + klasse); + for (int i = 0; i < texte.length; ++i) { + System.out.println(z + " " + texte[i]); + notifyMediathekListener(LOG_FEHLER, texte[i]); + } + System.out.println(z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z + z); + } + + private static void meldung(String[] texte) { + if (prog) { + // dann brauchen wir erst eine Leerzeite um die Progresszeile zu löschen + System.out.print(" \r"); + prog = false; + } + final String SYSTEMMELDUNG = ""; + final String z = "."; + System.out.println(z + " " + SYSTEMMELDUNG + texte[0]); + notifyMediathekListener(LOG_SYSTEM, texte[0]); + for (int i = 1; i < texte.length; ++i) { + System.out.println(z + " " + texte[i]); + notifyMediathekListener(LOG_SYSTEM, texte[i]); + } + } + + private static void playermeldung(String[] texte) { + if (prog) { + // dann brauchen wir erst eine Leerzeite um die Progresszeile zu löschen + System.out.print(" \r"); + prog = false; + } + final String z = " >>"; + System.out.println(z + " " + texte[0]); + notifyMediathekListener(LOG_PLAYER, texte[0]); + for (int i = 1; i < texte.length; ++i) { + System.out.println(z + " " + texte[i]); + notifyMediathekListener(LOG_PLAYER, texte[i]); + } + } + + private static void notifyMediathekListener(String art, String zeile) { + for (MediathekListener l : listeners.getListeners(MediathekListener.class)) { + l.ping(art, zeile); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.HttpURLConnection` acquired by call to `openConnection()` at line 47 is not released after line 47. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Log.startMeldungen(String) + +### Procedure Id: +mediathek.Log.startMeldungen(java.lang.String):void.3463ae8624fa0e2cf7af9508b197ab1a + +### File: +src/mediathek/Log.java + +### Key: +Log.java|startMeldungen|RESOURCE_LEAK + +### Node Key: +4ca352405b7b88367bd1ea08956d3411 + +### Hash: +680be24aee568285a71e99b84a6c0cf5 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8938/instruction.md b/inferredbugs-8938/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94f15e4d763aa1d2e5bb4dd8fe3ef07b13f26cdd --- /dev/null +++ b/inferredbugs-8938/instruction.md @@ -0,0 +1,777 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.gui; + +import java.awt.Point; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import mediathek.Daten; +import mediathek.MediathekGui; +import mediathek.controller.filme.filmeImportieren.MediathekListener; +import mediathek.controller.io.starter.StartEvent; +import mediathek.controller.io.starter.StartListener; +import mediathek.controller.io.starter.Starts; +import mediathek.daten.DDaten; +import mediathek.daten.DatenDownload; +import mediathek.daten.DatenFilm; +import mediathek.daten.DatenPset; +import mediathek.gui.beobachter.BeobMpanel; +import mediathek.gui.beobachter.CellRendererDownloads; +import mediathek.gui.dialog.DialogDatenFilm; +import mediathek.gui.dialog.DialogEditDownload; +import mediathek.tool.*; + +public class GuiDownloads extends PanelVorlage { + + private DialogDatenFilm dialogDatenFilm = null; + + public GuiDownloads(DDaten d) { + super(d); + initComponents(); + dialogDatenFilm = new DialogDatenFilm(null, false, ddaten); + init(); + load(); + GuiFunktionen.spaltenDownloadSetzen(jTable1); + } + //=================================== + //public + //=================================== + + @Override + public void isShown() { + super.isShown(); + ddaten.mediathekGui.setToolbar(MediathekGui.ButtonDonwload); + ddaten.infoPanel.setIdx(InfoPanel.IDX_GUI_DOWNLOAD); + } + + //toolbar + public void akualisieren() { + Daten.setGeaendert(); + aufraeumen(); + ddaten.listeDownloads.abosLoschen(); + ddaten.listeDownloads.abosEintragen(); + load(); + } + + public void starten() { + downloadAll(""); + } + + public void zurueckstellen() { + downloadLoeschen(false); + } + + public void loeschen() { + downloadLoeschen(true); + } + + public void aufraeumen() { + tabelleAufraeumen(); + } + + public void aendern() { + downloadAendern(); + } + + public void stoppen() { + filmStartenWiederholenStoppen(false /* starten */); + } + + public void alleStoppen() { + stopAll(); + } + + //=================================== + //private + //=================================== + private void init() { + Daten.addAdListener(new MediathekListener(MediathekListener.EREIGNIS_LISTE_DOWNLOADS, GuiDownloads.class.getSimpleName()) { + + @Override + public void ping() { + load(); + } + }); + jRadioButtonAbos.setForeground(GuiKonstanten.ABO_FOREGROUND); + jRadioButtonDownloads.setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); + jTable1.setDefaultRenderer(Object.class, new CellRendererDownloads(ddaten)); + jTable1.setDefaultRenderer(Datum.class, new CellRendererDownloads(ddaten)); + jTable1.setModel(new TModelDownload(new Object[][]{}, DatenDownload.DOWNLOAD_COLUMN_NAMES)); + jTable1.addMouseListener(new BeobMausTabelle()); + jTable1.getSelectionModel().addListSelectionListener(new BeobachterTableSelect1()); + //aendern + ActionMap am = jTable1.getActionMap(); + am.put("aendern", new BeobAbstractAction()); + InputMap im = jTable1.getInputMap(); + KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); + im.put(enter, "aendern"); + // + ddaten.starterClass.addListener(new BeobachterStart()); + jRadioButtonAlles.addActionListener(new BeobAnzeige()); + jRadioButtonAbos.addActionListener(new BeobAnzeige()); + jRadioButtonDownloads.addActionListener(new BeobAnzeige()); + jCheckBoxFilter.addActionListener(new BeobMpanel(jCheckBoxFilter, jPanelFilter, "Filter")); + } + + private void load() { + //Filme laden + boolean abo, download; + getSpalten(jTable1); + TModelDownload tModel = new TModelDownload(new Object[][]{}, DatenDownload.DOWNLOAD_COLUMN_NAMES); + if (jRadioButtonAlles.isSelected()) { + abo = true; + download = true; + } else if (jRadioButtonAbos.isSelected()) { + abo = true; + download = false; + } else { + abo = false; + download = true; + } + ddaten.listeDownloads.getModel(tModel, abo, download); + jTable1.setModel(tModel); + GuiFunktionen.spaltenDownloadSetzen(jTable1); + setSpalten(jTable1); + setInfo(); + } + + private void downloadAendern() { + int rows[] = jTable1.getSelectedRows(); + if (rows.length > 0) { + for (int i = rows.length - 1; i >= 0; --i) { + int delRow = jTable1.convertRowIndexToModel(rows[i]); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + DatenDownload d = download.getCopy(); + DialogEditDownload dialog = new DialogEditDownload(null, true, d); + dialog.setVisible(true); + if (dialog.ok) { + download.aufMichKopieren(d); + DDaten.setGeaendert(); + load(); + } + } + setInfo(); + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void downloadLoeschen(boolean dauerhaft) { + int rows[] = jTable1.getSelectedRows(); + if (rows.length > 0) { + for (int i = rows.length - 1; i >= 0; --i) { + int delRow = jTable1.convertRowIndexToModel(rows[i]); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (dauerhaft) { + if (download.istAbo()) { + // ein Abo wird zusätzlich ins Logfile geschrieben + ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR], + download.arr[DatenDownload.DOWNLOAD_TITEL_NR], + url); + } + ddaten.listeDownloads.delDownloadByUrl(url); + } + ddaten.starterClass.filmLoeschen(jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + ((TModelDownload) jTable1.getModel()).removeRow(delRow); + } + setInfo(); + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void filmStartenWiederholenStoppen(boolean starten /* starten/wiederstarten oder stoppen */) { + // ein Film der noch keinen Starts hat wird gestartet + // ein Film dessen Starts schon auf fertig/fehler steht wird wieder gestartet + int row = jTable1.getSelectedRow(); + if (row >= 0) { + int delRow = jTable1.convertRowIndexToModel(row); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Starts s = ddaten.starterClass.getStart(url); + if (s != null) { + if (starten && s.status > Starts.STATUS_RUN || !starten && s.status <= Starts.STATUS_RUN) { + //daten.starterClass.delStart(url); + ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + } + } + } + if (starten) { + downloadAll(url); + } + setInfo(); + } else { + new HinweisKeineAuswahl().zeigen(); + } + } + + private void stopAll() { + // es werden alle laufenden Downloads gestopt + for (int i = 0; i < jTable1.getRowCount(); ++i) { + int delRow = jTable1.convertRowIndexToModel(i); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Starts s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status <= Starts.STATUS_RUN) { + ddaten.starterClass.filmLoeschen(url); + } + } + setInfo(); + } + } + + private void stopWartende() { + // es werden alle noch nicht gestarteten Downloads gelöscht + for (int i = 0; i < jTable1.getRowCount(); ++i) { + int delRow = jTable1.convertRowIndexToModel(i); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Starts s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status < Starts.STATUS_RUN) { + ddaten.starterClass.filmLoeschen(url); + } + } + setInfo(); + } + } + + private void tabelleAufraeumen() { + for (int i = 0; i < jTable1.getModel().getRowCount(); ++i) { + int delRow = jTable1.convertRowIndexToModel(i); + String url = jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Starts s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status >= Starts.STATUS_FERTIG) { + ddaten.listeDownloads.delDownloadByUrl(url); + ((TModelDownload) jTable1.getModel()).removeRow(i); + --i; + } + } + } + setInfo(); + ddaten.starterClass.aufraeumen(); + } + + private boolean downloadAll(String uurl) { + // liefert false, wenn es nichts zu Laden gibt + boolean ret = false; + String url; + if (jTable1.getModel() != null) { + for (int i = 0; i < jTable1.getModel().getRowCount(); ++i) { + url = (jTable1.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (uurl.equals("") || uurl.equals(url)) { + //Start erstellen und zur Liste hinzufügen + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + ddaten.starterClass.addStarts(new Starts(download)); + ret = true; + } + } + } + setInfo(); + return ret; + } + + private void panelUpdate() { + setInfo(); + jTable1.repaint(); + this.validate(); + } + + private void setInfo() { + String textLinks; + // Text links: Zeilen Tabelle + int laufen = ddaten.starterClass.getDownloadsLaufen(); + int warten = ddaten.starterClass.getDownloadsWarten(); + int gesamt = jTable1.getModel().getRowCount(); + if (gesamt == 1) { + textLinks = "1 Download,"; + } else { + textLinks = gesamt + " Downloads,"; + } + textLinks += " ("; + if (laufen == 1) { + textLinks += "1 läuft,"; + } else { + textLinks += laufen + " laufen,"; + } + if (warten == 1) { + textLinks += " 1 wartet"; + } else { + textLinks += " " + warten + " warten"; + } + textLinks += ")"; + // Infopanel setzen + ddaten.infoPanel.setTextLinks(InfoPanel.IDX_GUI_DOWNLOAD, textLinks); + } + + private void table1Select() { + DatenFilm aktFilm = new DatenFilm(); + int selectedTableRow = jTable1.getSelectedRow(); + if (selectedTableRow >= 0) { + int selectedModelRow = jTable1.convertRowIndexToModel(selectedTableRow); + DatenFilm film = Daten.listeFilme.getFilmByUrl(jTable1.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + aktFilm = film; + } + } + dialogDatenFilm.setAktFilm(aktFilm); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + jScrollPane2 = new javax.swing.JScrollPane(); + jTable1 = new javax.swing.JTable(); + jPanelFilter = new javax.swing.JPanel(); + jCheckBoxFilter = new javax.swing.JCheckBox(); + jPanelFilterInnen = new javax.swing.JPanel(); + jRadioButtonAlles = new javax.swing.JRadioButton(); + jRadioButtonDownloads = new javax.swing.JRadioButton(); + jRadioButtonAbos = new javax.swing.JRadioButton(); + + jTable1.setAutoCreateRowSorter(true); + jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); + jScrollPane2.setViewportView(jTable1); + + jPanelFilter.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); + + jCheckBoxFilter.setBackground(new java.awt.Color(217, 217, 217)); + jCheckBoxFilter.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N + jCheckBoxFilter.setText("Filter"); + + buttonGroup1.add(jRadioButtonAlles); + jRadioButtonAlles.setSelected(true); + jRadioButtonAlles.setText(" alle"); + jRadioButtonAlles.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAlles.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonDownloads); + jRadioButtonDownloads.setText(" Downloads "); + jRadioButtonDownloads.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonDownloads.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonAbos); + jRadioButtonAbos.setText(" Abos "); + jRadioButtonAbos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAbos.setBorderPainted(true); + + javax.swing.GroupLayout jPanelFilterInnenLayout = new javax.swing.GroupLayout(jPanelFilterInnen); + jPanelFilterInnen.setLayout(jPanelFilterInnenLayout); + jPanelFilterInnenLayout.setHorizontalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jRadioButtonAlles) + .addGap(18, 18, 18) + .addComponent(jRadioButtonDownloads) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jRadioButtonAbos) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanelFilterInnenLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jRadioButtonAbos, jRadioButtonAlles, jRadioButtonDownloads}); + + jPanelFilterInnenLayout.setVerticalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jRadioButtonAlles) + .addComponent(jRadioButtonDownloads) + .addComponent(jRadioButtonAbos)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout jPanelFilterLayout = new javax.swing.GroupLayout(jPanelFilter); + jPanelFilter.setLayout(jPanelFilterLayout); + jPanelFilterLayout.setHorizontalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jCheckBoxFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + jPanelFilterLayout.setVerticalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterLayout.createSequentialGroup() + .addComponent(jCheckBoxFilter) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE) + .addComponent(jPanelFilter, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.JCheckBox jCheckBoxFilter; + private javax.swing.JPanel jPanelFilter; + private javax.swing.JPanel jPanelFilterInnen; + private javax.swing.JRadioButton jRadioButtonAbos; + private javax.swing.JRadioButton jRadioButtonAlles; + private javax.swing.JRadioButton jRadioButtonDownloads; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JTable jTable1; + // End of variables declaration//GEN-END:variables + + private class BeobachterStart implements StartListener { + + @Override + public void starter(StartEvent ev) { + panelUpdate(); + } + } + + private class BeobachterTableSelect1 implements ListSelectionListener { + + public int selectedModelRow = -1; + + @Override + public void valueChanged(ListSelectionEvent event) { + if (!event.getValueIsAdjusting()) { + table1Select(); + } + } + } + + public class BeobMausTabelle extends MouseAdapter { + + private Point p; + + public BeobMausTabelle() { + } + + @Override + public void mouseClicked(MouseEvent arg0) { + if (arg0.getButton() == MouseEvent.BUTTON1) { + if (arg0.getClickCount() > 1) { + downloadAendern(); + } + } else if (arg0.getButton() == MouseEvent.BUTTON3) { + showMenu(arg0); + } + } + + private void showMenu(MouseEvent evt) { + p = evt.getPoint(); + int nr = jTable1.rowAtPoint(p); + if (nr >= 0) { + jTable1.setRowSelectionInterval(nr, nr); + } + JPopupMenu menu = new JPopupMenu(); + //Film vorziehen + int row = jTable1.getSelectedRow(); + boolean wartenOderLaufen = false; + if (row >= 0) { + int delRow = jTable1.convertRowIndexToModel(row); + Starts s = ddaten.starterClass.getStart(jTable1.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (s != null) { + if (s.status <= Starts.STATUS_RUN) { + wartenOderLaufen = true; + } + } + } + JMenuItem itemStarten = new JMenuItem("Download starten"); + itemStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_play_16.png"))); + itemStarten.setEnabled(!wartenOderLaufen); + menu.add(itemStarten); + itemStarten.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* starten */); + } + }); + JMenuItem itemStoppen = new JMenuItem("Download stoppen"); + itemStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + itemStoppen.setEnabled(wartenOderLaufen); + menu.add(itemStoppen); + itemStoppen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* starten */); + } + }); + //####################################### + menu.addSeparator(); + //####################################### + JMenuItem itemLoeschen = new JMenuItem("Download zurückstellen"); + itemLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/undo_16.png"))); + menu.add(itemLoeschen); + itemLoeschen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(false /* dauerhaft */); + } + }); + //dauerhaft löschen + JMenuItem itemDauerhaftLoeschen = new JMenuItem("Download dauerhaft löschen"); + itemDauerhaftLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/del_16.png"))); + menu.add(itemDauerhaftLoeschen); + itemDauerhaftLoeschen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(true /* dauerhaft */); + } + }); + //ändern + JMenuItem itemAendern = new JMenuItem("Download Ändern"); + itemAendern.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/configure_16.png"))); + menu.add(itemAendern); + itemAendern.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + downloadAendern(); + } + }); + //####################################### + menu.addSeparator(); + //####################################### + JMenuItem itemAlleStarten = new JMenuItem("alle Downloads starten"); + itemAlleStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/next_16.png"))); + menu.add(itemAlleStarten); + itemAlleStarten.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + downloadAll(""); + } + }); + JMenuItem itemAlleStoppen = new JMenuItem("alle Downloads stoppen"); + itemAlleStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + menu.add(itemAlleStoppen); + itemAlleStoppen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + stopAll(); + } + }); + JMenuItem itemWartendeStoppen = new JMenuItem("wartende Downloads stoppen"); + itemWartendeStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + menu.add(itemWartendeStoppen); + itemWartendeStoppen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + stopWartende(); + } + }); + JMenuItem itemAktualisieren = new JMenuItem("Liste der Downloads aktualisieren"); + itemAktualisieren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/view-refresh_16.png"))); + menu.add(itemAktualisieren); + itemAktualisieren.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + akualisieren(); + } + }); + JMenuItem itemAufraeumen = new JMenuItem("Liste Aufräumen"); + itemAufraeumen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/edit-clear_16.png"))); + menu.add(itemAufraeumen); + itemAufraeumen.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent arg0) { + aufraeumen(); + } + }); + //####################################### + menu.addSeparator(); + //####################################### + //url + JMenuItem itemUrl = new JMenuItem("URL kopieren"); + itemUrl.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + int nr = jTable1.rowAtPoint(p); + if (nr >= 0) { + GuiFunktionen.copyToClipboard( + jTable1.getModel().getValueAt(jTable1.convertRowIndexToModel(nr), + DatenDownload.DOWNLOAD_URL_NR).toString()); + } + } + }); + menu.add(itemUrl); + //Infos + JMenuItem itemInfo = new JMenuItem("Infos anzeigen"); + itemInfo.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + dialogDatenFilm.setVis(); + } + }); + menu.add(itemInfo); + //Player + JMenuItem itemPlayer = new JMenuItem("Film abspielen"); + itemPlayer.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + int nr = jTable1.rowAtPoint(p); + if (nr >= 0) { + DatenPset gruppe = ddaten.listePset.getPsetAbspielen(); + if (gruppe != null) { + int selectedModelRow = jTable1.convertRowIndexToModel(nr); + DatenFilm film = Daten.listeFilme.getFilmByUrl(jTable1.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + // in die History eintragen + ddaten.history.add(film.getUrlOrg()); + // und starten + ddaten.starterClass.urlStarten(gruppe, film); + } + } else { + JOptionPane.showMessageDialog(null, "Im Menü unter \"Datei->Optionen->Videoplayer\" ein Programm zum Abspielen festlegen.", + "kein Videoplayer!", JOptionPane.INFORMATION_MESSAGE); + } + } + } + }); + menu.add(itemPlayer); + //Menü anzeigen + menu.show(evt.getComponent(), evt.getX(), evt.getY()); + } + } + + private class BeobAbstractAction extends AbstractAction { + + @Override + public void actionPerformed(ActionEvent e) { + downloadAendern(); + } + } + + private class BeobAnzeige implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + load(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `GuiDownloads.jTable1.getModel().getValueAt(delRow,7)` could be null and is dereferenced at line 184. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GuiDownloads.downloadLoeschen(boolean) + +### Procedure Id: +mediathek.gui.GuiDownloads.downloadLoeschen(boolean):void.a71a3ec3efbdf0818498ea192700462e + +### File: +src/mediathek/gui/GuiDownloads.java + +### Key: +GuiDownloads.java|downloadLoeschen|NULL_DEREFERENCE + +### Node Key: +9651bb3fa853002c439350544f30f896 + +### Hash: +5704b6c9a1228b36b144271d05934ac5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8939/instruction.md b/inferredbugs-8939/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..02fb63cf6ba231cc5e46602ac60f670396badf10 --- /dev/null +++ b/inferredbugs-8939/instruction.md @@ -0,0 +1,378 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.controller.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.SocketAddress; +import java.net.URL; +import java.net.URLConnection; +import java.util.Iterator; +import java.util.LinkedList; +import mediathek.daten.Daten; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; + +public class GetUrl { + + public static final int LISTE_SEITEN_ZAEHLER = 1; + public static final int LISTE_SEITEN_ZAEHLER_FEHlER = 2; + public static final int LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE = 3; + public static final int LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE = 4; + public static final int LISTE_SUMME_BYTE = 5; + private static final long UrlWartenBasis = 500;//ms, Basiswert zu dem dann der Faktor multipliziert wird + private int faktorWarten = 1; + private int timeout = 10000; + private long wartenBasis = UrlWartenBasis; + private static LinkedList listeSeitenZaehler = new LinkedList(); + private static LinkedList listeSeitenZaehlerFehler = new LinkedList(); + private static LinkedList listeSeitenZaehlerFehlerVersuche = new LinkedList(); + private static LinkedList listeSeitenZaehlerWartezeitFehlerVersuche = new LinkedList(); // Wartezeit für Wiederholungen [s] + private static LinkedList listeSummeByte = new LinkedList(); // Summe Daten in Byte für jeden Sender + + private class Seitenzaehler { + + String senderName = ""; + long seitenAnzahl = 0; + + public Seitenzaehler(String ssenderName) { + senderName = ssenderName; + seitenAnzahl = 1; + } + + public Seitenzaehler(String ssenderName, int sseitenAnzahl) { + senderName = ssenderName; + seitenAnzahl = sseitenAnzahl; + } + } + + public GetUrl(long wwartenBasis) { + wartenBasis = wwartenBasis; + } + + //=================================== + // public + //=================================== + public StringBuffer getUri_Utf(String sender, String addr, StringBuffer seite, String meldung) { + return getUri(sender, addr, Konstanten.KODIERUNG_UTF, 1 /* versuche */, seite, meldung); + } + + public StringBuffer getUri_Iso(String sender, String addr, StringBuffer seite, String meldung) { + return getUri(sender, addr, Konstanten.KODIERUNG_ISO15, 1 /* versuche */, seite, meldung); + } + + public synchronized StringBuffer getUri(String sender, String addr, String kodierung, int maxVersuche, StringBuffer seite, String meldung) { + final int PAUSE = 1000; +// int aktTimeout = (maxVersuche > 1) ? timeout / 2 : timeout; // wenns mehrere Versuche gibt, dann der erste mit verkürztem Timeout + int aktTimeout = timeout; + int aktVer = 0; + int wartezeit; + boolean letzterVersuch; + do { + ++aktVer; + try { +// if (aktVer >= maxVersuche) { +// // der letzte Versuch mit dem vollen Timeout +// aktTimeout = timeout; +// } + if (aktVer > 1) { + // und noch eine Pause vor dem nächsten Versuch + this.wait(PAUSE); + } + letzterVersuch = (aktVer >= maxVersuche) ? true : false; + seite = getUri(sender, addr, seite, kodierung, aktTimeout, meldung, maxVersuche, letzterVersuch); + if (seite.length() > 0) { + // und nix wie weiter + if (Daten.debug && aktVer > 1) { + String text = sender + " [" + aktVer + "/" + maxVersuche + "] ~~~> " + addr; + Log.systemMeldung(text); + } + // nur dann zählen + incSeitenZaehler(LISTE_SEITEN_ZAEHLER, sender, 1); + return seite; + } else { + // hat nicht geklappt + if (aktVer > 1) { + wartezeit = (aktTimeout + PAUSE); + } else { + wartezeit = (aktTimeout); + } + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, sender, wartezeit / 1000); + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, sender, 1); + if (letzterVersuch) { + // dann wars leider nichts + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_FEHlER, sender, 1); + } + } + } catch (Exception ex) { + Log.fehlerMeldung(698963200, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); + } + } while (!Daten.filmeLaden.getStop() && aktVer < maxVersuche); + return seite; + } + + public synchronized void getDummy(String sender) { + // Dummy zum hochzählen des Seitenzählers + incSeitenZaehler(LISTE_SEITEN_ZAEHLER, sender, 1); + } + + public void setTimeout(int ttimeout) { + timeout = ttimeout; + } + + public int getTimeout() { + return timeout; + } + + public static long getSeitenZaehler(int art, String sender) { + long ret = 0; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + Seitenzaehler sz; + while (it.hasNext()) { + sz = it.next(); + if (sz.senderName.equals(sender)) { + ret = sz.seitenAnzahl; + } + } + if (art == LISTE_SUMME_BYTE) { + // Byte in MByte + ret = ret / 1024 / 1024; + } + return ret; + } + + public static synchronized long getSeitenZaehler(int art) { + long ret = 0; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + while (it.hasNext()) { + ret += it.next().seitenAnzahl; + } + if (art == LISTE_SUMME_BYTE) { + // Byte in MByte + ret = ret / 1024 / 1024; + } + return ret; + } + + public static synchronized void resetZaehler() { + listeSeitenZaehler.clear(); + listeSeitenZaehlerFehler.clear(); + listeSeitenZaehlerFehlerVersuche.clear(); + listeSeitenZaehlerWartezeitFehlerVersuche.clear(); + listeSummeByte.clear(); + } + + //=================================== + // private + //=================================== + private static LinkedList getListe(int art) { + switch (art) { + case LISTE_SEITEN_ZAEHLER: + return listeSeitenZaehler; + case LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE: + return listeSeitenZaehlerFehlerVersuche; + case LISTE_SEITEN_ZAEHLER_FEHlER: + return listeSeitenZaehlerFehler; + case LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE: + return listeSeitenZaehlerWartezeitFehlerVersuche; + case LISTE_SUMME_BYTE: + return listeSummeByte; + default: + return null; + } + } + + private synchronized void incSeitenZaehler(int art, String sender, int inc) { + boolean gefunden = false; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + Seitenzaehler sz; + while (it.hasNext()) { + sz = it.next(); + if (sz.senderName.equals(sender)) { + sz.seitenAnzahl += inc; + gefunden = true; + break; + } + } + if (!gefunden) { + liste.add(new Seitenzaehler(sender, inc)); + } + } + + private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) { + int timeo = timeout; + boolean proxyB = false; + char[] zeichen = new char[1]; + seite.setLength(0); + URLConnection conn; + int code = 0; + InputStream in = null; + InputStreamReader inReader = null; + Proxy proxy = null; + SocketAddress saddr = null; + // immer etwas bremsen + try { + long w = wartenBasis * faktorWarten; + this.wait(w); + } catch (Exception ex) { + Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); + } + try { + URL url = new URL(addr); + // conn = url.openConnection(Proxy.NO_PROXY); + conn = url.openConnection(); + conn.setRequestProperty("User-Agent", Daten.getUserAgent()); + if (timeout > 0) { + conn.setReadTimeout(timeout); + conn.setConnectTimeout(timeout); + } + if (conn instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection) conn; + code = httpConnection.getResponseCode(); +// if (code >= 400) { +// if (true) { +// // wenn möglich, einen Proxy einrichten +// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---"); +// proxyB = true; +// saddr = new InetSocketAddress("localhost", 9050); +// proxy = new Proxy(Proxy.Type.SOCKS, saddr); +// conn = url.openConnection(proxy); +// conn.setRequestProperty("User-Agent", Daten.getUserAgent()); +// if (timeout > 0) { +// conn.setReadTimeout(timeout); +// conn.setConnectTimeout(timeout); +// } +// } else { +// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400"); +// } +// } + } else { + Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon"); + } + in = conn.getInputStream(); + inReader = new InputStreamReader(in, kodierung); + while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) { + seite.append(zeichen); + incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1); + } + } catch (IOException ex) { + if (lVersuch) { + String[] text; + if (meldung.equals("")) { + text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/}; + } else { + text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/}; + } + Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text); + } + } catch (Exception ex) { + Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, ""); + } finally { + try { + if (in != null) { + inReader.close(); + } + } catch (IOException ex) { + } + } + return seite; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileInputStream` acquired by call to `getInputStream()` at line 275 is not released after line 296. +**Note**: potential exception at line 276 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +StringBuffer GetUrl.getUri(String,String,StringBuffer,String,int,String,int,boolean) + +### Procedure Id: +mediathek.controller.io.GetUrl.getUri(java.lang.String,java.lang.String,java.lang.StringBuffer,java..132bd5d2f6152705ad5fe590013f92d5 + +### File: +src/mediathek/controller/io/GetUrl.java + +### Key: +GetUrl.java|getUri|RESOURCE_LEAK + +### Node Key: +44599c87e83680e0a6bc09b4cb3a71a9 + +### Hash: +af6652a1e51b8781bcfa65ef304ef398 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8953/instruction.md b/inferredbugs-8953/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1bd8e215e763505e93108f911ea745929b777b81 --- /dev/null +++ b/inferredbugs-8953/instruction.md @@ -0,0 +1,939 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 36 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.gui; + +import java.awt.Component; +import java.awt.Desktop; +import java.awt.Point; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.File; +import java.util.ArrayList; +import javax.swing.AbstractAction; +import javax.swing.ActionMap; +import javax.swing.InputMap; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPopupMenu; +import javax.swing.KeyStroke; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import mediathek.MediathekGui; +import mediathek.controller.filmeLaden.ListenerFilmeLaden; +import mediathek.controller.filmeLaden.ListenerFilmeLadenEvent; +import mediathek.controller.io.starter.Start; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenDownload; +import mediathek.daten.DatenFilm; +import mediathek.daten.DatenPset; +import mediathek.gui.dialog.DialogDatenFilm; +import mediathek.gui.dialog.DialogEditDownload; +import mediathek.gui.dialog.DialogProgrammOrdnerOeffnen; +import mediathek.tool.BeobMpanel; +import mediathek.tool.CellRendererDownloads; +import mediathek.tool.Datum; +import mediathek.tool.GuiFunktionen; +import mediathek.tool.GuiKonstanten; +import mediathek.tool.HinweisKeineAuswahl; +import mediathek.tool.JTableMed; +import mediathek.tool.Konstanten; +import mediathek.tool.ListenerMediathekView; +import mediathek.tool.Log; +import mediathek.tool.TModelDownload; + +public class GuiDownloads extends PanelVorlage { + + private DialogDatenFilm dialogDatenFilm = null; + + public GuiDownloads(DDaten d, Component parentComponent) { + super(d, parentComponent); + initComponents(); + tabelle = new JTableMed(JTableMed.TABELLE_TAB_DOWNLOADS); + jScrollPane1.setViewportView(tabelle); + dialogDatenFilm = new DialogDatenFilm(null, false, ddaten); + init(); + downloadsAktualisieren(); // die Tabelle wird dabei gleich geladen + tabelle.initTabelle(); + if (tabelle.getRowCount() > 0) { + tabelle.setRowSelectionInterval(0, 0); + } + } + //=================================== + //public + //=================================== + + @Override + public void isShown() { + super.isShown(); + ddaten.mediathekGui.setToolbar(MediathekGui.ButtonDonwload); + ddaten.infoPanel.setIdx(InfoPanel.IDX_GUI_DOWNLOAD); + } + + public void aktualisieren() { + downloadsAktualisieren(); + } + + public void starten(boolean alle) { + filmStartenWiederholenStoppen(alle, true /* starten */); + } + + public void stoppen(boolean alle) { + filmStartenWiederholenStoppen(alle, false /* starten */); + } + + public void vorziehen() { + downloadVorziehen(); + } + + public void zurueckstellen() { + downloadLoeschen(false); + } + + public void loeschen() { + downloadLoeschen(true); + } + + public void aufraeumen() { + downloadsAufraeumen(); + } + + public void aendern() { + downloadAendern(); + } + + //=================================== + //private + //=================================== + private void init() { + jRadioButtonAbos.setForeground(GuiKonstanten.ABO_FOREGROUND); + jRadioButtonDownloads.setForeground(GuiKonstanten.DOWNLOAD_FOREGROUND); + tabelle.setDefaultRenderer(Object.class, new CellRendererDownloads(ddaten)); + tabelle.setDefaultRenderer(Datum.class, new CellRendererDownloads(ddaten)); + tabelle.setModel(new TModelDownload(new Object[][]{}, DatenDownload.DOWNLOAD_COLUMN_NAMES)); + tabelle.addMouseListener(new BeobMausTabelle()); + tabelle.getSelectionModel().addListSelectionListener(new BeobachterTableSelect()); + //aendern + ActionMap am = tabelle.getActionMap(); + InputMap im = tabelle.getInputMap(); + //aendern + am.put("aendern", new BeobAbstractActionAendern()); + KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); + im.put(enter, "aendern"); + // + jRadioButtonAlles.addActionListener(new BeobAnzeige()); + jRadioButtonAbos.addActionListener(new BeobAnzeige()); + jRadioButtonDownloads.addActionListener(new BeobAnzeige()); + jCheckBoxFilter.addActionListener(new BeobMpanel(jCheckBoxFilter, jPanelFilter, "Filter")); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_DOWNLOADS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelleLaden(); + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_ART_DOWNLOAD_PROZENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelle.fireTableDataChanged(true /*setSpalten*/); + setInfo(); + //panelUpdate(); + } + }); + DDaten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig_(ListenerFilmeLadenEvent event) { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + downloadsAktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_LISTE_ABOS, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + if (Boolean.parseBoolean(Daten.system[Konstanten.SYSTEM_ABOS_SOFORT_SUCHEN_NR])) { + downloadsAktualisieren(); + } + } + }); + ListenerMediathekView.addListener(new ListenerMediathekView(ListenerMediathekView.EREIGNIS_START_EVENT, GuiDownloads.class.getSimpleName()) { + @Override + public void ping() { + tabelle.fireTableDataChanged(true /*setSpalten*/); + setInfo(); + } + }); + } + + private synchronized void tabelleLaden() { + // nur Downloads die schon in der Liste sind werden geladen + boolean abo, download; + tabelle.getSpalten(); + if (jRadioButtonAlles.isSelected()) { + abo = true; + download = true; + } else if (jRadioButtonAbos.isSelected()) { + abo = true; + download = false; + } else { + abo = false; + download = true; + } + ddaten.listeDownloads.getModel((TModelDownload) tabelle.getModel(), abo, download); + tabelle.setSpalten(); + setInfo(); + } + + private synchronized void downloadsAktualisieren() { + // erledigte entfernen, nicht gestartete Abos entfernen und neu nach Abos suchen + downloadsAufraeumen(); + ddaten.listeDownloads.zurueckgestellteWiederAktivieren(); + ddaten.listeDownloads.abosLoschenWennNochNichtGestartet(); + ddaten.listeDownloads.abosSuchen(); + tabelleLaden(); + } + + private synchronized void downloadsAufraeumen() { + // abgeschlossene Downloads werden aus der Tabelle/Liste entfernt + // die Starts dafür werden auch gelöscht + ddaten.listeDownloads.listePutzen(); + } + + private synchronized void downloadAendern() { + int row = tabelle.getSelectedRow(); + if (row != -1) { + int delRow = tabelle.convertRowIndexToModel(row); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + DatenDownload d = download.getCopy(); + DialogEditDownload dialog = new DialogEditDownload(null, true, d); + dialog.setVisible(true); + if (dialog.ok) { + download.aufMichKopieren(d); + tabelle.getSelected(); + tabelleLaden(); + tabelle.setSelected(); + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void downloadVorziehen() { + int row = tabelle.getSelectedRow(); + if (row != -1) { + int delRow = tabelle.convertRowIndexToModel(row); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + ddaten.listeDownloads.downloadVorziehen(url); + tabelleLaden(); + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void zielordnerOeffnen() { + boolean gut = false; + File sFile = null; + int row = tabelle.getSelectedRow(); + if (row >= 0) { + String url = tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(row), DatenDownload.DOWNLOAD_URL_NR).toString(); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + String s = download.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD_NR]; + if (!s.endsWith(File.separator)) { + s += File.separator; + } + try { + sFile = new File(s); + if (!sFile.exists()) { + sFile = sFile.getParentFile(); + } + if (Desktop.isDesktopSupported()) { + Desktop d = Desktop.getDesktop(); + if (d.isSupported(Desktop.Action.OPEN)) { + d.open(sFile); + gut = true; + } + } + } catch (Exception ex) { + try { + gut = false; + String programm = ""; + if (Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR].equals("")) { + DialogProgrammOrdnerOeffnen dialog = new DialogProgrammOrdnerOeffnen(ddaten.mediathekGui, ddaten, true, "", "Dateimanager suchen"); + dialog.setVisible(true); + if (dialog.ok) { + programm = dialog.ziel; + } + } else { + programm = Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR]; + } + if (sFile != null) { + Runtime.getRuntime().exec(programm + " " + sFile.getAbsolutePath()); + Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR] = programm; + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_PROGRAMM_ORDNER_OEFFNEN, GuiDownloads.class.getSimpleName()); + gut = true; + } + } catch (Exception eex) { + Log.fehlerMeldung(306590789, Log.FEHLER_ART_PROG, GuiDownloads.class.getName(), ex, "Ordner öffnen: " + download.arr[DatenDownload.DOWNLOAD_ZIEL_PFAD_NR]); + } + } finally { + if (!gut) { + Daten.system[Konstanten.SYSTEM_ORDNER_OEFFNEN_NR] = ""; + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_PROGRAMM_ORDNER_OEFFNEN, GuiDownloads.class.getSimpleName()); + JOptionPane.showMessageDialog(parentComponent, "Kann den Dateimanager nicht öffnen!", + "Fehler", JOptionPane.ERROR_MESSAGE); + } + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void downloadLoeschen(boolean dauerhaft) { + int rows[] = tabelle.getSelectedRows(); + if (rows.length > 0) { + String[] urls = new String[rows.length]; + for (int i = 0; i < rows.length; ++i) { + urls[i] = tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(rows[i]), DatenDownload.DOWNLOAD_URL_NR).toString(); + } + for (String url : urls) { + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (dauerhaft) { + if (download.istAbo()) { + // ein Abo wird zusätzlich ins Logfile geschrieben + ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR], download.arr[DatenDownload.DOWNLOAD_TITEL_NR], url); + } + ddaten.listeDownloads.delDownloadByUrl(url); + } else { + // wenn nicht dauerhaft + download.zurueckstellen(); + } + ddaten.starterClass.filmLoeschen(url); + } + tabelleLaden(); + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + + private void filmStartenWiederholenStoppen(boolean alle, boolean starten /* starten/wiederstarten oder stoppen */) { + // bezieht sich immer auf "alle" oder nur die markierten + // Film der noch keinen Starts hat wird gestartet + // Film dessen Start schon auf fertig/fehler steht wird wieder gestartet + // bei !starten wird der Film gestoppt + String[] urls; + // ========================== + // erst mal die URLs sammeln + if (alle) { + urls = new String[tabelle.getRowCount()]; + for (int i = 0; i < tabelle.getRowCount(); ++i) { + urls[i] = tabelle.getModel().getValueAt(i, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + } else { + int[] rows = tabelle.getSelectedRows(); + urls = new String[rows.length]; + if (rows.length >= 0) { + for (int i = 0; i < rows.length; i++) { + int row = tabelle.convertRowIndexToModel(rows[i]); + urls[i] = tabelle.getModel().getValueAt(row, DatenDownload.DOWNLOAD_URL_NR).toString(); + } + } else { + new HinweisKeineAuswahl().zeigen(parentComponent); + } + } + // ======================== + // und jetzt abarbeiten + for (String url : urls) { + Start s = ddaten.starterClass.getStart(url); + DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); + if (starten) { + // -------------- + // starten + if (s != null) { + if (s.status > Start.STATUS_RUN) { + // wenn er noch läuft gibts nix + // wenn er schon fertig ist, erst mal fragen vor dem erneuten Starten + int a = JOptionPane.showConfirmDialog(parentComponent, "Film nochmal starten? ==> " + s.datenDownload.arr[DatenDownload.DOWNLOAD_TITEL_NR], "Fertiger Download", JOptionPane.YES_NO_OPTION); + if (a != JOptionPane.YES_OPTION) { + // weiter mit der nächsten URL + continue; + } + ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + + } + } + } + // jetzt noch starten/wiederstarten + // Start erstellen und zur Liste hinzufügen + download.starten(ddaten); + } else { + // --------------- + // stoppen + if (s != null) { + // wenn kein s -> dann gibts auch nichts zum stoppen oder wieder-starten + if (s.status <= Start.STATUS_RUN) { + // löschen -> nur wenn noch läuft, sonst gibts nichts mehr zum löschen + ddaten.starterClass.filmLoeschen(url); + if (s.datenDownload.istAbo()) { + // bei Abos Url auch aus dem Logfile löschen, der Film ist damit wieder auf "Anfang" + ddaten.erledigteAbos.urlAusLogfileLoeschen(url); + } + } + download.startMelden(DatenDownload.PROGRESS_NICHT_GESTARTET); + } + } + } + } + + private void stopWartende() { + // es werden alle noch nicht gestarteten Downloads gelöscht + ArrayList urls = new ArrayList(); + for (int i = 0; i < tabelle.getRowCount(); ++i) { + int delRow = tabelle.convertRowIndexToModel(i); + String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); + Start s = ddaten.starterClass.getStart(url); + if (s != null) { + if (s.status < Start.STATUS_RUN) { + urls.add(url); + } + } + } + for (String url : urls) { + ddaten.starterClass.filmLoeschen(url); + } + } + + private void setInfo() { + String textLinks; + // Text links: Zeilen Tabelle + int laufen = ddaten.starterClass.getDownloadsLaufen(); + int warten = ddaten.starterClass.getDownloadsWarten(); + int gesamt = tabelle.getModel().getRowCount(); + if (gesamt == 1) { + textLinks = "1 Download,"; + } else { + textLinks = gesamt + " Downloads,"; + } + textLinks += " ("; + if (laufen == 1) { + textLinks += "1 läuft,"; + } else { + textLinks += laufen + " laufen,"; + } + if (warten == 1) { + textLinks += " 1 wartet"; + } else { + textLinks += " " + warten + " warten"; + } + textLinks += ")"; + // Infopanel setzen + ddaten.infoPanel.setTextLinks(InfoPanel.IDX_GUI_DOWNLOAD, textLinks); + } + + private void dialogDatenFilmSetzen() { + DatenFilm aktFilm = new DatenFilm(); + int selectedTableRow = tabelle.getSelectedRow(); + if (selectedTableRow >= 0) { + int selectedModelRow = tabelle.convertRowIndexToModel(selectedTableRow); + DatenFilm film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + aktFilm = film; + } + } + dialogDatenFilm.setAktFilm(aktFilm); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + + buttonGroup1 = new javax.swing.ButtonGroup(); + jScrollPane1 = new javax.swing.JScrollPane(); + jTable1 = new javax.swing.JTable(); + jPanelFilter = new javax.swing.JPanel(); + jCheckBoxFilter = new javax.swing.JCheckBox(); + jPanelFilterInnen = new javax.swing.JPanel(); + jRadioButtonAlles = new javax.swing.JRadioButton(); + jRadioButtonDownloads = new javax.swing.JRadioButton(); + jRadioButtonAbos = new javax.swing.JRadioButton(); + + jTable1.setAutoCreateRowSorter(true); + jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF); + jScrollPane1.setViewportView(jTable1); + + jPanelFilter.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(153, 153, 153))); + + jCheckBoxFilter.setBackground(new java.awt.Color(217, 217, 217)); + jCheckBoxFilter.setFont(new java.awt.Font("Dialog", 1, 10)); // NOI18N + jCheckBoxFilter.setText("Filter"); + + buttonGroup1.add(jRadioButtonAlles); + jRadioButtonAlles.setSelected(true); + jRadioButtonAlles.setText(" alle"); + jRadioButtonAlles.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAlles.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonDownloads); + jRadioButtonDownloads.setText(" Downloads "); + jRadioButtonDownloads.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonDownloads.setBorderPainted(true); + + buttonGroup1.add(jRadioButtonAbos); + jRadioButtonAbos.setText(" Abos "); + jRadioButtonAbos.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204))); + jRadioButtonAbos.setBorderPainted(true); + + javax.swing.GroupLayout jPanelFilterInnenLayout = new javax.swing.GroupLayout(jPanelFilterInnen); + jPanelFilterInnen.setLayout(jPanelFilterInnenLayout); + jPanelFilterInnenLayout.setHorizontalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addComponent(jRadioButtonAlles) + .addGap(18, 18, 18) + .addComponent(jRadioButtonDownloads) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jRadioButtonAbos) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + jPanelFilterInnenLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jRadioButtonAbos, jRadioButtonAlles, jRadioButtonDownloads}); + + jPanelFilterInnenLayout.setVerticalGroup( + jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterInnenLayout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanelFilterInnenLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) + .addComponent(jRadioButtonAlles) + .addComponent(jRadioButtonDownloads) + .addComponent(jRadioButtonAbos)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout jPanelFilterLayout = new javax.swing.GroupLayout(jPanelFilter); + jPanelFilter.setLayout(jPanelFilterLayout); + jPanelFilterLayout.setHorizontalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(jCheckBoxFilter, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + jPanelFilterLayout.setVerticalGroup( + jPanelFilterLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanelFilterLayout.createSequentialGroup() + .addComponent(jCheckBoxFilter) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jPanelFilterInnen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); + this.setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 670, Short.MAX_VALUE) + .addComponent(jPanelFilter, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanelFilter, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE) + .addContainerGap()) + ); + }// //GEN-END:initComponents + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.ButtonGroup buttonGroup1; + private javax.swing.JCheckBox jCheckBoxFilter; + private javax.swing.JPanel jPanelFilter; + private javax.swing.JPanel jPanelFilterInnen; + private javax.swing.JRadioButton jRadioButtonAbos; + private javax.swing.JRadioButton jRadioButtonAlles; + private javax.swing.JRadioButton jRadioButtonDownloads; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTable jTable1; + // End of variables declaration//GEN-END:variables + + private class BeobachterTableSelect implements ListSelectionListener { + + @Override + public void valueChanged(ListSelectionEvent event) { + if (!event.getValueIsAdjusting()) { + dialogDatenFilmSetzen(); + } + } + } + + public class BeobMausTabelle extends MouseAdapter { + + private Point p; + + public BeobMausTabelle() { + } + + @Override + public void mouseClicked(MouseEvent arg0) { + if (arg0.getButton() == MouseEvent.BUTTON1) { + if (arg0.getClickCount() > 1) { + downloadAendern(); + } +// } else if (arg0.getButton() == MouseEvent.BUTTON3) { +// showMenu(arg0); + } + } + + @Override + public void mousePressed(MouseEvent arg0) { + if (arg0.isPopupTrigger()) { + showMenu(arg0); + } + } + + @Override + public void mouseReleased(MouseEvent arg0) { + if (arg0.isPopupTrigger()) { + showMenu(arg0); + } + } + + private void showMenu(MouseEvent evt) { + p = evt.getPoint(); + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + tabelle.setRowSelectionInterval(nr, nr); + } + JPopupMenu jPopupMenu = new JPopupMenu(); + + //Film vorziehen + int row = tabelle.getSelectedRow(); + boolean wartenOderLaufen = false; + if (row >= 0) { + int delRow = tabelle.convertRowIndexToModel(row); + Start s = ddaten.starterClass.getStart(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (s != null) { + if (s.status <= Start.STATUS_RUN) { + wartenOderLaufen = true; + } + } + } + + // Download starten + JMenuItem itemStarten = new JMenuItem("Download starten"); + itemStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_play_16.png"))); + itemStarten.setEnabled(!wartenOderLaufen); + jPopupMenu.add(itemStarten); + itemStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, true /* starten */); + } + }); + + // Download stoppen + JMenuItem itemStoppen = new JMenuItem("Download stoppen"); + itemStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + itemStoppen.setEnabled(wartenOderLaufen); + jPopupMenu.add(itemStoppen); + itemStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(false /* alle */, false /* starten */); + } + }); + + // Zielordner öffnen + JMenuItem itemOeffnen = new JMenuItem("Zielordner öffnen"); + itemOeffnen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/fileopen_16.png"))); + jPopupMenu.add(itemOeffnen); + itemOeffnen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + zielordnerOeffnen(); + } + }); + + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemVorziehen = new JMenuItem("Download vorziehen"); + itemVorziehen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/up_blue_16.png"))); + jPopupMenu.add(itemVorziehen); + itemVorziehen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadVorziehen(); + } + }); + JMenuItem itemLoeschen = new JMenuItem("Download zurückstellen"); + itemLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/undo_16.png"))); + jPopupMenu.add(itemLoeschen); + itemLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(false /* dauerhaft */); + } + }); + //dauerhaft löschen + JMenuItem itemDauerhaftLoeschen = new JMenuItem("Download dauerhaft löschen"); + itemDauerhaftLoeschen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/del_16.png"))); + jPopupMenu.add(itemDauerhaftLoeschen); + itemDauerhaftLoeschen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadLoeschen(true /* dauerhaft */); + } + }); + //ändern + JMenuItem itemAendern = new JMenuItem("Download Ändern"); + itemAendern.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/configure_16.png"))); + jPopupMenu.add(itemAendern); + itemAendern.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadAendern(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + JMenuItem itemAlleStarten = new JMenuItem("alle Downloads starten"); + itemAlleStarten.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/next_16.png"))); + jPopupMenu.add(itemAlleStarten); + itemAlleStarten.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, true /* starten */); + } + }); + JMenuItem itemAlleStoppen = new JMenuItem("alle Downloads stoppen"); + itemAlleStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + jPopupMenu.add(itemAlleStoppen); + itemAlleStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + filmStartenWiederholenStoppen(true /* alle */, false /* starten */); + } + }); + JMenuItem itemWartendeStoppen = new JMenuItem("wartende Downloads stoppen"); + itemWartendeStoppen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/player_stop_16.png"))); + jPopupMenu.add(itemWartendeStoppen); + itemWartendeStoppen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + stopWartende(); + } + }); + JMenuItem itemAktualisieren = new JMenuItem("Liste der Downloads aktualisieren"); + itemAktualisieren.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/view-refresh_16.png"))); + jPopupMenu.add(itemAktualisieren); + itemAktualisieren.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadsAktualisieren(); + } + }); + JMenuItem itemAufraeumen = new JMenuItem("Liste Aufräumen"); + itemAufraeumen.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mediathek/res/edit-clear_16.png"))); + jPopupMenu.add(itemAufraeumen); + itemAufraeumen.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent arg0) { + downloadsAufraeumen(); + } + }); + + //####################################### + jPopupMenu.addSeparator(); + //####################################### + + // url + JMenuItem itemUrl = new JMenuItem("URL kopieren"); + itemUrl.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + GuiFunktionen.copyToClipboard( + tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(nr), + DatenDownload.DOWNLOAD_URL_NR).toString()); + } + } + }); + jPopupMenu.add(itemUrl); + + // Player + JMenuItem itemPlayer = new JMenuItem("Film abspielen"); + itemPlayer.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + int nr = tabelle.rowAtPoint(p); + if (nr >= 0) { + DatenPset gruppe = ddaten.listePset.getPsetAbspielen(); + if (gruppe != null) { + int selectedModelRow = tabelle.convertRowIndexToModel(nr); + DatenFilm film = Daten.listeFilme.getFilmByUrl(tabelle.getModel().getValueAt(selectedModelRow, DatenDownload.DOWNLOAD_URL_NR).toString()); + if (film != null) { + // in die History eintragen + ddaten.history.add(film.getUrlOrg()); + // und starten + ddaten.starterClass.urlStarten(gruppe, film); + } + } else { + JOptionPane.showMessageDialog(parentComponent, "Im Menü unter \"Datei->Optionen->Videoplayer\" ein Programm zum Abspielen festlegen.", + "kein Videoplayer!", JOptionPane.INFORMATION_MESSAGE); + } + } + } + }); + jPopupMenu.add(itemPlayer); + + // Infos + JMenuItem itemInfo = new JMenuItem("Infos anzeigen"); + itemInfo.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + dialogDatenFilm.setVis(); + } + }); + jPopupMenu.add(itemInfo); + + // Tabellenspalten zurücksetzen + JMenuItem item = new JMenuItem("Spalten zurücksetzen"); + item.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + tabelle.resetTabelle(); + } + }); + jPopupMenu.add(item); + // + // ###################### + // Menü anzeigen + jPopupMenu.show(evt.getComponent(), evt.getX(), evt.getY()); + } + } + + private class BeobAbstractActionAendern extends AbstractAction { + + @Override + public void actionPerformed(ActionEvent e) { + downloadAendern(); + } + } + + private class BeobAnzeige implements ActionListener { + + @Override + public void actionPerformed(ActionEvent e) { + tabelleLaden(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `download` last assigned on line 367 could be null and is dereferenced at line 390. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GuiDownloads.filmStartenWiederholenStoppen(boolean,boolean) + +### Procedure Id: +mediathek.gui.GuiDownloads.filmStartenWiederholenStoppen(boolean,boolean):void.705abf1e637e36763958f9c8ae95c3f1 + +### File: +src/mediathek/gui/GuiDownloads.java + +### Key: +GuiDownloads.java|filmStartenWiederholenStoppen|NULL_DEREFERENCE + +### Node Key: +fc3afcc06b1d978fbc0ea4830affd0cf + +### Hash: +b47b2e8abf0f72dba1f9d183311ff276 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8954/instruction.md b/inferredbugs-8954/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0490d134509c9323a9f3240a50342d3f396fe3c --- /dev/null +++ b/inferredbugs-8954/instruction.md @@ -0,0 +1,450 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 31 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.tool; + +import java.io.File; +import java.io.InputStream; +import java.util.Iterator; +import javax.swing.JOptionPane; +import mediathek.controller.io.IoXmlLesen; +import mediathek.daten.DDaten; +import mediathek.daten.Daten; +import mediathek.daten.DatenProg; +import mediathek.daten.DatenPset; +import mediathek.daten.ListePset; +import mediathek.file.GetFile; +import mediathek.gui.dialog.DialogHilfe; +import mediathek.gui.dialog.DialogOk; +import mediathek.gui.dialogEinstellungen.DialogImportPset; +import mediathek.gui.dialogEinstellungen.PanelProgrammPfade; + +public class GuiFunktionenProgramme { + + public static final int OS_UNKNOWN = 0; + public static final int OS_WIN_32BIT = 1; + public static final int OS_WIN_64BIT = 2; + public static final int OS_LINUX = 3; + public static final int OS_MAC = 4; + + private static String getWindowsMplayerPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Program Files\\SMPlayer\\mplayer\\mplayer.exe"; + final String PFAD_WIN = "\\SMPlayer\\mplayer\\mplayer.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + private static String getWindowsVlcPath() { + //Für Windows den Pfad des VLC ermitteln + //sonst den deutschen Defaultpfad für Programme verwenden verwenden + final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe"; + final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe"; + String vlcPfad; + try { + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + vlcPfad = System.getenv("ProgramFiles") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } + if (System.getenv("ProgramFiles(x86)") != null) { + vlcPfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; + if (new File(vlcPfad).exists()) { + return vlcPfad; + } + } + } catch (Exception ex) { + } + return PFAD_WIN_DEFAULT; + } + + public static String getMusterPfadMplayer() { + final String PFAD_LINUX = "/usr/bin/mplayer"; + final String PFAD_MAC = "/opt/local/bin/mplayer"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsMplayerPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadVlc() { + final String PFAD_LINUX_VLC = "/usr/bin/vlc"; + final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; + String pfad = ""; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + pfad = getWindowsVlcPath(); + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + pfad = PFAD_LINUX_VLC; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + pfad = PFAD_MAC_VLC; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getMusterPfadFlv() { + final String PFAD_LINUX_FLV = "/usr/bin/flvstreamer"; + final String PFAD_WINDOWS_FLV = "bin\\flvstreamer_win32_latest.exe"; + final String PFAD_MAC_FLV = "bin\\flvstreamer_macosx_intel_32bit_latest"; + String pfad; + switch (getOs()) { + case OS_LINUX: + pfad = PFAD_LINUX_FLV; + break; + case OS_MAC: + pfad = Funktionen.getPathJar() + PFAD_MAC_FLV; + break; + case OS_WIN_32BIT: + case OS_WIN_64BIT: + case OS_UNKNOWN: + default: + pfad = Funktionen.getPathJar() + PFAD_WINDOWS_FLV; + } + if (new File(pfad).exists()) { + return pfad; + } else { + return ""; + } + } + + public static String getPfadMplayer() { + if (Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, false /* flvstreamer */, true /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_MPLAYER_NR]; + } + + public static String getPfadVlc() { + if (Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(true /* vlc */, false /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_VLC_NR]; + } + + public static String getPfadFlv() { + if (Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR].equals("")) { + new DialogOk(null, true, new PanelProgrammPfade(false /* vlc */, true /* flvstreamer */, false /* mplayer */), "Pfade Standardprogramme").setVisible(true); + } + return Daten.system[Konstanten.SYSTEM_PFAD_FLVSTREAMER_NR]; + } + + public static int getOs() { + int os = OS_UNKNOWN; + if (System.getProperty("os.name").toLowerCase().contains("windows")) { + if (System.getenv("ProgramFiles") != null) { + // win 32Bit + os = OS_WIN_32BIT; + } else if (System.getenv("ProgramFiles(x86)") != null) { + // win 64Bit + os = OS_WIN_64BIT; + } + } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { + os = OS_LINUX; + } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { + os = OS_MAC; + } + return os; + } + + public static String getPfadScript() { + String pfadScript; + final String PFAD_LINUX_SCRIPT = "bin/flv.sh"; + final String PFAD_WINDOWS_SCRIPT = "bin\\flv.bat"; + switch (getOs()) { + case OS_LINUX: + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + break; + case OS_MAC: + pfadScript = Funktionen.getPathJar() + PFAD_LINUX_SCRIPT; + break; + case OS_WIN_32BIT: + case OS_WIN_64BIT: + case OS_UNKNOWN: + default: + pfadScript = Funktionen.getPathJar() + PFAD_WINDOWS_SCRIPT; + } + return pfadScript; + } + + public static ListePset getStandardprogramme(DDaten ddaten) { + ListePset pSet; + InputStream datei; + switch (getOs()) { + case OS_LINUX: + datei = new GetFile().getPsetVorlageLinux(); + break; + case OS_MAC: + datei = new GetFile().getPsetVorlageMac(); + break; + case OS_WIN_32BIT: + case OS_WIN_64BIT: + case OS_UNKNOWN: + default: + datei = new GetFile().getPsetVorlageWindows(); + } + // Standardgruppen laden + pSet = IoXmlLesen.importPset(datei, true); + return pSet; + } + + public static boolean addVorlagen(DDaten ddaten, ListePset pSet, boolean auto) { + // Standardgruppen laden + if (pSet != null) { + if (!auto) { + DialogImportPset dialog = new DialogImportPset(null, true, ddaten, pSet); + dialog.setVisible(true); + if (!dialog.ok) { + return false; + } + } + if (ddaten.listePset.addPset(pSet)) { + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_PSET, GuiFunktionenProgramme.class.getSimpleName()); + JOptionPane.showMessageDialog(null, pSet.size() + " Programmset importiert!", + "Ok", JOptionPane.INFORMATION_MESSAGE); + } + return true; + } else { + JOptionPane.showMessageDialog(null, "Die Datei wurde nicht importiert!", + "Fehler", JOptionPane.ERROR_MESSAGE); + return false; + } + } + + public static boolean praefixTesten(String str, String uurl, boolean praefix) { + //prüfen ob url beginnt/endet mit einem Argument in str + //wenn str leer dann true + boolean ret = false; + String url = uurl.toLowerCase(); + String s1 = ""; + if (str.equals("")) { + ret = true; + } else { + for (int i = 0; i < str.length(); ++i) { + if (str.charAt(i) != ',') { + s1 += str.charAt(i); + } + if (str.charAt(i) == ',' || i >= str.length() - 1) { + if (praefix) { + //Präfix prüfen + if (url.startsWith(s1.toLowerCase())) { + ret = true; + break; + } + } else { + //Suffix prüfen + if (url.endsWith(s1.toLowerCase())) { + ret = true; + break; + } + } + s1 = ""; + } + } + } + return ret; + } + + public static boolean checkPfadBeschreibbar(String pfad) { + boolean ret = false; + File testPfad = new File(pfad); + try { + if (!testPfad.exists()) { + testPfad.mkdirs(); + } + if (pfad.equals("")) { + } else if (!testPfad.isDirectory()) { + } else { + if (testPfad.canWrite()) { + File tmpFile = File.createTempFile("mediathek", "tmp", testPfad); + tmpFile.delete(); + ret = true; + } + } + } catch (Exception ex) { + } + return ret; + } + + public static boolean programmePruefen(DDaten daten) { + final String PIPE = "| "; + final String LEER = " "; + final String PFEIL = " -> "; + boolean ret = true; + String text = ""; + Iterator itPset = daten.listePset.iterator(); + DatenPset datenPset; + DatenProg datenProg; + while (itPset.hasNext()) { + datenPset = itPset.next(); + ret = true; + if (!datenPset.isFreeLine() && !datenPset.isLable()) { + // nur wenn kein Lable oder freeline + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n"; + text += PIPE + "Programmgruppe: " + datenPset.arr[DatenPset.PROGRAMMSET_NAME_NR] + "\n"; + String zielPfad = datenPset.arr[DatenPset.PROGRAMMSET_ZIEL_PFAD_NR]; + if (datenPset.progsContainPath()) { + // beim nur Abspielen wird er nicht gebraucht + if (zielPfad.equals("")) { + ret = false; + text += PIPE + LEER + "Zielpfad fehlt!\n"; + } else { + // Pfad beschreibbar? + if (!checkPfadBeschreibbar(zielPfad)) { + //da Pfad-leer und "kein" Pfad schon abgeprüft + ret = false; + text += PIPE + LEER + "Falscher Zielpfad!\n"; + text += PIPE + LEER + PFEIL + "Zielpfad \"" + zielPfad + "\" nicht beschreibbar!" + "\n"; + } + } + } + Iterator itProg = datenPset.getListeProg().iterator(); + while (itProg.hasNext()) { + datenProg = itProg.next(); + // Programmpfad prüfen + //if (!new File(datenProg.arr[Konstanten.PROGRAMM_PROGRAMMPFAD_NR]).exists()) { + if (!new File(datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR]).canExecute()) { + // Programme prüfen + ret = false; + text += PIPE + LEER + "Falscher Programmpfad!\n"; + text += PIPE + LEER + PFEIL + "Programmname: " + datenProg.arr[DatenProg.PROGRAMM_NAME_NR] + "\n"; + text += PIPE + LEER + LEER + "Pfad: " + datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR] + "\n"; + if (!datenProg.arr[DatenProg.PROGRAMM_PROGRAMMPFAD_NR].contains(File.separator)) { + text += PIPE + LEER + PFEIL + "Wenn das Programm nicht im Systempfad liegt, " + "\n"; + text += PIPE + LEER + LEER + "wird der Start nicht klappen!" + "\n"; + } + } + } + if (ret) { + //sollte alles passen + text += PIPE + PFEIL + "Ok!" + "\n"; + } + text += "++++++++++++++++++++++++++++++++++++++++++++" + "\n\n\n"; + } + } + new DialogHilfe(null, true, text).setVisible(true); + return ret; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getProperty("os.name")` could be null and is dereferenced at line 104. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String GuiFunktionenProgramme.getMusterPfadMplayer() + +### Procedure Id: +mediathek.tool.GuiFunktionenProgramme.getMusterPfadMplayer():java.lang.String.2a04323df0fc1af0e5e9b2a59cb67252 + +### File: +src/mediathek/tool/GuiFunktionenProgramme.java + +### Key: +GuiFunktionenProgramme.java|getMusterPfadMplayer|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +0397eca27321cdb7b87ce96735efde3b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8955/instruction.md b/inferredbugs-8955/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d76229192b6b5826c369d3891ba481e49ff1eed --- /dev/null +++ b/inferredbugs-8955/instruction.md @@ -0,0 +1,198 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 62 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2010 by Andreas M. + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.controller.io; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.util.HashSet; +import java.util.Iterator; +import mediathek.tool.ListenerMediathekView; +import mediathek.tool.Log; + +public class History extends HashSet { + + private String datei = ""; + + public History(String history_datei) { + datei = history_datei; + } + + @Override + public boolean add(String url) { + boolean ret = super.add(url); + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName()); + return ret; + } + + public void add(String[] url) { + for (String s : url) { + super.add(s); + } + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName()); + } + + @Override + public boolean remove(Object url) { + boolean ret = super.remove(url); + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName()); + return ret; + } + + public void laden() { + clear(); + File file = new File(datei); + if (!file.exists()) { + return; + } + try { + FileInputStream fstream = new FileInputStream(datei); + DataInputStream in = new DataInputStream(fstream); + BufferedReader br = new BufferedReader(new InputStreamReader(in)); + String strLine; + while ((strLine = br.readLine()) != null) { + super.add(strLine); + } + //Close the input stream + in.close(); + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName()); + } catch (Exception e) {//Catch exception if any + System.err.println("Fehler: " + e); + Log.fehlerMeldung(303049876, Log.FEHLER_ART_PROG, History.class.getName(), e); + } + } + + public void speichern() { + try { + FileOutputStream fstream = new FileOutputStream(datei); + DataOutputStream out = new DataOutputStream(fstream); + BufferedWriter br = new BufferedWriter(new OutputStreamWriter(out)); + for (String h : this) { + br.write(h + "\n"); + } + br.flush(); + out.close(); + } catch (Exception e) {//Catch exception if any + Log.fehlerMeldung(978786563, Log.FEHLER_ART_PROG, History.class.getName(), e); + } + } + + public void loschen() { + this.clear(); + File file = new File(datei); + if (!file.exists()) { + return; + } + file.delete(); + ListenerMediathekView.notify(ListenerMediathekView.EREIGNIS_LISTE_HISTORY_GEAENDERT, History.class.getSimpleName()); + } + + public Object[][] getObjectData() { + Object[][] object; + int i = 0; + Iterator iterator = this.iterator(); + object = new Object[this.size()][1]; + while (iterator.hasNext()) { + object[i][0] = iterator.next(); + ++i; + } + return object; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedWriter` acquired to `br` by call to `new()` at line 91 is not released after line 97. +**Note**: potential exception at line 93 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void History.speichern() + +### Procedure Id: +mediathek.controller.io.History.speichern():void.6a1ab5937b0160a686f6354f5f0476ef + +### File: +src/mediathek/controller/io/History.java + +### Key: +History.java|speichern|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +de117fe49de0807f27afb26748890f53 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8962/instruction.md b/inferredbugs-8962/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01974819c24ee576201304803f9d4523e72dc029 --- /dev/null +++ b/inferredbugs-8962/instruction.md @@ -0,0 +1,359 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 55 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.controller.filmeLaden.suchen.sender; + +import mediathek.controller.filmeLaden.suchen.FilmeSuchenSender; +import mediathek.controller.io.GetUrl; +import mediathek.daten.Daten; +import mediathek.daten.DatenFilm; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; +import mediathek.tool.MVStringBuilder; +import org.apache.commons.lang3.StringEscapeUtils; + +public class MediathekKika extends MediathekReader implements Runnable { + + public static final String SENDER = "KiKA"; + private MVStringBuilder seiteHttp = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + public MediathekKika(FilmeSuchenSender ssearch, int startPrio) { + super(ssearch, /* name */ SENDER, /* threads */ 2, /* urlWarten */ 500, startPrio); + } + + @Override + synchronized void meldungThreadUndFertig() { + if (threads <= 1) { + // vorher noch laufen + addToListHttp(); + } + --threads; + if (threads <= 0) { + //wird erst ausgeführt wenn alle Threads beendet sind + suchen.meldenFertig(nameSenderMReader); + } else { + // läuft noch was + suchen.melden(nameSenderMReader, max, progress, "" /* text */); + } + } + + @Override + void addToList() { + //Sesamstraße präsentiert: Eine Möhre für Zwei
    + //42. Ordnung ist das halbe Chaos
    + //41. Über den Wolken
    + final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; + final String MUSTER_URL = ""; + final String MUSTER_DATUM = "title=\"Sendung vom "; + listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + int pos = 0; + int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; + String url, thema, datum, titel; + while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { + try { + thema = ""; + pos += MUSTER_THEMA.length(); + stop = seite.indexOf(MUSTER_THEMA, pos); + pos1 = pos; + if ((pos2 = seite.indexOf("<", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { + titel = ""; + datum = ""; + if (stop != -1 && pos1 > stop) { + // dann schon das nächste Thema + break; + } + pos1 += MUSTER_URL.length(); + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + url = seite.substring(pos1, pos2); + //if (!url.equals("")) { + url = StringEscapeUtils.unescapeXml(url); + if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum + if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { + pDatum1 += MUSTER_DATUM.length(); + if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { + if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { + // dann schon das nächste Thema + datum = seite.substring(pDatum1, pDatum2); + } + } + } + + // Titel + if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { + pTitel1 += 1; + if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { + //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { + if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { + titel = seite.substring(pTitel1, pTitel2); + } + } + } + // in die Liste eintragen + String[] add = new String[]{ADRESSE + url, thema, titel, datum}; + listeThemen.addUrl(add); + } + } + } + } catch (Exception ex) { + Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); + } + } + if (Daten.filmeLaden.getStop()) { + meldungThreadUndFertig(); + } else if (listeThemen.size() == 0) { + meldungThreadUndFertig(); + } else { + listeSort(listeThemen, 1); + meldungAddMax(listeThemen.size()); + for (int t = 0; t < maxThreadLaufen; ++t) { + //new Thread(new ThemaLaden()).start(); + Thread th = new Thread(new ThemaLaden()); + th.setName(nameSenderMReader + t); + th.start(); + } + + } + } + + private class ThemaLaden implements Runnable { + + GetUrl getUrl = new GetUrl(wartenSeiteLaden); + private MVStringBuilder seite1 = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + + @Override + public synchronized void run() { + try { + meldungAddThread(); + String[] link; + while (!Daten.filmeLaden.getStop() && (link = listeThemen.getListeThemen()) != null) { + meldungProgress(link[0]); + laden(link[0] /* url */, link[1] /* Thema */, link[2] /* Titel */, link[3] /*Datum*/); + } + } catch (Exception ex) { + Log.fehlerMeldung(-987452384, Log.FEHLER_ART_MREADER, "Mediathek3Sat.ThemaLaden.run", ex, ""); + } + meldungThreadUndFertig(); + } + + void laden(String filmWebsite, String thema, String titel, String datum) { + //so.addVariable("pfad","rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f.mp4"); + //so.addVariable("fullscreenPfad", "rtmp://88.198.74.226/vod/mp4:1348908081-7b8b1356b478db154fdbf8bf6a01fc1f-01.mp4"); + //xajax.config.requestURI = "http://kikaplus.net/clients/kika/kikaplus/?programm=270&id=33172&ag=5"; + final String MUSTER_URL_1 = "so.addVariable(\"pfad\",\""; + final String MUSTER_URL_2 = "so.addVariable(\"fullscreenPfad\", \""; + final String MUSTER_ID = "xajax.config.requestURI = \""; + seite1 = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seite1, thema + " " + titel); + int pos1, pos2; + String id; + String urlFilm = ""; + id = seite1.extract(MUSTER_ID, "\""); + if ((pos1 = seite1.indexOf(MUSTER_URL_2)) != -1) { + pos1 += MUSTER_URL_2.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + if (urlFilm.equals("")) { + if ((pos1 = seite1.indexOf(MUSTER_URL_1)) != -1) { + pos1 += MUSTER_URL_1.length(); + if ((pos2 = seite1.indexOf("\"", pos1)) != -1) { + urlFilm = seite1.substring(pos1, pos2); + } + } + } + if (!urlFilm.equals("")) { + meldung(urlFilm); + addFilm(new DatenFilm(nameSenderMReader, thema, filmWebsite, titel, urlFilm, "-r " + urlFilm + " --flashVer WIN11,4,402,265"/* urlRtmp */, + datum/*datum*/, ""/*zeit*/, 0, "", "", "", new String[]{""})); + } + } + } + + void addToListHttp() { + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=3&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=6&page=all + //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=10&page=all + + final String ADRESSE_1 = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age="; + final String ADRESSE_2 = "&page=all"; + final String MUSTER_START = "var programletterlist = {\""; + final String[] ALTER = {"3", "6", "10"}; +// listeThemen.clear(); + MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); + meldungStart(); + int pos1 = 0, pos2, start = 0, stop = 0; + String id = "", thema = "", url = ""; + for (String alter : ALTER) { + seite = getUrlIo.getUri(nameSenderMReader, ADRESSE_1 + alter + ADRESSE_2, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); + if ((start = seite.indexOf(MUSTER_START)) != -1) { + start += MUSTER_START.length(); + pos1 = start; + if ((stop = seite.indexOf("}};", start)) != -1) { + while ((pos1 = seite.indexOf("\"", pos1)) != -1) { + thema = ""; + id = ""; + pos1 += 1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + id = seite.substring(pos1, pos2); + try { + // Testen auf Zehl + int z = Integer.parseInt(id); + } catch (Exception ex) { + continue; + } + ++pos2; + if ((pos1 = seite.indexOf("\"", pos2)) != -1) { + ++pos1; + if ((pos2 = seite.indexOf("\"", pos1)) != -1) { + thema = seite.substring(pos1, pos2); + } + } + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=165&age=10 + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=" + id + "&age=" + alter; + ladenHttp(url, thema, alter); + } + } + } + } + } + } + + void ladenHttp(String filmWebsite, String thema, String alter) { + // erst die Nummer suchen + // >25420<4<165<23. Die b + // ", "<"); + bild = seiteHttp.extract(MUSTER_BILD, "<"); + if (!bild.isEmpty()) { + bild = "http://www." + bild; + } + // die URL bauen: + // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az + if (!nummer.isEmpty()) { + url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az"; + seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); + final String MUSTER_URL = "var videofile = \""; + final String MUSTER_TITEL = "var videotitle = \""; + urlFilm = seiteHttp.extract(MUSTER_URL, "\""); + titel = seiteHttp.extract(MUSTER_TITEL, "\""); + if (!urlFilm.equals("")) { + meldung(urlFilm); + // DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp, + // String datum, String zeit, + // long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) { + DatenFilm film = null; + if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) { + film.addUrlKlein(urlFilm, ""); + } else { + // dann gibs ihn noch nicht + addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */, + ""/*datum*/, ""/*zeit*/, + 0, "", bild, "", new String[]{""})); + } + } else { + Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp` reads without synchronization from `this.mediathek.controller.filmeLaden.suchen.sender.MediathekKika.seiteHttp`. Potentially races with write in method `MediathekKika.meldungThreadUndFertig()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MediathekKika.ladenHttp(String,String,String) + +### Procedure Id: +mediathek.controller.filmeLaden.suchen.sender.MediathekKika.ladenHttp(java.lang.String,java.lang.Str.baacf86a2519544ecd111ab867b66324 + +### File: +src/mediathek/controller/filmeLaden/suchen/sender/MediathekKika.java + +### Key: +MediathekKika.java|ladenHttp|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +934c6a963fb7e05266ee2383d588684a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8963/instruction.md b/inferredbugs-8963/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d2db5bfbcfb21914579d40201dacf36407413e2 --- /dev/null +++ b/inferredbugs-8963/instruction.md @@ -0,0 +1,307 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek; + +import java.io.File; +import java.util.Iterator; +import java.util.LinkedList; +import mediathek.controller.filmeLaden.ListenerFilmeLaden; +import mediathek.controller.filmeLaden.ListenerFilmeLadenEvent; +import mediathek.controller.io.IoXmlFilmlisteSchreiben; +import mediathek.daten.Daten; +import mediathek.daten.ListeFilme; +import mediathek.tool.GuiFunktionen; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; + +public class MediathekNoGui implements Runnable { + + private String output = ""; + private String importUrl = ""; + private String userAgent = ""; + private boolean senderAllesLaden = false; + private boolean updateFilmliste = true; + private String pfad = ""; + private Daten daten; + private boolean serverLaufen = false; + private File logfile = null; + + public MediathekNoGui(String ppfad, boolean ssenderAllesLaden, boolean uupdateFilmliste, String ooutput, String iimprtUrl, String uuserAgent, File log, boolean ddebug) { + // NUR für den Start vom MediathekServer + pfad = ppfad; + senderAllesLaden = ssenderAllesLaden; + updateFilmliste = uupdateFilmliste; + output = ooutput; + importUrl = iimprtUrl; + userAgent = uuserAgent; + logfile = log; + serverLaufen = true; + if (ddebug) { + Daten.debug = ddebug; + } + } + + public MediathekNoGui(String[] ar) { + if (ar != null) { + if (ar.length > 0) { + if (!ar[0].startsWith("-")) { + if (!ar[0].endsWith(File.separator)) { + ar[0] += File.separator; + } + pfad = ar[0]; + } + } + for (int i = 0; i < ar.length; ++i) { + if (ar[i].equals(Main.STARTP_ALLES)) { + senderAllesLaden = true; + updateFilmliste = false; + } + if (ar[i].equalsIgnoreCase(Main.STARTP_EXPORT_DATEI)) { + if (ar.length > i) { + output = ar[i + 1]; + } + } + if (ar[i].equalsIgnoreCase(Main.STARTP_IMPORT_URL)) { + if (ar.length > i) { + importUrl = ar[i + 1]; + } + } + if (ar[i].equalsIgnoreCase(Main.STARTP_USER_AGENT)) { + if (ar.length > i) { + userAgent = ar[i + 1]; + } + } + } + } + } + + public synchronized void init(String[] sender) { + // für den MediathekServer zum Starten + daten = new Daten(pfad); + Daten.nogui = true; + if (Daten.debug) { + Log.systemMeldung("Debug on"); + } + if (!userAgent.equals("")) { + Daten.setUserAgentManuel(userAgent); + } + if (senderAllesLaden) { + Log.systemMeldung("Filme laden: alles laden"); + } else { + Log.systemMeldung("Filme laden: nur update laden"); + } + if (updateFilmliste) { + Log.systemMeldung("Filmliste: aktualisieren"); + } else { + Log.systemMeldung("Filmliste: neue erstellen"); + } + if (logfile != null) { + Log.setLogFile(logfile); + } + Log.systemMeldung("ImportUrl: " + importUrl); + Log.systemMeldung("Outputfile: " + output); + Log.systemMeldung(""); + Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig(ListenerFilmeLadenEvent event) { + serverLaufen = false; + } + }); + // laden was es schon gibt + Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); + // das eigentliche Suchen der Filme bei den Sendern starten + if (sender == null) { + Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); + } else { + Daten.filmeLaden.updateSender(sender, Daten.listeFilme, senderAllesLaden); + } + } + + @Override + public synchronized void run() { + // für den MediathekServer zum Warten aufs Ende + try { + while (serverLaufen) { + this.wait(5000); + } + } catch (Exception ex) { + Log.fehlerMeldung(965451236, Log.FEHLER_ART_NOGUI, MediathekNoGui.class.getName(), "ServerStarten"); + } + undTschuess(false /* exit */); + } + + public void stoppen() { + // für den MediathekServer zum Stroppen/Unerbrechen + Daten.filmeLaden.setStop(); + } + + public void starten() { + daten = new Daten(pfad); + Daten.nogui = true; + if (!userAgent.equals("")) { + Daten.setUserAgentManuel(userAgent); + } + // Infos schreiben + Log.startMeldungen(this.getClass().getName()); + if (senderAllesLaden) { + Log.systemMeldung("Programmstart: alles laden"); + } else { + Log.systemMeldung("Programmstart: nur update laden"); + } + Log.systemMeldung("ImportUrl: " + importUrl); + Log.systemMeldung("Outputfile: " + output); + Log.systemMeldung(""); + Log.systemMeldung(""); + Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig(ListenerFilmeLadenEvent event) { + undTschuess(true /* exit */); + } + }); + // laden was es schon gibt + Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); + // das eigentliche Suchen der Filme bei den Sendern starten + Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); + } + + private void addImportListe(String url) { + if (!url.equals("")) { + Log.systemMeldung("Filmliste importieren von: " + url); + ListeFilme tmpListe = new ListeFilme(); + Daten.ioXmlFilmlisteLesen.filmlisteLesen(url, GuiFunktionen.istUrl(url) /* istUrl */, tmpListe); + Daten.listeFilme.updateListe(tmpListe, false /* nur URL vergleichen */); + tmpListe.clear(); + } + } + + private void undTschuess(boolean exit) { + if (!importUrl.equals("")) { + // wenn eine ImportUrl angegeben, dann noch eine Liste importieren + addImportListe(importUrl); + } + new IoXmlFilmlisteSchreiben().filmeSchreiben(Daten.getBasisVerzeichnis(true) + Konstanten.XML_DATEI_FILME, Daten.listeFilme); + if (!output.equals("")) { + LinkedList out = new LinkedList(); + String tmp; + do { + if (output.startsWith(",")) { + output = output.substring(1); + } + if (output.contains(",")) { + tmp = output.substring(0, output.indexOf(",")); + output = output.substring(output.indexOf(",")); + out.add(tmp); + } else { + out.add(output); + } + } while (output.contains(",")); + Iterator it = out.iterator(); + while (it.hasNext()) { + //datei schreiben + new IoXmlFilmlisteSchreiben().filmeSchreiben(it.next(), Daten.listeFilme); + } + } + Log.printEndeMeldung(); + if (exit) { + // nur dann das Programm beenden + if (Daten.listeFilme.isEmpty()) { + //Satz mit x, war wohl nix + System.exit(1); + } else { + System.exit(0); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `mediathek.MediathekNoGui.starten` reads without synchronization from `daten.Daten.mediathek.daten.Daten.ioXmlFilmlisteLesen`. Potentially races with write in method `MediathekNoGui.init(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MediathekNoGui.starten() + +### Procedure Id: +mediathek.MediathekNoGui.starten():void.7e883e72d9a21d316edba27b85aa617d + +### File: +src/mediathek/MediathekNoGui.java + +### Key: +MediathekNoGui.java|starten|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e940da0fae9c6552441a01babb26b673 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8964/instruction.md b/inferredbugs-8964/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fcc57c6a74b5f17357837f6b7189eb2c798f30bb --- /dev/null +++ b/inferredbugs-8964/instruction.md @@ -0,0 +1,377 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 41 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek.controller.io; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.SocketAddress; +import java.net.URL; +import java.net.URLConnection; +import java.util.Iterator; +import java.util.LinkedList; +import mediathek.daten.Daten; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; + +public class GetUrl { + + public static final int LISTE_SEITEN_ZAEHLER = 1; + public static final int LISTE_SEITEN_ZAEHLER_FEHlER = 2; + public static final int LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE = 3; + public static final int LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE = 4; + public static final int LISTE_SUMME_BYTE = 5; + private static final long UrlWartenBasis = 500;//ms, Basiswert zu dem dann der Faktor multipliziert wird + private int faktorWarten = 1; + private int timeout = 10000; + private long wartenBasis = UrlWartenBasis; + private static LinkedList listeSeitenZaehler = new LinkedList(); + private static LinkedList listeSeitenZaehlerFehler = new LinkedList(); + private static LinkedList listeSeitenZaehlerFehlerVersuche = new LinkedList(); + private static LinkedList listeSeitenZaehlerWartezeitFehlerVersuche = new LinkedList(); // Wartezeit für Wiederholungen [s] + private static LinkedList listeSummeByte = new LinkedList(); // Summe Daten in Byte für jeden Sender + + private class Seitenzaehler { + + String senderName = ""; + long seitenAnzahl = 0; + + public Seitenzaehler(String ssenderName) { + senderName = ssenderName; + seitenAnzahl = 1; + } + + public Seitenzaehler(String ssenderName, int sseitenAnzahl) { + senderName = ssenderName; + seitenAnzahl = sseitenAnzahl; + } + } + + public GetUrl(long wwartenBasis) { + wartenBasis = wwartenBasis; + } + + //=================================== + // public + //=================================== + public StringBuffer getUri_Utf(String sender, String addr, StringBuffer seite, String meldung) { + return getUri(sender, addr, Konstanten.KODIERUNG_UTF, 1 /* versuche */, seite, meldung); + } + + public StringBuffer getUri_Iso(String sender, String addr, StringBuffer seite, String meldung) { + return getUri(sender, addr, Konstanten.KODIERUNG_ISO15, 1 /* versuche */, seite, meldung); + } + + public synchronized StringBuffer getUri(String sender, String addr, String kodierung, int maxVersuche, StringBuffer seite, String meldung) { + final int PAUSE = 1000; +// int aktTimeout = (maxVersuche > 1) ? timeout / 2 : timeout; // wenns mehrere Versuche gibt, dann der erste mit verkürztem Timeout + int aktTimeout = timeout; + int aktVer = 0; + int wartezeit; + boolean letzterVersuch; + do { + ++aktVer; + try { +// if (aktVer >= maxVersuche) { +// // der letzte Versuch mit dem vollen Timeout +// aktTimeout = timeout; +// } + if (aktVer > 1) { + // und noch eine Pause vor dem nächsten Versuch + this.wait(PAUSE); + } + letzterVersuch = (aktVer >= maxVersuche) ? true : false; + seite = getUri(sender, addr, seite, kodierung, aktTimeout, meldung, maxVersuche, letzterVersuch); + if (seite.length() > 0) { + // und nix wie weiter + if (Daten.debug && aktVer > 1) { + String text = sender + " [" + aktVer + "/" + maxVersuche + "] ~~~> " + addr; + Log.systemMeldung(text); + } + // nur dann zählen + incSeitenZaehler(LISTE_SEITEN_ZAEHLER, sender, 1); + return seite; + } else { + // hat nicht geklappt + if (aktVer > 1) { + wartezeit = (aktTimeout + PAUSE); + } else { + wartezeit = (aktTimeout); + } + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE, sender, wartezeit / 1000); + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE, sender, 1); + if (letzterVersuch) { + // dann wars leider nichts + incSeitenZaehler(LISTE_SEITEN_ZAEHLER_FEHlER, sender, 1); + } + } + } catch (Exception ex) { + Log.fehlerMeldung(698963200, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); + } + } while (!Daten.filmeLaden.getStop() && aktVer < maxVersuche); + return seite; + } + + public synchronized void getDummy(String sender) { + // Dummy zum hochzählen des Seitenzählers + incSeitenZaehler(LISTE_SEITEN_ZAEHLER, sender, 1); + } + + public void setTimeout(int ttimeout) { + timeout = ttimeout; + } + + public int getTimeout() { + return timeout; + } + + public static long getSeitenZaehler(int art, String sender) { + long ret = 0; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + Seitenzaehler sz; + while (it.hasNext()) { + sz = it.next(); + if (sz.senderName.equals(sender)) { + ret = sz.seitenAnzahl; + } + } + if (art == LISTE_SUMME_BYTE) { + // Byte in MByte + ret = ret / 1024 / 1024; + } + return ret; + } + + public static synchronized long getSeitenZaehler(int art) { + long ret = 0; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + while (it.hasNext()) { + ret += it.next().seitenAnzahl; + } + if (art == LISTE_SUMME_BYTE) { + // Byte in MByte + ret = ret / 1024 / 1024; + } + return ret; + } + + public static synchronized void resetZaehler() { + listeSeitenZaehler.clear(); + listeSeitenZaehlerFehler.clear(); + listeSeitenZaehlerFehlerVersuche.clear(); + listeSeitenZaehlerWartezeitFehlerVersuche.clear(); + listeSummeByte.clear(); + } + + //=================================== + // private + //=================================== + private static LinkedList getListe(int art) { + switch (art) { + case LISTE_SEITEN_ZAEHLER: + return listeSeitenZaehler; + case LISTE_SEITEN_ZAEHLER_FEHLERVERSUCHE: + return listeSeitenZaehlerFehlerVersuche; + case LISTE_SEITEN_ZAEHLER_FEHlER: + return listeSeitenZaehlerFehler; + case LISTE_SEITEN_ZAEHLER_WARTEZEIT_FEHLVERSUCHE: + return listeSeitenZaehlerWartezeitFehlerVersuche; + case LISTE_SUMME_BYTE: + return listeSummeByte; + default: + return null; + } + } + + private synchronized void incSeitenZaehler(int art, String sender, int inc) { + boolean gefunden = false; + LinkedList liste = getListe(art); + Iterator it = liste.iterator(); + Seitenzaehler sz; + while (it.hasNext()) { + sz = it.next(); + if (sz.senderName.equals(sender)) { + sz.seitenAnzahl += inc; + gefunden = true; + break; + } + } + if (!gefunden) { + liste.add(new Seitenzaehler(sender, inc)); + } + } + + private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) { + int timeo = timeout; + boolean proxyB = false; + char[] zeichen = new char[1]; + seite.setLength(0); + URLConnection conn; + int code = 0; + InputStream in = null; + InputStreamReader inReader = null; + Proxy proxy = null; + SocketAddress saddr = null; + // immer etwas bremsen + try { + long w = wartenBasis * faktorWarten; + this.wait(w); + } catch (Exception ex) { + Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); + } + try { + URL url = new URL(addr); + // conn = url.openConnection(Proxy.NO_PROXY); + conn = url.openConnection(); + conn.setRequestProperty("User-Agent", Daten.getUserAgent()); + if (timeout > 0) { + conn.setReadTimeout(timeout); + conn.setConnectTimeout(timeout); + } + if (conn instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection) conn; + code = httpConnection.getResponseCode(); +// if (code >= 400) { +// if (true) { +// // wenn möglich, einen Proxy einrichten +// Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---"); +// proxyB = true; +// saddr = new InetSocketAddress("localhost", 9050); +// proxy = new Proxy(Proxy.Type.SOCKS, saddr); +// conn = url.openConnection(proxy); +// conn.setRequestProperty("User-Agent", Daten.getUserAgent()); +// if (timeout > 0) { +// conn.setReadTimeout(timeout); +// conn.setConnectTimeout(timeout); +// } +// } else { +// Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400"); +// } +// } + } else { + Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon"); + } + in = conn.getInputStream(); + inReader = new InputStreamReader(in, kodierung); + while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) { + seite.append(zeichen); + incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1); + } + } catch (IOException ex) { + if (lVersuch) { + String[] text; + if (meldung.equals("")) { + text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/}; + } else { + text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/}; + } + Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text); + } + } catch (Exception ex) { + Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, ""); + } finally { + try { + if (in != null) { + inReader.close(); + } + } catch (IOException ex) { + } + } + return seite; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `inReader` last assigned on line 233 could be null and is dereferenced at line 296. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +StringBuffer GetUrl.getUri(String,String,StringBuffer,String,int,String,int,boolean) + +### Procedure Id: +mediathek.controller.io.GetUrl.getUri(java.lang.String,java.lang.String,java.lang.StringBuffer,java..132bd5d2f6152705ad5fe590013f92d5 + +### File: +src/mediathek/controller/io/GetUrl.java + +### Key: +GetUrl.java|getUri|NULL_DEREFERENCE + +### Node Key: +44599c87e83680e0a6bc09b4cb3a71a9 + +### Hash: +f91fecc3ba366f8f5b27abcd41c283a9 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8965/instruction.md b/inferredbugs-8965/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..307aff48cda22ba4751936e45165942ed32e938e --- /dev/null +++ b/inferredbugs-8965/instruction.md @@ -0,0 +1,341 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** MediathekView +**Bug ID:** 48 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * MediathekView + * Copyright (C) 2008 W. Xaver + * W.Xaver[at]googlemail.com + * http://zdfmediathk.sourceforge.net/ + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +package mediathek; + +import java.io.File; +import java.util.Iterator; +import java.util.LinkedList; +import mediathek.controller.filmeLaden.ListenerFilmeLaden; +import mediathek.controller.filmeLaden.ListenerFilmeLadenEvent; +import mediathek.controller.io.IoXmlFilmlisteLesen; +import mediathek.controller.io.IoXmlFilmlisteSchreiben; +import mediathek.daten.Daten; +import mediathek.daten.ListeFilme; +import mediathek.tool.GuiFunktionen; +import mediathek.tool.Konstanten; +import mediathek.tool.Log; + +public class MediathekNoGui implements Runnable { + + private String output = ""; + private String importUrl = ""; + private String userAgent = ""; + private boolean senderAllesLaden = false; + private boolean updateFilmliste = true; + private String pfad = ""; + private Daten daten; + private boolean serverLaufen = false; + private File logfile = null; + private String senderLoeschen = ""; + + public MediathekNoGui(String ppfad, boolean ssenderAllesLaden, boolean uupdateFilmliste, String ooutput, String iimprtUrl, String uuserAgent, File log, boolean ddebug) { + // NUR für den Start vom MediathekServer + pfad = ppfad; + senderAllesLaden = ssenderAllesLaden; + updateFilmliste = uupdateFilmliste; + output = ooutput; + importUrl = iimprtUrl; + userAgent = uuserAgent; + logfile = log; + serverLaufen = true; + if (ddebug) { + Daten.debug = ddebug; + } + } + + public MediathekNoGui(String[] ar) { + if (ar != null) { + if (ar.length > 0) { + if (!ar[0].startsWith("-")) { + if (!ar[0].endsWith(File.separator)) { + ar[0] += File.separator; + } + pfad = ar[0]; + } + } + for (int i = 0; i < ar.length; ++i) { + if (ar[i].equals(Main.STARTP_ALLES)) { + senderAllesLaden = true; + updateFilmliste = false; + } + if (ar[i].equalsIgnoreCase(Main.STARTP_EXPORT_DATEI)) { + if (ar.length > i) { + output = ar[i + 1]; + } + } + if (ar[i].equalsIgnoreCase(Main.STARTP_IMPORT_URL)) { + if (ar.length > i) { + importUrl = ar[i + 1]; + } + } + if (ar[i].equalsIgnoreCase(Main.STARTP_USER_AGENT)) { + if (ar.length > i) { + userAgent = ar[i + 1]; + } + } + if (ar[i].equalsIgnoreCase(Main.STARTP_SENDER_LOESCHEN)) { + if (ar.length > i) { + senderLoeschen = ar[i + 1]; + } + } + } + } + } + + public synchronized void init(String[] sender) { + // für den MediathekServer zum Starten + daten = new Daten(pfad); + Daten.nogui = true; + if (Daten.debug) { + Log.systemMeldung("Debug on"); + } + if (!userAgent.equals("")) { + Daten.setUserAgentManuel(userAgent); + } + if (senderAllesLaden) { + Log.systemMeldung("Filme laden: alles laden"); + } else { + Log.systemMeldung("Filme laden: nur update laden"); + } + if (updateFilmliste) { + Log.systemMeldung("Filmliste: aktualisieren"); + } else { + Log.systemMeldung("Filmliste: neue erstellen"); + } + if (logfile != null) { + Log.setLogFile(logfile); + } + Log.systemMeldung("ImportUrl: " + importUrl); + Log.systemMeldung("Outputfile: " + output); + Log.systemMeldung(""); + Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig(ListenerFilmeLadenEvent event) { + serverLaufen = false; + } + }); + // laden was es schon gibt + //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); + new IoXmlFilmlisteLesen().standardFilmlisteLesen(); + // das eigentliche Suchen der Filme bei den Sendern starten + if (sender == null) { + Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); + } else { + Daten.filmeLaden.updateSender(sender, Daten.listeFilme, senderAllesLaden); + } + } + + @Override + public synchronized void run() { + // für den MediathekServer zum Warten aufs Ende + try { + while (serverLaufen) { + this.wait(5000); + } + } catch (Exception ex) { + Log.fehlerMeldung(965451236, Log.FEHLER_ART_NOGUI, MediathekNoGui.class.getName(), "ServerStarten"); + } + undTschuess(false /* exit */); + } + + public void stoppen() { + // für den MediathekServer zum Stroppen/Unerbrechen + Daten.filmeLaden.setStop(); + } + + public void starten() { + daten = new Daten(pfad); + Daten.nogui = true; + if (!userAgent.equals("")) { + Daten.setUserAgentManuel(userAgent); + } + // Infos schreiben + Log.startMeldungen(this.getClass().getName()); + if (senderAllesLaden) { + Log.systemMeldung("Programmstart: alles laden"); + } else { + Log.systemMeldung("Programmstart: nur update laden"); + } + Log.systemMeldung("ImportUrl: " + importUrl); + Log.systemMeldung("Outputfile: " + output); + Log.systemMeldung(""); + Log.systemMeldung(""); + Daten.filmeLaden.addAdListener(new ListenerFilmeLaden() { + @Override + public void fertig(ListenerFilmeLadenEvent event) { + undTschuess(true /* exit */); + } + }); + // laden was es schon gibt + //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); + new IoXmlFilmlisteLesen().standardFilmlisteLesen(); + if (!senderLoeschen.isEmpty()) { + senderLoeschenUndExit(); + } else { + // das eigentliche Suchen der Filme bei den Sendern starten + Daten.filmeLaden.filmeBeimSenderSuchen(Daten.listeFilme, senderAllesLaden, updateFilmliste); + } + } + + private void addImportListe(String url) { + if (!url.equals("")) { + Log.systemMeldung("Filmliste importieren von: " + url); + ListeFilme tmpListe = new ListeFilme(); + new IoXmlFilmlisteLesen().dateiInListeEinlesen(url, GuiFunktionen.istUrl(url) /* istUrl */, tmpListe); + Daten.listeFilme.updateListe(tmpListe, false /* nur URL vergleichen */); + tmpListe.clear(); + } + } + + public void senderLoeschenUndExit() { + daten = new Daten(pfad); + Daten.nogui = true; + // Infos schreiben + Log.startMeldungen(this.getClass().getName()); + Log.systemMeldung(""); + Log.systemMeldung(""); + //Daten.ioXmlFilmlisteLesen.filmlisteLesen(Daten.getBasisVerzeichnis() + Konstanten.XML_DATEI_FILME, false /* istUrl */, Daten.listeFilme); + new IoXmlFilmlisteLesen().standardFilmlisteLesen(); + // dann nur einen Sender löschen und dann wieder beenden + Log.systemMeldung("Sender: " + senderLoeschen + " löschen"); + int anz1 = Daten.listeFilme.size(); + Log.systemMeldung("Anzehl Filme vorher: " + anz1); + Daten.listeFilme.delSender(senderLoeschen); + int anz2 = Daten.listeFilme.size(); + Log.systemMeldung("Anzehl Filme nachher: " + anz2); + Log.systemMeldung(" --> gelöscht: " + (anz1 - anz2)); + new IoXmlFilmlisteSchreiben().filmeSchreiben(Daten.getBasisVerzeichnis(true) + Konstanten.XML_DATEI_FILME, Daten.listeFilme); + System.exit(0); + } + + private void undTschuess(boolean exit) { + if (!importUrl.equals("")) { + // wenn eine ImportUrl angegeben, dann noch eine Liste importieren + addImportListe(importUrl); + } + new IoXmlFilmlisteSchreiben().filmeSchreiben(Daten.getBasisVerzeichnis(true) + Konstanten.XML_DATEI_FILME, Daten.listeFilme); + if (!output.equals("")) { + LinkedList out = new LinkedList(); + String tmp; + do { + if (output.startsWith(",")) { + output = output.substring(1); + } + if (output.contains(",")) { + tmp = output.substring(0, output.indexOf(",")); + output = output.substring(output.indexOf(",")); + out.add(tmp); + } else { + out.add(output); + } + } while (output.contains(",")); + Iterator it = out.iterator(); + while (it.hasNext()) { + //datei schreiben + new IoXmlFilmlisteSchreiben().filmeSchreiben(it.next(), Daten.listeFilme); + } + } + Log.printEndeMeldung(); + if (exit) { + // nur dann das Programm beenden + if (Daten.listeFilme.isEmpty()) { + //Satz mit x, war wohl nix + System.exit(1); + } else { + System.exit(0); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `mediathek.MediathekNoGui.starten` indirectly writes to field `daten.Daten.mediathek.daten.Daten.filmeLaden` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MediathekNoGui.starten() + +### Procedure Id: +mediathek.MediathekNoGui.starten():void.7e883e72d9a21d316edba27b85aa617d + +### File: +src/mediathek/MediathekNoGui.java + +### Key: +MediathekNoGui.java|starten|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6d3be0425e8f30d205f96f3623bd7987 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8991/instruction.md b/inferredbugs-8991/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..31f93962d4e70c472ce9b7872e5fbfaa377e29bd --- /dev/null +++ b/inferredbugs-8991/instruction.md @@ -0,0 +1,118 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nextrtc-signaling-server +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nextrtc.signalingserver.domain; + +import lombok.extern.log4j.Log4j; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import javax.websocket.RemoteEndpoint; +import javax.websocket.Session; + +@Component +@Scope("singleton") +@Log4j +public class DefaultMessageSender implements MessageSender { + + @Override + public void send(InternalMessage message) { + send(message, 3); + } + + private void send(InternalMessage message, int retry) { + Message messageToSend = message.transformToExternalMessage(); + if (message.getSignal() != Signal.PING) { + log.info("Outgoing: " + toString()); + } + Session destSession = message.getTo().getSession(); + if (!destSession.isOpen()) { + log.warn("Session is closed! Message will not be send: "); + return; + } + try { + RemoteEndpoint.Basic basic = destSession.getBasicRemote(); + synchronized (basic) { + basic.sendObject(messageToSend); + } + } catch (Exception e) { + if (retry >= 0) { + log.info("Retrying... " + messageToSend); + send(message, --retry); + } + log.error("Unable to send message: " + messageToSend + " error during sending!"); + throw new RuntimeException("Unable to send message: " + messageToSend, e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `message.getTo()` could be null and is dereferenced at line 25. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultMessageSender.send(InternalMessage,int) + +### Procedure Id: +org.nextrtc.signalingserver.domain.DefaultMessageSender.send(org.nextrtc.signalingserver.domain.Inte.77a7e39a87d13ebb6d0f6f223809bf10 + +### File: +src/main/java/org/nextrtc/signalingserver/domain/DefaultMessageSender.java + +### Key: +DefaultMessageSender.java|send|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +871eac6435f1470c04e4aa9510200683 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8996/instruction.md b/inferredbugs-8996/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb612229b813728b9542ff840df450268c3c1b81 --- /dev/null +++ b/inferredbugs-8996/instruction.md @@ -0,0 +1,202 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nextrtc-signaling-server +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nextrtc.signalingserver.domain; + +import lombok.extern.log4j.Log4j; +import org.apache.commons.lang3.tuple.Pair; +import org.nextrtc.signalingserver.api.NextRTCEventBus; +import org.nextrtc.signalingserver.cases.RegisterMember; +import org.nextrtc.signalingserver.cases.SignalHandler; +import org.nextrtc.signalingserver.domain.InternalMessage.InternalMessageBuilder; +import org.nextrtc.signalingserver.exception.SignalingException; +import org.nextrtc.signalingserver.repository.MemberRepository; +import org.springframework.stereotype.Component; + +import javax.inject.Inject; +import javax.websocket.CloseReason; +import javax.websocket.Session; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.function.Consumer; + +import static org.nextrtc.signalingserver.api.NextRTCEvents.SESSION_CLOSED; +import static org.nextrtc.signalingserver.api.NextRTCEvents.UNEXPECTED_SITUATION; +import static org.nextrtc.signalingserver.exception.Exceptions.MEMBER_NOT_FOUND; + +@Log4j +@Component +public class Server { + + private NextRTCEventBus eventBus; + private MemberRepository members; + private SignalResolver resolver; + private RegisterMember register; + + @Inject + public Server(NextRTCEventBus eventBus, + MemberRepository members, + SignalResolver resolver, + RegisterMember register) { + this.eventBus = eventBus; + this.members = members; + this.resolver = resolver; + this.register = register; + } + + public void register(Session s) { + doSaveExecution(s, session -> + register.incoming(session) + ); + } + + public void handle(Message external, Session s) { + doSaveExecution(s, session -> { + Pair resolve = resolver.resolve(external.getSignal()); + InternalMessage internalMessage = buildInternalMessage(external, resolve.getKey(), session); + processMessage(resolve.getValue(), internalMessage); + }); + } + + private void processMessage(SignalHandler handler, InternalMessage message) { + log.info("Incoming: " + message); + if (handler != null) { + handler.execute(message); + } + } + + private InternalMessage buildInternalMessage(Message message, Signal signal, Session session) { + InternalMessageBuilder bld = InternalMessage.create()// + .from(findMember(session))// + .content(message.getContent())// + .signal(signal)// + .custom(message.getCustom()); + members.findBy(message.getTo()).ifPresent(bld::to); + return bld.build(); + } + + private Member findMember(Session session) { + return members.findBy(session.getId()).orElseThrow(() -> new SignalingException(MEMBER_NOT_FOUND)); + } + + public void unregister(Session s, CloseReason reason) { + doSaveExecution(s, session -> { + members.unregister(session.getId()); + eventBus.post(SESSION_CLOSED.occurFor(session, reason.getReasonPhrase())); + } + ); + } + + + public void handleError(Session s, Throwable exception) { + doSaveExecution(new SessionWrapper(s), session -> { + members.unregister(session.getId()); + eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage())); + } + ); + } + + private void doSaveExecution(Session session, Consumer action) { + try { + action.accept(session); + } catch (Exception e) { + log.warn("Server will try to handle this exception and send information as normal message through websocket", e); + sendErrorOverWebSocket(session, e); + } + } + + private void sendErrorOverWebSocket(Session session, Exception e) { + try { + InternalMessage.create() + .to(new Member(session, null)) + .signal(Signal.ERROR) + .content(e.getMessage()) + .addCustom("stackTrace", writeStackTraceToString(e)) + .build() + .send(); + } catch (Exception resendException) { + log.error("Something goes wrong during resend! Exception omitted", resendException); + } + } + + private String writeStackTraceToString(Exception e) { + if (log.isDebugEnabled()) { + StringWriter errors = new StringWriter(); + e.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + } + return e.getClass().getSimpleName() + " - " + e.getMessage(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.nextrtc.signalingserver.domain.SessionWrapper` acquired by call to `new()` at line 89 is not released after line 89. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Server.handleError(Session,Throwable) + +### Procedure Id: +org.nextrtc.signalingserver.domain.Server.handleError(javax.websocket.Session,java.lang.Throwable):v.6e2e2badd07b4f595e8e9ebb2c4f6e58 + +### File: +src/main/java/org/nextrtc/signalingserver/domain/Server.java + +### Key: +Server.java|handleError|RESOURCE_LEAK + +### Node Key: +347fa73353724c6492972600ff422a93 + +### Hash: +cd157388ba28df157d322f060d3fbdea + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8997/instruction.md b/inferredbugs-8997/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d772ed4274684e2caaaaafedd9805d68aae40ce --- /dev/null +++ b/inferredbugs-8997/instruction.md @@ -0,0 +1,356 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** fw-cloud-framework +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.liuweijw.business.admin.service.impl; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import com.github.liuweijw.business.admin.beans.UserBean; +import com.github.liuweijw.business.admin.beans.UserForm; +import com.github.liuweijw.business.admin.cache.AdminCacheKey; +import com.github.liuweijw.business.admin.domain.QRole; +import com.github.liuweijw.business.admin.domain.QUser; +import com.github.liuweijw.business.admin.domain.QUserRole; +import com.github.liuweijw.business.admin.domain.Role; +import com.github.liuweijw.business.admin.domain.User; +import com.github.liuweijw.business.admin.domain.UserRole; +import com.github.liuweijw.business.admin.repository.UserRepository; +import com.github.liuweijw.business.admin.repository.UserRoleRepository; +import com.github.liuweijw.business.admin.service.PermissionService; +import com.github.liuweijw.business.admin.service.UserService; +import com.github.liuweijw.business.commons.beans.PageBean; +import com.github.liuweijw.business.commons.beans.PageParams; +import com.github.liuweijw.business.commons.web.jpa.JPAFactoryImpl; +import com.github.liuweijw.core.beans.system.AuthRole; +import com.github.liuweijw.core.beans.system.AuthUser; +import com.github.liuweijw.core.commons.constants.SecurityConstant; +import com.github.liuweijw.core.utils.StringHelper; +import com.querydsl.core.types.Predicate; + +@Component +public class UserServiceImpl extends JPAFactoryImpl implements UserService { + + @Autowired + private UserRepository userRepository; + + @SuppressWarnings("rawtypes") + @Autowired + private RedisTemplate redisTemplate; + + @Autowired + private PermissionService permissionService; + + @Autowired + private UserRoleRepository userRoleRepository; + + @Override + @Cacheable(value = AdminCacheKey.USER_INFO, key = "'user_' + #username") + public AuthUser findUserByUsername(String username) { + User user = findUserByUsername(username, true); + + return buildAuthUserByUser(user); + } + + @Override + public User findUserByUsername(String username, boolean isLoadRole) { + + if (StringHelper.isBlank(username)) return null; + + User user = userRepository.findUserByUsername(username.trim()); + if (null == user) return null; + + if (isLoadRole) user.setRoleList(findRoleListByUserId(user.getUserId())); + + return user; + } + + @Override + @Cacheable(value = AdminCacheKey.USER_INFO, key = "'user_' + #mobile") + public AuthUser findUserByMobile(String mobile) { + User user = userRepository.findUserByMobile(mobile.trim()); + if (null == user) return null; + + user.setRoleList(findRoleListByUserId(user.getUserId())); + + return buildAuthUserByUser(user); + } + + public List findRoleListByUserId(Integer userId) { + if (null == userId) return null; + + // load role + QUserRole qUserRole = QUserRole.userRole; + QRole qRole = QRole.role; + List rList = this.queryFactory.select(qRole).from(qUserRole, qRole).where( + qUserRole.userId.eq(userId)).where(qUserRole.roleId.eq(qRole.roleId)).fetch(); + + return rList; + } + + @Override + @SuppressWarnings("unchecked") + public void saveImageCode(String randomStr, String imageCode) { + redisTemplate.opsForValue().set(SecurityConstant.DEFAULT_CODE_KEY + randomStr, imageCode, + SecurityConstant.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS); + } + + @Override + public UserBean findUserInfo(AuthUser user) { + User dbUser = findUserByUsername(user.getUsername(), false); + + UserBean userInfo = new UserBean(); + // 过滤关键信息 + dbUser.setPassword(""); + dbUser.setCreateTime(null); + dbUser.setUpdateTime(null); + userInfo.setUser(dbUser); + + // 设置角色列表 + List roleList = user.getRoleList(); + List roleCodes = new ArrayList<>(); + + roleList.stream().forEach(r -> { + roleCodes.add(r.getRoleCode()); + }); + + String[] roles = roleCodes.toArray(new String[roleCodes.size()]); + + userInfo.setRoles(roles); + + // 设置权限列表(menu.permission) + Set permissions = new HashSet(); + for (String roleCode : roles) { + permissions.addAll(permissionService.findMenuPermissions(roleCode)); + } + + userInfo.setPermissions(permissions.toArray(new String[permissions.size()])); + + return userInfo; + } + + @Override + @Cacheable(value = AdminCacheKey.USER_INFO, key = "'user_' + #userId") + public AuthUser findByUserId(String userId) { + User user = userRepository.findUserByUserId(Integer.valueOf(userId)); + if (null == user) return null; + + user.setRoleList(findRoleListByUserId(user.getUserId())); + + return buildAuthUserByUser(user); + } + + private AuthUser buildAuthUserByUser(User user) { + if (null == user) return null; + + AuthUser authUser = new AuthUser(); + authUser.setPicUrl(user.getPicUrl()); + authUser.setStatu(user.getStatu()); + authUser.setPassword(user.getPassword()); + authUser.setUserId(user.getUserId()); + authUser.setUsername(user.getUsername()); + + if (null == user.getRoleList() || user.getRoleList().size() == 0) return authUser; + List rList = new ArrayList(); + for (Role r : user.getRoleList()) { + AuthRole aRole = new AuthRole(); + aRole.setStatu(r.getStatu()); + aRole.setRoleCode(r.getRoleCode()); + aRole.setRoleDesc(r.getRoleDesc()); + aRole.setRoleId(r.getRoleId()); + aRole.setRoleName(r.getRoleName()); + rList.add(aRole); + } + authUser.setRoleList(rList); + + return authUser; + } + + @Override + public PageBean findAll(PageParams pageParams, User user) { + QUser qUser = QUser.user; + // 用户名查询条件 + Predicate qUserNamePredicate = null; + if (null != user && StringHelper.isNotBlank(user.getUsername())) { + qUserNamePredicate = qUser.username.like("%" + user.getUsername().trim() + "%"); + } + + Predicate predicate = qUser.statu.eq(0).and(qUserNamePredicate); + + Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "createTime")); + PageRequest pageRequest = new PageRequest(pageParams.getCurrentPage(), pageParams + .getPageSize(), sort); + Page pageList = userRepository.findAll(predicate, pageRequest); + + if (null != pageList && null != pageList.getContent()) { + for (User dbUser : pageList.getContent()) { + dbUser.setRoleList(findRoleListByUserId(dbUser.getUserId())); + } + } + + PageBean pageData = new PageBean(); + pageData.setCurrentPage(pageParams.getCurrentPage()); + pageData.setPageSize(pageParams.getPageSize()); + pageData.setTotal(pageList.getTotalElements()); + pageData.setList(pageList.getContent()); + + return pageData; + } + + @Override + @Transactional + public Boolean delByUserId(Integer userId) { + if (null == userId || userId <= 0) return Boolean.FALSE; + + QUser qUser = QUser.user; + long num = this.queryFactory.update(qUser).set(qUser.statu, 1) // 0 正常 1删除 + .where(qUser.userId.eq(userId.intValue())).execute(); + + this.redisCacheClear(); + return num > 0; + } + + @Override + @Transactional + public boolean addUserAndRole(User user, Integer roleId) { + + User dbUser = this.userRepository.saveAndFlush(user); + + UserRole uRole = new UserRole(); + uRole.setRoleId(roleId); + uRole.setUserId(dbUser.getUserId()); + + this.userRoleRepository.saveAndFlush(uRole); + this.redisCacheClear(); + return true; + } + + @Override + @Transactional + public boolean updateUserAndRole(UserForm userForm) { + if (null == userForm.getUserId() || userForm.getUserId() <= 0) return Boolean.FALSE; + + User user = userRepository.findUserByUserId(userForm.getUserId()); + if (null == user) return false; + + user.setStatu(userForm.getStatu()); + user.setUpdateTime(new Date()); + user.setUserId(userForm.getUserId()); + user.setUsername(userForm.getUsername()); + userRepository.save(user); + + QUserRole qUserRole = QUserRole.userRole; + + this.queryFactory.delete(qUserRole).where(qUserRole.userId.eq(userForm.getUserId())) + .execute(); + + UserRole uRole = new UserRole(); + uRole.setRoleId(userForm.getRoleId()); + uRole.setUserId(userForm.getUserId()); + + this.userRoleRepository.saveAndFlush(uRole); + + this.redisCacheClear(); + return true; + } + + @Override + @Transactional + public boolean updateUser(User user) { + if (null == user || null == user.getUserId()) return false; + + this.userRepository.saveAndFlush(user); + + this.redisCacheClear(); + return true; + } + + @CacheEvict(value = { AdminCacheKey.USER_INFO }, allEntries = true) + public void redisCacheClear() { + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `pageList` last assigned on line 194 could be null and is dereferenced at line 205. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +PageBean UserServiceImpl.findAll(PageParams,User) + +### Procedure Id: +com.github.liuweijw.business.admin.service.impl.UserServiceImpl.findAll(com.github.liuweijw.business.1367f09491a45c507804296c98e0d325 + +### File: +fw-cloud-business/fw-cloud-business-admin/src/main/java/com/github/liuweijw/business/admin/service/impl/UserServiceImpl.java + +### Key: +UserServiceImpl.java|findAll|NULL_DEREFERENCE + +### Node Key: +5e001e54a11c8632051468f614c7e799 + +### Hash: +4023a11b439fadd7f6c99656b1a3b106 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8998/instruction.md b/inferredbugs-8998/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9657e5d476db4caee035db330670085ae1b706f9 --- /dev/null +++ b/inferredbugs-8998/instruction.md @@ -0,0 +1,682 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** swagger-maven-plugin +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.kongchen.swagger.docgen.reader; + +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.models.properties.StringProperty; +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.HEAD; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.OPTIONS; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; + +import org.apache.commons.lang3.StringUtils; +import org.apache.maven.plugin.logging.Log; +import org.reflections.Reflections; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.AnnotationUtils; + +import com.github.kongchen.swagger.docgen.jaxrs.BeanParamInjectParamExtension; +import com.github.kongchen.swagger.docgen.jaxrs.JaxrsParameterExtension; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; +import io.swagger.annotations.SwaggerDefinition; +import io.swagger.converter.ModelConverters; +import io.swagger.jaxrs.ext.SwaggerExtension; +import io.swagger.jaxrs.ext.SwaggerExtensions; +import io.swagger.jersey.SwaggerJerseyJaxrs; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.Response; +import io.swagger.models.SecurityRequirement; +import io.swagger.models.Swagger; +import io.swagger.models.Tag; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.parameters.RefParameter; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.refs.RefType; +import io.swagger.util.BaseReaderUtils; +import io.swagger.util.ReflectionUtils; + +public class JaxrsReader extends AbstractReader implements ClassSwaggerReader { + private static final Logger LOGGER = LoggerFactory.getLogger(JaxrsReader.class); + private static final ResponseContainerConverter RESPONSE_CONTAINER_CONVERTER = new ResponseContainerConverter(); + + public JaxrsReader(Swagger swagger, Log LOG) { + super(swagger, LOG); + } + + @Override + protected void updateExtensionChain() { + List extensions = new ArrayList<>(); + extensions.add(new BeanParamInjectParamExtension(this)); + extensions.add(new SwaggerJerseyJaxrs()); + extensions.add(new JaxrsParameterExtension()); + SwaggerExtensions.setExtensions(extensions); + } + + @Override + public Swagger read(Set> classes) { + for (Class cls : classes) { + read(cls); + } + return swagger; + } + + public Swagger getSwagger() { + return swagger; + } + + public Swagger read(Class cls) { + return read(cls, "", null, false, new String[0], new String[0], new HashMap(), new ArrayList()); + } + + protected Swagger read(Class cls, String parentPath, String parentMethod, boolean readHidden, String[] parentConsumes, + String[] parentProduces, Map parentTags, List parentParameters) { + if (swagger == null) { + swagger = new Swagger(); + } + Api api = AnnotationUtils.findAnnotation(cls, Api.class); + Path apiPath = AnnotationUtils.findAnnotation(cls, Path.class); + + // only read if allowing hidden apis OR api is not marked as hidden + if (!canReadApi(readHidden, api)) { + return swagger; + } + + Map tags = updateTagsForApi(parentTags, api); + List securities = getSecurityRequirements(api); + Map discoveredTags = scanClasspathForTags(); + + // merge consumes, produces + + readCommonParameters(cls); + + // look for method-level annotated properties + + // handle subresources by looking at return type + + // parse the method + List filteredMethods = getFilteredMethods(cls); + for (Method method : filteredMethods) { + ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); + if (apiOperation != null && apiOperation.hidden()) { + continue; + } + Path methodPath = AnnotationUtils.findAnnotation(method, Path.class); + + String parentPathValue = String.valueOf(parentPath); + //is method default handler within a subresource + if(apiPath == null && methodPath == null && parentPath != null && readHidden){ + final String updatedMethodPath = String.valueOf(parentPath); + Path path = new Path(){ + @Override + public String value(){ + return updatedMethodPath; + } + + @Override + public Class annotationType() { + return Path.class; + } + }; + methodPath = path; + parentPathValue = null; + } + String operationPath = getPath(apiPath, methodPath, parentPathValue); + if (operationPath != null) { + Map regexMap = new HashMap<>(); + operationPath = parseOperationPath(operationPath, regexMap); + + String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain()); + + Operation operation = parseMethod(httpMethod, method); + updateOperationParameters(parentParameters, regexMap, operation); + updateOperationProtocols(apiOperation, operation); + + String[] apiConsumes = new String[0]; + String[] apiProduces = new String[0]; + + Consumes consumes = AnnotationUtils.findAnnotation(cls, Consumes.class); + if (consumes != null) { + apiConsumes = consumes.value(); + } + Produces produces = AnnotationUtils.findAnnotation(cls, Produces.class); + if (produces != null) { + apiProduces = produces.value(); + } + + apiConsumes = updateOperationConsumes(parentConsumes, apiConsumes, operation); + apiProduces = updateOperationProduces(parentProduces, apiProduces, operation); + + handleSubResource(apiConsumes, httpMethod, apiProduces, tags, method, apiOperation, operationPath, operation); + + // can't continue without a valid http method + httpMethod = (httpMethod == null) ? parentMethod : httpMethod; + updateTagsForOperation(operation, apiOperation); + updateOperation(apiConsumes, apiProduces, tags, securities, operation); + updatePath(operationPath, httpMethod, operation); + } + updateTagDescriptions(discoveredTags); + } + + return swagger; + } + + private List getFilteredMethods(Class cls) { + Method[] methods = cls.getMethods(); + List filteredMethods = new ArrayList<>(); + for (Method method : methods) { + if (!method.isBridge()) { + filteredMethods.add(method); + } + } + return filteredMethods; + } + + /** + * Returns true when the swagger object already contains a common parameter + * with the same name and type as the passed parameter. + * + * @param parameter The parameter to check. + * @return true if the swagger object already contains a common parameter with the same name and type + */ + private boolean hasCommonParameter(Parameter parameter) { + Parameter commonParameter = swagger.getParameter(parameter.getName()); + return commonParameter != null && parameter.getIn().equals(commonParameter.getIn()); + } + + private void readCommonParameters(Class cls) { + Path path = AnnotationUtils.findAnnotation(cls, Path.class); + if (path != null) { + return; + } + + List filteredMethods = getFilteredMethods(cls); + for (Method method : filteredMethods) { + path = AnnotationUtils.findAnnotation(method, Path.class); + if (path != null) { + return; + } + + String httpMethod = extractOperationMethod(null, method, SwaggerExtensions.chain()); + if (httpMethod != null) { + return; + } + } + + Field[] fields = cls.getDeclaredFields(); + for (Field field : fields) { + Annotation[] annotations = field.getAnnotations(); + if (annotations.length > 0) { + List params = getParameters(cls, Arrays.asList(annotations)); + for (Parameter param : params) { + if (hasCommonParameter(param)) { + String msg = "[" + cls.getCanonicalName() + "] Redefining common parameter '" + param.getName() + + "' already defined elsewhere"; + throw new RuntimeException(msg); + } + swagger.addParameter(param.getName(), param); + } + } + } + } + + private void updateTagDescriptions(Map discoveredTags) { + if (swagger.getTags() != null) { + for (Tag tag : swagger.getTags()) { + Tag rightTag = discoveredTags.get(tag.getName()); + if (rightTag != null && rightTag.getDescription() != null) { + tag.setDescription(rightTag.getDescription()); + } + } + } + } + + private Map scanClasspathForTags() { + Map tags = new HashMap<>(); + for (Class aClass: new Reflections("").getTypesAnnotatedWith(SwaggerDefinition.class)) { + SwaggerDefinition swaggerDefinition = AnnotationUtils.findAnnotation(aClass, SwaggerDefinition.class); + + for (io.swagger.annotations.Tag tag : swaggerDefinition.tags()) { + + String tagName = tag.name(); + if (!tagName.isEmpty()) { + tags.put(tag.name(), new Tag().name(tag.name()).description(tag.description())); + } + } + } + + return tags; + } + + private void handleSubResource(String[] apiConsumes, String httpMethod, String[] apiProduces, Map tags, Method method, ApiOperation apiOperation, String operationPath, Operation operation) { + if (isSubResource(httpMethod, method)) { + Class responseClass = method.getReturnType(); + if (apiOperation != null && !apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { + responseClass = apiOperation.response(); + } + LOGGER.debug("handling sub-resource method " + method.toString() + " -> " + responseClass); + read(responseClass, operationPath, httpMethod, true, apiConsumes, apiProduces, tags, operation.getParameters()); + } + } + + protected boolean isSubResource(String httpMethod, Method method) { + Class responseClass = method.getReturnType(); + return (responseClass != null) && (httpMethod == null) && (AnnotationUtils.findAnnotation(method, Path.class) != null); + } + + private String getPath(Path classLevelPath, Path methodLevelPath, String parentPath) { + if (classLevelPath == null && methodLevelPath == null) { + return null; + } + StringBuilder stringBuilder = new StringBuilder(); + if (parentPath != null && !parentPath.isEmpty() && !parentPath.equals("/")) { + if (!parentPath.startsWith("/")) { + parentPath = "/" + parentPath; + } + if (parentPath.endsWith("/")) { + parentPath = parentPath.substring(0, parentPath.length() - 1); + } + + stringBuilder.append(parentPath); + } + if (classLevelPath != null) { + stringBuilder.append(classLevelPath.value()); + } + if (methodLevelPath != null && !methodLevelPath.value().equals("/")) { + String methodPath = methodLevelPath.value(); + if (!methodPath.startsWith("/") && !stringBuilder.toString().endsWith("/")) { + stringBuilder.append("/"); + } + if (methodPath.endsWith("/")) { + methodPath = methodPath.substring(0, methodPath.length() - 1); + } + stringBuilder.append(methodPath); + } + String output = stringBuilder.toString(); + if (!output.startsWith("/")) { + output = "/" + output; + } + if (output.endsWith("/") && output.length() > 1) { + return output.substring(0, output.length() - 1); + } else { + return output; + } + } + + + public Operation parseMethod(String httpMethod, Method method) { + int responseCode = 200; + Operation operation = new Operation(); + ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); + + String operationId = getOperationId(method, httpMethod); + + String responseContainer = null; + + Type responseClassType = null; + Map defaultResponseHeaders = null; + + if (apiOperation != null) { + if (apiOperation.hidden()) { + return null; + } + if (!apiOperation.nickname().isEmpty()) { + operationId = apiOperation.nickname(); + } + + defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); + operation.summary(apiOperation.value()).description(apiOperation.notes()); + + Map customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); + operation.setVendorExtensions(customExtensions); + + if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { + responseClassType = apiOperation.response(); + } + if (!apiOperation.responseContainer().isEmpty()) { + responseContainer = apiOperation.responseContainer(); + } + List securities = new ArrayList<>(); + for (Authorization auth : apiOperation.authorizations()) { + if (!auth.value().isEmpty()) { + SecurityRequirement security = new SecurityRequirement(); + security.setName(auth.value()); + for (AuthorizationScope scope : auth.scopes()) { + if (!scope.scope().isEmpty()) { + security.addScope(scope.scope()); + } + } + securities.add(security); + } + } + + for (SecurityRequirement sec : securities) { + operation.security(sec); + } + } + operation.operationId(operationId); + + if (responseClassType == null) { + // pick out response from method declaration + LOGGER.debug("picking up response class from method " + method); + responseClassType = method.getGenericReturnType(); + } + boolean hasApiAnnotation = false; + if (responseClassType instanceof Class) { + hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; + } + if ((responseClassType != null) + && !responseClassType.equals(Void.class) + && !responseClassType.equals(void.class) + && !responseClassType.equals(javax.ws.rs.core.Response.class) + && !hasApiAnnotation + && !isSubResource(httpMethod, method)) { + if (isPrimitive(responseClassType)) { + Property property = ModelConverters.getInstance().readAsProperty(responseClassType); + if (property != null) { + Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); + + operation.response(responseCode, new Response() + .description("successful operation") + .schema(responseProperty) + .headers(defaultResponseHeaders)); + } + } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { + Map models = readModels(responseClassType); + if (models.isEmpty()) { + Property p = ModelConverters.getInstance().readAsProperty(responseClassType); + operation.response(responseCode, new Response() + .description("successful operation") + .schema(p) + .headers(defaultResponseHeaders)); + } + for (String key : models.keySet()) { + Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); + + + operation.response(responseCode, new Response() + .description("successful operation") + .schema(responseProperty) + .headers(defaultResponseHeaders)); + swagger.model(key, models.get(key)); + } + } + Map models = readAllModels(responseClassType); + for (Map.Entry entry : models.entrySet()) { + swagger.model(entry.getKey(), entry.getValue()); + } + } + + Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); + if (consumes != null) { + for (String mediaType : consumes.value()) { + operation.consumes(mediaType); + } + } + + Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); + if (produces != null) { + for (String mediaType : produces.value()) { + operation.produces(mediaType); + } + } + + ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); + if (responseAnnotation != null) { + updateApiResponse(operation, responseAnnotation); + } + + if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { + operation.deprecated(true); + } + + // process parameters + Class[] parameterTypes = method.getParameterTypes(); + Type[] genericParameterTypes = method.getGenericParameterTypes(); + Annotation[][] paramAnnotations = findParamAnnotations(method); + + for (int i = 0; i < parameterTypes.length; i++) { + Type type = genericParameterTypes[i]; + List annotations = Arrays.asList(paramAnnotations[i]); + List parameters = getParameters(type, annotations); + + for (Parameter parameter : parameters) { + if (hasCommonParameter(parameter)) { + Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); + operation.parameter(refParameter); + } else { + parameter = replaceArrayModelForOctetStream(operation, parameter); + operation.parameter(parameter); + } + } + } + if (operation.getResponses() == null) { + operation.defaultResponse(new Response().description("successful operation")); + } + + // Process @ApiImplicitParams + this.readImplicitParameters(method, operation); + + processOperationDecorator(operation, method); + + return operation; + } + + public static Annotation[][] findParamAnnotations(Method method) { + Annotation[][] paramAnnotation = method.getParameterAnnotations(); + + Method overriddenMethod = ReflectionUtils.getOverriddenMethod(method); + while(overriddenMethod != null) { + paramAnnotation = merge(overriddenMethod.getParameterAnnotations(), paramAnnotation); + overriddenMethod = ReflectionUtils.getOverriddenMethod(overriddenMethod); + } + return paramAnnotation; + } + + + private static Annotation[][] merge(Annotation[][] overriddenMethodParamAnnotation, + Annotation[][] currentParamAnnotations) { + Annotation[][] mergedAnnotations = new Annotation[overriddenMethodParamAnnotation.length][]; + + for(int i=0; i mergedAnnotations = new ArrayList<>(); + mergedAnnotations.addAll(Arrays.asList(annotations)); + mergedAnnotations.addAll(Arrays.asList(annotations2)); + return mergedAnnotations.toArray(new Annotation[0]); + } + + private Parameter replaceArrayModelForOctetStream(Operation operation, Parameter parameter) { + if (parameter instanceof BodyParameter + && operation.getConsumes() != null + && operation.getConsumes().contains("application/octet-stream")) { + BodyParameter bodyParam = (BodyParameter) parameter; + Model schema = bodyParam.getSchema(); + if (schema instanceof ArrayModel) { + ArrayModel arrayModel = (ArrayModel) schema; + Property items = arrayModel.getItems(); + if (items != null && items.getFormat() == "byte" && items.getType() == "string") { + ModelImpl model = new ModelImpl(); + model.setFormat("byte"); + model.setType("string"); + bodyParam.setSchema(model); + } + } + } + return parameter; + } + + public String extractOperationMethod(ApiOperation apiOperation, Method method, Iterator chain) { + if (apiOperation != null && !apiOperation.httpMethod().isEmpty()) { + return apiOperation.httpMethod().toLowerCase(); + } else if (AnnotationUtils.findAnnotation(method, GET.class) != null) { + return "get"; + } else if (AnnotationUtils.findAnnotation(method, PUT.class) != null) { + return "put"; + } else if (AnnotationUtils.findAnnotation(method, POST.class) != null) { + return "post"; + } else if (AnnotationUtils.findAnnotation(method, DELETE.class) != null) { + return "delete"; + } else if (AnnotationUtils.findAnnotation(method, OPTIONS.class) != null) { + return "options"; + } else if (AnnotationUtils.findAnnotation(method, HEAD.class) != null) { + return "head"; + } else if (AnnotationUtils.findAnnotation(method, io.swagger.jaxrs.PATCH.class) != null) { + return "patch"; + } else { + // check for custom HTTP Method annotations + for (Annotation declaredAnnotation : method.getDeclaredAnnotations()) { + Annotation[] innerAnnotations = declaredAnnotation.annotationType().getAnnotations(); + for (Annotation innerAnnotation : innerAnnotations) { + if (innerAnnotation instanceof HttpMethod) { + HttpMethod httpMethod = (HttpMethod) innerAnnotation; + return httpMethod.value().toLowerCase(); + } + } + } + + if (chain.hasNext()) { + return chain.next().extractOperationMethod(apiOperation, method, chain); + } + } + + return null; + } + + private Map readAllModels(Type responseClassType) { + Map modelMap = ModelConverters.getInstance().readAll(responseClassType); + if (modelMap != null) { + handleJsonTypeInfo(responseClassType, modelMap); + } + + return modelMap; + } + + private Map readModels(Type responseClassType) { + Map modelMap = ModelConverters.getInstance().read(responseClassType); + if (modelMap != null) { + handleJsonTypeInfo(responseClassType, modelMap); + } + + return modelMap; + } + + private void handleJsonTypeInfo(Type responseClassType, Map modelMap) { + if (responseClassType instanceof Class){ + JsonTypeInfo typeInfo = ((Class)responseClassType).getAnnotation(JsonTypeInfo.class); + if (typeInfo != null && !StringUtils.isEmpty(typeInfo.property())) { + for (Model model : modelMap.values()) { + Map properties = model.getProperties(); + if (properties != null) { + properties.put(typeInfo.property(), new StringProperty()); + } + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `models` last assigned on line 410 could be null and is dereferenced at line 411. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Operation JaxrsReader.parseMethod(String,Method) + +### Procedure Id: +com.github.kongchen.swagger.docgen.reader.JaxrsReader.parseMethod(java.lang.String,java.lang.reflect.7deb083cb986babda7362306c2d10d24 + +### File: +src/main/java/com/github/kongchen/swagger/docgen/reader/JaxrsReader.java + +### Key: +JaxrsReader.java|parseMethod|NULL_DEREFERENCE + +### Node Key: +18086a76ec6f499138a84f176568ec09 + +### Hash: +f2c0535824554797a3348c80d81b06ac + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-8999/instruction.md b/inferredbugs-8999/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86514913a7ae9e99107fe9af176d7fb6d0b84c72 --- /dev/null +++ b/inferredbugs-8999/instruction.md @@ -0,0 +1,540 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** swagger-maven-plugin +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.github.kongchen.swagger.docgen.reader; + +import com.github.kongchen.swagger.docgen.GenerateException; +import com.github.kongchen.swagger.docgen.LogAdapter; +import com.github.kongchen.swagger.docgen.spring.SpringResource; +import com.github.kongchen.swagger.docgen.util.Annotations; +import io.swagger.annotations.*; +import io.swagger.converter.ModelConverters; +import io.swagger.models.*; +import io.swagger.models.Tag; +import io.swagger.models.parameters.Parameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; +import org.codehaus.plexus.util.StringUtils; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseStatus; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.*; + +public class SpringMvcApiReader extends AbstractReader implements ClassSwaggerReader { + private String resourcePath; + + public SpringMvcApiReader(Swagger swagger, LogAdapter log) { + super(swagger, log); + + } + + @Override + public Swagger read(Set> classes) throws GenerateException { + //relate all methods to one base request mapping if multiple controllers exist for that mapping + //get all methods from each controller & find their request mapping + //create map - resource string (after first slash) as key, new SpringResource as value + Map resourceMap = generateResourceMap(classes); + for (String str : resourceMap.keySet()) { + SpringResource resource = resourceMap.get(str); + read(resource); + } + + return swagger; + } + + public Swagger read(SpringResource resource) { + if (swagger == null) { + swagger = new Swagger(); + } + List methods = resource.getMethods(); + Map tags = new HashMap(); + + List resourceSecurities = new ArrayList(); + + // Add the description from the controller api + Class controller = resource.getControllerClass(); + RequestMapping controllerRM = Annotations.get(controller, RequestMapping.class); + + + String[] controllerProduces = new String[0]; + String[] controllerConsumes = new String[0]; + if (controllerRM != null) { + controllerConsumes = controllerRM.consumes(); + controllerProduces = controllerRM.produces(); + } + + if (controller != null && controller.isAnnotationPresent(Api.class)) { + Api api = Annotations.get(controller, Api.class); + if (!canReadApi(false, api)) { + return swagger; + } + tags = updateTagsForApi(null, api); + resourceSecurities = getSecurityRequirements(api); + } + + resourcePath = resource.getControllerMapping(); + + //collect api from method with @RequestMapping + Map> apiMethodMap = collectApisByRequestMapping(methods); + + for (String path : apiMethodMap.keySet()) { + for (Method method : apiMethodMap.get(path)) { + + RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); + if (requestMapping == null) { + continue; + } + ApiOperation apiOperation = Annotations.get(method, ApiOperation.class); + if (apiOperation == null || apiOperation.hidden()) { + continue; + } + String httpMethod = null; + + + Map regexMap = new HashMap(); + String operationPath = parseOperationPath(path, regexMap); + + //http method + for (RequestMethod requestMethod : requestMapping.method()) { + httpMethod = requestMethod.toString().toLowerCase(); + Operation operation = parseMethod(method); + + updateOperationParameters(new ArrayList(), regexMap, operation); + + updateOperationProtocols(apiOperation, operation); + + String[] apiProduces = requestMapping.produces(); + String[] apiConsumes = requestMapping.consumes(); + + apiProduces = (apiProduces == null || apiProduces.length == 0) ? controllerProduces : apiProduces; + apiConsumes = (apiConsumes == null || apiProduces.length == 0) ? controllerConsumes : apiConsumes; + + apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); + apiProduces = updateOperationProduces(new String[0], apiProduces, operation); + + updateTagsForOperation(operation, apiOperation); + updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); + updatePath(operationPath, httpMethod, operation); + } + } + + } + return swagger; + } + + private Operation parseMethod(Method method) { + Operation operation = new Operation(); + + RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); + Class responseClass = null; + List produces = new ArrayList(); + List consumes = new ArrayList(); + String responseContainer = null; + String operationId = method.getName(); + Map defaultResponseHeaders = null; + Set> customExtensions = null; + + ApiOperation apiOperation = Annotations.get(method, ApiOperation.class); + + if (apiOperation.hidden()) + return null; + if (!"".equals(apiOperation.nickname())) + operationId = apiOperation.nickname(); + + defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); + + operation.summary(apiOperation.value()).description(apiOperation.notes()); + + customExtensions = parseCustomExtensions(apiOperation.extensions()); + if (customExtensions != null) { + for (Map extension : customExtensions) { + if (extension != null) { + for (Map.Entry map : extension.entrySet()) { + operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); + } + } + } + } + + if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) + responseClass = apiOperation.response(); + if (!"".equals(apiOperation.responseContainer())) + responseContainer = apiOperation.responseContainer(); + + ///security + if (apiOperation.authorizations() != null) { + List securities = new ArrayList(); + for (Authorization auth : apiOperation.authorizations()) { + if (auth.value() != null && !"".equals(auth.value())) { + SecurityRequirement security = new SecurityRequirement(); + security.setName(auth.value()); + AuthorizationScope[] scopes = auth.scopes(); + for (AuthorizationScope scope : scopes) { + if (scope.scope() != null && !"".equals(scope.scope())) { + security.addScope(scope.scope()); + } + } + securities.add(security); + } + } + if (securities.size() > 0) { + for (SecurityRequirement sec : securities) + operation.security(sec); + } + } + + if (responseClass == null) { + // pick out response from method declaration + LOG.info("picking up response class from method " + method); + Type t = method.getGenericReturnType(); + responseClass = method.getReturnType(); + if (responseClass.equals(ResponseEntity.class)) { + responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); + } + if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && Annotations.get(responseClass, Api.class) == null) { + LOG.info("reading model " + responseClass); + Map models = ModelConverters.getInstance().readAll(t); + } + } + if (responseClass != null + && !responseClass.equals(Void.class) + && !responseClass.equals(ResponseEntity.class) + && Annotations.get(responseClass, Api.class) == null) { + if (isPrimitive(responseClass)) { + Property responseProperty = null; + Property property = ModelConverters.getInstance().readAsProperty(responseClass); + if (property != null) { + if ("list".equalsIgnoreCase(responseContainer)) + responseProperty = new ArrayProperty(property); + else if ("map".equalsIgnoreCase(responseContainer)) + responseProperty = new MapProperty(property); + else + responseProperty = property; + operation.response(apiOperation.code(), new Response() + .description("successful operation") + .schema(responseProperty) + .headers(defaultResponseHeaders)); + } + } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { + Map models = ModelConverters.getInstance().read(responseClass); + if (models.size() == 0) { + Property pp = ModelConverters.getInstance().readAsProperty(responseClass); + operation.response(apiOperation.code(), new Response() + .description("successful operation") + .schema(pp) + .headers(defaultResponseHeaders)); + } + for (String key : models.keySet()) { + Property responseProperty = null; + + if ("list".equalsIgnoreCase(responseContainer)) + responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); + else if ("map".equalsIgnoreCase(responseContainer)) + responseProperty = new MapProperty(new RefProperty().asDefault(key)); + else + responseProperty = new RefProperty().asDefault(key); + operation.response(apiOperation.code(), new Response() + .description("successful operation") + .schema(responseProperty) + .headers(defaultResponseHeaders)); + swagger.model(key, models.get(key)); + } + models = ModelConverters.getInstance().readAll(responseClass); + for (String key : models.keySet()) { + swagger.model(key, models.get(key)); + } + } + } + + operation.operationId(operationId); + + if (requestMapping.produces() != null) { + for (String str : Arrays.asList(requestMapping.produces())) { + if (!produces.contains(str)) { + produces.add(str); + } + } + } + if (requestMapping.consumes() != null) { + for (String str : Arrays.asList(requestMapping.consumes())) { + if (!consumes.contains(str)) { + consumes.add(str); + } + } + } + + ApiResponses responseAnnotation = Annotations.get(method, ApiResponses.class); + if (responseAnnotation != null) { + updateApiResponse(operation, responseAnnotation); + } else { + ResponseStatus responseStatus = Annotations.get(method, ResponseStatus.class); + if (responseStatus != null) { + operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); + } + } + + Deprecated annotation = Annotations.get(method, Deprecated.class); + if (annotation != null) + operation.deprecated(true); + + // FIXME `hidden` is never used + boolean hidden = false; + if (apiOperation != null) + hidden = apiOperation.hidden(); + + // process parameters + Class[] parameterTypes = method.getParameterTypes(); + Type[] genericParameterTypes = method.getGenericParameterTypes(); + Annotation[][] paramAnnotations = method.getParameterAnnotations(); + // paramTypes = method.getParameterTypes + // genericParamTypes = method.getGenericParameterTypes + for (int i = 0; i < parameterTypes.length; i++) { + Type type = genericParameterTypes[i]; + List annotations = Arrays.asList(paramAnnotations[i]); + List parameters = getParameters(type, annotations); + + for (Parameter parameter : parameters) { + operation.parameter(parameter); + } + } + + if (operation.getResponses() == null) { + operation.defaultResponse(new Response().description("successful operation")); + } + + // Process @ApiImplicitParams + this.readImplicitParameters(method, operation); + + return operation; + + } + + private Map> collectApisByRequestMapping(List methods) { + Map> apiMethodMap = new HashMap>(); + for (Method method : methods) { + if (method.isAnnotationPresent(RequestMapping.class)) { + RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); + String path = ""; + if (requestMapping.value() != null && requestMapping.value().length != 0) { + path = generateFullPath(requestMapping.value()[0]); + } else { + path = resourcePath; + } + if (apiMethodMap.containsKey(path)) { + apiMethodMap.get(path).add(method); + } else { + List ms = new ArrayList(); + ms.add(method); + apiMethodMap.put(path, ms); + } + } + } + + return apiMethodMap; + } + + private String generateFullPath(String path) { + if (StringUtils.isNotEmpty(path)) { + return this.resourcePath + (path.startsWith("/") ? path : '/' + path); + } else { + return this.resourcePath; + } + } + + private Class getGenericSubtype(Class clazz, Type t) { + if (!(clazz.getName().equals("void") || t.toString().equals("void"))) { + try { + ParameterizedType paramType = (ParameterizedType) t; + Type[] argTypes = paramType.getActualTypeArguments(); + if (argTypes.length > 0) { + Class c = (Class) argTypes[0]; + return c; + } + } catch (ClassCastException e) { + //FIXME: find out why this happens to only certain types + } + } + return clazz; + } + + //Helper method for loadDocuments() + private Map analyzeController(Class clazz, Map resourceMap, String description) throws ClassNotFoundException { + String controllerCanonicalName = clazz.getCanonicalName(); + String[] controllerRequestMappingValues = null; + + //Determine if we will use class-level requestmapping or dummy string + if (Annotations.get(clazz, RequestMapping.class) != null && Annotations.get(clazz, RequestMapping.class).value() != null) { + controllerRequestMappingValues = Annotations.get(clazz, RequestMapping.class).value(); + } else { + controllerRequestMappingValues = new String[1]; + controllerRequestMappingValues[0] = ""; + } + + // Iterate over all value attributes of the class-level RequestMapping annotation + for (int i = 0; i < controllerRequestMappingValues.length; i++) { + + // Iterate over all methods inside the controller + Method[] methods = clazz.getMethods(); + for (Method method : methods) { + RequestMapping methodRequestMapping = Annotations.get(method, RequestMapping.class); + + // Look for method-level @RequestMapping annotation + if (methodRequestMapping instanceof RequestMapping) { + RequestMethod[] requestMappingRequestMethods = methodRequestMapping.method(); + + // For each method-level @RequestMapping annotation, iterate over HTTP Verb + for (RequestMethod requestMappingRequestMethod : requestMappingRequestMethods) { + String[] methodRequestMappingValues = methodRequestMapping.value(); + + // Check for cases where method-level @RequestMapping#value is not set, and use the controllers @RequestMapping + if (methodRequestMappingValues == null || methodRequestMappingValues.length == 0) { + // The map key is a concat of the following: + // 1. The controller package + // 2. The controller class name + // 3. The controller-level @RequestMapping#value + String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + requestMappingRequestMethod; + if ((!(resourceMap.containsKey(resourceKey)))) { + resourceMap.put( + resourceKey, + new SpringResource(clazz, controllerRequestMappingValues[i], resourceKey, description)); + } + resourceMap.get(resourceKey).addMethod(method); + } else { + // Here we know that method-level @RequestMapping#value is populated, so + // iterate over all the @RequestMapping#value attributes, and add them to the resource map. + for (String methodRequestMappingValue : methodRequestMappingValues) { + String resourceName = methodRequestMappingValue; + // The map key is a concat of the following: + // 1. The controller package + // 2. The controller class name + // 3. The controller-level @RequestMapping#value + // 4. The method-level @RequestMapping#value + // 5. The method-level @RequestMapping#method + String resourceKey = controllerCanonicalName + controllerRequestMappingValues[i] + resourceName + requestMappingRequestMethod; + if (!(resourceName.equals(""))) { + if ((!(resourceMap.containsKey(resourceKey)))) { + resourceMap.put(resourceKey, new SpringResource(clazz, resourceName, resourceKey, description)); + } + resourceMap.get(resourceKey).addMethod(method); + } + } + } + } + } + } + } + clazz.getFields(); + clazz.getDeclaredFields(); //<--In case developer declares a field without an associated getter/setter. + //this will allow NoClassDefFoundError to be caught before it triggers bamboo failure. + + return resourceMap; + } + + protected Map generateResourceMap(Set> validClasses) throws GenerateException { + Map resourceMap = new HashMap(); + for (Class c : validClasses) { + RequestMapping requestMapping = Annotations.get(c, RequestMapping.class); + String description = ""; + //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError + //This occurs when a class or method loaded by reflections contains a type that has no dependency + try { + resourceMap = analyzeController(c, resourceMap, description); + List mList = new ArrayList(Arrays.asList(c.getMethods())); + if (c.getSuperclass() != null) { + mList.addAll(Arrays.asList(c.getSuperclass().getMethods())); + } + + } catch (NoClassDefFoundError e) { + LOG.error(e.getMessage()); + LOG.info(c.getName()); + //exception occurs when a method type or annotation is not recognized by the plugin + } catch (ClassNotFoundException e) { + LOG.error(e.getMessage()); + LOG.info(c.getName()); + } + + } + + return resourceMap; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `requestMapping` last assigned on line 321 could be null and is dereferenced at line 323. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Map SpringMvcApiReader.collectApisByRequestMapping(List) + +### Procedure Id: +com.github.kongchen.swagger.docgen.reader.SpringMvcApiReader.collectApisByRequestMapping(java.util.L.9e27328daeff4f729bc657590c6cc532 + +### File: +src/main/java/com/github/kongchen/swagger/docgen/reader/SpringMvcApiReader.java + +### Key: +SpringMvcApiReader.java|collectApisByRequestMapping|NULL_DEREFERENCE + +### Node Key: +c281f77c6dae544ee5fb7d5e2bb35118 + +### Hash: +515fb41fb51d94d6b441b5b3d0146c15 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9013/instruction.md b/inferredbugs-9013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7e2fd2d2562fe873354eaf83f9fdc67c8e895fe --- /dev/null +++ b/inferredbugs-9013/instruction.md @@ -0,0 +1,742 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package jnr.posix; + +import jnr.constants.platform.Access; +import jnr.constants.platform.Fcntl; +import jnr.constants.platform.Errno; +import jnr.constants.platform.OpenFlags; +import jnr.ffi.Pointer; +import jnr.posix.util.Platform; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class FileTest { + private static POSIX posix; + + @BeforeClass + public static void setUpClass() throws Exception { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + } + + @Test + public void utimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + int rval = posix.utimes(f.getAbsolutePath(), new long[]{800, 200}, new long[]{900, 300}); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We really just want to verify that the + // nsec portion of the timeval is passed through to the POSIX call. + // Mac seems to fail this test sporadically. + if (stat instanceof NanosecondFileStat && !Platform.IS_MAC) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + + assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimesDefaultValuesTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + + int rval = posix.utimes(f.getAbsolutePath(), null, null); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertTrue("atime failed", stat.atime() > oldTime); + assertTrue("mtime failed", stat.mtime() > oldTime); + + f.delete(); + } + } + + @Test + public void utimesPointerTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + Pointer times = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(8 * 4); // long[2][2] == 4 longs. + times.putLong(0, 800); + times.putLong(8, 200); + times.putLong(16, 900); + times.putLong(24, 300); + + int rval = posix.utimes(f.getAbsolutePath(), times); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We use Linux x86_64 because it's + // representative. We really just want to verify that the usec portion of the timeval is passed throug + // to the POSIX call. + if (hasNanosecondPrecision(stat)) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + +// assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimensatAbsolutePath() throws Throwable { + File file = File.createTempFile("utimensat", null); + utimensat(file, 0); + } + + @Test + public void utimensatRelativePath() throws Throwable { + String path = "utimensat"; + File file = new File(path); + file.createNewFile(); + int parentFd = posix.open(".", OpenFlags.O_DIRECTORY.intValue(), 0444); + utimensat(file, parentFd); + } + + @Test + public void futimens() throws Throwable { + File file = File.createTempFile("futimens", null); + FileStat fileStat = posix.stat(file.getPath()); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+1; + long mtimeSeconds = fileStat.mtime()-1; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + int fd = posix.open(file.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0444); + posix.futimens(fd, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + @Test + public void lutimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f1 = File.createTempFile("lutimes", null); + File f2 = new File(f1.getParentFile(), "lutimes-link"); + posix.symlink(f1.getAbsolutePath(), f2.getAbsolutePath()); + + int rval = posix.utimes(f1.getAbsolutePath(), new long[]{800, 0}, new long[]{900, 0}); + assertEquals("utimes did not return 0", 0, rval); + + rval = posix.lutimes(f2.getAbsolutePath(), new long[]{1800, 0}, new long[]{1900, 0}); + assertEquals("lutimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f1.getAbsolutePath()); + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + stat = posix.lstat(f2.getAbsolutePath()); + assertEquals("atime seconds failed", 1800, stat.atime()); + assertEquals("mtime seconds failed", 1900, stat.mtime()); + + f1.delete(); + f2.delete(); + } + } + + @Test + public void futimeTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("jnr-posix-futime", "tmp"); + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + int fd = posix.open(f.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + int rval = posix.futimes(fd, null, null); + assertEquals("futime did not return 0", 0, rval); + long newTime = posix.stat(f.getAbsolutePath()).mtime(); + f.delete(); + assertTrue("mtime failed", newTime > oldTime); + } + } + + @Test + public void linkTest() throws Throwable { + File f1 = File.createTempFile("utime", null); + File f2 = new File(f1.getAbsolutePath() + "link"); + int rval = posix.link(f1.getAbsolutePath(), f2.getAbsolutePath()); + assertEquals("link did not return 0", 0, rval); + assertTrue("Link was not created", f2.exists()); + f1.delete(); + f2.delete(); + } + + @Test + public void mkdirRelativeTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getPath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void mkdirAbsoluteTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getAbsolutePath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void flockTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("flockTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + RandomAccessFile raf2 = new RandomAccessFile(tmp, "rw"); + FileChannel fc = raf.getChannel(); + FileChannel fc2 = raf2.getChannel(); + FileDescriptor FD = JavaLibCHelper.getDescriptorFromChannel(fc); + FileDescriptor FD2 = JavaLibCHelper.getDescriptorFromChannel(fc2); + int fd = JavaLibCHelper.getfdFromDescriptor(FD); + int fd2 = JavaLibCHelper.getfdFromDescriptor(FD2); + + assertEquals(0, posix.flock(fd, 1)); // LOCK_SH + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + assertEquals(0, posix.flock(fd, 2)); // LOCK_EX + assertEquals(-1, posix.flock(fd2, 2 | 4)); // LOCK_EX | LOCK_NB + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + } + } + + @Test + public void dupTest() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + FileChannel fileChannel = raf.getChannel(); + int fileDescriptor = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(fileChannel)); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = toDescriptor(posix.dup(fileDescriptor)); + + new FileOutputStream(toDescriptor(fileDescriptor)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void dup2Test() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int oldFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + // NB: Windows differs a bit from POSIX's return value. Both will return -1 on failure, but Windows will return + // 0 upon success, while POSIX will return the new FD. Since we already know what the FD will be if the call + // is successful, it's easy to make code that works with both forms. But it is something to watch out for. + assertNotEquals(-1, posix.dup2(oldFd, newFd)); + FileDescriptor newFileDescriptor = toDescriptor(newFd); + + new FileOutputStream(toDescriptor(oldFd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void fcntlDupfdTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("fcntlTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + int newFd = posix.fcntl(fd, Fcntl.F_DUPFD); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void fcntlDupfdWithArgTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("dupTest", "tmp"); + int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + + byte[] outContent = "foo".getBytes(); + + int dupFd = posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(dupFd)).read(inContent, 0, 3); + + assertTrue(dupFd > newFd); + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void closeTest() throws Throwable { + File tmp = File.createTempFile("closeTest", "tmp"); + int fd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + + int result; + + result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + + // TODO (nirvdrum 06-May-15) We're not getting the correct errno value from Windows currently, so we need to skip this test. + if (!Platform.IS_WINDOWS) { + assertEquals(Errno.EBADF.intValue(), posix.errno()); + } + } + + @Test + public void unlinkTestNonWindows() throws Throwable { + if (! Platform.IS_WINDOWS) { + File tmp = File.createTempFile("unlinkTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + + raf.write("hello".getBytes()); + + int res = posix.unlink(tmp.getCanonicalPath()); + + assertEquals(0, res); + assertFalse(tmp.exists()); + + raf.write("world".getBytes()); + raf.seek(0); + + byte[] actual = new byte[10]; + raf.read(actual); + + assertArrayEquals("helloworld".getBytes(), actual); + } + } + + @Test + public void openTest() throws Throwable { + int fd = posix.open("pom.xml", 0, 0666); + + assertNotEquals(-1, fd); + + int result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + } + + @Test + public void writeTest() throws Throwable { + String str = "To thine own self be true"; + File tmp = File.createTempFile("writeTest", "tmp"); + ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.write(fd, buffer, str.length()); + posix.close(fd); + + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + assertEquals(raf.readLine(), new String(buffer.array())); + posix.unlink(tmp.getAbsolutePath()); + } + + @Test + public void pwriteTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + String str = "Now is the winter of our discontent"; + File tmp = File.createTempFile("pwriteTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + String str2 = "summer"; + ByteBuffer buffer = ByteBuffer.wrap(str2.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.pwrite(fd, buffer, str2.length(), 11); + posix.close(fd); + + raf = new RandomAccessFile(tmp, "r"); + assertEquals(raf.readLine(), "Now is the summer of our discontent"); + posix.unlink(tmp.getAbsolutePath()); + } + } + + @Test + public void truncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("truncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int shorterLength = str.length() - 10; + int longerLength = shorterLength * 2; + + // Truncate should make a file shorter if the new length is less than the old length. + posix.truncate(tmp.getAbsolutePath(), shorterLength); + assertEquals(shorterLength, tmp.length()); + + // Truncate should extend a file if the new length is greater than the old length. + posix.truncate(tmp.getAbsolutePath(), longerLength); + assertEquals(longerLength, tmp.length()); + } + + @Test + public void ftruncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("ftruncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + posix.ftruncate(fd, 21); + posix.lseekLong(fd, 0, 0); + byte[] buf = new byte[21]; + int read = posix.read(fd, buf, 31); + assertEquals(21, read); + assertArrayEquals(buf, "Beware the Jabberwock".getBytes()); + } + + @Test + public void fcntlIntTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + int[] fds = new int[2]; + int ret = posix.pipe(fds); + assertEquals(0, ret); + int flags = posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0); + posix.fcntlInt(fds[0], Fcntl.F_SETFD, flags | 1); // FD_CLOEXEC + assertEquals(flags | 1, posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0)); + } + } + + @Test + public void fchmodTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("jnr-posix-chmod-test", "tmp"); + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0600); + + assertEquals("chmod: ", 0, posix.fchmod(fd, 0)); + assertEquals("chmod: ", 0, posix.fchmod(fd, 0777)); + tmp.delete(); + } + } + + + @Test + public void renameTest() throws IOException { + File oldFile = File.createTempFile("jnr-posix-rename-test", "tmp"); + File newFile = new File(oldFile.getParent() + File.separatorChar + "jnr-posix-rename-test-new"); + + assertTrue(oldFile.exists()); + assertFalse(newFile.exists()); + + posix.rename(oldFile.getCanonicalPath(), newFile.getCanonicalPath()); + + assertFalse(oldFile.exists()); + assertTrue(newFile.exists()); + + newFile.delete(); + } + + @Test + public void accessTest() throws IOException { + File tmp = File.createTempFile("jnr-posix-access-test", "tmp"); + + jnr.constants.platform.Access.F_OK.intValue(); + + // Set permissions to read-only and verify we don't have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0400); + assertEquals("access: ", -1, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // Reset the permissions to read-wrinte and verify we now have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0600); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // F_OK just checks the file exists and should pass. + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.F_OK.intValue())); + } + + @Test + public void readlinkTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + byte[] buffer = new byte[fileLength]; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.length)); + + assertArrayEquals(fileBytes, buffer); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkByteBufferTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + ByteBuffer buffer = ByteBuffer.allocate(fileLength); + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.capacity())); + + assertArrayEquals(buffer.array(), file.getAbsolutePath().getBytes()); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkPointerTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + int bufSize = 1024; + + Pointer buffer = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(bufSize); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, bufSize)); + + assertEquals(file.getAbsolutePath(), buffer.getString(0, fileLength, Charset.defaultCharset())); + + link.delete(); + file.delete(); + } + } + + @Test + public void mkfifoTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("mkfifoTest", "tmp"); + tmp.deleteOnExit(); + + int ret = posix.mkfifo(tmp.getAbsolutePath(), 0666); + + FileInputStream fis = new FileInputStream(tmp); + FileOutputStream fos = new FileOutputStream(tmp); + + byte[] content = "hello".getBytes(); + + fos.write(content); + fis.read(content); + + assertArrayEquals("hello".getBytes(), content); + } + } + + @Test + public void lseekTest() throws Throwable { + if (Platform.IS_MAC) { + int fd = posix.open("/dev/zero", 0, 0); + + // use 2^33 to ensure we're out of int range + long offset = (long) Math.pow(2, 33); + long seek = posix.lseekLong(fd, offset, 0); + + assertEquals(seek, offset); + } + } + + private int getFdFromDescriptor(FileDescriptor descriptor) { + if (Platform.IS_WINDOWS) { + HANDLE handle = JavaLibCHelper.gethandle(descriptor); + return ((WindowsLibC) posix.libc())._open_osfhandle(handle, 0); + } else { + return JavaLibCHelper.getfdFromDescriptor(descriptor); + } + } + + private FileDescriptor toDescriptor(int fd) { + if (Platform.IS_WINDOWS) { + HANDLE handle = ((WindowsLibC) posix.libc())._get_osfhandle(fd); + return JavaLibCHelper.toFileDescriptor(handle); + } else { + return JavaLibCHelper.toFileDescriptor(fd); + } + } + + private boolean hasNanosecondPrecision(FileStat fileStat) { + return fileStat instanceof NanosecondFileStat && !Platform.IS_MAC; + } + + private void utimensat(File file, int parentFd) { + String path = file.getAbsolutePath(); + FileStat fileStat = posix.stat(path); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+2; + long mtimeSeconds = fileStat.mtime()-2; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + posix.utimensat(parentFd, + path, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}, + 0); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + private void assertStatNanoSecond(File file, long atimeSeconds, long atimeNanoSeconds, long mtimeSeconds, long mtimeNanoSeconds) { + NanosecondFileStat nanosecondFileStat = (NanosecondFileStat) posix.stat(file.getPath()); + assertEquals("Access timestamp should be updated", atimeSeconds, nanosecondFileStat.atime()); + assertEquals("Modification timestamp should be updated", mtimeSeconds, nanosecondFileStat.mtime()); + assertEquals("Access time precision should be in ns", atimeNanoSeconds, nanosecondFileStat.aTimeNanoSecs()); + assertEquals("Modification time precision should be in ns", mtimeNanoSeconds, nanosecondFileStat.mTimeNanoSecs()); + file.delete(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired to `raf` by call to `RandomAccessFile(...)` at line 287 is not released after line 302. +**Note**: potential exception at line 294 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileTest.fcntlDupfdTest() + +### Procedure Id: +jnr.posix.FileTest.fcntlDupfdTest():void.2d4d6ec67940c406afe88c8010a1de29 + +### File: +src/test/java/jnr/posix/FileTest.java + +### Key: +FileTest.java|fcntlDupfdTest|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +5f4ad29ca47a0aa0683ca4fc379f5358 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9014/instruction.md b/inferredbugs-9014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10309ffd0aeb4df80c2872986e2cf33ca4e09ce4 --- /dev/null +++ b/inferredbugs-9014/instruction.md @@ -0,0 +1,741 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jnr-posix +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package jnr.posix; + +import jnr.constants.platform.Access; +import jnr.constants.platform.Fcntl; +import jnr.constants.platform.Errno; +import jnr.constants.platform.OpenFlags; +import jnr.ffi.Pointer; +import jnr.posix.util.Platform; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.charset.Charset; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +public class FileTest { + private static POSIX posix; + + @BeforeClass + public static void setUpClass() throws Exception { + posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true); + } + + @Test + public void utimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + int rval = posix.utimes(f.getAbsolutePath(), new long[]{800, 200}, new long[]{900, 300}); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We really just want to verify that the + // nsec portion of the timeval is passed through to the POSIX call. + // Mac seems to fail this test sporadically. + if (stat instanceof NanosecondFileStat && !Platform.IS_MAC) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + + assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimesDefaultValuesTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + + int rval = posix.utimes(f.getAbsolutePath(), null, null); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertTrue("atime failed", stat.atime() > oldTime); + assertTrue("mtime failed", stat.mtime() > oldTime); + + f.delete(); + } + } + + @Test + public void utimesPointerTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("utimes", null); + + Pointer times = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(8 * 4); // long[2][2] == 4 longs. + times.putLong(0, 800); + times.putLong(8, 200); + times.putLong(16, 900); + times.putLong(24, 300); + + int rval = posix.utimes(f.getAbsolutePath(), times); + assertEquals("utimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f.getAbsolutePath()); + + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + // The nano secs part is available in other stat implementations. We use Linux x86_64 because it's + // representative. We really just want to verify that the usec portion of the timeval is passed throug + // to the POSIX call. + if (hasNanosecondPrecision(stat)) { + NanosecondFileStat linuxStat = (NanosecondFileStat) stat; + +// assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs()); + assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs()); + } + + f.delete(); + } + } + + @Test + public void utimensatAbsolutePath() throws Throwable { + File file = File.createTempFile("utimensat", null); + utimensat(file, 0); + } + + @Test + public void utimensatRelativePath() throws Throwable { + String path = "utimensat"; + File file = new File(path); + file.createNewFile(); + int parentFd = posix.open(".", OpenFlags.O_DIRECTORY.intValue(), 0444); + utimensat(file, parentFd); + } + + @Test + public void futimens() throws Throwable { + File file = File.createTempFile("futimens", null); + FileStat fileStat = posix.stat(file.getPath()); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+1; + long mtimeSeconds = fileStat.mtime()-1; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + int fd = posix.open(file.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0444); + posix.futimens(fd, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + @Test + public void lutimesTest() throws Throwable { + // FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results. + if (!Platform.IS_WINDOWS) { + File f1 = File.createTempFile("lutimes", null); + File f2 = new File(f1.getParentFile(), "lutimes-link"); + posix.symlink(f1.getAbsolutePath(), f2.getAbsolutePath()); + + int rval = posix.utimes(f1.getAbsolutePath(), new long[]{800, 0}, new long[]{900, 0}); + assertEquals("utimes did not return 0", 0, rval); + + rval = posix.lutimes(f2.getAbsolutePath(), new long[]{1800, 0}, new long[]{1900, 0}); + assertEquals("lutimes did not return 0", 0, rval); + + FileStat stat = posix.stat(f1.getAbsolutePath()); + assertEquals("atime seconds failed", 800, stat.atime()); + assertEquals("mtime seconds failed", 900, stat.mtime()); + + stat = posix.lstat(f2.getAbsolutePath()); + assertEquals("atime seconds failed", 1800, stat.atime()); + assertEquals("mtime seconds failed", 1900, stat.mtime()); + + f1.delete(); + f2.delete(); + } + } + + @Test + public void futimeTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File f = File.createTempFile("jnr-posix-futime", "tmp"); + long oldTime = posix.stat(f.getAbsolutePath()).mtime(); + Thread.sleep(2000); + int fd = posix.open(f.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + int rval = posix.futimes(fd, null, null); + assertEquals("futime did not return 0", 0, rval); + long newTime = posix.stat(f.getAbsolutePath()).mtime(); + f.delete(); + assertTrue("mtime failed", newTime > oldTime); + } + } + + @Test + public void linkTest() throws Throwable { + File f1 = File.createTempFile("utime", null); + File f2 = new File(f1.getAbsolutePath() + "link"); + int rval = posix.link(f1.getAbsolutePath(), f2.getAbsolutePath()); + assertEquals("link did not return 0", 0, rval); + assertTrue("Link was not created", f2.exists()); + f1.delete(); + f2.delete(); + } + + @Test + public void mkdirRelativeTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getPath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void mkdirAbsoluteTest() throws Throwable { + File dir = new File("tmp"); + int rval = posix.mkdir(dir.getAbsolutePath(), 0); + assertEquals("mkdir did not return 0", 0, rval); + assertTrue("Directory was not created", dir.exists()); + dir.delete(); + } + + @Test + public void flockTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("flockTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + RandomAccessFile raf2 = new RandomAccessFile(tmp, "rw"); + FileChannel fc = raf.getChannel(); + FileChannel fc2 = raf2.getChannel(); + FileDescriptor FD = JavaLibCHelper.getDescriptorFromChannel(fc); + FileDescriptor FD2 = JavaLibCHelper.getDescriptorFromChannel(fc2); + int fd = JavaLibCHelper.getfdFromDescriptor(FD); + int fd2 = JavaLibCHelper.getfdFromDescriptor(FD2); + + assertEquals(0, posix.flock(fd, 1)); // LOCK_SH + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + assertEquals(0, posix.flock(fd, 2)); // LOCK_EX + assertEquals(-1, posix.flock(fd2, 2 | 4)); // LOCK_EX | LOCK_NB + assertEquals(0, posix.flock(fd, 8)); // LOCK_UN + } + } + + @Test + public void dupTest() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + FileChannel fileChannel = raf.getChannel(); + int fileDescriptor = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(fileChannel)); + + byte[] outContent = "foo".getBytes(); + + FileDescriptor newFileDescriptor = toDescriptor(posix.dup(fileDescriptor)); + + new FileOutputStream(toDescriptor(fileDescriptor)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void dup2Test() throws Throwable { + File tmp = File.createTempFile("dupTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int oldFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + // NB: Windows differs a bit from POSIX's return value. Both will return -1 on failure, but Windows will return + // 0 upon success, while POSIX will return the new FD. Since we already know what the FD will be if the call + // is successful, it's easy to make code that works with both forms. But it is something to watch out for. + assertNotEquals(-1, posix.dup2(oldFd, newFd)); + FileDescriptor newFileDescriptor = toDescriptor(newFd); + + new FileOutputStream(toDescriptor(oldFd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(newFileDescriptor).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + + @Test + public void fcntlDupfdTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("fcntlTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel())); + + byte[] outContent = "foo".getBytes(); + + int newFd = posix.fcntl(fd, Fcntl.F_DUPFD); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent); + raf.seek(0); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3); + + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void fcntlDupfdWithArgTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("dupTest", "tmp"); + int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel( + new RandomAccessFile(tmp, "rw").getChannel())); + + byte[] outContent = "foo".getBytes(); + + int dupFd = posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd); + + new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent); + + byte[] inContent = new byte[outContent.length]; + new FileInputStream(JavaLibCHelper.toFileDescriptor(dupFd)).read(inContent, 0, 3); + + assertTrue(dupFd > newFd); + assertArrayEquals(inContent, outContent); + } + } + + @Test + public void closeTest() throws Throwable { + File tmp = File.createTempFile("closeTest", "tmp"); + int fd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel())); + + int result; + + result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + + // TODO (nirvdrum 06-May-15) We're not getting the correct errno value from Windows currently, so we need to skip this test. + if (!Platform.IS_WINDOWS) { + assertEquals(Errno.EBADF.intValue(), posix.errno()); + } + } + + @Test + public void unlinkTestNonWindows() throws Throwable { + if (! Platform.IS_WINDOWS) { + File tmp = File.createTempFile("unlinkTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + + raf.write("hello".getBytes()); + + int res = posix.unlink(tmp.getCanonicalPath()); + + assertEquals(0, res); + assertFalse(tmp.exists()); + + raf.write("world".getBytes()); + raf.seek(0); + + byte[] actual = new byte[10]; + raf.read(actual); + + assertArrayEquals("helloworld".getBytes(), actual); + } + } + + @Test + public void openTest() throws Throwable { + int fd = posix.open("pom.xml", 0, 0666); + + assertNotEquals(-1, fd); + + int result = posix.close(fd); + assertEquals(0, result); + + result = posix.close(fd); + assertEquals(-1, result); + } + + @Test + public void writeTest() throws Throwable { + String str = "To thine own self be true"; + File tmp = File.createTempFile("writeTest", "tmp"); + ByteBuffer buffer = ByteBuffer.wrap(str.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.write(fd, buffer, str.length()); + posix.close(fd); + + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + assertEquals(raf.readLine(), new String(buffer.array())); + posix.unlink(tmp.getAbsolutePath()); + } + + @Test + public void pwriteTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + String str = "Now is the winter of our discontent"; + File tmp = File.createTempFile("pwriteTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + String str2 = "summer"; + ByteBuffer buffer = ByteBuffer.wrap(str2.getBytes()); + + int fd = posix.open(tmp.getAbsolutePath(), 1, 066); + posix.pwrite(fd, buffer, str2.length(), 11); + posix.close(fd); + + raf = new RandomAccessFile(tmp, "r"); + assertEquals(raf.readLine(), "Now is the summer of our discontent"); + posix.unlink(tmp.getAbsolutePath()); + } + } + + @Test + public void truncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("truncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int shorterLength = str.length() - 10; + int longerLength = shorterLength * 2; + + // Truncate should make a file shorter if the new length is less than the old length. + posix.truncate(tmp.getAbsolutePath(), shorterLength); + assertEquals(shorterLength, tmp.length()); + + // Truncate should extend a file if the new length is greater than the old length. + posix.truncate(tmp.getAbsolutePath(), longerLength); + assertEquals(longerLength, tmp.length()); + } + + @Test + public void ftruncateTest() throws Throwable { + String str = "Beware the Jabberwock, my son!"; + File tmp = File.createTempFile("ftruncateTest", "tmp"); + RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); + raf.write(str.getBytes()); + raf.close(); + + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666); + posix.ftruncate(fd, 21); + posix.lseekLong(fd, 0, 0); + byte[] buf = new byte[21]; + int read = posix.read(fd, buf, 31); + assertEquals(21, read); + assertArrayEquals(buf, "Beware the Jabberwock".getBytes()); + } + + @Test + public void fcntlIntTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + int[] fds = new int[2]; + int ret = posix.pipe(fds); + assertEquals(0, ret); + int flags = posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0); + posix.fcntlInt(fds[0], Fcntl.F_SETFD, flags | 1); // FD_CLOEXEC + assertEquals(flags | 1, posix.fcntlInt(fds[0], Fcntl.F_GETFD, 0)); + } + } + + @Test + public void fchmodTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("jnr-posix-chmod-test", "tmp"); + int fd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0600); + + assertEquals("chmod: ", 0, posix.fchmod(fd, 0)); + assertEquals("chmod: ", 0, posix.fchmod(fd, 0777)); + tmp.delete(); + } + } + + + @Test + public void renameTest() throws IOException { + File oldFile = File.createTempFile("jnr-posix-rename-test", "tmp"); + File newFile = new File(oldFile.getParent() + File.separatorChar + "jnr-posix-rename-test-new"); + + assertTrue(oldFile.exists()); + assertFalse(newFile.exists()); + + posix.rename(oldFile.getCanonicalPath(), newFile.getCanonicalPath()); + + assertFalse(oldFile.exists()); + assertTrue(newFile.exists()); + + newFile.delete(); + } + + @Test + public void accessTest() throws IOException { + File tmp = File.createTempFile("jnr-posix-access-test", "tmp"); + + jnr.constants.platform.Access.F_OK.intValue(); + + // Set permissions to read-only and verify we don't have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0400); + assertEquals("access: ", -1, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // Reset the permissions to read-wrinte and verify we now have permissions to write. + posix.chmod(tmp.getCanonicalPath(), 0600); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.W_OK.intValue())); + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.R_OK.intValue())); + + // F_OK just checks the file exists and should pass. + assertEquals("access: ", 0, posix.access(tmp.getCanonicalPath(), Access.F_OK.intValue())); + } + + @Test + public void readlinkTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + byte[] buffer = new byte[fileLength]; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.length)); + + assertArrayEquals(fileBytes, buffer); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkByteBufferTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + ByteBuffer buffer = ByteBuffer.allocate(fileLength); + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, buffer.capacity())); + + assertArrayEquals(buffer.array(), file.getAbsolutePath().getBytes()); + + link.delete(); + file.delete(); + } + } + + @Test + public void readlinkPointerTest() throws IOException { + if (!Platform.IS_WINDOWS) { + File file = File.createTempFile("jnr-pøsix-réådlînk-tést", "tmp"); + File link = new File(file.getAbsolutePath() + "link"); + + int bufSize = 1024; + + Pointer buffer = jnr.ffi.Runtime.getSystemRuntime().getMemoryManager().allocateDirect(bufSize); + + posix.symlink(file.getAbsolutePath(), link.getAbsolutePath()); + + byte[] fileBytes = file.getAbsolutePath().getBytes(); + int fileLength = fileBytes.length; + + assertEquals(fileLength, posix.readlink(link.getAbsolutePath(), buffer, bufSize)); + + assertEquals(file.getAbsolutePath(), buffer.getString(0, fileLength, Charset.defaultCharset())); + + link.delete(); + file.delete(); + } + } + + @Test + public void mkfifoTest() throws Throwable { + if (!Platform.IS_WINDOWS) { + File tmp = File.createTempFile("mkfifoTest", "tmp"); + tmp.deleteOnExit(); + + int ret = posix.mkfifo(tmp.getAbsolutePath(), 0666); + + FileInputStream fis = new FileInputStream(tmp); + FileOutputStream fos = new FileOutputStream(tmp); + + byte[] content = "hello".getBytes(); + + fos.write(content); + fis.read(content); + + assertArrayEquals("hello".getBytes(), content); + } + } + + @Test + public void lseekTest() throws Throwable { + if (Platform.IS_MAC) { + int fd = posix.open("/dev/zero", 0, 0); + + // use 2^33 to ensure we're out of int range + long offset = (long) Math.pow(2, 33); + long seek = posix.lseekLong(fd, offset, 0); + + assertEquals(seek, offset); + } + } + + private int getFdFromDescriptor(FileDescriptor descriptor) { + if (Platform.IS_WINDOWS) { + HANDLE handle = JavaLibCHelper.gethandle(descriptor); + return ((WindowsLibC) posix.libc())._open_osfhandle(handle, 0); + } else { + return JavaLibCHelper.getfdFromDescriptor(descriptor); + } + } + + private FileDescriptor toDescriptor(int fd) { + if (Platform.IS_WINDOWS) { + HANDLE handle = ((WindowsLibC) posix.libc())._get_osfhandle(fd); + return JavaLibCHelper.toFileDescriptor(handle); + } else { + return JavaLibCHelper.toFileDescriptor(fd); + } + } + + private boolean hasNanosecondPrecision(FileStat fileStat) { + return fileStat instanceof NanosecondFileStat && !Platform.IS_MAC; + } + + private void utimensat(File file, int parentFd) { + String path = file.getAbsolutePath(); + FileStat fileStat = posix.stat(path); + if (!hasNanosecondPrecision(fileStat)) { + file.delete(); + return; + } + + long atimeSeconds = fileStat.atime()+2; + long mtimeSeconds = fileStat.mtime()-2; + long atimeNanoSeconds = 123456789; + long mtimeNanoSeconds = 135; + posix.utimensat(parentFd, + path, + new long[] {atimeSeconds, atimeNanoSeconds}, + new long[] {mtimeSeconds, mtimeNanoSeconds}, + 0); + assertStatNanoSecond(file, atimeSeconds, atimeNanoSeconds, mtimeSeconds, mtimeNanoSeconds); + } + + private void assertStatNanoSecond(File file, long atimeSeconds, long atimeNanoSeconds, long mtimeSeconds, long mtimeNanoSeconds) { + NanosecondFileStat nanosecondFileStat = (NanosecondFileStat) posix.stat(file.getPath()); + assertEquals("Access timestamp should be updated", atimeSeconds, nanosecondFileStat.atime()); + assertEquals("Modification timestamp should be updated", mtimeSeconds, nanosecondFileStat.mtime()); + assertEquals("Access time precision should be in ns", atimeNanoSeconds, nanosecondFileStat.aTimeNanoSecs()); + assertEquals("Modification time precision should be in ns", mtimeNanoSeconds, nanosecondFileStat.mTimeNanoSecs()); + file.delete(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.RandomAccessFile` acquired to `raf` by call to `RandomAccessFile(...)` at line 287 is not released after line 295. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void FileTest.fcntlDupfdTest() + +### Procedure Id: +jnr.posix.FileTest.fcntlDupfdTest():void.2d4d6ec67940c406afe88c8010a1de29 + +### File: +src/test/java/jnr/posix/FileTest.java + +### Key: +FileTest.java|fcntlDupfdTest|RESOURCE_LEAK + +### Node Key: +734de9b26e688966a79959c29dc4ba96 + +### Hash: +0ea72fa34e9626b851f645e1eefabf56 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9022/instruction.md b/inferredbugs-9022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81d734730822f410874b0227345000a1bf4d7000 --- /dev/null +++ b/inferredbugs-9022/instruction.md @@ -0,0 +1,278 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** graphchi-java +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package edu.cmu.graphchi.shards; + +import edu.cmu.graphchi.ChiVertex; +import edu.cmu.graphchi.datablocks.BytesToValueConverter; +import edu.cmu.graphchi.datablocks.DataBlockManager; + +import java.io.*; + +/** + * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class MemoryShard { + + private String edgeDataFilename; + private String adjDataFilename; + private int rangeStart; + private int rangeEnd; + + private byte[] adjData; + private int blockId; + private int edataFilesize; + private boolean loaded = false; + private boolean hasSetRangeOffset = false, hasSetOffset = false; + + private int rangeStartOffset, rangeStartEdgePtr, rangeContVid; + + private DataBlockManager dataBlockManager; + private BytesToValueConverter converter; + private int streamingOffset, streamingOffsetEdgePtr, streamingOffsetVid; + + private MemoryShard() {} + + public MemoryShard(String edgeDataFilename, String adjDataFilename, int rangeStart, int rangeEnd) { + this.edgeDataFilename = edgeDataFilename; + this.adjDataFilename = adjDataFilename; + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException { + byte[] data = dataBlockManager.getRawBlock(blockId); + + if (modifiesInedges) { + FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename)); + fos.write(data); + fos.close(); + } else if (modifiesOutedges) { + ucar.unidata.io.RandomAccessFile rFile = + new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd"); + rFile.seek(rangeStartEdgePtr); + int last = streamingOffsetEdgePtr; + if (last == 0) last = edataFilesize; + rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr); + rFile.close(); + } + dataBlockManager.release(blockId); + + } + + public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices) + throws FileNotFoundException, IOException { + if (adjData == null) { + loadAdj(); + + edataFilesize = (int) new File(edgeDataFilename).length(); + blockId = dataBlockManager.allocateBlock(edataFilesize); + } + + + System.out.println("Load memory shard"); + int vid = 0; + int edataPtr = 0; + int adjOffset = 0; + int sizeOf = converter.sizeOf(); + DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData)); + while(adjInput.available() > 0) { + if (!hasSetOffset && vid > rangeEnd) { + streamingOffset = adjOffset; + streamingOffsetEdgePtr = edataPtr; + streamingOffsetVid = vid; + hasSetOffset = true; + } + if (!hasSetRangeOffset && vid >= rangeStart) { + rangeStartOffset = adjOffset; + rangeStartEdgePtr = edataPtr; + hasSetRangeOffset = true; + } + + int n = 0; + int ns = adjInput.readUnsignedByte(); + adjOffset += 1; + assert(ns >= 0); + if (ns == 0) { + // next value tells the number of vertices with zeros + vid++; + int nz = adjInput.readUnsignedByte(); + adjOffset += 1; + vid += nz; + continue; + } + if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after. + n = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + } else { + n = ns; + } + + ChiVertex vertex = null; + if (vid >= windowStart && vid <= windowEnd) { + vertex = vertices[vid - windowStart]; + } + + while (--n >= 0) { + int target = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + if (!(target >= rangeStart && target <= rangeEnd)) + throw new IllegalStateException("Target " + target + " not in range!"); + if (vertex != null) { + vertex.addOutEdge(blockId, edataPtr, target); + } + + if (target >= windowStart) { + if (target <= windowEnd) { + ChiVertex dstVertex = vertices[target - windowStart]; + if (dstVertex != null) { + dstVertex.addInEdge(blockId, edataPtr, vid); + } + if (vertex != null && dstVertex != null) { + dstVertex.parallelSafe = false; + vertex.parallelSafe = false; + } + } + } + edataPtr += sizeOf; + + // TODO: skip + } + vid++; + } + + /* Load the edge data from file. Should be done asynchronously. */ + if (!loaded) { + int read = 0; + FileInputStream fdis = new FileInputStream(new File(edgeDataFilename)); + while (read < edataFilesize) { + read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read); + } + + loaded = true; + } + } + + + private void loadAdj() throws FileNotFoundException, IOException { + File adjFile = new File(adjDataFilename); + FileInputStream fis = new FileInputStream(adjFile); + + int filesize = (int) adjFile.length(); + adjData = new byte[filesize]; + + int read = 0; + while (read < filesize) { + read += fis.read(adjData, read, filesize - read); + } + + } + + public DataBlockManager getDataBlockManager() { + return dataBlockManager; + } + + public void setDataBlockManager(DataBlockManager dataBlockManager) { + this.dataBlockManager = dataBlockManager; + } + + public void setConverter(BytesToValueConverter converter) { + this.converter = converter; + } + + public int getStreamingOffset() { + return streamingOffset; + } + + public int getStreamingOffsetEdgePtr() { + return streamingOffsetEdgePtr; + } + + public int getStreamingOffsetVid() { + return streamingOffsetVid; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileOutputStream` acquired to `fos` by call to `FileOutputStream(...)` at line 56 is not released after line 70. +**Note**: potential exception at line 57 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryShard.commitAndRelease(boolean,boolean) + +### Procedure Id: +edu.cmu.graphchi.shards.MemoryShard.commitAndRelease(boolean,boolean):void.2d929323907b6d7f6e71be996df592b1 + +### File: +src/edu/cmu/graphchi/shards/MemoryShard.java + +### Key: +MemoryShard.java|commitAndRelease|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +75dcc8ea05b6b116cfe783201608b79d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9025/instruction.md b/inferredbugs-9025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8d8d2be1bc9ccd7c5ed40a413380edd46625677c --- /dev/null +++ b/inferredbugs-9025/instruction.md @@ -0,0 +1,277 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** graphchi-java +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package edu.cmu.graphchi.shards; + +import edu.cmu.graphchi.ChiVertex; +import edu.cmu.graphchi.datablocks.BytesToValueConverter; +import edu.cmu.graphchi.datablocks.DataBlockManager; + +import java.io.*; + +/** + * Copyright [2012] [Aapo Kyrola, Guy Blelloch, Carlos Guestrin / Carnegie Mellon University] + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +public class MemoryShard { + + private String edgeDataFilename; + private String adjDataFilename; + private int rangeStart; + private int rangeEnd; + + private byte[] adjData; + private int blockId; + private int edataFilesize; + private boolean loaded = false; + private boolean hasSetRangeOffset = false, hasSetOffset = false; + + private int rangeStartOffset, rangeStartEdgePtr, rangeContVid; + + private DataBlockManager dataBlockManager; + private BytesToValueConverter converter; + private int streamingOffset, streamingOffsetEdgePtr, streamingOffsetVid; + + private MemoryShard() {} + + public MemoryShard(String edgeDataFilename, String adjDataFilename, int rangeStart, int rangeEnd) { + this.edgeDataFilename = edgeDataFilename; + this.adjDataFilename = adjDataFilename; + this.rangeStart = rangeStart; + this.rangeEnd = rangeEnd; + } + + public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException { + byte[] data = dataBlockManager.getRawBlock(blockId); + + if (modifiesInedges) { + FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename)); + fos.write(data); + fos.close(); + } else if (modifiesOutedges) { + ucar.unidata.io.RandomAccessFile rFile = + new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd"); + rFile.seek(rangeStartEdgePtr); + int last = streamingOffsetEdgePtr; + if (last == 0) last = edataFilesize; + rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr); + rFile.close(); + } + dataBlockManager.release(blockId); + + } + + public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices) + throws FileNotFoundException, IOException { + if (adjData == null) { + loadAdj(); + + edataFilesize = (int) new File(edgeDataFilename).length(); + blockId = dataBlockManager.allocateBlock(edataFilesize); + } + + + System.out.println("Load memory shard"); + int vid = 0; + int edataPtr = 0; + int adjOffset = 0; + int sizeOf = converter.sizeOf(); + DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData)); + while(adjInput.available() > 0) { + if (!hasSetOffset && vid > rangeEnd) { + streamingOffset = adjOffset; + streamingOffsetEdgePtr = edataPtr; + streamingOffsetVid = vid; + hasSetOffset = true; + } + if (!hasSetRangeOffset && vid >= rangeStart) { + rangeStartOffset = adjOffset; + rangeStartEdgePtr = edataPtr; + hasSetRangeOffset = true; + } + + int n = 0; + int ns = adjInput.readUnsignedByte(); + adjOffset += 1; + assert(ns >= 0); + if (ns == 0) { + // next value tells the number of vertices with zeros + vid++; + int nz = adjInput.readUnsignedByte(); + adjOffset += 1; + vid += nz; + continue; + } + if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after. + n = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + } else { + n = ns; + } + + ChiVertex vertex = null; + if (vid >= windowStart && vid <= windowEnd) { + vertex = vertices[vid - windowStart]; + } + + while (--n >= 0) { + int target = Integer.reverseBytes(adjInput.readInt()); + adjOffset += 4; + if (!(target >= rangeStart && target <= rangeEnd)) + throw new IllegalStateException("Target " + target + " not in range!"); + if (vertex != null) { + vertex.addOutEdge(blockId, edataPtr, target); + } + + if (target >= windowStart) { + if (target <= windowEnd) { + ChiVertex dstVertex = vertices[target - windowStart]; + if (dstVertex != null) { + dstVertex.addInEdge(blockId, edataPtr, vid); + } + if (vertex != null && dstVertex != null) { + dstVertex.parallelSafe = false; + vertex.parallelSafe = false; + } + } + } + edataPtr += sizeOf; + + // TODO: skip + } + vid++; + } + + /* Load the edge data from file. Should be done asynchronously. */ + if (!loaded) { + int read = 0; + FileInputStream fdis = new FileInputStream(new File(edgeDataFilename)); + while (read < edataFilesize) { + read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read); + } + + loaded = true; + } + } + + + private void loadAdj() throws FileNotFoundException, IOException { + File adjFile = new File(adjDataFilename); + FileInputStream fis = new FileInputStream(adjFile); + + int filesize = (int) adjFile.length(); + adjData = new byte[filesize]; + + int read = 0; + while (read < filesize) { + read += fis.read(adjData, read, filesize - read); + } + + } + + public DataBlockManager getDataBlockManager() { + return dataBlockManager; + } + + public void setDataBlockManager(DataBlockManager dataBlockManager) { + this.dataBlockManager = dataBlockManager; + } + + public void setConverter(BytesToValueConverter converter) { + this.converter = converter; + } + + public int getStreamingOffset() { + return streamingOffset; + } + + public int getStreamingOffsetEdgePtr() { + return streamingOffsetEdgePtr; + } + + public int getStreamingOffsetVid() { + return streamingOffsetVid; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.DataInputStream` acquired to `read` by call to `new()` at line 87 is not released after line 155. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MemoryShard.loadVertices(int,int,edu.cmu.graphchi.ChiVertex[]) + +### Procedure Id: +edu.cmu.graphchi.shards.MemoryShard.loadVertices(int,int,edu.cmu.graphchi.ChiVertex[]):void.08eca2a67801347d010929569207ca9c + +### File: +src/edu/cmu/graphchi/shards/MemoryShard.java + +### Key: +MemoryShard.java|loadVertices|RESOURCE_LEAK + +### Node Key: +4edd0cf623436d61e7851a9cd143b6e5 + +### Hash: +17d09caeea199d80ae94c2de6c757e14 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9040/instruction.md b/inferredbugs-9040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6924144817e4e3e6811caca172327d1b033ac5d --- /dev/null +++ b/inferredbugs-9040/instruction.md @@ -0,0 +1,447 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// PSO.java +// +// Author: +// Antonio J. Nebro +// Juan J. Durillo +// +// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see . + +package jmetal.metaheuristics.singleObjective.particleSwarmOptimization; + +import jmetal.core.*; +import jmetal.operators.selection.BestSolutionSelection; +import jmetal.util.JMException; +import jmetal.util.PseudoRandom; +import jmetal.util.comparators.ObjectiveComparator; +import jmetal.util.wrapper.XReal; + +import java.io.IOException; +import java.util.Comparator; +import java.util.HashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Class implementing a single-objective PSO algorithm + */ +public class StandardPSO2011 extends Algorithm { + + /** + * Stores the number of swarm_ used + */ + private int swarmSize_; + /** + * Stores the maximum number of iteration_ + */ + private int maxIterations_; + /** + * Stores the current number of iteration_ + */ + private int iteration_; + /** + * Stores the particles + */ + private SolutionSet swarm_; + /** + * Stores the local best solutions found so far for each particles + */ + private Solution[] localBest_; + /** + * Stores the global best solution found + */ + private Solution globalBest_; + /** + * Stores the speed_ of each particle + */ + private double[][] speed_; + + int evaluations_ ; + + /** + * Comparator object + */ + Comparator comparator_ ; + + Operator findBestSolution_ ; + + double r1Max_; + double r1Min_; + double r2Max_; + double r2Min_; + double C1Max_; + double C1Min_; + double C2Max_; + double C2Min_; + double WMax_; + double WMin_; + double ChVel1_; + double ChVel2_; + + /** + * Constructor + * @param problem Problem to solve + */ + public StandardPSO2011(Problem problem) { + super(problem) ; + + r1Max_ = 1.0; + r1Min_ = 0.0; + r2Max_ = 1.0; + r2Min_ = 0.0; + C1Max_ = 1.5; + C1Min_ = 1.5; + C2Max_ = 1.5; + C2Min_ = 1.5; + WMax_ = 0.9; + WMin_ = 0.1; + ChVel1_ = 1.0; + ChVel2_ = 1.0; + + comparator_ = new ObjectiveComparator(0) ; // Single objective comparator + HashMap parameters ; // Operator parameters + + parameters = new HashMap() ; + parameters.put("comparator", comparator_) ; + findBestSolution_ = new BestSolutionSelection(parameters) ; + + evaluations_ = 0 ; + } // Constructor + + boolean success_; + + + public int[] getNeighbourhood(int i) { + int[] neighbors = new int[3] ; + neighbors[0] = (i - 1 + swarmSize_)% swarmSize_; + neighbors[1] = i ; + neighbors[2] = (i + 1)% swarmSize_; + + return neighbors ; + } + + /** + * Initialize all parameter of the algorithm + */ + public void initParams() { + swarmSize_ = ((Integer) getInputParameter("swarmSize")).intValue(); + maxIterations_ = ((Integer) getInputParameter("maxIterations")).intValue(); + + iteration_ = 0 ; + + success_ = false; + + swarm_ = new SolutionSet(swarmSize_); + localBest_ = new Solution[swarmSize_]; + + // Create the speed_ vector + speed_ = new double[swarmSize_][problem_.getNumberOfVariables()]; + + } // initParams + + // Adaptive inertia + private double inertiaWeight(int iter, int miter, double wmax, double wmin) { + //return wmax; // - (((wmax-wmin)*(double)iter)/(double)miter); + return wmax - (((wmax-wmin)*(double)iter)/(double)miter); + } // inertiaWeight + + // constriction coefficient (M. Clerc) + private double constrictionCoefficient(double c1, double c2) { + double rho = c1 + c2; + //rho = 1.0 ; + if (rho <= 4) { + return 1.0; + } else { + return 2 / Math.abs((2 - rho - Math.sqrt(Math.pow(rho, 2.0) - 4.0 * rho))); + } + } // constrictionCoefficient + + + // velocity bounds + private double velocityConstriction(double v, double[] deltaMax, + double[] deltaMin, int variableIndex, + int particleIndex) throws IOException { + + return v; + /* + + //System.out.println("v: " + v + "\tdmax: " + dmax + "\tdmin: " + dmin) ; + double result; + + double dmax = deltaMax[variableIndex]; + double dmin = deltaMin[variableIndex]; + + result = v; + + if (v > dmax) { + result = dmax; + } + + if (v < dmin) { + result = dmin; + } + + return result; + */ + } // velocityConstriction + + /** + * Update the speed of each particle + * @throws jmetal.util.JMException + */ + private void computeSpeed(int iter, int miter) throws JMException, IOException { + double r1, r2 ; + //double W ; + double C1, C2; + double wmax, wmin, deltaMax, deltaMin; + XReal bestGlobal; + + bestGlobal = new XReal(globalBest_) ; + + for (int i = 0; i < swarmSize_; i++) { + XReal particle = new XReal(swarm_.get(i)) ; + XReal bestParticle = new XReal(localBest_[i]) ; + + //int bestIndividual = (Integer)findBestSolution_.execute(swarm_) ; + + C1Max_ = 2.5; + C1Min_ = 1.5; + C2Max_ = 2.5; + C2Min_ = 1.5; + + r1 = PseudoRandom.randDouble(r1Min_, r1Max_); + r2 = PseudoRandom.randDouble(r2Min_, r2Max_); + C1 = PseudoRandom.randDouble(C1Min_, C1Max_); + C2 = PseudoRandom.randDouble(C2Min_, C2Max_); + //W = PseudoRandom.randDouble(WMin_, WMax_); + // + + WMax_ = 0.9; + WMin_ = 0.9; + ChVel1_ = 1.0; + ChVel2_ = 1.0; + + C1 = 2.5 ; + C2 = 1.5 ; + + wmax = WMax_; + wmin = WMin_; +/* + for (int var = 0; var < particle.size(); var++) { + //Computing the velocity of this particle + speed_[i][var] = velocityConstriction(constrictionCoefficient(C1, C2) * + (inertiaWeight(iter, miter, wmax, wmin) * + speed_[i][var] + + C1 * r1 * (bestParticle.getValue(var) - particle.getValue(var)) + + C2 * r2 * (bestGlobal.getValue(var) - + particle.getValue(var))), deltaMax_, + deltaMin_, //[var], + var, + i); + } +*/ + C1 = 1.5 ; + C2 = 1.5 ; + double W = 0.9 ; + for (int var = 0; var < particle.size(); var++) { + //Computing the velocity of this particle + speed_[i][var] = inertiaWeight(iter, miter, wmax, wmin) * speed_[i][var] + + C1 * r1 * (bestParticle.getValue(var) - particle.getValue(var)) + + C2 * r2 * (bestGlobal.getValue(var) - particle.getValue(var)) ; + } + } + } // computeSpeed + + /** + * Update the position of each particle + * @throws jmetal.util.JMException + */ + private void computeNewPositions() throws JMException { + for (int i = 0; i < swarmSize_; i++) { + //Variable[] particle = swarm_.get(i).getDecisionVariables(); + XReal particle = new XReal(swarm_.get(i)) ; + //particle.move(speed_[i]); + for (int var = 0; var < particle.size(); var++) { + particle.setValue(var, particle.getValue(var) + speed_[i][var]) ; + + if (particle.getValue(var) < problem_.getLowerLimit(var)) { + particle.setValue(var, problem_.getLowerLimit(var)); + speed_[i][var] = speed_[i][var] * ChVel1_; // + } + if (particle.getValue(var) > problem_.getUpperLimit(var)) { + particle.setValue(var, problem_.getUpperLimit(var)); + speed_[i][var] = speed_[i][var] * ChVel2_; // + } + + } + } + } // computeNewPositions + + + /** + * Runs of the SMPSO algorithm. + * @return a SolutionSet that is a set of non dominated solutions + * as a result of the algorithm execution + * @throws jmetal.util.JMException + */ + public SolutionSet execute() throws JMException, ClassNotFoundException { + initParams(); + + success_ = false; + globalBest_ = null ; + //->Step 1 (and 3) Create the initial population and evaluate + for (int i = 0; i < swarmSize_; i++) { + Solution particle = new Solution(problem_); + problem_.evaluate(particle); + evaluations_ ++ ; + swarm_.add(particle); + if ((globalBest_ == null) || (particle.getObjective(0) < globalBest_.getObjective(0))) + globalBest_ = new Solution(particle) ; + } + + //-> Step2. Initialize the speed_ of each particle to 0 + for (int i = 0; i < swarmSize_; i++) { + for (int j = 0; j < problem_.getNumberOfVariables(); j++) { + speed_[i][j] = 0.0; + } + } + + //-> Step 6. Initialize the memory of each particle + for (int i = 0; i < swarm_.size(); i++) { + Solution particle = new Solution(swarm_.get(i)); + localBest_[i] = particle; + } + + //-> Step 7. Iterations .. + while (iteration_ < maxIterations_) { + int bestIndividual = (Integer)findBestSolution_.execute(swarm_) ; + try { + //Compute the speed_ + computeSpeed(iteration_, maxIterations_); + } catch (IOException ex) { + Logger.getLogger(StandardPSO2011.class.getName()).log(Level.SEVERE, null, ex); + } + + //Compute the new positions for the swarm_ + computeNewPositions(); + + //Mutate the swarm_ + //mopsoMutation(iteration_, maxIterations_); + + //Evaluate the new swarm_ in new positions + for (int i = 0; i < swarm_.size(); i++) { + Solution particle = swarm_.get(i); + problem_.evaluate(particle); + evaluations_ ++ ; + } + + //Actualize the memory of this particle + for (int i = 0; i < swarm_.size(); i++) { + //int flag = comparator_.compare(swarm_.get(i), localBest_[i]); + //if (flag < 0) { // the new particle is best_ than the older remember + if ((swarm_.get(i).getObjective(0) < localBest_[i].getObjective(0))) { + Solution particle = new Solution(swarm_.get(i)); + localBest_[i] = particle; + } // if + if ((swarm_.get(i).getObjective(0) < globalBest_.getObjective(0))) { + Solution particle = new Solution(swarm_.get(i)); + globalBest_ = particle; + } // if + + } + iteration_++; + } + + // Return a population with the best individual + SolutionSet resultPopulation = new SolutionSet(1) ; + resultPopulation.add(swarm_.get((Integer)findBestSolution_.execute(swarm_))) ; + + return resultPopulation ; + } // execute +} // PSO + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `StandardPSO2011.globalBest_` last assigned on line 303 could be null and is dereferenced at line 358. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +SolutionSet StandardPSO2011.execute() + +### Procedure Id: +jmetal.metaheuristics.singleObjective.particleSwarmOptimization.StandardPSO2011.execute():jmetal.cor.1a028acbbd04cd6d504a10c397e76964 + +### File: +src/main/java/jmetal/metaheuristics/singleObjective/particleSwarmOptimization/StandardPSO2011.java + +### Key: +StandardPSO2011.java|execute|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +6617164ce98933165948e1e8301b1a0a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9041/instruction.md b/inferredbugs-9041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..696cca97d53d333693f757dade7aa28a3c73b6ec --- /dev/null +++ b/inferredbugs-9041/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// NSGAIIRunner.java +// +// Author: +// Antonio J. Nebro +// +// Copyright (c) 2014 Antonio J. Nebro +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see . + +package jmetal.runner; + +import jmetal.core.Algorithm; +import jmetal.core.Operator; +import jmetal.core.Problem; +import jmetal.core.SolutionSet; +import jmetal.metaheuristics.nsgaII.NSGAIITemplate; +import jmetal.operators.crossover.SBXCrossover; +import jmetal.operators.mutation.PolynomialMutation; +import jmetal.operators.selection.BinaryTournament2; +import jmetal.problems.Kursawe; +import jmetal.problems.ProblemFactory; +import jmetal.qualityIndicator.QualityIndicator; +import jmetal.util.AlgorithmRunner; +import jmetal.util.Configuration; +import jmetal.util.JMException; +import jmetal.util.evaluator.SequentialSolutionSetEvaluator; +import jmetal.util.evaluator.SolutionSetEvaluator; +import jmetal.util.fileOutput.DefaultFileOutputContext; +import jmetal.util.fileOutput.SolutionSetOutput; + +import java.io.IOException; +import java.util.logging.FileHandler; +import java.util.logging.Logger; + +/** + * Class to configure and execute the NSGA-II algorithm. + *

    + * Besides the classic NSGA-II, a steady-state version (ssNSGAII) is also + * included (See: J.J. Durillo, A.J. Nebro, F. Luna and E. Alba + * "On the Effect of the Steady-State Selection Scheme in + * Multi-Objective Genetic Algorithms" + * 5th International Conference, EMO 2009, pp: 183-197. + * April 2009) + */ + +public class NSGAIIRunner { + private static Logger logger_; + private static FileHandler fileHandler_; + + /** + * @param args Command line arguments. + * @throws jmetal.util.JMException + * @throws java.io.IOException + * @throws SecurityException Usage: three options + * - jmetal.metaheuristics.nsgaII.NSGAIIRunner + * - jmetal.metaheuristics.nsgaII.NSGAIIRunner problemName + * - jmetal.metaheuristics.nsgaII.NSGAIIRunner problemName paretoFrontFile + */ + public static void main(String[] args) throws + JMException, + SecurityException, + IOException, + ClassNotFoundException { + + Problem problem; + Algorithm algorithm; + Operator crossover; + Operator mutation; + Operator selection; + + QualityIndicator indicators; + + // Logger object and file to store log messages + logger_ = Configuration.logger_; + fileHandler_ = new FileHandler("NSGAII_main.log"); + logger_.addHandler(fileHandler_); + + indicators = null; + if (args.length == 1) { + Object[] params = {"Real"}; + problem = (new ProblemFactory()).getProblem(args[0], params); + } else if (args.length == 2) { + Object[] params = {"Real"}; + problem = (new ProblemFactory()).getProblem(args[0], params); + indicators = new QualityIndicator(problem, args[1]); + } else { + problem = new Kursawe("Real", 3); + /* + Examples: + problem = new Water("Real"); + problem = new ZDT3("ArrayReal", 30); + problem = new ConstrEx("Real"); + problem = new DTLZ1("Real"); + problem = new OKA2("Real") + */ + } + + /* + * Alternatives: + * - "NSGAII" + * - "SteadyStateNSGAII" + */ + String nsgaIIVersion = "NSGAII" ; + + /* + * Alternatives: + * - evaluator = new SequentialSolutionSetEvaluator() // NSGAII + * - evaluator = new new MultithreadedSolutionSetEvaluator(threads, problem) // parallel NSGAII + */ + SolutionSetEvaluator evaluator = new SequentialSolutionSetEvaluator() ; + + crossover = new SBXCrossover.Builder() + .distributionIndex(20.0) + .probability(0.9) + .build() ; + + mutation = new PolynomialMutation.Builder() + .distributionIndex(20.0) + .probability(1.0/problem.getNumberOfVariables()) + .build(); + + selection = new BinaryTournament2.Builder() + .build(); + + algorithm = new NSGAIITemplate.Builder(problem, evaluator) + .crossover(crossover) + .mutation(mutation) + .selection(selection) + .maxEvaluations(25000) + .populationSize(100) + .build(nsgaIIVersion) ; + + AlgorithmRunner algorithmRunner = new AlgorithmRunner.Executor(algorithm) + .execute() ; + + SolutionSet population = algorithmRunner.getSolutionSet() ; + long computingTime = algorithmRunner.getComputingTime() ; + + new SolutionSetOutput.Printer(population) + .separator("\t") + .varFileOutputContext(new DefaultFileOutputContext("VAR.tsv")) + .funFileOutputContext(new DefaultFileOutputContext("FUN.tsv")) + .print(); + + logger_.info("Total execution time: " + computingTime + "ms"); + logger_.info("Objectives values have been written to file FUN.tsv"); + logger_.info("Variables values have been written to file VAR.tsv"); + + if (indicators != null) { + logger_.info("Quality indicators"); + logger_.info("Hypervolume: " + indicators.getHypervolume(population)); + logger_.info("GD : " + indicators.getGD(population)); + logger_.info("IGD : " + indicators.getIGD(population)); + logger_.info("Spread : " + indicators.getSpread(population)); + logger_.info("Epsilon : " + indicators.getEpsilon(population)); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.BufferedWriter` acquired by call to `SolutionSetOutput$Printer(...)` at line 150 is not released after line 152. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NSGAIIRunner.main(java.lang.String[]) + +### Procedure Id: +jmetal.runner.NSGAIIRunner.main(java.lang.String[]):void.14240db51ba6234a0f7e6588d9a5ee00 + +### File: +src/main/java/jmetal/runner/NSGAIIRunner.java + +### Key: +NSGAIIRunner.java|main|RESOURCE_LEAK + +### Node Key: +e81c98eb27f9c4dc71be4209079d3c45 + +### Hash: +9985b8b8637026e90c93b1276c238680 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9046/instruction.md b/inferredbugs-9046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..896c6238160f354eb71b13ca51c0e692af9303e6 --- /dev/null +++ b/inferredbugs-9046/instruction.md @@ -0,0 +1,133 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// RankComparator.java +// +// Author: +// Antonio J. Nebro +// Juan J. Durillo +// +// Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see . + +package org.uma.jmetal3.util.comparator; + +import org.uma.jmetal3.core.Solution; + +import java.util.Comparator; + +/** + * This class implements a Comparator (a method for comparing + * Solution objects) based on the rank of the solutions. + */ +public class RankingComparator implements Comparator { + /** + * Compares two solutions. + * + * @param solution1 Object representing the first Solution. + * @param solution2 Object representing the second Solution. + * @return -1, or 0, or 1 if o1 is less than, equal, or greater than o2, + * respectively. + */ + @Override + public int compare(Solution solution1, Solution solution2) { + if (solution1 == null) { + return 1; + } else if (solution2 == null) { + return -1; + } + + if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") < (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) { + return -1; + } + + if ((int)solution1.getAlgorithmAttributes().getAttribute("Rank") > (int)solution2.getAlgorithmAttributes().getAttribute("Rank")) { + return 1; + } + + return 0; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `solution1.getAlgorithmAttributes().getAttribute("Rank")` could be null and is dereferenced at line 49. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int RankingComparator.compare(Solution,Solution) + +### Procedure Id: +org.uma.jmetal3.util.comparator.RankingComparator.compare(org.uma.jmetal3.core.Solution,org.uma.jmet.486fedf3628bdb395aa1f566bb29deab + +### File: +jmetal-core/src/main/java/org/uma/jmetal3/util/comparator/RankingComparator.java + +### Key: +RankingComparator.java|compare|NULL_DEREFERENCE + +### Node Key: +dc678d91476904c7b1b2af11d980af71 + +### Hash: +ae57b07d39fe3203c4e17bee985cb5b3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9047/instruction.md b/inferredbugs-9047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..962db4334242a5011f8ab29d30ba81d412391fad --- /dev/null +++ b/inferredbugs-9047/instruction.md @@ -0,0 +1,735 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// +// Special Session on Real-Parameter Optimization at CEC-05 +// Edinburgh, UK, 2-5 Sept. 2005 +// +// Organizers: +// Prof. Kalyanmoy Deb +// deb@iitk.ac.in +// http://www.iitk.ac.in/kangal/deb.htm +// A/Prof. P. N. Suganthan +// epnsugan@ntu.edu.sg +// http://www.ntu.edu.sg/home/EPNSugan +// +// Java version of the org.uma.test functions +// +// Matlab reference code +// http://www.ntu.edu.sg/home/EPNSugan +// +// Java version developer: +// Assistant Prof. Ying-ping Chen +// Department of Computer Science +// National Chiao Tung University +// HsinChu City, Taiwan +// ypchen@csie.nctu.edu.tw +// http://www.csie.nctu.edu.tw/~ypchen/ +// +// Typical use of the org.uma.test functions in the Benchmark: +// +// // Create a Benchmark object +// Benchmark theBenchmark = new Benchmark(); +// // Use the factory function call to create a org.uma.test function object +// // org.uma.test function 3 with 50 dimension +// // the object class is "TestFunc" +// TestFunc aTestFunc = theBenchmark.testFunctionFactory(3, 50); +// // Invoke the function with x +// double experimentoutput = aTestFunc.f(x); +// +// Version 0.90 +// Currently, this version cannot handle any numbers of dimensions. +// It cannot generate the shifted global optima and rotation matrices +// that are not provided with the Matlab reference code. +// It can handle all cases whose data files are provided with +// the Matlab reference code. +// Version 0.91 +// Revised according to the Matlab reference code and the PDF document +// dated March 8, 2005. +// + +package org.uma.jmetal.problem.singleobjective.cec2005competitioncode; + +import org.uma.jmetal.util.JMetalException; +import org.uma.jmetal.util.JMetalLogger; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.text.DecimalFormat; +import java.util.Random; +import java.util.StringTokenizer; +import java.util.logging.Level; + +public class Benchmark { + + // Fixed (class) parameters + static final public int NUM_TEST_FUNC = 25; + static final public String DEFAULT_FILE_BIAS = + JMetalLogger.cec2005SupportDataDirectory + "/fbias_data.txt"; + static final public String[] test_func_class_names = { + "F01_shifted_sphere", + "F02_shifted_schwefel", + "F03_shifted_rotated_high_cond_elliptic", + "F04_shifted_schwefel_noise", + "F05_schwefel_global_opt_bound", + "F06_shifted_rosenbrock", + "F07_shifted_rotated_griewank", + "F08_shifted_rotated_ackley_global_opt_bound", + "F09_shifted_rastrigin", + "F10_shifted_rotated_rastrigin", + "F11_shifted_rotated_weierstrass", + "F12_schwefel", + "F13_shifted_expanded_griewank_rosenbrock", + "F14_shifted_rotated_expanded_scaffer", + "F15_hybrid_composition_1", + "F16_rotated_hybrid_composition_1", + "F17_rotated_hybrid_composition_1_noise", + "F18_rotated_hybrid_composition_2", + "F19_rotated_hybrid_composition_2_narrow_basin_global_opt", + "F20_rotated_hybrid_composition_2_global_opt_bound", + "F21_rotated_hybrid_composition_3", + "F22_rotated_hybrid_composition_3_high_cond_num_matrix", + "F23_noncontinuous_rotated_hybrid_composition_3", + "F24_rotated_hybrid_composition_4", + "F25_rotated_hybrid_composition_4_bound" + }; + + // For certain functions, some essential data can be calculated beforehand. + // Hence, a maximum supported number of dimensions should be specified. + // Specifiy the number of dimensions here if you need more. + static final public int MAX_SUPPORT_DIM = 100; + static final public double PIx2 = Math.PI * 2.0; + + // Formatter for the number representation + static final public DecimalFormat scientificFormatter = + new DecimalFormat("0.0000000000000000E00"); + static final public DecimalFormat numberFormatter = scientificFormatter; + static final public DecimalFormat percentageFormatter = new DecimalFormat("0.0000000000"); + + // Random number generator + // If you want to plan a specific seed, do it here. + static final public Random random = new Random(); + + // Class loader & reflection + static final public ClassLoader loader = ClassLoader.getSystemClassLoader(); + static final Class[] test_func_arg_types = {int.class, double.class}; + + // Class variables + static private double[] m_iSqrt; + + // Instance variables + private double[] m_biases; + + // Constructors + // Load the data common to all org.uma.test functions. + // Get ready for creating org.uma.test function instances. + public Benchmark() throws JMetalException { + this(DEFAULT_FILE_BIAS); + } + + public Benchmark(String file_bias) throws JMetalException { + m_biases = new double[NUM_TEST_FUNC]; + m_iSqrt = new double[MAX_SUPPORT_DIM]; + + loadRowVectorFromFile(file_bias, NUM_TEST_FUNC, m_biases); + + for (int i = 0; i < MAX_SUPPORT_DIM; i++) { + m_iSqrt[i] = Math.sqrt(((double) i) + 1.0); + } + } + + // Entry point + // If the Benchmark class is executed as a stand-alone application, + // its job is to run the org.uma.test on all the org.uma.test functions. + static public void main(String args[]) throws JMetalException { + Benchmark theBenchmark = new Benchmark(); + theBenchmark.runTest(0); + } + + // Sphere function + static public double sphere(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += x[i] * x[i]; + } + + return (sum); + } + + // Sphere function with noise + static public double sphere_noise(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += x[i] * x[i]; + } + + // NOISE + // Comment the next line to remove the noise + sum *= (1.0 + 0.1 * Math.abs(random.nextGaussian())); + + return (sum); + } + + // Schwefel's problem 1.2 + static public double schwefel_102(double[] x) { + + double prev_sum, curr_sum, outer_sum; + + curr_sum = x[0]; + outer_sum = (curr_sum * curr_sum); + + for (int i = 1; i < x.length; i++) { + prev_sum = curr_sum; + curr_sum = prev_sum + x[i]; + outer_sum += (curr_sum * curr_sum); + } + + return (outer_sum); + } + + // + // Basic functions + // + + // Rosenbrock's function + static public double rosenbrock(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < (x.length - 1); i++) { + double temp1 = (x[i] * x[i]) - x[i + 1]; + double temp2 = x[i] - 1.0; + sum += (100.0 * temp1 * temp1) + (temp2 * temp2); + } + + return (sum); + } + + // F2: Rosenbrock's Function -- 2D version + static public double F2(double x, double y) { + double temp1 = (x * x) - y; + double temp2 = x - 1.0; + return ((100.0 * temp1 * temp1) + (temp2 * temp2)); + } + + // Griewank's function + static public double griewank(double[] x) { + + double sum = 0.0; + double product = 1.0; + + for (int i = 0; i < x.length; i++) { + sum += ((x[i] * x[i]) / 4000.0); + product *= Math.cos(x[i] / m_iSqrt[i]); + } + + return (sum - product + 1.0); + } + + // F8: Griewank's Function -- 1D version + static public double F8(double x) { + return (((x * x) / 4000.0) - Math.cos(x) + 1.0); + } + + // Ackley's function + static public double ackley(double[] x) { + + double sum1 = 0.0; + double sum2 = 0.0; + + for (int i = 0; i < x.length; i++) { + sum1 += (x[i] * x[i]); + sum2 += (Math.cos(PIx2 * x[i])); + } + + return (-20.0 * Math.exp(-0.2 * Math.sqrt(sum1 / ((double) x.length))) - Math + .exp(sum2 / ((double) x.length)) + 20.0 + Math.E); + } + + // Round function + // 0. Use the Matlab version for rounding numbers + static public double myRound(double x) { + return (Math.signum(x) * Math.round(Math.abs(x))); + } + + // 1. "o" is provided + static public double myXRound(double x, double o) { + return ((Math.abs(x - o) < 0.5) ? x : (myRound(2.0 * x) / 2.0)); + } + + // 2. "o" is not provided + static public double myXRound(double x) { + return ((Math.abs(x) < 0.5) ? x : (myRound(2.0 * x) / 2.0)); + } + + // Rastrigin's function + static public double rastrigin(double[] x) { + + double sum = 0.0; + + for (int i = 0; i < x.length; i++) { + sum += (x[i] * x[i]) - (10.0 * Math.cos(PIx2 * x[i])) + 10.0; + } + + return (sum); + } + + // Non-Continuous Rastrigin's function + static public double rastriginNonCont(double[] x) { + + double sum = 0.0; + double currX; + + for (int i = 0; i < x.length; i++) { + currX = myXRound(x[i]); + sum += (currX * currX) - (10.0 * Math.cos(PIx2 * currX)) + 10.0; + } + + return (sum); + } + + // Weierstrass function + static public double weierstrass(double[] x) { + return (weierstrass(x, 0.5, 3.0, 20)); + } + + static public double weierstrass(double[] x, double a, double b, int Kmax) { + + double sum1 = 0.0; + for (int i = 0; i < x.length; i++) { + for (int k = 0; k <= Kmax; k++) { + sum1 += Math.pow(a, k) * Math.cos(PIx2 * Math.pow(b, k) * (x[i] + 0.5)); + } + } + + double sum2 = 0.0; + for (int k = 0; k <= Kmax; k++) { + sum2 += Math.pow(a, k) * Math.cos(PIx2 * Math.pow(b, k) * (0.5)); + } + + return (sum1 - sum2 * ((double) (x.length))); + } + + // F8F2 + static public double F8F2(double[] x) { + + double sum = 0.0; + + for (int i = 1; i < x.length; i++) { + sum += F8(F2(x[i - 1], x[i])); + } + sum += F8(F2(x[x.length - 1], x[0])); + + return (sum); + } + + // Scaffer's F6 function + static public double ScafferF6(double x, double y) { + double temp1 = x * x + y * y; + double temp2 = Math.sin(Math.sqrt(temp1)); + double temp3 = 1.0 + 0.001 * temp1; + return (0.5 + ((temp2 * temp2 - 0.5) / (temp3 * temp3))); + } + + // Expanded Scaffer's F6 function + static public double EScafferF6(double[] x) { + + double sum = 0.0; + + for (int i = 1; i < x.length; i++) { + sum += ScafferF6(x[i - 1], x[i]); + } + sum += ScafferF6(x[x.length - 1], x[0]); + + return (sum); + } + + // Non-Continuous Expanded Scaffer's F6 function + static public double EScafferF6NonCont(double[] x) { + + double sum = 0.0; + double prevX, currX; + + currX = myXRound(x[0]); + for (int i = 1; i < x.length; i++) { + prevX = currX; + currX = myXRound(x[i]); + sum += ScafferF6(prevX, currX); + } + prevX = currX; + currX = myXRound(x[0]); + sum += ScafferF6(prevX, currX); + + return (sum); + } + + // Elliptic + static public double elliptic(double[] x) { + + double sum = 0.0; + double a = 1e6; + + for (int i = 0; i < x.length; i++) { + sum += Math.pow(a, (((double) i) / ((double) (x.length - 1)))) * x[i] * x[i]; + } + + return (sum); + } + + // Hybrid composition + static public double hybrid_composition(double[] x, HCJob job) throws JMetalException { + + int num_func = job.num_func; + int num_dim = job.num_dim; + + // Get the raw weights + double wMax = Double.NEGATIVE_INFINITY; + for (int i = 0; i < num_func; i++) { + double sumSqr = 0.0; + shift(job.z[i], x, job.o[i]); + for (int j = 0; j < num_dim; j++) { + sumSqr += (job.z[i][j] * job.z[i][j]); + } + job.w[i] = Math.exp(-1.0 * sumSqr / (2.0 * num_dim * job.sigma[i] * job.sigma[i])); + if (wMax < job.w[i]) { + wMax = job.w[i]; + } + } + + // Modify the weights + double wSum = 0.0; + double w1mMaxPow = 1.0 - Math.pow(wMax, 10.0); + for (int i = 0; i < num_func; i++) { + if (job.w[i] != wMax) { + job.w[i] *= w1mMaxPow; + } + wSum += job.w[i]; + } + + // Normalize the weights + for (int i = 0; i < num_func; i++) { + job.w[i] /= wSum; + } + + double sumF = 0.0; + for (int i = 0; i < num_func; i++) { + for (int j = 0; j < num_dim; j++) { + job.z[i][j] /= job.lambda[i]; + } + rotate(job.zM[i], job.z[i], job.M[i]); + sumF += + job.w[i] * + ( + job.C * job.basic_func(i, job.zM[i]) / job.fmax[i] + + job.biases[i] + ); + } + return (sumF); + } + + // Shift + static public void shift(double[] results, double[] x, double[] o) { + for (int i = 0; i < x.length; i++) { + results[i] = x[i] - o[i]; + } + } + + // Rotate + static public void rotate(double[] results, double[] x, double[][] matrix) { + xA(results, x, matrix); + } + + // (1xD) row vector * (Dx1) column vector = (1) scalar + static public double xy(double[] x, double[] y) { + double result = 0.0; + for (int i = 0; i < x.length; i++) { + result += (x[i] * y[i]); + } + + return (result); + } + + // + // Elementary operations + // + + // (1xD) row vector * (DxD) matrix = (1xD) row vector + static public void xA(double[] result, double[] x, double[][] A) { + for (int i = 0; i < result.length; i++) { + result[i] = 0.0; + for (int j = 0; j < result.length; j++) { + result[i] += (x[j] * A[j][i]); + } + } + } + + // (DxD) matrix * (Dx1) column vector = (Dx1) column vector + static public void Ax(double[] result, double[][] A, double[] x) { + for (int i = 0; i < result.length; i++) { + result[i] = 0.0; + for (int j = 0; j < result.length; j++) { + result[i] += (A[i][j] * x[j]); + } + } + } + + // + // Matrix & vector operations + // + + // + // Utility functions for loading data from the given text file + // + static public void loadTestDataFromFile(String file, int num_test_points, int test_dimension, + double[][] x, double[] f) throws JMetalException { + try { + JMetalLogger.logger.info("File bias: " + file); + + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadMatrix(brSrc, num_test_points, test_dimension, x); + loadColumnVector(brSrc, num_test_points, f); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadRowVectorFromFile(String file, int columns, double[] row) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadRowVector(brSrc, columns, row); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadRowVector(BufferedReader brSrc, int columns, double[] row) + throws Exception { + String stToken; + StringTokenizer stTokenizer = new StringTokenizer(brSrc.readLine()); + for (int i = 0; i < columns; i++) { + stToken = stTokenizer.nextToken(); + row[i] = Double.parseDouble(stToken); + } + } + + static public void loadColumnVectorFromFile(String file, int rows, double[] column) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadColumnVector(brSrc, rows, column); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadColumnVector(BufferedReader brSrc, int rows, double[] column) + throws Exception { + String stToken; + for (int i = 0; i < rows; i++) { + StringTokenizer stTokenizer = new StringTokenizer(brSrc.readLine()); + stToken = stTokenizer.nextToken(); + column[i] = Double.parseDouble(stToken); + } + } + + static public void loadNMatrixFromFile(String file, int N, int rows, int columns, + double[][][] matrix) throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + for (int i = 0; i < N; i++) { + loadMatrix(brSrc, rows, columns, matrix[i]); + } + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadMatrixFromFile(String file, int rows, int columns, double[][] matrix) + throws JMetalException { + try { + BufferedReader brSrc = new BufferedReader(new FileReader(file)); + loadMatrix(brSrc, rows, columns, matrix); + brSrc.close(); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + } + + static public void loadMatrix(BufferedReader brSrc, int rows, int columns, double[][] matrix) + throws Exception { + for (int i = 0; i < rows; i++) { + loadRowVector(brSrc, columns, matrix[i]); + } + } + + // + // Use this function to manufacture new org.uma.test function objects + // + public TestFunc testFunctionFactory(int func_num, int dimension) throws JMetalException { + TestFunc returnFunc = null; + try { + returnFunc = (TestFunc) + loader.loadClass(JMetalLogger.cec2005Package + "." + test_func_class_names[func_num - 1]) + .getConstructor(test_func_arg_types) + .newInstance( + new Object[] { + new Integer(dimension), + new Double(m_biases[func_num - 1]) + } + ); + } catch (Exception e) { + JMetalLogger.logger.log(Level.SEVERE, "Error in Benchmark.java", e); + throw new JMetalException("Error in Benchmark.java"); + } + return (returnFunc); + } + + // Run tests on the org.uma.test functions + // < 0: Error! + // = 0: On all the functions + // > 0: On the specified org.uma.test function + public void runTest() throws JMetalException { + runTest(0); + } + + public void runTest(int func_num) throws JMetalException { + if (func_num == 0) { + for (int i = 1; i <= NUM_TEST_FUNC; i++) { + runTest(i); + } + } else if ((func_num < 0) || (func_num > NUM_TEST_FUNC)) { + throw new JMetalException("The specified func_num is out of range."); + } else { + // Run the org.uma.test function against the check points + int num_test_points = 10; + int test_dimension = 50; + + double[] test_f = new double[num_test_points]; + double[][] test_x = new double[num_test_points][test_dimension]; + + String file_test = "testData/test_data_func" + func_num + ".txt"; + + // Create the org.uma.test function object + TestFunc aFunc = testFunctionFactory(func_num, test_dimension); + + JMetalLogger.logger.info("Run tests on function " + func_num + + " (" + aFunc.name() + "):"); + JMetalLogger.logger.info(" " + + num_test_points + " " + + aFunc.dimension() + "-dimension check points"); + + loadTestDataFromFile(file_test, num_test_points, test_dimension, test_x, test_f); + + for (int i = 0; i < num_test_points; i++) { + // Execute the org.uma.test function + // Collect and compare the results + double result = aFunc.f(test_x[i]); + double diff = result - test_f[i]; + double ratio = Math.abs(diff / test_f[i]); + JMetalLogger.logger.info(" " + + numberFormatter.format(result) + + " - " + + numberFormatter.format(test_f[i]) + + " = " + + numberFormatter.format(diff)); + JMetalLogger.logger.info(" " + " " + + "Difference ratio = " + numberFormatter.format(ratio)); + if (ratio != 0.0) { + if (ratio <= 1e-12) { + JMetalLogger.logger.info(" (<= 1E-12)"); + } else { + JMetalLogger.logger.info(" (> 1E-12) *****"); + } + } else { + JMetalLogger.logger.info(""); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.FileReader` acquired by call to `new()` at line 502 is not released after line 505. +**Note**: potential exception at line 503 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Benchmark.loadRowVectorFromFile(String,int,double[]) + +### Procedure Id: +org.uma.jmetal.problem.singleobjective.cec2005competitioncode.Benchmark.loadRowVectorFromFile(java.l.83e55fb7722d22e9d61ff14de0d6c477 + +### File: +jmetal-core/src/main/java/org/uma/jmetal/problem/singleobjective/cec2005competitioncode/Benchmark.java + +### Key: +Benchmark.java|loadRowVectorFromFile|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +98489b2c1a69e4f6525607e71a4474a2 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9048/instruction.md b/inferredbugs-9048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..925324ec122769bb3512f34d8d35d9dbbf316411 --- /dev/null +++ b/inferredbugs-9048/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jMetal +**Bug ID:** 23 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// SMSEMOA_SettingsTest.java +// +// Author: +// Antonio J. Nebro +// +// Copyright (c) 2014 Antonio J. Nebro +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this program. If not, see + +package org.uma.test.experiment.settings; + +import org.uma.jmetal.core.Algorithm; +import org.uma.jmetal.core.Problem; +import org.uma.jmetal.experiment.Settings; +import org.uma.jmetal.experiment.settings.SMSEMOASettings; +import org.uma.jmetal.operator.crossover.SBXCrossover; +import org.uma.jmetal.operator.mutation.PolynomialMutation; +import org.uma.jmetal.problem.Fonseca; + +import org.junit.Before; +import org.junit.Test; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Properties; + +import static org.junit.Assert.assertEquals; + +/** + * Created with IntelliJ IDEA. + * User: antelverde + * Date: 27/06/13 + * Time: 23:08 + * To change this template use File | Settings | File Templates. + */ +public class SMSEMOASettingsTest { + Properties configuration_ ; + + @Before + public void init() throws FileNotFoundException, IOException { + configuration_ = new Properties(); + InputStreamReader isr = new InputStreamReader(new FileInputStream(ClassLoader.getSystemResource("SMSEMOA.conf").getPath())); + configuration_.load(isr); + } + + @Test + public void testConfigure() throws Exception { + double epsilon = 0.000000000000001 ; + Settings smsemoaSettings = new SMSEMOASettings("Fonseca"); + Algorithm algorithm = smsemoaSettings.configure() ; + Problem problem = new Fonseca("Real") ; + SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ; + double pc = (Double)crossover.getParameter("probability") ; + double dic = (Double)crossover.getParameter("distributionIndex") ; + PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ; + double pm = (Double)mutation.getParameter("probability") ; + double dim = (Double)mutation.getParameter("distributionIndex") ; + + assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); + assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); + + assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon); + assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon); + + assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon); + assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon); + assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon); + } + + @Test + public void testConfigure2() throws Exception { + double epsilon = 0.000000000000001 ; + Settings smsemoaSettings = new SMSEMOASettings("Fonseca"); + Algorithm algorithm = smsemoaSettings.configure(configuration_) ; + Problem problem = new Fonseca("Real") ; + SBXCrossover crossover = (SBXCrossover)algorithm.getOperator("crossover") ; + double pc = (Double)crossover.getParameter("probability") ; + double dic = (Double)crossover.getParameter("distributionIndex") ; + PolynomialMutation mutation = (PolynomialMutation)algorithm.getOperator("mutation") ; + double pm = (Double)mutation.getParameter("probability") ; + double dim = (Double)mutation.getParameter("distributionIndex") ; + + assertEquals("SMSEMOA_SettingsTest", 100, ((Integer)algorithm.getInputParameter("populationSize")).intValue()); + assertEquals("SMSEMOA_SettingsTest", 25000, ((Integer)algorithm.getInputParameter("maxEvaluations")).intValue()); + + assertEquals("SMSEMOA_SettingsTest", 0.9, pc, epsilon); + assertEquals("SMSEMOA_SettingsTest", 20.0, dic, epsilon); + + assertEquals("SMSEMOA_SettingsTest", 1.0/problem.getNumberOfVariables(), pm, epsilon); + assertEquals("SMSEMOA_SettingsTest", 20.0, dim, epsilon); + assertEquals("SMSEMOA_SettingsTest", 100.0, ((Double)algorithm.getInputParameter("offset")).doubleValue(), epsilon); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `algorithm.operators_` last assigned on line 87 could be null and is dereferenced by call to `getOperator(...)` at line 89. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SMSEMOASettingsTest.testConfigure2() + +### Procedure Id: +org.uma.test.experiment.settings.SMSEMOASettingsTest.testConfigure2():void.9f8c0c96d3ad1c5ae0383ed2a1cb5bdf + +### File: +jmetal-core/src/test/java/org/uma/test/experiment/settings/SMSEMOASettingsTest.java + +### Key: +SMSEMOASettingsTest.java|testConfigure2|NULL_DEREFERENCE + +### Node Key: +ecb005b3b398757c0871c208dae4f8e6 + +### Hash: +f9e7c55d512bb0bcdcaffab5476bbc65 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9070/instruction.md b/inferredbugs-9070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a106e3dd3236c4dd4f21b89976c52ad8e8c26f8a --- /dev/null +++ b/inferredbugs-9070/instruction.md @@ -0,0 +1,205 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** vlingo-actors +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +// Copyright © 2012-2018 Vaughn Vernon. All rights reserved. +// +// This Source Code Form is subject to the terms of the +// Mozilla Public License, v. 2.0. If a copy of the MPL +// was not distributed with this file, You can obtain +// one at https://mozilla.org/MPL/2.0/. + +package io.vlingo.actors; + +import java.lang.reflect.Constructor; +import static io.vlingo.common.compiler.DynaNaming.fullyQualifiedClassnameFor; + +import io.vlingo.actors.ProxyGenerator.Result; +import io.vlingo.common.compiler.DynaClassLoader; +import io.vlingo.common.compiler.DynaCompiler; +import io.vlingo.common.compiler.DynaCompiler.Input; + +public final class ActorProxy { + private static final DynaCompiler proxyCompiler = new DynaCompiler(); + + public static T createFor(final Class protocol, final Actor actor, final Mailbox mailbox) { + final T maybeCachedProxy = actor.lifeCycle.environment.lookUpProxy(protocol); + + if (maybeCachedProxy != null) { + return maybeCachedProxy; + } + + final String proxyClassname = fullyQualifiedClassnameFor(protocol, "__Proxy"); + + final T maybeProxy = tryProxyFor(proxyClassname, actor, mailbox); + + if (maybeProxy != null) { + actor.lifeCycle.environment.cacheProxy(maybeProxy); + return maybeProxy; + } + + synchronized (protocol) { + T newProxy; + + try { + newProxy = tryCreate(protocol, actor, mailbox, proxyClassname); + } catch (Exception e) { + newProxy = tryGenerateCreate(protocol, actor, mailbox, proxyClassname); + } + + actor.lifeCycle.environment.cacheProxy(newProxy); + + return newProxy; + } + } + + private static DynaClassLoader classLoaderFor(final Actor actor) { + DynaClassLoader classLoader = actor.lifeCycle.environment.stage.world().classLoader(); + if (classLoader == null) { + classLoader = new DynaClassLoader(ActorProxy.class.getClassLoader()); + actor.stage().world().classLoader(classLoader); + } + return classLoader; + } + + private static Class loadProxyClassFor( + final String targetClassname, + final Actor actor) + throws ClassNotFoundException { + final Class proxyClass = Class.forName(targetClassname, true, classLoaderFor(actor)); + return proxyClass; + } + + @SuppressWarnings("unchecked") + private static T tryCreate( + final Class protocol, + final Actor actor, + final Mailbox mailbox, + final String targetClassname) + throws Exception { + final Class proxyClass = loadProxyClassFor(targetClassname, actor); + return (T) tryCreateWithProxyClass(proxyClass, actor, mailbox); + } + + @SuppressWarnings("unchecked") + private static T tryProxyFor(final String targetClassname, final Actor actor, final Mailbox mailbox) { + try { + final Class maybeProxyClass = (Class) loadProxyClassFor(targetClassname, actor); + if (maybeProxyClass != null) { + return tryCreateWithProxyClass(maybeProxyClass, actor, mailbox); + } + } catch (Exception e) { + // fall through + } + return null; + } + + @SuppressWarnings("unchecked") + private static T tryCreateWithProxyClass(final Class proxyClass, final Actor actor, final Mailbox mailbox) throws Exception { + Constructor ctor = proxyClass.getConstructor(new Class[] {Actor.class, Mailbox.class}); + return (T) ctor.newInstance(actor, mailbox); + } + + private static T tryGenerateCreate( + final Class protocol, + final Actor actor, + final Mailbox mailbox, + final String targetClassname) { + try (final ProxyGenerator generator = ProxyGenerator.forMain(true, actor.logger())) { + return tryGenerateCreate(protocol, actor, mailbox, generator, targetClassname); + } catch (Exception emain) { + try (final ProxyGenerator generator = ProxyGenerator.forTest(true, actor.logger())) { + return tryGenerateCreate(protocol, actor, mailbox, generator, targetClassname); + } catch (Exception etest) { + throw new IllegalArgumentException("Actor proxy " + protocol.getName() + " not created for main or test: " + etest.getMessage(), etest); + } + } + } + + private static T tryGenerateCreate( + final Class protocol, + final Actor actor, + final Mailbox mailbox, + final ProxyGenerator generator, + final String targetClassname) { + try { + final Result result = generator.generateFor(protocol.getName()); + final Input input = new Input(protocol, targetClassname, result.source, result.sourceFile, classLoaderFor(actor), generator.type(), true); + final Class proxyClass = proxyCompiler.compile(input); + return tryCreateWithProxyClass(proxyClass, actor, mailbox); + } catch (Exception e) { + throw new IllegalArgumentException("Actor proxy " + protocol.getName() + " not created because: " + e.getMessage(), e); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `io.vlingo.actors.ActorProxy.createFor` indirectly writes to field `n$20.io.vlingo.actors.World.classLoader` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object ActorProxy.createFor(Class,Actor,Mailbox) + +### Procedure Id: +io.vlingo.actors.ActorProxy.createFor(java.lang.Class,io.vlingo.actors.Actor,io.vlingo.actors.Mailbo.72a0db559ac2b8ae8a1e2a354377659b + +### File: +src/main/java/io/vlingo/actors/ActorProxy.java + +### Key: +ActorProxy.java|createFor|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +2381ee392545d532fb91086b2f047701 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9071/instruction.md b/inferredbugs-9071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..80e6c83d5a7f78f7ef7601d3dea61b203ec002af --- /dev/null +++ b/inferredbugs-9071/instruction.md @@ -0,0 +1,856 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 50 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import com.igormaznitsa.jbbp.utils.JBBPSystemProperty; +import com.igormaznitsa.jbbp.utils.JBBPUtils; +import java.io.*; + +/** + * A Filter stream implementing a countable bit stream interface. It allows read + * not only bytes but also bits from an input stream. The Class is not a + * thread-safe one. + * + * @since 1.0 + */ +public class JBBPBitInputStream extends FilterInputStream implements JBBPCountableBitStream { + + /** + * The Initial an Array buffer size for whole stream read. + */ + protected static final int INITIAL_ARRAY_BUFFER_SIZE = JBBPSystemProperty.PROPERTY_INPUT_INITIAL_ARRAY_BUFFER_SIZE.getAsInteger(32); + + /** + * The Inside bit buffer, + */ + private int bitBuffer; + /** + * The Inside counter of bits in the bit buffer. + */ + private int bitsInBuffer; + /** + * The Byte counter. + */ + private long byteCounter; + + /** + * Inside temp variable to keep the bit buffer temporarily. + */ + private int markedBitBuffer; + /** + * Inside temp variable to keep the bit buffer counter temporarily. + */ + private int markedBitsInBuffer; + /** + * Inside temp variable to keep the byte counter temporarily. + */ + private long markedByteCounter; + + /** + * Flag shows that bit operations must be processed for MSB0 (most significant + * bit 0) mode. + */ + private final boolean msb0; + + /** + * A Constructor, the LSB0 bit order will be used by default. + * + * @param in an input stream to be filtered. + */ + public JBBPBitInputStream(final InputStream in) { + this(in, JBBPBitOrder.LSB0); + } + + /** + * A Constructor. + * + * @param in an input stream to be filtered. + * @param order a bit order mode for the filter. + * @see JBBPBitOrder#LSB0 + * @see JBBPBitOrder#MSB0 + */ + public JBBPBitInputStream(final InputStream in, final JBBPBitOrder order) { + super(in); + this.bitsInBuffer = 0; + this.msb0 = order == JBBPBitOrder.MSB0; + } + + /** + * Read array of boolean values. + * + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return read values as boolean array + * @throws IOException it will be thrown for transport error + */ + public boolean[] readBoolArray(final int items) throws IOException { + int pos = 0; + byte[] buffer; + if (items < 0) { + buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int read = this.read(buffer, pos, buffer.length - pos); + if (read < 0) { + break; + } + pos += read; + + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + } + } + else { + // number + buffer = new byte[items]; + int len = items; + while (len > 0) { + final int read = this.read(buffer, pos, len); + if (read < 0) { + throw new EOFException("Have read only " + pos + " bit portions instead of " + items); + } + pos += read; + len -= read; + } + } + + final boolean[] result = new boolean[pos]; + for (int i = 0; i < pos; i++) { + result[i] = buffer[i] != 0; + } + return result; + } + + /** + * Read array of bit sequence. + * + * @param bitNumber bit number for each bit sequence item, must be 1..8 + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return array of read bit items as a byte array + * @throws IOException it will be thrown for any transport problem during the + * operation + */ + public byte[] readBitsArray(final int items, final JBBPBitNumber bitNumber) throws IOException { + int pos = 0; + if (items < 0) { + byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int next = readBits(bitNumber); + if (next < 0) { + break; + } + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (byte) next; + } + if (buffer.length == pos) { + return buffer; + } + final byte[] result = new byte[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final byte[] buffer = new byte[items]; + for (int i = 0; i < items; i++) { + final int next = readBits(bitNumber); + if (next < 0) { + throw new EOFException("Have read only " + i + " bit portions instead of " + items); + } + buffer[i] = (byte) next; + } + return buffer; + } + } + + /** + * Read number of bytes for the stream. + * + * @param items number of items to be read, if less than zero then read whole + * stream till the end + * @return read byte items as a byte array + * @throws IOException it will be thrown for any transport problem during the + * operation + */ + public byte[] readByteArray(final int items) throws IOException { + int pos = 0; + if (items < 0) { + byte[] buffer = new byte[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (true) { + final int next = read(); + if (next < 0) { + break; + } + if (buffer.length == pos) { + final byte[] newbuffer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (byte) next; + } + if (buffer.length == pos) { + return buffer; + } + final byte[] result = new byte[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final byte[] buffer = new byte[items]; + final int read = this.read(buffer, 0, items); + if (read != items) { + throw new EOFException("Have read only " + read + " byte(s) instead of " + items + " byte(s)"); + } + return buffer; + } + } + + /** + * Read number of short items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode short values + * @return read items as a short array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public short[] readShortArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + short[] buffer = new short[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final int next = readUnsignedShort(byteOrder); + if (buffer.length == pos) { + final short[] newbuffer = new short[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (short) next; + } + if (buffer.length == pos) { + return buffer; + } + final short[] result = new short[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final short[] buffer = new short[items]; + for (int i = 0; i < items; i++) { + buffer[i] = (short) readUnsignedShort(byteOrder); + } + return buffer; + } + } + + /** + * Read number of integer items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode values + * @return read items as an integer array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int[] readIntArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + int[] buffer = new int[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final long next = readInt(byteOrder); + if (buffer.length == pos) { + final int[] newbuffer = new int[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = (int) next; + } + if (buffer.length == pos) { + return buffer; + } + final int[] result = new int[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final int[] buffer = new int[items]; + for (int i = 0; i < items; i++) { + buffer[i] = readInt(byteOrder); + } + return buffer; + } + } + + /** + * Read number of long items from the input stream. + * + * @param items number of items to be read from the input stream, if less than + * zero then all stream till the end will be read + * @param byteOrder the order of bytes to be used to decode values + * @return read items as a long array + * @throws IOException it will be thrown for any transport problem during the + * operation + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public long[] readLongArray(final int items, final JBBPByteOrder byteOrder) throws IOException { + int pos = 0; + if (items < 0) { + long[] buffer = new long[INITIAL_ARRAY_BUFFER_SIZE]; + // till end + while (hasAvailableData()) { + final long next = readLong(byteOrder); + if (buffer.length == pos) { + final long[] newbuffer = new long[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffer, 0, buffer.length); + buffer = newbuffer; + } + buffer[pos++] = next; + } + if (buffer.length == pos) { + return buffer; + } + final long[] result = new long[pos]; + System.arraycopy(buffer, 0, result, 0, pos); + return result; + } + else { + // number + final long[] buffer = new long[items]; + for (int i = 0; i < items; i++) { + buffer[i] = readLong(byteOrder); + } + return buffer; + } + } + + /** + * Read a unsigned short value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int readUnsignedShort(final JBBPByteOrder byteOrder) throws IOException { + final int b0 = this.read(); + if (b0 < 0) { + throw new EOFException(); + } + final int b1 = this.read(); + if (b1 < 0) { + throw new EOFException(); + } + return byteOrder == JBBPByteOrder.BIG_ENDIAN ? (b0 << 8) | b1 : (b1 << 8) | b0; + } + + /** + * Read an integer value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream or -1 if the end of + * stream has been reached + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public int readInt(final JBBPByteOrder byteOrder) throws IOException { + if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { + return (readUnsignedShort(byteOrder) << 16) | readUnsignedShort(byteOrder); + } + else { + return readUnsignedShort(byteOrder) | (readUnsignedShort(byteOrder) << 16); + } + } + + /** + * Read a long value from the stream. + * + * @param byteOrder he order of bytes to be used to decode the read value + * @return the unsigned short value read from stream or -1 if the end of + * stream has been reached + * @throws IOException it will be thrown for any transport problem during the + * operation + * @throws EOFException if the end of the stream has been reached + * @see JBBPByteOrder#BIG_ENDIAN + * @see JBBPByteOrder#LITTLE_ENDIAN + */ + public long readLong(final JBBPByteOrder byteOrder) throws IOException { + if (byteOrder == JBBPByteOrder.BIG_ENDIAN) { + return (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32) | ((long) readInt(byteOrder) & 0xFFFFFFFFL); + } + else { + return ((long) readInt(byteOrder) & 0xFFFFFFFFL) | (((long) readInt(byteOrder) & 0xFFFFFFFFL) << 32); + } + } + + /** + * Get the current fully read byte counter. + * + * @return the number of bytes read fully from the stream + */ + public long getCounter() { + return this.byteCounter; + } + + /** + * Get the value of the inside bit buffer + * + * @return the bit buffer state + */ + public int getBitBuffer() { + return this.bitBuffer; + } + + /** + * Get the number of buffered bits in the inside bit buffer + * + * @return the number of buffered bits in the bit buffer + */ + public int getBufferedBitsNumber() { + return this.bitsInBuffer; + } + + /** + * Get the bit order option for read operations. + * + * @return the bit order parameter + * @see JBBPBitOrder#LSB0 + * @see JBBPBitOrder#MSB0 + */ + public JBBPBitOrder getBitOrder() { + return this.msb0 ? JBBPBitOrder.MSB0 : JBBPBitOrder.LSB0; + } + + /** + * Read number of bits from the input stream. It reads bits from input stream + * since 0 bit and make reversion to return bits in the right order when 0 bit + * is 0 bit. if the stream is completed early than the data read then reading + * is just stopped and read value returned. The First read bit is placed as + * 0th bit. + * + * @param numOfBitsToRead the number of bits to be read, must be 1..8 + * @return the read bits as integer, -1 if the end of stream has been reached + * @throws IOException it will be thrown for transport errors to be read + * @throws NullPointerException if number of bits to be read is null + */ + public int readBits(final JBBPBitNumber numOfBitsToRead) throws IOException { + int result; + + final int numOfBitsAsNumber = numOfBitsToRead.getBitNumber(); + + if (this.bitsInBuffer == 0 && numOfBitsAsNumber == 8) { + result = this.readByteFromStream(); + if (result >= 0) { + this.byteCounter++; + } + return result; + } + else { + result = 0; + + if (numOfBitsAsNumber == this.bitsInBuffer) { + result = this.bitBuffer; + this.bitBuffer = 0; + this.bitsInBuffer = 0; + this.byteCounter++; + return result; + } + + int i = numOfBitsAsNumber; + int theBitBuffer = this.bitBuffer; + int theBitBufferCounter = this.bitsInBuffer; + + final boolean doIncCounter = theBitBufferCounter!=0; + + while (i > 0) { + if (theBitBufferCounter == 0) { + if (doIncCounter) this.byteCounter++; + final int nextByte = this.readByteFromStream(); + if (nextByte < 0) { + if (i == numOfBitsAsNumber) { + return nextByte; + } + else { + break; + } + } + else { + theBitBuffer = nextByte; + theBitBufferCounter = 8; + } + } + + result = (result << 1) | (theBitBuffer & 1); + theBitBuffer >>= 1; + theBitBufferCounter--; + i--; + } + + this.bitBuffer = theBitBuffer; + this.bitsInBuffer = theBitBufferCounter; + + return JBBPUtils.reverseBitsInByte(JBBPBitNumber.decode(numOfBitsAsNumber - i), (byte) result) & 0xFF; + } + } + + /** + * Read a boolean value saved as a byte. + * + * @return true if the value is not zero, false if the value is zero + * @throws IOException it will be thrown for transport errors. + */ + public boolean readBoolean() throws IOException { + final int read = this.read(); + if (read < 0) { + throw new EOFException("Can't read a boolean value"); + } + return read != 0; + } + + /** + * Read a byte value. + * + * @return the byte value read from the stream + * @throws IOException it will be thrown for transport errors. + */ + public int readByte() throws IOException { + final int read = this.read(); + if (read < 0) { + throw new EOFException("Can't read a byte value"); + } + return read; + } + + @Override + public boolean markSupported() { + return super.markSupported(); + } + + @Override + public synchronized void reset() throws IOException { + in.reset(); + this.bitBuffer = this.markedBitBuffer; + this.byteCounter = this.markedByteCounter; + this.bitsInBuffer = this.markedBitsInBuffer; + } + + @Override + public synchronized void mark(final int readlimit) { + in.mark(readlimit); + this.markedBitBuffer = this.bitBuffer; + this.markedByteCounter = this.byteCounter; + this.markedBitsInBuffer = this.bitsInBuffer; + } + + @Override + public int available() throws IOException { + return super.available(); + } + + /** + * Read padding bytes from the stream and ignore them to align the stream + * counter. + * + * @param alignByteNumber the byte number to align the stream + * @throws IOException it will be thrown for transport errors + * @throws EOFException it will be thrown if the stream end has been reached + * the before align border. + */ + public void align(final long alignByteNumber) throws IOException { + this.alignByte(); + + if (alignByteNumber > 0) { + long padding = (alignByteNumber - (this.byteCounter % alignByteNumber)) % alignByteNumber; + + while (padding > 0) { + final int skippedByte = this.read(); + if (skippedByte < 0) { + throw new EOFException("Can't align for " + alignByteNumber + " byte(s)"); + } + padding--; + } + } + + } + + @Override + public long skip(final long numOfBytes) throws IOException { + if (this.bitsInBuffer == 0) { + final long r = in.skip(numOfBytes); + this.byteCounter += (int) r; + return r; + } + else { + long i = numOfBytes; + long count = 0L; + while (i > 0) { + final int nxt = readBits(JBBPBitNumber.BITS_8); + if (nxt < 0) { + break; + } + count++; + i--; + } + return count; + } + } + + /** + * Inside method to read a byte from stream. + * + * @return the read byte or -1 if the end of the stream has been reached + * @throws IOException it will be thrown for transport errors + */ + private int readByteFromStream() throws IOException { + int result = this.in.read(); + if (result >= 0) { + if (this.msb0) { + result = JBBPUtils.reverseBitsInByte((byte) result) & 0xFF; + } + } + return result; + } + + /** + * Read the next stream byte into bit buffer. + * + * @return the read byte or -1 if the endo of stream has been reached. + * @throws IOException it will be thrown for transport errors + */ + private int loadNextByteInBuffer() throws IOException { + final int value = this.readByteFromStream(); + if (value < 0) { + return value; + } + + this.bitBuffer = value; + this.bitsInBuffer = 8; + + return value; + } + + /** + * Align read byte. If there are unread bits in inside bit buffer, it will be + * aligned to read the next byte from stream instead of reading from the bit + * buffer. + */ + public void alignByte() { + if (this.bitsInBuffer > 0 && this.bitsInBuffer < 8) { + this.byteCounter++; + this.bitsInBuffer = 0; + } + } + + /** + * Check that there is available data to read from stream. NB: It will read + * one byte from the stream and will save it into inside bit buffer. + * + * @return true if there is data to be read + * @throws IOException it will be thrown for transport errors + */ + public boolean hasAvailableData() throws IOException { + if (this.bitsInBuffer > 0) { + return true; + } + return loadNextByteInBuffer() >= 0; + } + + @Override + public int read(final byte[] array, final int offset, final int length) throws IOException { + if (this.bitsInBuffer == 0) { + int readBytes = 0; + int tmpoffset = offset; + int tmplen = length; + while (tmplen > 0) { + int read = this.in.read(array, tmpoffset, tmplen); + if (read < 0) { + readBytes = readBytes == 0 ? read : readBytes; + break; + } + tmplen -= read; + tmpoffset += read; + readBytes += read; + this.byteCounter += read; + } + + if (this.msb0) { + int index = offset; + int number = readBytes; + while (number > 0) { + array[index] = JBBPUtils.reverseBitsInByte(array[index]); + index++; + number--; + } + } + + return readBytes; + } + else { + int count = length; + int i = offset; + while (count > 0) { + final int nextByte = this.readBits(JBBPBitNumber.BITS_8); + if (nextByte < 0) { + break; + } + count--; + array[i++] = (byte) nextByte; + } + return length - count; + } + } + + /** + * Reset the byte counter for the stream. The Inside bit buffer will be reset + * also if it is not full. + * + * @see #align(long) + * @see #alignByte() + * @see #getBitBuffer() + * @see #getBufferedBitsNumber() + * @see #hasAvailableData() . + */ + public void resetCounter() { + if (this.bitsInBuffer < 8) { + this.bitsInBuffer = 0; + this.bitBuffer = 0; + } + this.byteCounter = 0L; + } + + @Override + public int read(final byte[] array) throws IOException { + return this.read(array, 0, array.length); + } + + @Override + public int read() throws IOException { + final int result; + if (this.bitsInBuffer == 0) { + result = this.readByteFromStream(); + if (result >= 0) { + this.byteCounter++; + } + return result; + } + else { + return this.readBits(JBBPBitNumber.BITS_8); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.igormaznitsa.jbbp.io.JBBPBitInputStream.readByteArray` indirectly reads without synchronization from `this.com.igormaznitsa.jbbp.io.JBBPBitInputStream.bitBuffer`. Potentially races with write in method `JBBPBitInputStream.reset()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +byte[] JBBPBitInputStream.readByteArray(int) + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPBitInputStream.readByteArray(int):byte[].9905c343d985338a2ebb240cb4121f4b + +### File: +src/main/java/com/igormaznitsa/jbbp/io/JBBPBitInputStream.java + +### Key: +JBBPBitInputStream.java|readByteArray|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +07208325277e5da830a9c2b74619306b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9076/instruction.md b/inferredbugs-9076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff5cc953262d0e8602a2de3a0a3de8a119ab9522 --- /dev/null +++ b/inferredbugs-9076/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 221 is not released after line 372. +**Note**: potential exception at line 222 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testExceptionForOperatioOverEndedProcess() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testExceptionForOperatioOverEndedProcess():void.2c9ce3e426be732cc80f75c30337c0f9 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testExceptionForOperatioOverEndedProcess|RESOURCE_LEAK + +### Node Key: +f252c7633c834625d30364a2d12a8c07 + +### Hash: +72bb4a83c45d8281b52473b28b289803 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9077/instruction.md b/inferredbugs-9077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..443d9b540a1c7e3a8b05dcd5402cc6432d15028b --- /dev/null +++ b/inferredbugs-9077/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 150 is not released after line 150. +**Note**: potential exception at line 150 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testShortArray_AsIntegers_BigEndian() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testShortArray_AsIntegers_BigEndian():void.5a99bc204287bb56b0dc40e717204d77 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testShortArray_AsIntegers_BigEndian|RESOURCE_LEAK + +### Node Key: +e59d4f13a13a32109c447461abe95ea0 + +### Hash: +2129f8c0187c340abd97f43732571039 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9078/instruction.md b/inferredbugs-9078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c9072404ffe399fca42dc5241567d2402fd2f95 --- /dev/null +++ b/inferredbugs-9078/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 140 is not released after line 140. +**Note**: potential exception at line 140 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testShort_LittleEndian() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testShort_LittleEndian():void.a0718963985e53030d20b0f3bd17e01b + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testShort_LittleEndian|RESOURCE_LEAK + +### Node Key: +c8378f07bc7517fb0817a34558e677de + +### Hash: +db82faef52ce015253c171a096cd9651 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9079/instruction.md b/inferredbugs-9079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc5e5048d74d47f44d4e93216ef0407a25a553ce --- /dev/null +++ b/inferredbugs-9079/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 185 is not released after line 185. +**Note**: potential exception at line 185 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testInt_LittleEndian() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testInt_LittleEndian():void.f5ba19c2d9df5ea94b717bd0abb5c232 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testInt_LittleEndian|RESOURCE_LEAK + +### Node Key: +c8378f07bc7517fb0817a34558e677de + +### Hash: +c7177ee736a23a57c29da5a93428f1f7 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9082/instruction.md b/inferredbugs-9082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3fc8e3336232359227de3410ad56ebb687f7115 --- /dev/null +++ b/inferredbugs-9082/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 97 is not released after line 97. +**Note**: potential exception at line 97 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testBits_Int() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testBits_Int():void.13034337459c88964a65e78fc2e18b83 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testBits_Int|RESOURCE_LEAK + +### Node Key: +c8378f07bc7517fb0817a34558e677de + +### Hash: +18a532b72fd50e8c7ab78349e42558ce + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9083/instruction.md b/inferredbugs-9083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..32659e67e6588b7ceee0ff9788d4a7e943fbf7e2 --- /dev/null +++ b/inferredbugs-9083/instruction.md @@ -0,0 +1,493 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 29 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 195 is not released after line 195. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testLongArray() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testLongArray():void.c87bf15e8102838eca636f86d717b9d1 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testLongArray|RESOURCE_LEAK + +### Node Key: +4993c9594a0fc46e69f9bfd2837c960e + +### Hash: +4d167dc7b45a1e82f7a8c68e21019b3c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9084/instruction.md b/inferredbugs-9084/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..580ea5230d288a66ca04852136c6d6aaee9e5e40 --- /dev/null +++ b/inferredbugs-9084/instruction.md @@ -0,0 +1,494 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp.io; + +import static com.igormaznitsa.jbbp.io.JBBPOut.*; +import java.io.*; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPOutTest { + + @Test + public void testBinStart() throws Exception { + assertArrayEquals(new byte[]{1},binStart().Byte(1).end().toByteArray()); + assertArrayEquals(new byte[]{0x02,0x01},binStart(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{0x40,(byte)0x80},binStart(JBBPByteOrder.LITTLE_ENDIAN,JBBPBitOrder.MSB0).Short(0x0102).end().toByteArray()); + assertArrayEquals(new byte[]{(byte)0x80},binStart(JBBPBitOrder.MSB0).Byte(1).end().toByteArray()); + + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + assertSame(buffer, binStart(buffer).end()); + } + + @Test + public void testAlign() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align().Byte(0xFF).end().toByteArray()); + } + + @Test + public void testAlignWithArgument() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).Align(2).end().toByteArray().length); + assertArrayEquals(new byte[]{(byte) 0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Align(3).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(1).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(2).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2).Align(4).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x00, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x00, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 0x03, 0x04, 0x05, (byte) 0xFF}, new JBBPOut(new ByteArrayOutputStream()).Byte(1, 2, 3, 4, 5).Align(5).Byte(0xFF).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, (byte) 0x01, 0x00, 0x02, 0x00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(2).Byte(1).Align(2).Byte(2).Align(2).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0xF1, 0x00, 0x00, (byte) 0x01, 0x00, 00, 0x02, 0x00, 00, (byte) 0x03}, new JBBPOut(new ByteArrayOutputStream()).Byte(0xF1).Align(3).Byte(1).Align(3).Byte(2).Align(3).Byte(3).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x02, 03, 0x04, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Int(0x01020304).Align(5).Byte(0xF1).end().toByteArray()); + assertArrayEquals(new byte[]{0x01, 0x00, 0x00, 0x00, 0x00, (byte)0xF1}, new JBBPOut(new ByteArrayOutputStream()).Bit(1).Align(5).Byte(0xF1).end().toByteArray()); + } + + @Test + public void testEmptyArray() throws Exception { + assertEquals(0, new JBBPOut(new ByteArrayOutputStream()).end().toByteArray().length); + } + + @Test + public void testByte() throws Exception { + assertArrayEquals(new byte[]{-34}, binStart().Byte(-34).end().toByteArray()); + } + + @Test + public void testByteArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + } + + @Test + public void testByteArrayAsByteArray() throws Exception { + assertArrayEquals(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}, binStart().Byte(new byte[]{1, 3, 0, 2, 4, 1, 3, 7}).end().toByteArray()); + } + + @Test + public void testBit() throws Exception { + assertArrayEquals(new byte[]{1}, binStart().Bit(1).end().toByteArray()); + } + + @Test + public void testBit_MSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x80}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.MSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBit_LSB0() throws Exception { + assertArrayEquals(new byte[]{(byte) 0x01}, binStart(JBBPByteOrder.BIG_ENDIAN, JBBPBitOrder.LSB0).Bit(1).end().toByteArray()); + } + + @Test + public void testBits_Int() throws Exception { + assertArrayEquals(new byte[]{0xD}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD).end().toByteArray()); + } + + @Test + public void testBits_IntArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, 0xFD, 0xFE).end().toByteArray()); + } + + @Test + public void testBits_ByteArray() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xED}, binStart().Bits(JBBPNumberOfBits.BITS_4, (byte) 0xFD, (byte) 0x8E).end().toByteArray()); + } + + @Test + public void testBitArrayAsInts() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(1, 3, 0, 2, 4, 1, 3, 7).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(1, 3, 0, 7).end().toByteArray()); + } + + @Test + public void testBitArrayAsBytes() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 2, (byte) 4, (byte) 1, (byte) 3, (byte) 7}).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(new byte[]{(byte) 1, (byte) 3, (byte) 0, (byte) 7}).end().toByteArray()); + } + + @Test + public void testBitArrayAsBooleans() throws Exception { + assertArrayEquals(new byte[]{(byte) 0xE3}, binStart().Bit(true, true, false, false, false, true, true, true).end().toByteArray()); + assertArrayEquals(new byte[]{(byte) 0x0B}, binStart().Bit(true, true, false, true).end().toByteArray()); + } + + @Test + public void testShort() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,02}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShort_LittleEndian() throws Exception { + assertArrayEquals(new byte []{0x02,01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_BigEndian() throws Exception { + assertArrayEquals(new byte []{1,2,3,4}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsIntegers_LittleEndian() throws Exception { + assertArrayEquals(new byte []{2,1,4,3}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Short(0x0102,0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShorts() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short((short)0x0102, (short)0x0304).end().toByteArray()); + } + + @Test + public void testShortArray_AsShortArray() throws Exception { + assertArrayEquals(new byte[]{1, 2, 3, 4}, binStart().Short(new short[]{(short)0x0102, (short)0x0304}).end().toByteArray()); + } + + @Test + public void testInt() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04}, binStart().Int(0x01020304).end().toByteArray()); + } + + @Test + public void testIntArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Int(0x01020304, 0x05060708).end().toByteArray()); + } + + @Test + public void testInt_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01,0x02,0x03,0x04}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testInt_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Int(0x01020304).end().toByteArray()); + } + + @Test + public void testLong() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08}, binStart().Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLongArray() throws Exception { + assertArrayEquals(new byte []{0x01,02,0x03,0x04,0x05,0x06,0x07,0x08, 0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18}, binStart().Long(0x0102030405060708L,0x1112131415161718L).end().toByteArray()); + } + + @Test + public void testLong_BigEndian() throws Exception { + assertArrayEquals(new byte []{0x01, 02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}, binStart().ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testLong_LittleEndian() throws Exception { + assertArrayEquals(new byte[]{0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01}, binStart().ByteOrder(JBBPByteOrder.LITTLE_ENDIAN).Long(0x0102030405060708L).end().toByteArray()); + } + + @Test + public void testFlush() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPOut out = binStart(buffer); + + out.Bit(true); + assertEquals(0, buffer.size()); + out.Flush(); + assertEquals(1, buffer.size()); + } + + @Test + public void testExceptionForOperatioOverEndedProcess() throws Exception { + final JBBPOut out = binStart(); + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN).Long(0x0102030405060708L).end(); + try{ + out.Align(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Align(3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit((byte)34,(byte)12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bit(34,12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, 12,13,14); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bits(JBBPNumberOfBits.BITS_3, (byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Bool(true,false); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte((byte)1,(byte)2,(byte)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Byte(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.ByteOrder(JBBPByteOrder.BIG_ENDIAN); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Flush(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Int(1,2); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Long(1L,2L); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short(1,2,3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.Short((short)1,(short)2,(short)3); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + + try{ + out.end(); + fail("Must throw ISE"); + }catch(IllegalStateException ex){ + } + } + + @Test + public void testExternalStreamButNoByteArrayOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final DataOutputStream dout = new DataOutputStream(buffer); + + assertNull(binStart(dout).Byte(1,2,3).end()); + assertArrayEquals(new byte[]{1,2,3}, buffer.toByteArray()); + } + + @Test(expected = IllegalArgumentException.class) + public void testExceptionForBitOrderConfilctInCaseOfUsageBitOutputStream() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + final JBBPBitOutputStream bitstream = new JBBPBitOutputStream(buffer,JBBPBitOrder.LSB0); + + new JBBPOut(bitstream,JBBPByteOrder.BIG_ENDIAN,JBBPBitOrder.MSB0); + } + + @Test + public void testComplexWriting_1() throws Exception { + final ByteArrayOutputStream buffer = new ByteArrayOutputStream(16384); + + final JBBPOut begin = new JBBPOut(buffer); + + begin. + Bit(1, 2, 3, 0). + Bit(true, false, true). + Align(). + Byte(5). + Short(1, 2, 3, 4, 5). + Bool(true, false, true, true). + Int(0xABCDEF23, 0xCAFEBABE). + Long(0x123456789ABCDEF1L, 0x212356239091AB32L). + end(); + + final byte[] array = buffer.toByteArray(); + + assertEquals(40, array.length); + assertArrayEquals(new byte[]{ + (byte) 0x55, 5, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 1, 0, 1, 1, + (byte) 0xAB, (byte) 0xCD, (byte) 0xEF, 0x23, (byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE, + 0x12, 0x34, 0x56, 0x78, (byte) 0x9A, (byte) 0xBC, (byte) 0xDE, (byte) 0xF1, 0x21, 0x23, 0x56, 0x23, (byte) 0x90, (byte) 0x91, (byte) 0xAB, 0x32 + + }, array); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.igormaznitsa.jbbp.io.JBBPBitOutputStream` acquired by call to `binStart()` at line 130 is not released after line 130. +**Note**: potential exception at line 130 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void JBBPOutTest.testShort() + +### Procedure Id: +com.igormaznitsa.jbbp.io.JBBPOutTest.testShort():void.06082cb5922016d947c9eeecf34c2a92 + +### File: +src/test/java/com/igormaznitsa/jbbp/io/JBBPOutTest.java + +### Key: +JBBPOutTest.java|testShort|RESOURCE_LEAK + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +65bb54f50afec3a085c2acff54006227 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9085/instruction.md b/inferredbugs-9085/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a889ad9e2855fcba35ca3408f414c752e1fb18e --- /dev/null +++ b/inferredbugs-9085/instruction.md @@ -0,0 +1,1149 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-binary-block-parser +**Bug ID:** 42 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2014 Igor Maznitsa (http://www.igormaznitsa.com). + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.igormaznitsa.jbbp; + +import com.igormaznitsa.jbbp.exceptions.JBBPParsingException; +import com.igormaznitsa.jbbp.exceptions.JBBPTooManyFieldsFoundException; +import com.igormaznitsa.jbbp.model.*; +import java.io.EOFException; +import static org.junit.Assert.*; +import org.junit.Test; + +public class JBBPParserTest { + + @Test(expected=EOFException.class) + public void testParse_Bool_ErrorForEOF() throws Exception { + final JBBPParser parser = JBBPParser.prepare("bool;"); + parser.parse(new byte[0]); + } + + @Test + public void testParse_SingleDefaultNonamedBool_Default() throws Exception { + final JBBPParser parser = JBBPParser.prepare("bool;"); + JBBPFieldStruct result = parser.parse(new byte[]{(byte) 1}); + assertTrue(result.findFieldForType(JBBPFieldBoolean.class).getAsBool()); + result = parser.parse(new byte[]{(byte) 0}); + assertFalse(result.findFieldForType(JBBPFieldBoolean.class).getAsBool()); + } + + @Test + public void testParse_SingleDefaultNonamedBool_BigEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare(">bool;"); + JBBPFieldStruct result = parser.parse(new byte[]{(byte) 1}); + assertTrue(result.findFieldForType(JBBPFieldBoolean.class).getAsBool()); + result = parser.parse(new byte[]{(byte) 0}); + assertFalse(result.findFieldForType(JBBPFieldBoolean.class).getAsBool()); + } + + @Test + public void testParse_SingleDefaultNonamedBool_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("byte;"); + final JBBPFieldStruct result = parser.parse(new byte[]{(byte)-42}); + assertEquals(-42, result.findFieldForType(JBBPFieldByte.class).getAsInt()); + } + + @Test + public void testParse_SingleDefaultNonamedByte_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("ubyte;"); + final JBBPFieldStruct result = parser.parse(new byte[]{(byte)-42}); + assertEquals(-42 & 0xFF, result.findFieldForType(JBBPFieldUByte.class).getAsInt()); + } + + @Test + public void testParse_SingleDefaultNonamedUByte_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("short;"); + final JBBPFieldStruct result = parser.parse(new byte[]{1,2}); + assertEquals(0x0102, result.findFieldForType(JBBPFieldShort.class).getAsInt()); + } + + @Test + public void testParse_SingleDefaultNonamedShort_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("ushort;"); + final JBBPFieldStruct result = parser.parse(new byte[]{-1,-2}); + assertEquals(((-1 << 8) | (-2 & 0xFF)) & 0xFFFF, result.findFieldForType(JBBPFieldUShort.class).getAsInt()); + } + + @Test + public void testParse_SingleDefaultNonamedUShort_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("int;"); + final JBBPFieldStruct result = parser.parse(new byte[]{1,2,3,4}); + assertEquals(0x01020304, result.findFieldForType(JBBPFieldInt.class).getAsInt()); + } + + @Test + public void testParse_SingleDefaultNonamedInt_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("long;"); + final JBBPFieldStruct result = parser.parse(new byte[]{1,2,3,4,5,6,7,8}); + assertEquals(0x0102030405060708L, result.findFieldForType(JBBPFieldLong.class).getAsLong()); + } + + @Test + public void testParse_SingleDefaultNonamedLong_LittleEndian() throws Exception { + final JBBPParser parser = JBBPParser.prepare("byte[4];").parse(new byte[]{0x21, 0x43, 0x65, (byte)0x87}).findFieldForType(JBBPFieldArrayByte.class); + assertEquals(4, bytes.size()); + assertEquals(0x21, bytes.getAsInt(0) & 0xFF); + assertEquals(0x43, bytes.getAsInt(1) & 0xFF); + assertEquals(0x65, bytes.getAsInt(2) & 0xFF); + assertEquals(0x87, bytes.getAsInt(3) & 0xFF); + } + + @Test + public void testParse_FixedByteArray_LittleEndian() throws Exception { + final JBBPFieldArrayByte bytes = JBBPParser.prepare("byte[_];").parse(new byte[]{0x21, 0x43, 0x65, (byte)0x87}).findFieldForType(JBBPFieldArrayByte.class); + assertEquals(4, bytes.size()); + assertEquals(0x21, bytes.getAsInt(0) & 0xFF); + assertEquals(0x43, bytes.getAsInt(1) & 0xFF); + assertEquals(0x65, bytes.getAsInt(2) & 0xFF); + assertEquals(0x87, bytes.getAsInt(3) & 0xFF); + } + + @Test + public void testParse_NonFixedByteArray_LittleEndian() throws Exception { + final JBBPFieldArrayByte bytes = JBBPParser.prepare("ubyte[4];").parse(new byte[]{0x21, 0x43, 0x65, (byte)0x87}).findFieldForType(JBBPFieldArrayUByte.class); + assertEquals(4, bytes.size()); + assertEquals(0x21, bytes.getAsInt(0)); + assertEquals(0x43, bytes.getAsInt(1)); + assertEquals(0x65, bytes.getAsInt(2)); + assertEquals(0x87, bytes.getAsInt(3)); + } + + @Test + public void testParse_FixedUByteArray_LittleEndian() throws Exception { + final JBBPFieldArrayUByte bytes = JBBPParser.prepare("ubyte[_];").parse(new byte[]{0x21, 0x43, 0x65, (byte)0x87}).findFieldForType(JBBPFieldArrayUByte.class); + assertEquals(4, bytes.size()); + assertEquals(0x21, bytes.getAsInt(0)); + assertEquals(0x43, bytes.getAsInt(1)); + assertEquals(0x65, bytes.getAsInt(2)); + assertEquals(0x87, bytes.getAsInt(3)); + } + + @Test + public void testParse_NonFixedUByteArray_LittleEndian() throws Exception { + final JBBPFieldArrayUByte bytes = JBBPParser.prepare("bool[4];").parse(new byte[]{0, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayBoolean.class); + assertEquals(4, bools.size()); + assertFalse(bools.getAsBool(0)); + assertTrue(bools.getAsBool(1)); + assertTrue(bools.getAsBool(2)); + assertFalse(bools.getAsBool(3)); + } + + @Test + public void testParse_FixedBooleanArray_LittleEndian() throws Exception { + final JBBPFieldArrayBoolean bools = JBBPParser.prepare("bool[_];").parse(new byte[]{0, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayBoolean.class); + assertEquals(4, bools.size()); + assertFalse(bools.getAsBool(0)); + assertTrue(bools.getAsBool(1)); + assertTrue(bools.getAsBool(2)); + assertFalse(bools.getAsBool(3)); + } + + @Test + public void testParse_NonFixedBooleanArray_LittleEndian() throws Exception { + final JBBPFieldArrayBoolean bools = JBBPParser.prepare("short[2];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayShort.class); + assertEquals(2, shorts.size()); + assertEquals((short)0xF743, shorts.getAsInt(0)); + assertEquals((short)0x6500, shorts.getAsInt(1)); + } + + @Test + public void testParse_FixedShortArray_LittleEndian() throws Exception { + final JBBPFieldArrayShort shorts = JBBPParser.prepare("short[_];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayShort.class); + assertEquals(2, shorts.size()); + assertEquals((short)0xF743, shorts.getAsInt(0)); + assertEquals((short)0x6500, shorts.getAsInt(1)); + } + + @Test + public void testParse_NonFixedShortArray_LittleEndian() throws Exception { + final JBBPFieldArrayShort shorts = JBBPParser.prepare("ushort[2];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayUShort.class); + assertEquals(2, shorts.size()); + assertEquals(0xF743, shorts.getAsInt(0)); + assertEquals(0x6500, shorts.getAsInt(1)); + } + + @Test + public void testParse_FixedUShortArray_LittleEndian() throws Exception { + final JBBPFieldArrayUShort shorts = JBBPParser.prepare("ushort[_];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0}).findFieldForType(JBBPFieldArrayUShort.class); + assertEquals(2, shorts.size()); + assertEquals(0xF743, shorts.getAsInt(0)); + assertEquals(0x6500, shorts.getAsInt(1)); + } + + @Test + public void testParse_NonFixedUShortArray_LittleEndian() throws Exception { + final JBBPFieldArrayUShort shorts = JBBPParser.prepare("int[2];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0x10, 0x35, 0x23, 0x67, (byte)0xA0}).findFieldForType(JBBPFieldArrayInt.class); + assertEquals(2, ints.size()); + assertEquals(0xF7436510, ints.getAsInt(0)); + assertEquals(0x352367A0, ints.getAsInt(1)); + } + + @Test + public void testParse_FixedIntArray_LittleEndian() throws Exception { + final JBBPFieldArrayInt ints = JBBPParser.prepare("int[_];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0x10, 0x35, 0x23, 0x67, (byte)0xA0}).findFieldForType(JBBPFieldArrayInt.class); + assertEquals(2, ints.size()); + assertEquals(0xF7436510, ints.getAsInt(0)); + assertEquals(0x352367A0, ints.getAsInt(1)); + } + + @Test + public void testParse_NonFixedIntArray_LittleEndian() throws Exception { + final JBBPFieldArrayInt ints = JBBPParser.prepare("long[2];").parse(new byte[]{(byte)0xF7, 0x43, 0x65, 0x10, 0x35, 0x23, 0x67, (byte)0xA0, 0x32, 0x33, 0x61, (byte)0xCA, (byte)0xBE, 0x22, 0x12, 0x30}).findFieldForType(JBBPFieldArrayLong.class); + assertEquals(2, longs.size()); + assertEquals(0xF7436510352367A0L, longs.getAsLong(0)); + assertEquals(0x323361CABE221230L, longs.getAsLong(1)); + } + + @Test + public void testParse_FixedLongArray_LittleEndian() throws Exception { + final JBBPFieldArrayLong longs = JBBPParser.prepare("long[_];").parse(new byte[]{(byte) 0xF7, 0x43, 0x65, 0x10, 0x35, 0x23, 0x67, (byte) 0xA0, 0x32, 0x33, 0x61, (byte) 0xCA, (byte) 0xBE, 0x22, 0x12, 0x30}).findFieldForType(JBBPFieldArrayLong.class); + assertEquals(2, longs.size()); + assertEquals(0xF7436510352367A0L, longs.getAsLong(0)); + assertEquals(0x323361CABE221230L, longs.getAsLong(1)); + } + + @Test + public void testParse_NonFixedLongArray_LittleEndian() throws Exception { + final JBBPFieldArrayLong longs = JBBPParser.prepare("(10000)) // + .threadFactory(new NamedThreadFactory("JRaft-RPC-Processor-", true)) // + .build(); + if (this.rpcOptions.getMetricRegistry() != null) { + this.rpcOptions.getMetricRegistry().register("raft-rpc-client-thread-pool", + new ThreadPoolMetricSet(this.rpcExecutor)); + Utils.registerClosureExecutorMetrics(this.rpcOptions.getMetricRegistry()); + } + return true; + } + + @Override + public synchronized void shutdown() { + if (this.rpcClient != null) { + this.rpcClient.shutdown(); + this.rpcClient = null; + this.rpcExecutor.shutdown(); + } + } + + @Override + public boolean connect(final Endpoint endpoint) { + if (this.rpcClient == null) { + throw new IllegalStateException("Client service is not inited."); + } + if (isConnected(endpoint)) { + return true; + } + try { + final PingRequest req = PingRequest.newBuilder() // + .setSendTimestamp(System.currentTimeMillis()) // + .build(); + final ErrorResponse resp = (ErrorResponse) this.rpcClient.invokeSync(endpoint.toString(), req, + this.defaultInvokeCtx, this.rpcOptions.getRpcConnectTimeoutMs()); + return resp.getErrorCode() == 0; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (final RemotingException e) { + LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage()); + return false; + } + } + + @Override + public boolean disconnect(final Endpoint endpoint) { + LOG.info("Disconnect from {}", endpoint); + this.rpcClient.closeConnection(endpoint.toString()); + return true; + } + + @Override + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final RpcResponseClosure done, final int timeoutMs) { + return invokeWithDone(endpoint, request, this.defaultInvokeCtx, done, timeoutMs, this.rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final RpcResponseClosure done, final int timeoutMs, + final Executor rpcExecutor) { + return invokeWithDone(endpoint, request, this.defaultInvokeCtx, done, timeoutMs, rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final InvokeContext ctx, + final RpcResponseClosure done, final int timeoutMs) { + return invokeWithDone(endpoint, request, ctx, done, timeoutMs, this.rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final InvokeContext ctx, + final RpcResponseClosure done, final int timeoutMs, + final Executor rpcExecutor) { + final FutureImpl future = new FutureImpl<>(); + try { + final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString()); + this.rpcClient.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() { + + @SuppressWarnings("unchecked") + @Override + public void onResponse(final Object result) { + if (future.isCancelled()) { + onCanceled(request, done); + return; + } + Status status = Status.OK(); + if (result instanceof ErrorResponse) { + final ErrorResponse eResp = (ErrorResponse) result; + status = new Status(); + status.setCode(eResp.getErrorCode()); + if (eResp.hasErrorMsg()) { + status.setErrorMsg(eResp.getErrorMsg()); + } + } else { + if (done != null) { + done.setResponse((T) result); + } + } + if (done != null) { + try { + done.run(status); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + if (!future.isDone()) { + future.setResult((Message) result); + } + } + + @Override + public void onException(final Throwable e) { + if (future.isCancelled()) { + onCanceled(request, done); + return; + } + if (done != null) { + try { + done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT + : RaftError.EINTERNAL, "RPC exception:" + e.getMessage())); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + if (!future.isDone()) { + future.failure(e); + } + } + + @Override + public Executor getExecutor() { + return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor; + } + }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + future.failure(e); + // should be in another thread to avoid dead locking. + Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted")); + } catch (final RemotingException e) { + future.failure(e); + // should be in another thread to avoid dead locking. + Utils.runClosureInThread(done, + new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage())); + + } + return future; + } + + private void onCanceled(final Message request, final RpcResponseClosure done) { + if (done != null) { + try { + done.run(new Status(RaftError.ECANCELED, "RPC request was canceled by future.")); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.isConnected` reads without synchronization from `this.com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.rpcClient`. Potentially races with write in method `AbstractBoltClientService.shutdown()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean AbstractBoltClientService.isConnected(Endpoint) + +### Procedure Id: +com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.isConnected(com.alipay.sofa.jraft.util.Endp.ed519bb62f09d85510d0a1b2be9c754f + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/rpc/impl/AbstractBoltClientService.java + +### Key: +AbstractBoltClientService.java|isConnected|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6d021383ca6d3955f97f8d21be99631e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9217/instruction.md b/inferredbugs-9217/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2a35248466cb66d20b0345c46e611afa583a019 --- /dev/null +++ b/inferredbugs-9217/instruction.md @@ -0,0 +1,1710 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 26 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Recyclable; +import com.alipay.sofa.jraft.util.RecyclableByteBufferList; +import com.alipay.sofa.jraft.util.RecycleUtil; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", + (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, // install snapshot + AppendEntries // replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + r.releaseReader(); + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + // success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final RecyclableByteBufferList dateBuffer) { + if (dateBuffer.getCapacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + // should slice entry data + dateBuffer.add(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}", opts.getPeerId()); + // Return and it will be retried later. + return null; + } + + // Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + // ignore + } + } + + // Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + // id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, + final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + try { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.blockTimer != null) { + r.blockTimer.cancel(true); + r.blockTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + } finally { + r.destroy(); + } + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != RaftError.SUCCESS.getNumber()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + // timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + releaseReader(); + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().isEnabled()) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + savedId.unlockAndDestroy(); + } + + private void releaseReader() { + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + boolean doUnlock = true; + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (!response.getSuccess() && response.hasLastLogIndex()) { + if (isLogDebugEnabled) { + sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") + .append(response.getLastLogIndex()); + LOG.debug(sb.toString()); + } + LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); + doUnlock = false; + r.sendEmptyEntries(false); + r.startHeartbeatTimer(startTimeMs); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + if (doUnlock) { + id.unlock(); + } + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + //sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + //Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + releaseReader(); + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, request prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + // unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + // record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + // unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + // Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + // The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + // unlock id in installSnapshot + installSnapshot(); + return false; + } + + ByteBufferCollector dataBuf = null; + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance(); + try { + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + if (byteBufList.getCapacity() > 0) { + dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity()); + for (final ByteBuffer b : byteBufList) { + dataBuf.put(b); + } + final ByteBuffer buf = dataBuf.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + } finally { + RecycleUtil.recycle(byteBufList); + } + + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final Recyclable recyclable = dataBuf; + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + RecycleUtil.recycle(recyclable); + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + // unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + this.sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.Replicator.onTimeoutNowReturned` indirectly reads with synchronization from `n$20.com.alipay.sofa.jraft.entity.PeerId.endpoint.com.alipay.sofa.jraft.util.Endpoint.str`. Potentially races with unsynchronized write in method `Replicator.onInstallSnapshotReturned(...)`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +Note that the prefix path n$20 has been contaminated during the execution, so the reported race on n$20.com.alipay.sofa.jraft.entity.PeerId.endpoint.com.alipay.sofa.jraft.util.Endpoint.str might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.onTimeoutNowReturned(ThreadId,Status,RpcRequests$TimeoutNowRequest,RpcRequests$TimeoutNowResponse,boolean) + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.onTimeoutNowReturned(com.alipay.sofa.jraft.util.ThreadId,com.a.6987879c1f6ebbfa06df076f1b8b71df + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|onTimeoutNowReturned|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +edcb319307ea52ab2134e5e025e5e3da + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9219/instruction.md b/inferredbugs-9219/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8cb371dda49e89b8f04387bad82297631580485 --- /dev/null +++ b/inferredbugs-9219/instruction.md @@ -0,0 +1,1710 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 21 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Recyclable; +import com.alipay.sofa.jraft.util.RecyclableByteBufferList; +import com.alipay.sofa.jraft.util.RecycleUtil; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", + (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, // install snapshot + AppendEntries // replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + r.releaseReader(); + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + // success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final RecyclableByteBufferList dateBuffer) { + if (dateBuffer.getCapacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + // should slice entry data + dateBuffer.add(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}", opts.getPeerId()); + // Return and it will be retried later. + return null; + } + + // Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + // ignore + } + } + + // Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + // id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, + final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + try { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.blockTimer != null) { + r.blockTimer.cancel(true); + r.blockTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + } finally { + r.destroy(); + } + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != RaftError.SUCCESS.getNumber()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + // timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + releaseReader(); + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().isEnabled()) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + savedId.unlockAndDestroy(); + } + + private void releaseReader() { + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + boolean doUnlock = true; + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (!response.getSuccess() && response.hasLastLogIndex()) { + if (isLogDebugEnabled) { + sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") + .append(response.getLastLogIndex()); + LOG.debug(sb.toString()); + } + LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); + doUnlock = false; + r.sendEmptyEntries(false); + r.startHeartbeatTimer(startTimeMs); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + if (doUnlock) { + id.unlock(); + } + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + //sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + //Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + releaseReader(); + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, request prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + // unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + // record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + // unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + // Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + // The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + // unlock id in installSnapshot + installSnapshot(); + return false; + } + + ByteBufferCollector dataBuf = null; + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance(); + try { + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + if (byteBufList.getCapacity() > 0) { + dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity()); + for (final ByteBuffer b : byteBufList) { + dataBuf.put(b); + } + final ByteBuffer buf = dataBuf.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + } finally { + RecycleUtil.recycle(byteBufList); + } + + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final Recyclable recyclable = dataBuf; + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + RecycleUtil.recycle(recyclable); + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + // unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + this.sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.Replicator.installSnapshot` indirectly reads with synchronization from `n$20.com.alipay.sofa.jraft.entity.PeerId.str`. Potentially races with unsynchronized write in method `Replicator.onInstallSnapshotReturned(...)`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +Note that the prefix path n$20 has been contaminated during the execution, so the reported race on n$20.com.alipay.sofa.jraft.entity.PeerId.str might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.installSnapshot() + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.installSnapshot():void.e3306dc042cb27a2a7f7c45d7a122510 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|installSnapshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +c8b7782a2b13f0d0aeb4a357c4b6115b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9221/instruction.md b/inferredbugs-9221/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c2d88e0b11cc36271a6b1e3216445faba4848d26 --- /dev/null +++ b/inferredbugs-9221/instruction.md @@ -0,0 +1,1801 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 43 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Node; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Recyclable; +import com.alipay.sofa.jraft.util.RecyclableByteBufferList; +import com.alipay.sofa.jraft.util.RecycleUtil; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", + (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + enum ReplicatorEvent { + CREATED, // created + ERROR, // error + DESTROYED // destroyed + } + + /** + * User can implement the ReplicatorStateListener interface by themselves. + * So they can do some their own logic codes when replicator created, destroyed or had some errors. + * + * @author zongtanghu + * + * 2019-Aug-20 2:32:10 PM + */ + public interface ReplicatorStateListener { + + /** + * Called when this replicator has been created. + * + * @param peer replicator related peerId + */ + void onCreated(final PeerId peer); + + /** + * Called when this replicator has some errors. + * + * @param peer replicator related peerId + * @param status replicator's error detailed status + */ + void onError(final PeerId peer, final Status status); + + /** + * Called when this replicator has been destroyed. + * + * @param peer replicator related peerId + */ + void onDestroyed(final PeerId peer); + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users. + * + * @param replicator replicator object + * @param event replicator's state listener event type + * @param status replicator's error detailed status + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event, final Status status) { + final ReplicatorOptions replicatorOpts = Requires.requireNonNull(replicator.getOpts(), "replicatorOptions"); + final Node node = Requires.requireNonNull(replicatorOpts.getNode(), "node"); + final PeerId peer = Requires.requireNonNull(replicatorOpts.getPeerId(), "peer"); + + final List listenerList = node.getReplicatorStatueListeners(); + for (int i = 0; i < listenerList.size(); i++) { + final ReplicatorStateListener listener = listenerList.get(i); + if(listener != null) { + try { + switch (event) { + case CREATED: + Utils.runInThread(() -> listener.onCreated(peer)); + break; + case ERROR: + Utils.runInThread(() -> listener.onError(peer, status)); + break; + case DESTROYED: + Utils.runInThread(() -> listener.onDestroyed(peer)); + break; + default: + break; + } + } catch (final Exception e) { + LOG.error("Fail to notify ReplicatorStatusListener, listener={}, event={}.", listener, event); + } + } + } + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users for none status. + * + * @param replicator replicator object + * @param event replicator's state listener event type + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event) { + notifyReplicatorStatusListener(replicator, event, null); + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, // install snapshot + AppendEntries // replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + r.releaseReader(); + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + // success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final RecyclableByteBufferList dateBuffer) { + if (dateBuffer.getCapacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + // should slice entry data + dateBuffer.add(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}.", opts.getPeerId()); + // Return and it will be retried later. + return null; + } + + // Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + // ignore + } + } + + // Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + notifyReplicatorStatusListener(r, ReplicatorEvent.CREATED); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + // id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, + final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + try { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.blockTimer != null) { + r.blockTimer.cancel(true); + r.blockTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + } finally { + r.destroy(); + } + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != RaftError.SUCCESS.getNumber()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + // timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + releaseReader(); + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().isEnabled()) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); + savedId.unlockAndDestroy(); + } + + private void releaseReader() { + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + boolean doUnlock = true; + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (!response.getSuccess() && response.hasLastLogIndex()) { + if (isLogDebugEnabled) { + sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") + .append(response.getLastLogIndex()); + LOG.debug(sb.toString()); + } + LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); + doUnlock = false; + r.sendEmptyEntries(false); + r.startHeartbeatTimer(startTimeMs); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + if (doUnlock) { + id.unlock(); + } + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + // Sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + // Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + releaseReader(); + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, request prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + // unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + // record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + // unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + // Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + // The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + // unlock id in installSnapshot + installSnapshot(); + return false; + } + + ByteBufferCollector dataBuf = null; + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance(); + try { + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + if (byteBufList.getCapacity() > 0) { + dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity()); + for (final ByteBuffer b : byteBufList) { + dataBuf.put(b); + } + final ByteBuffer buf = dataBuf.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + } finally { + RecycleUtil.recycle(byteBufList); + } + + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final Recyclable recyclable = dataBuf; + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + RecycleUtil.recycle(recyclable); + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + // unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +INTERFACE_NOT_THREAD_SAFE + +### Qualifier: +Unprotected call to method of un-annotated interface org.slf4j.Logger. Consider annotating the class with `@ThreadSafe`, adding a lock, or using an interface that is known to be thread-safe. + Reporting because the current class is annotated `@ThreadSafe`. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.destroy() + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.destroy():void.7d6a56b93dd19c576109b0cec5680863 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|destroy|INTERFACE_NOT_THREAD_SAFE + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a29760b742b51bce7000b008d85573d5 + +### Bug Type Hum: +Interface Not Thread Safe + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9226/instruction.md b/inferredbugs-9226/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d5b3f2f923bdc1e4cce5ac78aa27766913eaf88 --- /dev/null +++ b/inferredbugs-9226/instruction.md @@ -0,0 +1,1801 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 37 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.core; + +import java.nio.ByteBuffer; +import java.util.ArrayDeque; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.PriorityQueue; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import javax.annotation.concurrent.ThreadSafe; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Node; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.closure.CatchUpClosure; +import com.alipay.sofa.jraft.entity.EnumOutter; +import com.alipay.sofa.jraft.entity.LogEntry; +import com.alipay.sofa.jraft.entity.PeerId; +import com.alipay.sofa.jraft.entity.RaftOutter; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.error.RaftException; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.option.ReplicatorOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.AppendEntriesResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.InstallSnapshotResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.TimeoutNowResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.snapshot.SnapshotReader; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Recyclable; +import com.alipay.sofa.jraft.util.RecyclableByteBufferList; +import com.alipay.sofa.jraft.util.RecycleUtil; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.ThreadId; +import com.alipay.sofa.jraft.util.Utils; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.Metric; +import com.codahale.metrics.MetricRegistry; +import com.codahale.metrics.MetricSet; +import com.google.protobuf.Message; +import com.google.protobuf.ZeroByteStringHelper; + +/** + * Replicator for replicating log entry from leader to followers. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:32:02 AM + */ +@ThreadSafe +public class Replicator implements ThreadId.OnError { + + private static final Logger LOG = LoggerFactory.getLogger(Replicator.class); + + private final RaftClientService rpcService; + // Next sending log index + private volatile long nextIndex; + private int consecutiveErrorTimes = 0; + private boolean hasSucceeded; + private long timeoutNowIndex; + private volatile long lastRpcSendTimestamp; + private volatile long heartbeatCounter = 0; + private volatile long appendEntriesCounter = 0; + private volatile long installSnapshotCounter = 0; + protected Stat statInfo = new Stat(); + private ScheduledFuture blockTimer; + + // Cached the latest RPC in-flight request. + private Inflight rpcInFly; + // Heartbeat RPC future + private Future heartbeatInFly; + // Timeout request RPC future + private Future timeoutNowInFly; + // In-flight RPC requests, FIFO queue + private final ArrayDeque inflights = new ArrayDeque<>(); + + private long waitId = -1L; + protected ThreadId id; + private final ReplicatorOptions options; + private final RaftOptions raftOptions; + + private ScheduledFuture heartbeatTimer; + private volatile SnapshotReader reader; + private CatchUpClosure catchUpClosure; + private final TimerManager timerManager; + private final NodeMetrics nodeMetrics; + private volatile State state; + + // Request sequence + private int reqSeq = 0; + // Response sequence + private int requiredNextSeq = 0; + // Replicator state reset version + private int version = 0; + + // Pending response queue; + private final PriorityQueue pendingResponses = new PriorityQueue<>(50); + + private int getAndIncrementReqSeq() { + final int prev = this.reqSeq; + this.reqSeq++; + if (this.reqSeq < 0) { + this.reqSeq = 0; + } + return prev; + } + + private int getAndIncrementRequiredNextSeq() { + final int prev = this.requiredNextSeq; + this.requiredNextSeq++; + if (this.requiredNextSeq < 0) { + this.requiredNextSeq = 0; + } + return prev; + } + + /** + * Replicator state + * @author dennis + * + */ + public enum State { + Probe, // probe follower state + Snapshot, // installing snapshot to follower + Replicate, // replicate logs normally + Destroyed // destroyed + } + + public Replicator(final ReplicatorOptions replicatorOptions, final RaftOptions raftOptions) { + super(); + this.options = replicatorOptions; + this.nodeMetrics = this.options.getNode().getNodeMetrics(); + this.nextIndex = this.options.getLogManager().getLastLogIndex() + 1; + this.timerManager = replicatorOptions.getTimerManager(); + this.raftOptions = raftOptions; + this.rpcService = replicatorOptions.getRaftRpcService(); + } + + /** + * Replicator metric set. + * @author dennis + * + */ + private static final class ReplicatorMetricSet implements MetricSet { + private final ReplicatorOptions opts; + private final Replicator r; + + private ReplicatorMetricSet(final ReplicatorOptions opts, final Replicator r) { + this.opts = opts; + this.r = r; + } + + @Override + public Map getMetrics() { + final Map gauges = new HashMap<>(); + gauges.put("log-lags", + (Gauge) () -> this.opts.getLogManager().getLastLogIndex() - (this.r.nextIndex - 1)); + gauges.put("next-index", (Gauge) () -> this.r.nextIndex); + gauges.put("heartbeat-times", (Gauge) () -> this.r.heartbeatCounter); + gauges.put("install-snapshot-times", (Gauge) () -> this.r.installSnapshotCounter); + gauges.put("append-entries-times", (Gauge) () -> this.r.appendEntriesCounter); + return gauges; + } + } + + /** + * Internal state + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:45 AM + */ + enum RunningState { + IDLE, // idle + BLOCKING, // blocking state + APPENDING_ENTRIES, // appending log entries + INSTALLING_SNAPSHOT // installing snapshot + } + + enum ReplicatorEvent { + CREATED, // created + ERROR, // error + DESTROYED // destroyed + } + + /** + * User can implement the ReplicatorStateListener interface by themselves. + * So they can do some their own logic codes when replicator created, destroyed or had some errors. + * + * @author zongtanghu + * + * 2019-Aug-20 2:32:10 PM + */ + public interface ReplicatorStateListener { + + /** + * Called when this replicator has been created. + * + * @param peer replicator related peerId + */ + void onCreated(final PeerId peer); + + /** + * Called when this replicator has some errors. + * + * @param peer replicator related peerId + * @param status replicator's error detailed status + */ + void onError(final PeerId peer, final Status status); + + /** + * Called when this replicator has been destroyed. + * + * @param peer replicator related peerId + */ + void onDestroyed(final PeerId peer); + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users. + * + * @param replicator replicator object + * @param event replicator's state listener event type + * @param status replicator's error detailed status + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event, final Status status) { + final ReplicatorOptions replicatorOpts = Requires.requireNonNull(replicator.getOpts(), "replicatorOptions"); + final Node node = Requires.requireNonNull(replicatorOpts.getNode(), "node"); + final PeerId peer = Requires.requireNonNull(replicatorOpts.getPeerId(), "peer"); + + final List listenerList = node.getReplicatorStatueListeners(); + for (int i = 0; i < listenerList.size(); i++) { + final ReplicatorStateListener listener = listenerList.get(i); + if(listener != null) { + try { + switch (event) { + case CREATED: + Utils.runInThread(() -> listener.onCreated(peer)); + break; + case ERROR: + Utils.runInThread(() -> listener.onError(peer, status)); + break; + case DESTROYED: + Utils.runInThread(() -> listener.onDestroyed(peer)); + break; + default: + break; + } + } catch (final Exception e) { + LOG.error("Fail to notify ReplicatorStatusListener, listener={}, event={}.", listener, event); + } + } + } + } + + /** + * Notify replicator event(such as created, error, destroyed) to replicatorStateListener which is implemented by users for none status. + * + * @param replicator replicator object + * @param event replicator's state listener event type + */ + private static void notifyReplicatorStatusListener(final Replicator replicator, final ReplicatorEvent event) { + notifyReplicatorStatusListener(replicator, event, null); + } + + /** + * Statistics structure + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-04 10:38:53 AM + */ + static class Stat { + RunningState runningState; + long firstLogIndex; + long lastLogIncluded; + long lastLogIndex; + long lastTermIncluded; + + @Override + public String toString() { + return ""; + } + + } + + // In-flight request type + enum RequestType { + Snapshot, // install snapshot + AppendEntries // replicate logs + } + + /** + * In-flight request. + * @author dennis + * + */ + static class Inflight { + // In-flight request count + final int count; + // Start log index + final long startIndex; + // Entries size in bytes + final int size; + // RPC future + final Future rpcFuture; + final RequestType requestType; + // Request sequence. + final int seq; + + public Inflight(final RequestType requestType, final long startIndex, final int count, final int size, + final int seq, final Future rpcFuture) { + super(); + this.seq = seq; + this.requestType = requestType; + this.count = count; + this.startIndex = startIndex; + this.size = size; + this.rpcFuture = rpcFuture; + } + + @Override + public String toString() { + return "Inflight [count=" + this.count + ", startIndex=" + this.startIndex + ", size=" + this.size + + ", rpcFuture=" + this.rpcFuture + ", requestType=" + this.requestType + ", seq=" + this.seq + "]"; + } + + boolean isSendingLogEntries() { + return this.requestType == RequestType.AppendEntries && this.count > 0; + } + } + + /** + * RPC response for AppendEntries/InstallSnapshot. + * @author dennis + * + */ + static class RpcResponse implements Comparable { + final Status status; + final Message request; + final Message response; + final long rpcSendTime; + final int seq; + final RequestType requestType; + + public RpcResponse(final RequestType reqType, final int seq, final Status status, final Message request, + final Message response, final long rpcSendTime) { + super(); + this.requestType = reqType; + this.seq = seq; + this.status = status; + this.request = request; + this.response = response; + this.rpcSendTime = rpcSendTime; + } + + @Override + public String toString() { + return "RpcResponse [status=" + this.status + ", request=" + this.request + ", response=" + this.response + + ", rpcSendTime=" + this.rpcSendTime + ", seq=" + this.seq + ", requestType=" + this.requestType + + "]"; + } + + /** + * Sort by sequence. + */ + @Override + public int compareTo(final RpcResponse o) { + return Integer.compare(this.seq, o.seq); + } + } + + @OnlyForTest + ArrayDeque getInflights() { + return this.inflights; + } + + @OnlyForTest + State getState() { + return this.state; + } + + @OnlyForTest + void setState(final State state) { + this.state = state; + } + + @OnlyForTest + int getReqSeq() { + return this.reqSeq; + } + + @OnlyForTest + int getRequiredNextSeq() { + return this.requiredNextSeq; + } + + @OnlyForTest + int getVersion() { + return this.version; + } + + @OnlyForTest + public PriorityQueue getPendingResponses() { + return this.pendingResponses; + } + + @OnlyForTest + long getWaitId() { + return this.waitId; + } + + @OnlyForTest + ScheduledFuture getBlockTimer() { + return this.blockTimer; + } + + @OnlyForTest + long getTimeoutNowIndex() { + return this.timeoutNowIndex; + } + + @OnlyForTest + ReplicatorOptions getOpts() { + return this.options; + } + + @OnlyForTest + long getRealNextIndex() { + return this.nextIndex; + } + + @OnlyForTest + Future getRpcInFly() { + if (this.rpcInFly == null) { + return null; + } + return this.rpcInFly.rpcFuture; + } + + @OnlyForTest + Future getHeartbeatInFly() { + return this.heartbeatInFly; + } + + @OnlyForTest + ScheduledFuture getHeartbeatTimer() { + return this.heartbeatTimer; + } + + @OnlyForTest + void setHasSucceeded() { + this.hasSucceeded = true; + } + + @OnlyForTest + Future getTimeoutNowInFly() { + return this.timeoutNowInFly; + } + + /** + * Adds a in-flight request + * @param reqType type of request + * @param count count if request + * @param size size in bytes + */ + private void addInflight(final RequestType reqType, final long startIndex, final int count, final int size, + final int seq, final Future rpcInfly) { + this.rpcInFly = new Inflight(reqType, startIndex, count, size, seq, rpcInfly); + this.inflights.add(this.rpcInFly); + this.nodeMetrics.recordSize("replicate-inflights-count", this.inflights.size()); + } + + /** + * Returns the next in-flight sending index, return -1 when can't send more in-flight requests. + * + * @return next in-flight sending index + */ + long getNextSendIndex() { + // Fast path + if (this.inflights.isEmpty()) { + return this.nextIndex; + } + // Too many in-flight requests. + if (this.inflights.size() > this.raftOptions.getMaxReplicatorInflightMsgs()) { + return -1L; + } + // Last request should be a AppendEntries request and has some entries. + if (this.rpcInFly != null && this.rpcInFly.isSendingLogEntries()) { + return this.rpcInFly.startIndex + this.rpcInFly.count; + } + return -1L; + } + + private Inflight pollInflight() { + return this.inflights.poll(); + } + + private void startHeartbeatTimer(final long startMs) { + final long dueTime = startMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + this.heartbeatTimer = this.timerManager.schedule(() -> onTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + } catch (final Exception e) { + LOG.error("Fail to schedule heartbeat timer", e); + onTimeout(this.id); + } + } + + void installSnapshot() { + if (this.state == State.Snapshot) { + LOG.warn("Replicator {} is installing snapshot, ignore the new request.", this.options.getPeerId()); + this.id.unlock(); + return; + } + boolean doUnlock = true; + try { + Requires.requireTrue(this.reader == null, + "Replicator %s already has a snapshot reader, current state is %s", this.options.getPeerId(), + this.state); + this.reader = this.options.getSnapshotStorage().open(); + if (this.reader == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to open snapshot")); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final String uri = this.reader.generateURIForCopy(); + if (uri == null) { + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to generate uri for snapshot reader")); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final RaftOutter.SnapshotMeta meta = this.reader.load(); + if (meta == null) { + final String snapshotPath = this.reader.getPath(); + final NodeImpl node = this.options.getNode(); + final RaftException error = new RaftException(EnumOutter.ErrorType.ERROR_TYPE_SNAPSHOT); + error.setStatus(new Status(RaftError.EIO, "Fail to load meta from %s", snapshotPath)); + releaseReader(); + this.id.unlock(); + doUnlock = false; + node.onError(error); + return; + } + final InstallSnapshotRequest.Builder rb = InstallSnapshotRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setMeta(meta); + rb.setUri(uri); + + this.statInfo.runningState = RunningState.INSTALLING_SNAPSHOT; + this.statInfo.lastLogIncluded = meta.getLastIncludedIndex(); + this.statInfo.lastTermIncluded = meta.getLastIncludedTerm(); + + final InstallSnapshotRequest request = rb.build(); + this.state = State.Snapshot; + // noinspection NonAtomicOperationOnVolatileField + this.installSnapshotCounter++; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.installSnapshot(this.options.getPeerId().getEndpoint(), + request, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.Snapshot, status, request, getResponse(), seq, + stateVersion, monotonicSendTimeMs); + } + }); + addInflight(RequestType.Snapshot, this.nextIndex, 0, 0, seq, rpcFuture); + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + } + + @SuppressWarnings("unused") + static boolean onInstallSnapshotReturned(final ThreadId id, final Replicator r, final Status status, + final InstallSnapshotRequest request, + final InstallSnapshotResponse response) { + boolean success = true; + r.releaseReader(); + // noinspection ConstantConditions + do { + final StringBuilder sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received InstallSnapshotResponse from ").append(r.options.getPeerId()). // + append(" lastIncludedIndex=").append(request.getMeta().getLastIncludedIndex()). // + append(" lastIncludedTerm=").append(request.getMeta().getLastIncludedTerm()); + if (!status.isOk()) { + sb.append(" error:").append(status); + LOG.info(sb.toString()); + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to install snapshot at peer={}, error={}", r.options.getPeerId(), status); + } + success = false; + break; + } + if (!response.getSuccess()) { + sb.append(" success=false"); + LOG.info(sb.toString()); + success = false; + break; + } + // success + r.nextIndex = request.getMeta().getLastIncludedIndex() + 1; + sb.append(" success=true"); + LOG.info(sb.toString()); + } while (false); + // We don't retry installing the snapshot explicitly. + // id is unlock in sendEntries + if (!success) { + //should reset states + r.resetInflights(); + r.state = State.Probe; + r.block(Utils.nowMs(), status.getCode()); + return false; + } + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + // id is unlock in _send_entriesheartbeatCounter + r.state = State.Replicate; + return true; + } + + private void sendEmptyEntries(final boolean isHeartbeat) { + sendEmptyEntries(isHeartbeat, null); + } + + /** + * Send probe or heartbeat request + * @param isHeartbeat if current entries is heartbeat + * @param heartBeatClosure heartbeat callback + */ + @SuppressWarnings("NonAtomicOperationOnVolatileField") + private void sendEmptyEntries(final boolean isHeartbeat, + final RpcResponseClosure heartBeatClosure) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, this.nextIndex - 1, isHeartbeat)) { + // id is unlock in installSnapshot + installSnapshot(); + if (isHeartbeat && heartBeatClosure != null) { + Utils.runClosureInThread(heartBeatClosure, new Status(RaftError.EAGAIN, + "Fail to send heartbeat to peer %s", this.options.getPeerId())); + } + return; + } + try { + final long monotonicSendTimeMs = Utils.monotonicMs(); + final AppendEntriesRequest request = rb.build(); + + if (isHeartbeat) { + // Sending a heartbeat request + this.heartbeatCounter++; + RpcResponseClosure heartbeatDone; + // Prefer passed-in closure. + if (heartBeatClosure != null) { + heartbeatDone = heartBeatClosure; + } else { + heartbeatDone = new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onHeartbeatReturned(Replicator.this.id, status, request, getResponse(), monotonicSendTimeMs); + } + }; + } + this.heartbeatInFly = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), request, + this.options.getElectionTimeoutMs() / 2, heartbeatDone); + } else { + // Sending a probe request. + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = this.nextIndex; + this.statInfo.lastLogIndex = this.nextIndex - 1; + this.appendEntriesCounter++; + this.state = State.Probe; + final int stateVersion = this.version; + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, + getResponse(), seq, stateVersion, monotonicSendTimeMs); + } + + }); + + addInflight(RequestType.AppendEntries, this.nextIndex, 0, 0, seq, rpcFuture); + } + LOG.debug("Node {} send HeartbeatRequest to {} term {} lastCommittedIndex {}", this.options.getNode() + .getNodeId(), this.options.getPeerId(), this.options.getTerm(), request.getCommittedIndex()); + } finally { + this.id.unlock(); + } + } + + boolean prepareEntry(final long nextSendingIndex, final int offset, final RaftOutter.EntryMeta.Builder emb, + final RecyclableByteBufferList dateBuffer) { + if (dateBuffer.getCapacity() >= this.raftOptions.getMaxBodySize()) { + return false; + } + final long logIndex = nextSendingIndex + offset; + final LogEntry entry = this.options.getLogManager().getEntry(logIndex); + if (entry == null) { + return false; + } + emb.setTerm(entry.getId().getTerm()); + if (entry.hasChecksum()) { + emb.setChecksum(entry.getChecksum()); //since 1.2.6 + } + emb.setType(entry.getType()); + if (entry.getPeers() != null) { + Requires.requireTrue(!entry.getPeers().isEmpty(), "Empty peers at logIndex=%d", logIndex); + for (final PeerId peer : entry.getPeers()) { + emb.addPeers(peer.toString()); + } + if (entry.getOldPeers() != null) { + for (final PeerId peer : entry.getOldPeers()) { + emb.addOldPeers(peer.toString()); + } + } + } else { + Requires.requireTrue(entry.getType() != EnumOutter.EntryType.ENTRY_TYPE_CONFIGURATION, + "Empty peers but is ENTRY_TYPE_CONFIGURATION type at logIndex=%d", logIndex); + } + final int remaining = entry.getData() != null ? entry.getData().remaining() : 0; + emb.setDataLen(remaining); + if (entry.getData() != null) { + // should slice entry data + dateBuffer.add(entry.getData().slice()); + } + return true; + } + + public static ThreadId start(final ReplicatorOptions opts, final RaftOptions raftOptions) { + if (opts.getLogManager() == null || opts.getBallotBox() == null || opts.getNode() == null) { + throw new IllegalArgumentException("Invalid ReplicatorOptions."); + } + final Replicator r = new Replicator(opts, raftOptions); + if (!r.rpcService.connect(opts.getPeerId().getEndpoint())) { + LOG.error("Fail to init sending channel to {}.", opts.getPeerId()); + // Return and it will be retried later. + return null; + } + + // Register replicator metric set. + final MetricRegistry metricRegistry = opts.getNode().getNodeMetrics().getMetricRegistry(); + if (metricRegistry != null) { + try { + final String replicatorMetricName = getReplicatorMetricName(opts); + if (!metricRegistry.getNames().contains(replicatorMetricName)) { + metricRegistry.register(replicatorMetricName, new ReplicatorMetricSet(opts, r)); + } + } catch (final IllegalArgumentException e) { + // ignore + } + } + + // Start replication + r.id = new ThreadId(r, r); + r.id.lock(); + notifyReplicatorStatusListener(r, ReplicatorEvent.CREATED); + LOG.info("Replicator={}@{} is started", r.id, r.options.getPeerId()); + r.catchUpClosure = null; + r.lastRpcSendTimestamp = Utils.monotonicMs(); + r.startHeartbeatTimer(Utils.nowMs()); + // id.unlock in sendEmptyEntries + r.sendEmptyEntries(false); + return r.id; + } + + private static String getReplicatorMetricName(final ReplicatorOptions opts) { + return "replicator-" + opts.getNode().getGroupId() + "/" + opts.getPeerId(); + } + + public static void waitForCaughtUp(final ThreadId id, final long maxMargin, final long dueTime, + final CatchUpClosure done) { + final Replicator r = (Replicator) id.lock(); + + if (r == null) { + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "No such replicator")); + return; + } + try { + if (r.catchUpClosure != null) { + LOG.error("Previous wait_for_caught_up is not over"); + Utils.runClosureInThread(done, new Status(RaftError.EINVAL, "Duplicated call")); + return; + } + done.setMaxMargin(maxMargin); + if (dueTime > 0) { + done.setTimer(r.timerManager.schedule(() -> onCatchUpTimedOut(id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS)); + } + r.catchUpClosure = done; + } finally { + id.unlock(); + } + } + + @Override + public String toString() { + return "Replicator [state=" + this.state + ", statInfo=" + this.statInfo + ",peerId=" + + this.options.getPeerId() + "]"; + } + + static void onBlockTimeoutInNewThread(final ThreadId id) { + if (id != null) { + continueSending(id, RaftError.ETIMEDOUT.getNumber()); + } + } + + /** + * Unblock and continue sending right now. + */ + static void unBlockAndSendNow(final ThreadId id) { + if (id == null) { + // It was destroyed already + return; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + if (r.blockTimer != null) { + if (r.blockTimer.cancel(true)) { + onBlockTimeout(id); + } + } + } finally { + id.unlock(); + } + } + + static boolean continueSending(final ThreadId id, final int errCode) { + if (id == null) { + //It was destroyed already + return true; + } + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.waitId = -1; + if (errCode == RaftError.ETIMEDOUT.getNumber()) { + // Send empty entries after block timeout to check the correct + // _next_index otherwise the replicator is likely waits in executor.shutdown(); + // _wait_more_entries and no further logs would be replicated even if the + // last_index of this followers is less than |next_index - 1| + r.sendEmptyEntries(false); + } else if (errCode != RaftError.ESTOP.getNumber()) { + // id is unlock in _send_entries + r.sendEntries(); + } else { + LOG.warn("Replicator {} stops sending entries.", id); + id.unlock(); + } + return true; + } + + static void onBlockTimeout(final ThreadId arg) { + Utils.runInThread(() -> onBlockTimeoutInNewThread(arg)); + } + + void block(final long startTimeMs, @SuppressWarnings("unused") final int errorCode) { + // TODO: Currently we don't care about error_code which indicates why the + // very RPC fails. To make it better there should be different timeout for + // each individual error (e.g. we don't need check every + // heartbeat_timeout_ms whether a dead follower has come back), but it's just + // fine now. + final long dueTime = startTimeMs + this.options.getDynamicHeartBeatTimeoutMs(); + try { + LOG.debug("Blocking {} for {} ms", this.options.getPeerId(), this.options.getDynamicHeartBeatTimeoutMs()); + this.blockTimer = this.timerManager.schedule(() -> onBlockTimeout(this.id), dueTime - Utils.nowMs(), + TimeUnit.MILLISECONDS); + this.statInfo.runningState = RunningState.BLOCKING; + this.id.unlock(); + } catch (final Exception e) { + LOG.error("Fail to add timer", e); + // id unlock in sendEmptyEntries. + sendEmptyEntries(false); + } + } + + @Override + public void onError(final ThreadId id, final Object data, final int errorCode) { + final Replicator r = (Replicator) data; + if (errorCode == RaftError.ESTOP.getNumber()) { + try { + for (final Inflight inflight : r.inflights) { + if (inflight != r.rpcInFly) { + inflight.rpcFuture.cancel(true); + } + } + if (r.rpcInFly != null) { + r.rpcInFly.rpcFuture.cancel(true); + r.rpcInFly = null; + } + if (r.heartbeatInFly != null) { + r.heartbeatInFly.cancel(true); + r.heartbeatInFly = null; + } + if (r.timeoutNowInFly != null) { + r.timeoutNowInFly.cancel(true); + r.timeoutNowInFly = null; + } + if (r.heartbeatTimer != null) { + r.heartbeatTimer.cancel(true); + r.heartbeatTimer = null; + } + if (r.blockTimer != null) { + r.blockTimer.cancel(true); + r.blockTimer = null; + } + if (r.waitId >= 0) { + r.options.getLogManager().removeWaiter(r.waitId); + } + r.notifyOnCaughtUp(errorCode, true); + } finally { + r.destroy(); + } + } else if (errorCode == RaftError.ETIMEDOUT.getNumber()) { + id.unlock(); + Utils.runInThread(() -> sendHeartbeat(id)); + } else { + id.unlock(); + // noinspection ConstantConditions + Requires.requireTrue(false, "Unknown error code for replicator: " + errorCode); + } + } + + private static void onCatchUpTimedOut(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + try { + r.notifyOnCaughtUp(RaftError.ETIMEDOUT.getNumber(), false); + } finally { + id.unlock(); + } + } + + private void notifyOnCaughtUp(final int code, final boolean beforeDestroy) { + if (this.catchUpClosure == null) { + return; + } + if (code != RaftError.ETIMEDOUT.getNumber()) { + if (this.nextIndex - 1 + this.catchUpClosure.getMaxMargin() < this.options.getLogManager() + .getLastLogIndex()) { + return; + } + if (this.catchUpClosure.isErrorWasSet()) { + return; + } + this.catchUpClosure.setErrorWasSet(true); + if (code != RaftError.SUCCESS.getNumber()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + if (this.catchUpClosure.hasTimer()) { + if (!beforeDestroy && !this.catchUpClosure.getTimer().cancel(true)) { + // There's running timer task, let timer task trigger + // on_caught_up to void ABA problem + return; + } + } + } else { + // timed out + if (!this.catchUpClosure.isErrorWasSet()) { + this.catchUpClosure.getStatus().setError(code, RaftError.describeCode(code)); + } + } + final CatchUpClosure savedClosure = this.catchUpClosure; + this.catchUpClosure = null; + Utils.runClosureInThread(savedClosure, savedClosure.getStatus()); + } + + private static void onTimeout(final ThreadId id) { + if (id != null) { + id.setError(RaftError.ETIMEDOUT.getNumber()); + } else { + LOG.warn("Replicator id is null when timeout, maybe it's destroyed."); + } + } + + void destroy() { + final ThreadId savedId = this.id; + LOG.info("Replicator {} is going to quit", savedId); + this.id = null; + releaseReader(); + // Unregister replicator metric set + if (this.options.getNode().getNodeMetrics().isEnabled()) { + this.options.getNode().getNodeMetrics().getMetricRegistry().remove(getReplicatorMetricName(this.options)); + } + this.state = State.Destroyed; + notifyReplicatorStatusListener((Replicator) savedId.getData(), ReplicatorEvent.DESTROYED); + savedId.unlockAndDestroy(); + } + + private void releaseReader() { + if (this.reader != null) { + Utils.closeQuietly(this.reader); + this.reader = null; + } + } + + static void onHeartbeatReturned(final ThreadId id, final Status status, final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime) { + if (id == null) { + // replicator already was destroyed. + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + boolean doUnlock = true; + try { + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received HeartbeatResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + r.state = State.Probe; + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.startHeartbeatTimer(startTimeMs); + return; + } + r.consecutiveErrorTimes = 0; + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return; + } + if (!response.getSuccess() && response.hasLastLogIndex()) { + if (isLogDebugEnabled) { + sb.append(" fail, response term ").append(response.getTerm()).append(" lastLogIndex ") + .append(response.getLastLogIndex()); + LOG.debug(sb.toString()); + } + LOG.warn("Heartbeat to peer {} failure, try to send a probe request.", r.options.getPeerId()); + doUnlock = false; + r.sendEmptyEntries(false); + r.startHeartbeatTimer(startTimeMs); + return; + } + if (isLogDebugEnabled) { + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + r.startHeartbeatTimer(startTimeMs); + } finally { + if (doUnlock) { + id.unlock(); + } + } + } + + @SuppressWarnings("ContinueOrBreakFromFinallyBlock") + static void onRpcReturned(final ThreadId id, final RequestType reqType, final Status status, final Message request, + final Message response, final int seq, final int stateVersion, final long rpcSendTime) { + if (id == null) { + return; + } + final long startTimeMs = Utils.nowMs(); + Replicator r; + if ((r = (Replicator) id.lock()) == null) { + return; + } + + if (stateVersion != r.version) { + LOG.debug( + "Replicator {} ignored old version response {}, current version is {}, request is {}\n, and response is {}\n, status is {}.", + r, stateVersion, r.version, request, response, status); + id.unlock(); + return; + } + + final PriorityQueue holdingQueue = r.pendingResponses; + holdingQueue.add(new RpcResponse(reqType, seq, status, request, response, rpcSendTime)); + + if (holdingQueue.size() > r.raftOptions.getMaxReplicatorInflightMsgs()) { + LOG.warn("Too many pending responses {} for replicator {}, maxReplicatorInflightMsgs={}", + holdingQueue.size(), r.options.getPeerId(), r.raftOptions.getMaxReplicatorInflightMsgs()); + r.resetInflights(); + r.state = State.Probe; + r.sendEmptyEntries(false); + return; + } + + boolean continueSendEntries = false; + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Replicator ").append(r).append(" is processing RPC responses,"); + } + try { + int processed = 0; + while (!holdingQueue.isEmpty()) { + final RpcResponse queuedPipelinedResponse = holdingQueue.peek(); + + // Sequence mismatch, waiting for next response. + if (queuedPipelinedResponse.seq != r.requiredNextSeq) { + if (processed > 0) { + if (isLogDebugEnabled) { + sb.append("has processed ").append(processed).append(" responses,"); + } + break; + } else { + // Do not processed any responses, UNLOCK id and return. + continueSendEntries = false; + id.unlock(); + return; + } + } + holdingQueue.remove(); + processed++; + final Inflight inflight = r.pollInflight(); + if (inflight == null) { + // The previous in-flight requests were cleared. + if (isLogDebugEnabled) { + sb.append("ignore response because request not found:").append(queuedPipelinedResponse) + .append(",\n"); + } + continue; + } + if (inflight.seq != queuedPipelinedResponse.seq) { + // reset state + LOG.warn( + "Replicator {} response sequence out of order, expect {}, but it is {}, reset state to try again.", + r, inflight.seq, queuedPipelinedResponse.seq); + r.resetInflights(); + r.state = State.Probe; + continueSendEntries = false; + r.block(Utils.nowMs(), RaftError.EREQUEST.getNumber()); + return; + } + try { + switch (queuedPipelinedResponse.requestType) { + case AppendEntries: + continueSendEntries = onAppendEntriesReturned(id, inflight, queuedPipelinedResponse.status, + (AppendEntriesRequest) queuedPipelinedResponse.request, + (AppendEntriesResponse) queuedPipelinedResponse.response, rpcSendTime, startTimeMs, r); + break; + case Snapshot: + continueSendEntries = onInstallSnapshotReturned(id, r, queuedPipelinedResponse.status, + (InstallSnapshotRequest) queuedPipelinedResponse.request, + (InstallSnapshotResponse) queuedPipelinedResponse.response); + break; + } + } finally { + if (continueSendEntries) { + // Success, increase the response sequence. + r.getAndIncrementRequiredNextSeq(); + } else { + // The id is already unlocked in onAppendEntriesReturned/onInstallSnapshotReturned, we SHOULD break out. + break; + } + } + } + } finally { + if (isLogDebugEnabled) { + sb.append(", after processed, continue to send entries: ").append(continueSendEntries); + LOG.debug(sb.toString()); + } + if (continueSendEntries) { + // unlock in sendEntries. + r.sendEntries(); + } + } + } + + /** + * Reset in-flight state. + */ + void resetInflights() { + this.version++; + this.inflights.clear(); + this.pendingResponses.clear(); + final int rs = Math.max(this.reqSeq, this.requiredNextSeq); + this.reqSeq = this.requiredNextSeq = rs; + releaseReader(); + } + + private static boolean onAppendEntriesReturned(final ThreadId id, final Inflight inflight, final Status status, + final AppendEntriesRequest request, + final AppendEntriesResponse response, final long rpcSendTime, + final long startTimeMs, final Replicator r) { + if (inflight.startIndex != request.getPrevLogIndex() + 1) { + LOG.warn( + "Replicator {} received invalid AppendEntriesResponse, in-flight startIndex={}, request prevLogIndex={}, reset the replicator state and probe again.", + r, inflight.startIndex, request.getPrevLogIndex()); + r.resetInflights(); + r.state = State.Probe; + // unlock id in sendEmptyEntries + r.sendEmptyEntries(false); + return false; + } + // record metrics + if (request.getEntriesCount() > 0) { + r.nodeMetrics.recordLatency("replicate-entries", Utils.monotonicMs() - rpcSendTime); + r.nodeMetrics.recordSize("replicate-entries-count", request.getEntriesCount()); + r.nodeMetrics.recordSize("replicate-entries-bytes", request.getData() != null ? request.getData().size() + : 0); + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received AppendEntriesResponse from "). // + append(r.options.getPeerId()). // + append(" prevLogIndex=").append(request.getPrevLogIndex()). // + append(" prevLogTerm=").append(request.getPrevLogTerm()). // + append(" count=").append(request.getEntriesCount()); + } + if (!status.isOk()) { + // If the follower crashes, any RPC to the follower fails immediately, + // so we need to block the follower for a while instead of looping until + // it comes back or be removed + // dummy_id is unlock in block + if (isLogDebugEnabled) { + sb.append(" fail, sleep."); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (++r.consecutiveErrorTimes % 10 == 0) { + LOG.warn("Fail to issue RPC to {}, consecutiveErrorTimes={}, error={}", r.options.getPeerId(), + r.consecutiveErrorTimes, status); + } + r.resetInflights(); + r.state = State.Probe; + // unlock in in block + r.block(startTimeMs, status.getCode()); + return false; + } + r.consecutiveErrorTimes = 0; + if (!response.getSuccess()) { + if (response.getTerm() > r.options.getTerm()) { + if (isLogDebugEnabled) { + sb.append(" fail, greater term ").append(response.getTerm()).append(" expect term ") + .append(r.options.getTerm()); + LOG.debug(sb.toString()); + } + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term heartbeat_response from peer:%s", r.options.getPeerId())); + return false; + } + if (isLogDebugEnabled) { + sb.append(" fail, find nextIndex remote lastLogIndex ").append(response.getLastLogIndex()) + .append(" local nextIndex ").append(r.nextIndex); + LOG.debug(sb.toString()); + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + // Fail, reset the state to try again from nextIndex. + r.resetInflights(); + // prev_log_index and prev_log_term doesn't match + if (response.getLastLogIndex() + 1 < r.nextIndex) { + LOG.debug("LastLogIndex at peer={} is {}", r.options.getPeerId(), response.getLastLogIndex()); + // The peer contains less logs than leader + r.nextIndex = response.getLastLogIndex() + 1; + } else { + // The peer contains logs from old term which should be truncated, + // decrease _last_log_at_peer by one to test the right index to keep + if (r.nextIndex > 1) { + LOG.debug("logIndex={} dismatch", r.nextIndex); + r.nextIndex--; + } else { + LOG.error("Peer={} declares that log at index=0 doesn't match, which is not supposed to happen", + r.options.getPeerId()); + } + } + // dummy_id is unlock in _send_heartbeat + r.sendEmptyEntries(false); + return false; + } + if (isLogDebugEnabled) { + sb.append(", success"); + LOG.debug(sb.toString()); + } + // success + if (response.getTerm() != r.options.getTerm()) { + r.resetInflights(); + r.state = State.Probe; + LOG.error("Fail, response term {} dismatch, expect term {}", response.getTerm(), r.options.getTerm()); + id.unlock(); + return false; + } + if (rpcSendTime > r.lastRpcSendTimestamp) { + r.lastRpcSendTimestamp = rpcSendTime; + } + final int entriesSize = request.getEntriesCount(); + if (entriesSize > 0) { + r.options.getBallotBox().commitAt(r.nextIndex, r.nextIndex + entriesSize - 1, r.options.getPeerId()); + if (LOG.isDebugEnabled()) { + LOG.debug("Replicated logs in [{}, {}] to peer {}", r.nextIndex, r.nextIndex + entriesSize - 1, + r.options.getPeerId()); + } + } else { + // The request is probe request, change the state into Replicate. + r.state = State.Replicate; + } + r.nextIndex += entriesSize; + r.hasSucceeded = true; + r.notifyOnCaughtUp(RaftError.SUCCESS.getNumber(), false); + // dummy_id is unlock in _send_entries + if (r.timeoutNowIndex > 0 && r.timeoutNowIndex < r.nextIndex) { + r.sendTimeoutNow(false, false); + } + return true; + } + + private boolean fillCommonFields(final AppendEntriesRequest.Builder rb, long prevLogIndex, final boolean isHeartbeat) { + final long prevLogTerm = this.options.getLogManager().getTerm(prevLogIndex); + if (prevLogTerm == 0 && prevLogIndex != 0) { + if (!isHeartbeat) { + Requires.requireTrue(prevLogIndex < this.options.getLogManager().getFirstLogIndex()); + LOG.debug("logIndex={} was compacted", prevLogIndex); + return false; + } else { + // The log at prev_log_index has been compacted, which indicates + // we is or is going to install snapshot to the follower. So we let + // both prev_log_index and prev_log_term be 0 in the heartbeat + // request so that follower would do nothing besides updating its + // leader timestamp. + prevLogIndex = 0; + } + } + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + rb.setPrevLogIndex(prevLogIndex); + rb.setPrevLogTerm(prevLogTerm); + rb.setCommittedIndex(this.options.getBallotBox().getLastCommittedIndex()); + return true; + } + + private void waitMoreEntries(final long nextWaitIndex) { + try { + LOG.debug("Node {} waits more entries", this.options.getNode().getNodeId()); + if (this.waitId >= 0) { + return; + } + this.waitId = this.options.getLogManager().wait(nextWaitIndex - 1, + (arg, errorCode) -> continueSending((ThreadId) arg, errorCode), this.id); + this.statInfo.runningState = RunningState.IDLE; + } finally { + this.id.unlock(); + } + } + + /** + * Send as many requests as possible. + */ + void sendEntries() { + boolean doUnlock = true; + try { + long prevSendIndex = -1; + while (true) { + final long nextSendingIndex = getNextSendIndex(); + if (nextSendingIndex > prevSendIndex) { + if (sendEntries(nextSendingIndex)) { + prevSendIndex = nextSendingIndex; + } else { + doUnlock = false; + // id already unlock in sendEntries when it returns false. + break; + } + } else { + break; + } + } + } finally { + if (doUnlock) { + this.id.unlock(); + } + } + + } + + /** + * Send log entries to follower, returns true when success, otherwise false and unlock the id. + * + * @param nextSendingIndex next sending index + * @return send result. + */ + private boolean sendEntries(final long nextSendingIndex) { + final AppendEntriesRequest.Builder rb = AppendEntriesRequest.newBuilder(); + if (!fillCommonFields(rb, nextSendingIndex - 1, false)) { + // unlock id in installSnapshot + installSnapshot(); + return false; + } + + ByteBufferCollector dataBuf = null; + final int maxEntriesSize = this.raftOptions.getMaxEntriesSize(); + final RecyclableByteBufferList byteBufList = RecyclableByteBufferList.newInstance(); + try { + for (int i = 0; i < maxEntriesSize; i++) { + final RaftOutter.EntryMeta.Builder emb = RaftOutter.EntryMeta.newBuilder(); + if (!prepareEntry(nextSendingIndex, i, emb, byteBufList)) { + break; + } + rb.addEntries(emb.build()); + } + if (rb.getEntriesCount() == 0) { + if (nextSendingIndex < this.options.getLogManager().getFirstLogIndex()) { + installSnapshot(); + return false; + } + // _id is unlock in _wait_more + waitMoreEntries(nextSendingIndex); + return false; + } + if (byteBufList.getCapacity() > 0) { + dataBuf = ByteBufferCollector.allocateByRecyclers(byteBufList.getCapacity()); + for (final ByteBuffer b : byteBufList) { + dataBuf.put(b); + } + final ByteBuffer buf = dataBuf.getBuffer(); + buf.flip(); + rb.setData(ZeroByteStringHelper.wrap(buf)); + } + } finally { + RecycleUtil.recycle(byteBufList); + } + + final AppendEntriesRequest request = rb.build(); + if (LOG.isDebugEnabled()) { + LOG.debug( + "Node {} send AppendEntriesRequest to {} term {} lastCommittedIndex {} prevLogIndex {} prevLogTerm {} logIndex {} count {}", + this.options.getNode().getNodeId(), this.options.getPeerId(), this.options.getTerm(), + request.getCommittedIndex(), request.getPrevLogIndex(), request.getPrevLogTerm(), nextSendingIndex, + request.getEntriesCount()); + } + this.statInfo.runningState = RunningState.APPENDING_ENTRIES; + this.statInfo.firstLogIndex = rb.getPrevLogIndex() + 1; + this.statInfo.lastLogIndex = rb.getPrevLogIndex() + rb.getEntriesCount(); + + final Recyclable recyclable = dataBuf; + final int v = this.version; + final long monotonicSendTimeMs = Utils.monotonicMs(); + final int seq = getAndIncrementReqSeq(); + final Future rpcFuture = this.rpcService.appendEntries(this.options.getPeerId().getEndpoint(), + request, -1, new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + RecycleUtil.recycle(recyclable); + onRpcReturned(Replicator.this.id, RequestType.AppendEntries, status, request, getResponse(), seq, + v, monotonicSendTimeMs); + } + + }); + addInflight(RequestType.AppendEntries, nextSendingIndex, request.getEntriesCount(), request.getData().size(), + seq, rpcFuture); + return true; + + } + + public static void sendHeartbeat(final ThreadId id, final RpcResponseClosure closure) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + Utils.runClosureInThread(closure, new Status(RaftError.EHOSTDOWN, "Peer %s is not connected", id)); + return; + } + //id unlock in send empty entries. + r.sendEmptyEntries(true, closure); + } + + private static void sendHeartbeat(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + // unlock in sendEmptyEntries + r.sendEmptyEntries(true); + } + + @SuppressWarnings("SameParameterValue") + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish) { + sendTimeoutNow(unlockId, stopAfterFinish, -1); + } + + private void sendTimeoutNow(final boolean unlockId, final boolean stopAfterFinish, final int timeoutMs) { + final TimeoutNowRequest.Builder rb = TimeoutNowRequest.newBuilder(); + rb.setTerm(this.options.getTerm()); + rb.setGroupId(this.options.getGroupId()); + rb.setServerId(this.options.getServerId().toString()); + rb.setPeerId(this.options.getPeerId().toString()); + try { + if (!stopAfterFinish) { + // This RPC is issued by transfer_leadership, save this call_id so that + // the RPC can be cancelled by stop. + this.timeoutNowInFly = timeoutNow(rb, false, timeoutMs); + this.timeoutNowIndex = 0; + } else { + timeoutNow(rb, true, timeoutMs); + } + } finally { + if (unlockId) { + this.id.unlock(); + } + } + + } + + private Future timeoutNow(final TimeoutNowRequest.Builder rb, final boolean stopAfterFinish, + final int timeoutMs) { + final TimeoutNowRequest request = rb.build(); + return this.rpcService.timeoutNow(this.options.getPeerId().getEndpoint(), request, timeoutMs, + new RpcResponseClosureAdapter() { + + @Override + public void run(final Status status) { + if (Replicator.this.id != null) { + onTimeoutNowReturned(Replicator.this.id, status, request, getResponse(), stopAfterFinish); + } + } + + }); + } + + @SuppressWarnings("unused") + static void onTimeoutNowReturned(final ThreadId id, final Status status, final TimeoutNowRequest request, + final TimeoutNowResponse response, final boolean stopAfterFinish) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return; + } + + final boolean isLogDebugEnabled = LOG.isDebugEnabled(); + StringBuilder sb = null; + if (isLogDebugEnabled) { + sb = new StringBuilder("Node "). // + append(r.options.getGroupId()).append(":").append(r.options.getServerId()). // + append(" received TimeoutNowResponse from "). // + append(r.options.getPeerId()); + } + if (!status.isOk()) { + if (isLogDebugEnabled) { + sb.append(" fail:").append(status); + LOG.debug(sb.toString()); + } + notifyReplicatorStatusListener(r, ReplicatorEvent.ERROR, status); + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + return; + } + if (isLogDebugEnabled) { + sb.append(response.getSuccess() ? " success" : " fail"); + LOG.debug(sb.toString()); + } + if (response.getTerm() > r.options.getTerm()) { + final NodeImpl node = r.options.getNode(); + r.notifyOnCaughtUp(RaftError.EPERM.getNumber(), true); + r.destroy(); + node.increaseTermTo(response.getTerm(), new Status(RaftError.EHIGHERTERMRESPONSE, + "Leader receives higher term timeout_now_response from peer:%s", r.options.getPeerId())); + return; + } + if (stopAfterFinish) { + r.notifyOnCaughtUp(RaftError.ESTOP.getNumber(), true); + r.destroy(); + } else { + id.unlock(); + } + + } + + public static boolean stop(final ThreadId id) { + id.setError(RaftError.ESTOP.getNumber()); + return true; + } + + public static boolean join(final ThreadId id) { + id.join(); + return true; + } + + public static long getLastRpcSendTimestamp(final ThreadId id) { + final Replicator r = (Replicator) id.getData(); + if (r == null) { + return 0L; + } + return r.lastRpcSendTimestamp; + } + + public static boolean transferLeadership(final ThreadId id, final long logIndex) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // dummy is unlock in _transfer_leadership + return r.transferLeadership(logIndex); + } + + private boolean transferLeadership(final long logIndex) { + if (this.hasSucceeded && this.nextIndex > logIndex) { + // _id is unlock in _send_timeout_now + sendTimeoutNow(true, false); + return true; + } + // Register log_index so that _on_rpc_return trigger + // _send_timeout_now if _next_index reaches log_index + this.timeoutNowIndex = logIndex; + this.id.unlock(); + return true; + } + + public static boolean stopTransferLeadership(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + r.timeoutNowIndex = 0; + id.unlock(); + return true; + } + + public static boolean sendTimeoutNowAndStop(final ThreadId id, final int timeoutMs) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return false; + } + // id unlock in sendTimeoutNow + r.sendTimeoutNow(true, true, timeoutMs); + return true; + } + + public static long getNextIndex(final ThreadId id) { + final Replicator r = (Replicator) id.lock(); + if (r == null) { + return 0; + } + long nextIdx = 0; + if (r.hasSucceeded) { + nextIdx = r.nextIndex; + } + id.unlock(); + return nextIdx; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.core.Replicator.installSnapshot` reads without synchronization from `this.com.alipay.sofa.jraft.core.Replicator.id`. Potentially races with write in method `Replicator.destroy()`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Replicator.installSnapshot() + +### Procedure Id: +com.alipay.sofa.jraft.core.Replicator.installSnapshot():void.e3306dc042cb27a2a7f7c45d7a122510 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/core/Replicator.java + +### Key: +Replicator.java|installSnapshot|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +66d0c3ec97f31e9d23eaf3a4dacea30c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9228/instruction.md b/inferredbugs-9228/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a36bddfb74095a94b0a235797803750922598c69 --- /dev/null +++ b/inferredbugs-9228/instruction.md @@ -0,0 +1,339 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.rpc.impl; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.Executor; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadPoolExecutor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.remoting.InvokeCallback; +import com.alipay.remoting.InvokeContext; +import com.alipay.remoting.Url; +import com.alipay.remoting.exception.RemotingException; +import com.alipay.remoting.rpc.RpcClient; +import com.alipay.remoting.rpc.exception.InvokeTimeoutException; +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.RpcOptions; +import com.alipay.sofa.jraft.rpc.ClientService; +import com.alipay.sofa.jraft.rpc.ProtobufMsgFactory; +import com.alipay.sofa.jraft.rpc.RpcRequests.ErrorResponse; +import com.alipay.sofa.jraft.rpc.RpcRequests.PingRequest; +import com.alipay.sofa.jraft.rpc.RpcResponseClosure; +import com.alipay.sofa.jraft.rpc.impl.core.JRaftRpcAddressParser; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.NamedThreadFactory; +import com.alipay.sofa.jraft.util.ThreadPoolMetricSet; +import com.alipay.sofa.jraft.util.ThreadPoolUtil; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Abstract RPC client service based on bolt. + + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-09 3:27:33 PM + */ +public abstract class AbstractBoltClientService implements ClientService { + + protected static final Logger LOG = LoggerFactory.getLogger(AbstractBoltClientService.class); + + static { + ProtobufMsgFactory.load(); + } + + protected RpcClient rpcClient; + protected ThreadPoolExecutor rpcExecutor; + protected RpcOptions rpcOptions; + protected JRaftRpcAddressParser rpcAddressParser; + protected InvokeContext defaultInvokeCtx; + + public RpcClient getRpcClient() { + return this.rpcClient; + } + + @Override + public boolean isConnected(final Endpoint endpoint) { + return this.rpcClient.checkConnection(endpoint.toString()); + } + + @Override + public synchronized boolean init(final RpcOptions rpcOptions) { + if (this.rpcClient != null) { + return true; + } + this.rpcOptions = rpcOptions; + this.rpcAddressParser = new JRaftRpcAddressParser(); + this.defaultInvokeCtx = new InvokeContext(); + this.defaultInvokeCtx.put(InvokeContext.BOLT_CRC_SWITCH, this.rpcOptions.isEnableRpcChecksum()); + return initRpcClient(this.rpcOptions.getRpcProcessorThreadPoolSize()); + } + + protected void configRpcClient(final RpcClient rpcClient) { + // NO-OP + } + + protected boolean initRpcClient(final int rpcProcessorThreadPoolSize) { + this.rpcClient = new RpcClient(); + configRpcClient(this.rpcClient); + this.rpcClient.init(); + this.rpcExecutor = ThreadPoolUtil.newBuilder() // + .poolName("JRaft-RPC-Processor") // + .enableMetric(true) // + .coreThreads(rpcProcessorThreadPoolSize / 3) // + .maximumThreads(rpcProcessorThreadPoolSize) // + .keepAliveSeconds(60L) // + .workQueue(new ArrayBlockingQueue<>(10000)) // + .threadFactory(new NamedThreadFactory("JRaft-RPC-Processor-", true)) // + .build(); + if (this.rpcOptions.getMetricRegistry() != null) { + this.rpcOptions.getMetricRegistry().register("raft-rpc-client-thread-pool", + new ThreadPoolMetricSet(this.rpcExecutor)); + Utils.registerClosureExecutorMetrics(this.rpcOptions.getMetricRegistry()); + } + return true; + } + + @Override + public synchronized void shutdown() { + if (this.rpcClient != null) { + this.rpcClient.shutdown(); + this.rpcClient = null; + this.rpcExecutor.shutdown(); + } + } + + @Override + public boolean connect(final Endpoint endpoint) { + if (this.rpcClient == null) { + throw new IllegalStateException("Client service is not inited."); + } + if (isConnected(endpoint)) { + return true; + } + try { + final PingRequest req = PingRequest.newBuilder() // + .setSendTimestamp(System.currentTimeMillis()) // + .build(); + final ErrorResponse resp = (ErrorResponse) this.rpcClient.invokeSync(endpoint.toString(), req, + this.defaultInvokeCtx, this.rpcOptions.getRpcConnectTimeoutMs()); + return resp.getErrorCode() == 0; + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } catch (final RemotingException e) { + LOG.error("Fail to connect {}, remoting exception: {}.", endpoint, e.getMessage()); + return false; + } + } + + @Override + public boolean disconnect(final Endpoint endpoint) { + LOG.info("Disconnect from {}", endpoint); + this.rpcClient.closeConnection(endpoint.toString()); + return true; + } + + @Override + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final RpcResponseClosure done, final int timeoutMs) { + return invokeWithDone(endpoint, request, this.defaultInvokeCtx, done, timeoutMs, this.rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final RpcResponseClosure done, final int timeoutMs, + final Executor rpcExecutor) { + return invokeWithDone(endpoint, request, this.defaultInvokeCtx, done, timeoutMs, rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final InvokeContext ctx, + final RpcResponseClosure done, final int timeoutMs) { + return invokeWithDone(endpoint, request, ctx, done, timeoutMs, this.rpcExecutor); + } + + public Future invokeWithDone(final Endpoint endpoint, final Message request, + final InvokeContext ctx, + final RpcResponseClosure done, final int timeoutMs, + final Executor rpcExecutor) { + final FutureImpl future = new FutureImpl<>(); + try { + final Url rpcUrl = this.rpcAddressParser.parse(endpoint.toString()); + this.rpcClient.invokeWithCallback(rpcUrl, request, ctx, new InvokeCallback() { + + @SuppressWarnings("unchecked") + @Override + public void onResponse(final Object result) { + if (future.isCancelled()) { + onCanceled(request, done); + return; + } + Status status = Status.OK(); + if (result instanceof ErrorResponse) { + final ErrorResponse eResp = (ErrorResponse) result; + status = new Status(); + status.setCode(eResp.getErrorCode()); + if (eResp.hasErrorMsg()) { + status.setErrorMsg(eResp.getErrorMsg()); + } + } else { + if (done != null) { + done.setResponse((T) result); + } + } + if (done != null) { + try { + done.run(status); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + if (!future.isDone()) { + future.setResult((Message) result); + } + } + + @Override + public void onException(final Throwable e) { + if (future.isCancelled()) { + onCanceled(request, done); + return; + } + if (done != null) { + try { + done.run(new Status(e instanceof InvokeTimeoutException ? RaftError.ETIMEDOUT + : RaftError.EINTERNAL, "RPC exception:" + e.getMessage())); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + if (!future.isDone()) { + future.failure(e); + } + } + + @Override + public Executor getExecutor() { + return rpcExecutor != null ? rpcExecutor : AbstractBoltClientService.this.rpcExecutor; + } + }, timeoutMs <= 0 ? this.rpcOptions.getRpcDefaultTimeout() : timeoutMs); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + future.failure(e); + // should be in another thread to avoid dead locking. + Utils.runClosureInThread(done, new Status(RaftError.EINTR, "Sending rpc was interrupted")); + } catch (final RemotingException e) { + future.failure(e); + // should be in another thread to avoid dead locking. + Utils.runClosureInThread(done, + new Status(RaftError.EINTERNAL, "Fail to send a RPC request:" + e.getMessage())); + + } + return future; + } + + private void onCanceled(final Message request, final RpcResponseClosure done) { + if (done != null) { + try { + done.run(new Status(RaftError.ECANCELED, "RPC request was canceled by future.")); + } catch (final Throwable t) { + LOG.error("Fail to run RpcResponseClosure, the request is {}.", request, t); + } + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.connect` reads without synchronization from `this.com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.rpcClient`. Potentially races with write in method `AbstractBoltClientService.shutdown()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean AbstractBoltClientService.connect(Endpoint) + +### Procedure Id: +com.alipay.sofa.jraft.rpc.impl.AbstractBoltClientService.connect(com.alipay.sofa.jraft.util.Endpoint.fca7ed64d9306b96a818ab5dc4db9ca7 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/rpc/impl/AbstractBoltClientService.java + +### Key: +AbstractBoltClientService.java|connect|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +a168158a89f6722ef6614126963dac17 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9242/instruction.md b/inferredbugs-9242/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb599d7d00326806d518af6c4be752bd4808f726 --- /dev/null +++ b/inferredbugs-9242/instruction.md @@ -0,0 +1,379 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.storage.snapshot.remote; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.core.TimerManager; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.CopyOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.SnapshotThrottle; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Copy session based on bolt framework. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-08 12:01:23 PM + */ +@ThreadSafe +public class BoltSession implements Session { + + private static final Logger LOG = LoggerFactory.getLogger(BoltSession.class); + + private final Lock lock; + private final Status st; + private final RaftClientService rpcService; + private int retryTimes; + private boolean finished; + private ByteBufferCollector destBuf; + private CopyOptions copyOptions; + private GetFileRequest.Builder requestBuilder; + private final CountDownLatch finishLatch; + private OutputStream outputStream; + private final Endpoint endpoint; + private final GetFileResponseClosure done = new GetFileResponseClosure(); + private ScheduledFuture timer; + private String destPath; + private final RaftOptions raftOptions; + private Future rpcCall; + private final TimerManager timerManager; + private final SnapshotThrottle snapshotThrottle; + + /** + * Get file response closure to answer client. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-13 4:50:21 PM + */ + private class GetFileResponseClosure extends RpcResponseClosureAdapter { + + @Override + public void run(Status status) { + onRpcReturned(status, getResponse()); + } + + } + + public void setDestPath(String destPath) { + this.destPath = destPath; + } + + @OnlyForTest + GetFileResponseClosure getDone() { + return this.done; + } + + @OnlyForTest + Future getRpcCall() { + return this.rpcCall; + } + + @OnlyForTest + ScheduledFuture getTimer() { + return this.timer; + } + + @Override + public void close() throws IOException { + lock.lock(); + try { + if (!this.finished) { + Utils.closeQuietly(this.outputStream); + } + } finally { + lock.unlock(); + } + } + + public BoltSession(RaftClientService rpcService, TimerManager timerManager, SnapshotThrottle snapshotThrottle, + RaftOptions raftOptions, GetFileRequest.Builder rb, Endpoint ep) { + super(); + this.snapshotThrottle = snapshotThrottle; + this.raftOptions = raftOptions; + this.timerManager = timerManager; + this.rpcService = rpcService; + this.requestBuilder = rb; + this.retryTimes = 0; + this.copyOptions = new CopyOptions(); + this.lock = new ReentrantLock(); + this.endpoint = ep; + this.st = Status.OK(); + this.finishLatch = new CountDownLatch(1); + + } + + public void setDestBuf(ByteBufferCollector bufRef) { + this.destBuf = bufRef; + } + + public void setCopyOptions(CopyOptions copyOptions) { + this.copyOptions = copyOptions; + } + + public void setOutputStream(OutputStream out) { + this.outputStream = out; + } + + @Override + public void cancel() { + lock.lock(); + try { + if (this.finished) { + return; + } + if (this.timer != null) { + this.timer.cancel(true); + } + if (this.rpcCall != null) { + this.rpcCall.cancel(true); + } + if (st.isOk()) { + st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); + } + + this.onFinished(); + } finally { + lock.unlock(); + } + + } + + @Override + public void join() throws InterruptedException { + this.finishLatch.await(); + } + + @Override + public Status status() { + return st; + } + + private void onFinished() { + if (!this.finished) { + if (outputStream != null) { + Utils.closeQuietly(this.outputStream); + this.outputStream = null; + } + if (this.destBuf != null) { + final ByteBuffer buf = this.destBuf.getBuffer(); + if (buf != null) { + buf.flip(); + } + this.destBuf = null; + } + this.finished = true; + this.finishLatch.countDown(); + } + } + + private void onTimer() { + Utils.runInThread(this::sendNextRpc); + } + + void onRpcReturned(Status status, GetFileResponse response) { + lock.lock(); + try { + if (this.finished) { + return; + } + if (!status.isOk()) { + // Reset count to make next rpc retry the previous one + requestBuilder.setCount(0); + if (status.getCode() == RaftError.ECANCELED.getNumber()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + + // Throttled reading failure does not increase _retry_times + if (status.getCode() != RaftError.EAGAIN.getNumber() + && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + this.retryTimes = 0; + Requires.requireNonNull(response, "response"); + // Reset count to |real_read_size| to make next rpc get the right offset + if (response.hasReadSize() && response.getReadSize() != 0) { + this.requestBuilder.setCount(response.getReadSize()); + } + if (outputStream != null) { + try { + response.getData().writeTo(outputStream); + } catch (final IOException e) { + LOG.error("Fail to write into file {}", this.destPath); + st.setError(RaftError.EIO, RaftError.EIO.name()); + this.onFinished(); + return; + } + } else { + final byte[] data = response.getData().toByteArray(); + this.destBuf.put(data); + } + if (response.getEof()) { + onFinished(); + return; + } + } finally { + lock.unlock(); + } + this.sendNextRpc(); + } + + /** + * Send next RPC request to get a piece of file data. + */ + void sendNextRpc() { + this.timer = null; + final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); + final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; + this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); + this.lock.lock(); + try { + if (this.finished) { + return; + } + // throttle + long newMaxCount = maxCount; + if (this.snapshotThrottle != null) { + newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); + if (newMaxCount == 0) { + // Reset count to make next rpc retry the previous one + this.requestBuilder.setCount(0); + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + } + this.requestBuilder.setCount(newMaxCount); + LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); + this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), + this.copyOptions.getTimeoutMs(), done); + } finally { + lock.unlock(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc` writes to field `this.com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.timer` outside of synchronization. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BoltSession.sendNextRpc() + +### Procedure Id: +com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc():void.df8bf8734eb44ec2bca56be19a43f342 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/storage/snapshot/remote/BoltSession.java + +### Key: +BoltSession.java|sendNextRpc|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +70c5f4c43e96caaf51f3b3d8d4c71ce0 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9243/instruction.md b/inferredbugs-9243/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..606cc91889da8ffe554408131a22b88ee4cab7ac --- /dev/null +++ b/inferredbugs-9243/instruction.md @@ -0,0 +1,379 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-jraft +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.jraft.storage.snapshot.remote; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +import javax.annotation.concurrent.ThreadSafe; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.alipay.sofa.jraft.Status; +import com.alipay.sofa.jraft.core.TimerManager; +import com.alipay.sofa.jraft.error.RaftError; +import com.alipay.sofa.jraft.option.CopyOptions; +import com.alipay.sofa.jraft.option.RaftOptions; +import com.alipay.sofa.jraft.rpc.RaftClientService; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileRequest; +import com.alipay.sofa.jraft.rpc.RpcRequests.GetFileResponse; +import com.alipay.sofa.jraft.rpc.RpcResponseClosureAdapter; +import com.alipay.sofa.jraft.storage.SnapshotThrottle; +import com.alipay.sofa.jraft.util.ByteBufferCollector; +import com.alipay.sofa.jraft.util.Endpoint; +import com.alipay.sofa.jraft.util.OnlyForTest; +import com.alipay.sofa.jraft.util.Requires; +import com.alipay.sofa.jraft.util.Utils; +import com.google.protobuf.Message; + +/** + * Copy session based on bolt framework. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-08 12:01:23 PM + */ +@ThreadSafe +public class BoltSession implements Session { + + private static final Logger LOG = LoggerFactory.getLogger(BoltSession.class); + + private final Lock lock; + private final Status st; + private final RaftClientService rpcService; + private int retryTimes; + private boolean finished; + private ByteBufferCollector destBuf; + private CopyOptions copyOptions; + private GetFileRequest.Builder requestBuilder; + private final CountDownLatch finishLatch; + private OutputStream outputStream; + private final Endpoint endpoint; + private final GetFileResponseClosure done = new GetFileResponseClosure(); + private ScheduledFuture timer; + private String destPath; + private final RaftOptions raftOptions; + private Future rpcCall; + private final TimerManager timerManager; + private final SnapshotThrottle snapshotThrottle; + + /** + * Get file response closure to answer client. + * @author boyan (boyan@alibaba-inc.com) + * + * 2018-Apr-13 4:50:21 PM + */ + private class GetFileResponseClosure extends RpcResponseClosureAdapter { + + @Override + public void run(Status status) { + onRpcReturned(status, getResponse()); + } + + } + + public void setDestPath(String destPath) { + this.destPath = destPath; + } + + @OnlyForTest + GetFileResponseClosure getDone() { + return this.done; + } + + @OnlyForTest + Future getRpcCall() { + return this.rpcCall; + } + + @OnlyForTest + ScheduledFuture getTimer() { + return this.timer; + } + + @Override + public void close() throws IOException { + lock.lock(); + try { + if (!this.finished) { + Utils.closeQuietly(this.outputStream); + } + } finally { + lock.unlock(); + } + } + + public BoltSession(RaftClientService rpcService, TimerManager timerManager, SnapshotThrottle snapshotThrottle, + RaftOptions raftOptions, GetFileRequest.Builder rb, Endpoint ep) { + super(); + this.snapshotThrottle = snapshotThrottle; + this.raftOptions = raftOptions; + this.timerManager = timerManager; + this.rpcService = rpcService; + this.requestBuilder = rb; + this.retryTimes = 0; + this.copyOptions = new CopyOptions(); + this.lock = new ReentrantLock(); + this.endpoint = ep; + this.st = Status.OK(); + this.finishLatch = new CountDownLatch(1); + + } + + public void setDestBuf(ByteBufferCollector bufRef) { + this.destBuf = bufRef; + } + + public void setCopyOptions(CopyOptions copyOptions) { + this.copyOptions = copyOptions; + } + + public void setOutputStream(OutputStream out) { + this.outputStream = out; + } + + @Override + public void cancel() { + lock.lock(); + try { + if (this.finished) { + return; + } + if (this.timer != null) { + this.timer.cancel(true); + } + if (this.rpcCall != null) { + this.rpcCall.cancel(true); + } + if (st.isOk()) { + st.setError(RaftError.ECANCELED, RaftError.ECANCELED.name()); + } + + this.onFinished(); + } finally { + lock.unlock(); + } + + } + + @Override + public void join() throws InterruptedException { + this.finishLatch.await(); + } + + @Override + public Status status() { + return st; + } + + private void onFinished() { + if (!this.finished) { + if (outputStream != null) { + Utils.closeQuietly(this.outputStream); + this.outputStream = null; + } + if (this.destBuf != null) { + final ByteBuffer buf = this.destBuf.getBuffer(); + if (buf != null) { + buf.flip(); + } + this.destBuf = null; + } + this.finished = true; + this.finishLatch.countDown(); + } + } + + private void onTimer() { + Utils.runInThread(this::sendNextRpc); + } + + void onRpcReturned(Status status, GetFileResponse response) { + lock.lock(); + try { + if (this.finished) { + return; + } + if (!status.isOk()) { + // Reset count to make next rpc retry the previous one + requestBuilder.setCount(0); + if (status.getCode() == RaftError.ECANCELED.getNumber()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + + // Throttled reading failure does not increase _retry_times + if (status.getCode() != RaftError.EAGAIN.getNumber() + && ++this.retryTimes >= this.copyOptions.getMaxRetry()) { + if (st.isOk()) { + st.setError(status.getCode(), status.getErrorMsg()); + this.onFinished(); + return; + } + } + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + this.retryTimes = 0; + Requires.requireNonNull(response, "response"); + // Reset count to |real_read_size| to make next rpc get the right offset + if (response.hasReadSize() && response.getReadSize() != 0) { + this.requestBuilder.setCount(response.getReadSize()); + } + if (outputStream != null) { + try { + response.getData().writeTo(outputStream); + } catch (final IOException e) { + LOG.error("Fail to write into file {}", this.destPath); + st.setError(RaftError.EIO, RaftError.EIO.name()); + this.onFinished(); + return; + } + } else { + final byte[] data = response.getData().toByteArray(); + this.destBuf.put(data); + } + if (response.getEof()) { + onFinished(); + return; + } + } finally { + lock.unlock(); + } + this.sendNextRpc(); + } + + /** + * Send next RPC request to get a piece of file data. + */ + void sendNextRpc() { + this.timer = null; + final long offset = requestBuilder.getOffset() + requestBuilder.getCount(); + final long maxCount = this.destBuf == null ? raftOptions.getMaxByteCountPerRpc() : Integer.MAX_VALUE; + this.requestBuilder = requestBuilder.setOffset(offset).setCount(maxCount).setReadPartly(true); + this.lock.lock(); + try { + if (this.finished) { + return; + } + // throttle + long newMaxCount = maxCount; + if (this.snapshotThrottle != null) { + newMaxCount = snapshotThrottle.throttledByThroughput(maxCount); + if (newMaxCount == 0) { + // Reset count to make next rpc retry the previous one + this.requestBuilder.setCount(0); + this.timer = this.timerManager.schedule(this::onTimer, this.copyOptions.getRetryIntervalMs(), + TimeUnit.MILLISECONDS); + return; + } + } + this.requestBuilder.setCount(newMaxCount); + LOG.debug("Send get file request {} to peer {}", this.requestBuilder.build(), this.endpoint); + this.rpcCall = this.rpcService.getFile(endpoint, this.requestBuilder.build(), + this.copyOptions.getTimeoutMs(), done); + } finally { + lock.unlock(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc` reads with synchronization from `this.com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.requestBuilder`. Potentially races with unsynchronized write in method `BoltSession.sendNextRpc()`. + Reporting because the current class is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void BoltSession.sendNextRpc() + +### Procedure Id: +com.alipay.sofa.jraft.storage.snapshot.remote.BoltSession.sendNextRpc():void.df8bf8734eb44ec2bca56be19a43f342 + +### File: +jraft-core/src/main/java/com/alipay/sofa/jraft/storage/snapshot/remote/BoltSession.java + +### Key: +BoltSession.java|sendNextRpc|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +957bce773212146be898a98bed0dd1af + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9272/instruction.md b/inferredbugs-9272/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0bab4fc1e8ea6da4ebe0f518960a488f385ef4a6 --- /dev/null +++ b/inferredbugs-9272/instruction.md @@ -0,0 +1,256 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.hystrix; + +import com.alipay.sofa.rpc.common.utils.ClassUtils; +import com.alipay.sofa.rpc.config.ConsumerConfig; +import com.alipay.sofa.rpc.context.RpcInternalContext; +import com.alipay.sofa.rpc.context.RpcInvokeContext; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.core.exception.SofaTimeOutException; +import com.alipay.sofa.rpc.core.request.SofaRequest; +import com.alipay.sofa.rpc.core.response.SofaResponse; +import com.alipay.sofa.rpc.filter.FilterInvoker; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.message.ResponseFuture; +import com.netflix.hystrix.HystrixCommand; +import com.netflix.hystrix.HystrixEventType; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * {@link HystrixCommand} for async requests + * + * @author ScienJus + */ +public class SofaAsyncHystrixCommand extends HystrixCommand implements SofaHystrixInvokable { + + private static final Logger LOGGER = LoggerFactory + .getLogger(SofaAsyncHystrixCommand.class); + + private static final long DEFAULT_LOCK_TIMEOUT = 1000; + + private final FilterInvoker invoker; + + private final SofaRequest request; + + private final RpcInternalContext rpcInternalContext; + + private final RpcInvokeContext rpcInvokeContext; + + private final CountDownLatch lock = new CountDownLatch(1); + + private final List events = new ArrayList(); + + private SofaResponse sofaResponse; + + public SofaAsyncHystrixCommand(FilterInvoker invoker, SofaRequest request) { + super(SofaHystrixConfig.loadSetterFactory((ConsumerConfig) invoker.getConfig()).createSetter(invoker, + request)); + this.rpcInternalContext = RpcInternalContext.peekContext(); + this.rpcInvokeContext = RpcInvokeContext.peekContext(); + this.invoker = invoker; + this.request = request; + } + + @Override + public SofaResponse invoke() { + if (isCircuitBreakerOpen() && LOGGER.isWarnEnabled(invoker.getConfig().getAppName())) { + LOGGER.warnWithApp(invoker.getConfig().getAppName(), "Circuit Breaker is opened, method: {}#{}", + invoker.getConfig().getInterfaceId(), request.getMethodName()); + } + HystrixResponseFuture delegate = new HystrixResponseFuture(this.queue()); + try { + boolean finished = lock.await(getLockTimeout(), TimeUnit.MILLISECONDS); + if (!finished && !this.isExecutionComplete()) { + throw new SofaTimeOutException( + "Asynchronous execution timed out, please check Hystrix configuration. Events: " + + getExecutionEventsString()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + RpcInternalContext.getContext().setFuture(delegate); + if (this.sofaResponse == null) { + this.sofaResponse = buildEmptyResponse(request); + } + return this.sofaResponse; + } + + @Override + protected Object run() throws Exception { + events.add(SofaAsyncHystrixEvent.EMIT); + RpcInternalContext.setContext(rpcInternalContext); + RpcInvokeContext.setContext(rpcInvokeContext); + + this.sofaResponse = invoker.invoke(request); + ResponseFuture responseFuture = RpcInternalContext.getContext().getFuture(); + lock.countDown(); + events.add(SofaAsyncHystrixEvent.INVOKE_UNLOCKED); + try { + return responseFuture.get(); + } finally { + events.add(SofaAsyncHystrixEvent.INVOKE_SUCCESS); + } + } + + @Override + protected Object getFallback() { + events.add(SofaAsyncHystrixEvent.FALLBACK_EMIT); + if (lock.getCount() > 0) { + // > 0 说明 run 方法没有执行,或是执行时立刻失败了 + this.sofaResponse = buildEmptyResponse(request); + lock.countDown(); + events.add(SofaAsyncHystrixEvent.FALLBACK_UNLOCKED); + } + FallbackFactory fallbackFactory = SofaHystrixConfig.loadFallbackFactory((ConsumerConfig) invoker.getConfig()); + if (fallbackFactory == null) { + return super.getFallback(); + } + Object fallback = fallbackFactory.create(null, this.getExecutionException()); + if (fallback == null) { + return super.getFallback(); + } + try { + return request.getMethod().invoke(fallback, request.getMethodArgs()); + } catch (IllegalAccessException e) { + throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", e); + } catch (InvocationTargetException e) { + throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", + e.getTargetException()); + } finally { + events.add(SofaAsyncHystrixEvent.FALLBACK_SUCCESS); + } + } + + // Copy from AbstractCluster#buildEmptyResponse + private SofaResponse buildEmptyResponse(SofaRequest request) { + SofaResponse response = new SofaResponse(); + Method method = request.getMethod(); + if (method != null) { + response.setAppResponse(ClassUtils.getDefaultPrimitiveValue(method.getReturnType())); + } + return response; + } + + private long getLockTimeout() { + if (this.getProperties().executionTimeoutEnabled().get()) { + return this.getProperties().executionTimeoutInMilliseconds().get(); + } + return DEFAULT_LOCK_TIMEOUT; + } + + private String getExecutionEventsString() { + List executionEvents = getExecutionEvents(); + if (executionEvents == null) { + executionEvents = Collections.emptyList(); + } + StringBuilder message = new StringBuilder("["); + for (HystrixEventType executionEvent : executionEvents) { + message.append(HystrixEventType.class.getSimpleName()).append("#").append(executionEvent.name()) + .append(","); + } + for (SofaAsyncHystrixEvent event : events) { + message.append(SofaAsyncHystrixEvent.class.getSimpleName()).append("#").append(event.name()).append(","); + } + if (message.length() > 1) { + message.deleteCharAt(message.length() - 1); + } + return message.append("]").toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `SofaAsyncHystrixCommand.request.getMethod()` could be null and is dereferenced at line 136. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object SofaAsyncHystrixCommand.getFallback() + +### Procedure Id: +com.alipay.sofa.rpc.hystrix.SofaAsyncHystrixCommand.getFallback():java.lang.Object.0895e8ecf8af6fc8f2f80e45d0c6ddf0 + +### File: +extension-impl/fault-hystrix/src/main/java/com/alipay/sofa/rpc/hystrix/SofaAsyncHystrixCommand.java + +### Key: +SofaAsyncHystrixCommand.java|getFallback|NULL_DEREFERENCE + +### Node Key: +bf8329e96fa3e9f24edd2b191dde4cd0 + +### Hash: +ec2672283709ce4e2630d278d4cea9d4 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9273/instruction.md b/inferredbugs-9273/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28cb04a0549e7e130fe7e3ee28edec0d514be523 --- /dev/null +++ b/inferredbugs-9273/instruction.md @@ -0,0 +1,308 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.server.rest; + +import com.alipay.sofa.rpc.common.utils.CommonUtils; +import com.alipay.sofa.rpc.config.JAXRSProviderManager; +import com.alipay.sofa.rpc.config.ProviderConfig; +import com.alipay.sofa.rpc.config.ServerConfig; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.ext.Extension; +import com.alipay.sofa.rpc.invoke.Invoker; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.server.Server; +import org.jboss.resteasy.spi.PropertyInjector; +import org.jboss.resteasy.spi.ResteasyDeployment; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Rest server base on resteasy. + * + * @author GengZhang + */ +@Extension("rest") +public class RestServer implements Server { + + /** + * Logger + */ + private static final Logger LOGGER = LoggerFactory.getLogger(RestServer.class); + + /** + * 是否已经启动 + */ + protected volatile boolean started; + + /** + * Bolt服务端 + */ + protected SofaNettyJaxrsServer httpServer; + + /** + * 服务端配置 + */ + protected ServerConfig serverConfig; + + /** + * invoker数量 + */ + protected AtomicInteger invokerCnt = new AtomicInteger(); + + @Override + public void init(ServerConfig serverConfig) { + this.serverConfig = serverConfig; + } + + private SofaNettyJaxrsServer buildServer() { + // 生成Server对象 + SofaNettyJaxrsServer httpServer = new SofaNettyJaxrsServer(serverConfig); + + int bossThreads = serverConfig.getIoThreads(); + if (bossThreads > 0) { + httpServer.setIoWorkerCount(bossThreads); // 其实是boss+worker线程 默认cpu*2 + } + httpServer.setExecutorThreadCount(serverConfig.getMaxThreads()); // 业务线程 + httpServer.setMaxRequestSize(serverConfig.getPayload()); + httpServer.setHostname(serverConfig.getBoundHost()); + httpServer.setPort(serverConfig.getPort()); + + ResteasyDeployment resteasyDeployment = httpServer.getDeployment(); + resteasyDeployment.start(); + + ResteasyProviderFactory providerFactory = resteasyDeployment.getProviderFactory(); + registerProvider(providerFactory); + + return httpServer; + } + + private void registerProvider(ResteasyProviderFactory providerFactory) { + // 注册内置 + Set internalProviderClasses = JAXRSProviderManager.getInternalProviderClasses(); + if (CommonUtils.isNotEmpty(internalProviderClasses)) { + for (Class providerClass : internalProviderClasses) { + providerFactory.register(providerClass); + } + } + // 注册自定义 + Set customProviderInstances = JAXRSProviderManager.getCustomProviderInstances(); + if (CommonUtils.isNotEmpty(customProviderInstances)) { + for (Object provider : customProviderInstances) { + PropertyInjector propertyInjector = providerFactory.getInjectorFactory() + .createPropertyInjector( + JAXRSProviderManager.getTargetClass(provider), providerFactory); + propertyInjector.inject(provider); + providerFactory.registerProviderInstance(provider); + } + } + + if (LOGGER.isDebugEnabled()) { + Set pcs = providerFactory.getProviderClasses(); + StringBuilder sb = new StringBuilder(); + sb.append("\ndefault-providers:\n"); + + for (Object provider : pcs) { + sb.append(" ").append(provider).append("\n"); + } + LOGGER.debug(sb.toString()); + } + } + + @Override + public void start() { + if (started) { + return; + } + synchronized (this) { + if (started) { + return; + } + // 绑定到端口 + try { + httpServer = buildServer(); + httpServer.start(); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Start the http rest server at port {}", serverConfig.getPort()); + } + } catch (Exception e) { + throw new SofaRpcRuntimeException( + "Failed to start jetty server at port " + serverConfig.getPort() + ", cause: " + e.getMessage(), e); + } + started = true; + } + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public boolean hasNoEntry() { + return false; + } + + @Override + public void stop() { + if (!started) { + return; + } + try { + // 关闭端口,不关闭线程池 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort()); + } + httpServer.stop(); + httpServer = null; + } catch (Exception e) { + LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e); + } + started = false; + } + + @Override + public void registerProcessor(ProviderConfig providerConfig, Invoker instance) { + if (!isStarted()) { + start(); + } + // 在httpserver中注册此jaxrs服务 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Register jaxrs service to base url http://" + serverConfig.getHost() + ":" + + serverConfig.getPort() + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .addResourceFactory(new SofaResourceFactory(providerConfig), serverConfig.getContextPath()); + + invokerCnt.incrementAndGet(); + } catch (Exception e) { + LOGGER.error("Register jaxrs service error", e); + } + } + + @Override + public void unRegisterProcessor(ProviderConfig providerConfig, boolean closeIfNoEntry) { + if (!isStarted()) { + return; + } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Unregister jaxrs service to port {} and base path is {}", serverConfig.getPort(), + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .removeRegistrations(providerConfig.getRef().getClass(), serverConfig.getContextPath()); + invokerCnt.decrementAndGet(); + } catch (Exception e) { + LOGGER.error("Unregister jaxrs service error", e); + } + // 如果最后一个需要关闭,则关闭 + if (closeIfNoEntry && invokerCnt.get() == 0) { + stop(); + } + } + + @Override + public void destroy() { + stop(); + } + + @Override + public void destroy(DestroyHook hook) { + hook.preDestroy(); + destroy(); + hook.postDestroy(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.rpc.server.rest.RestServer.destroy` indirectly writes to field `this.com.alipay.sofa.rpc.server.rest.RestServer.httpServer` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RestServer.destroy() + +### Procedure Id: +com.alipay.sofa.rpc.server.rest.RestServer.destroy():void.cffa6af9229bc49ccb74cf4721f387a2 + +### File: +extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/RestServer.java + +### Key: +RestServer.java|destroy|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f4b027a4c2ce6b53a5bd905ed4d39515 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9274/instruction.md b/inferredbugs-9274/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..382bc00cbd6476f227c89d8d7ad204a5439e00dc --- /dev/null +++ b/inferredbugs-9274/instruction.md @@ -0,0 +1,308 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.server.rest; + +import com.alipay.sofa.rpc.common.utils.CommonUtils; +import com.alipay.sofa.rpc.config.JAXRSProviderManager; +import com.alipay.sofa.rpc.config.ProviderConfig; +import com.alipay.sofa.rpc.config.ServerConfig; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.ext.Extension; +import com.alipay.sofa.rpc.invoke.Invoker; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.server.Server; +import org.jboss.resteasy.spi.PropertyInjector; +import org.jboss.resteasy.spi.ResteasyDeployment; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Rest server base on resteasy. + * + * @author GengZhang + */ +@Extension("rest") +public class RestServer implements Server { + + /** + * Logger + */ + private static final Logger LOGGER = LoggerFactory.getLogger(RestServer.class); + + /** + * 是否已经启动 + */ + protected volatile boolean started; + + /** + * Bolt服务端 + */ + protected SofaNettyJaxrsServer httpServer; + + /** + * 服务端配置 + */ + protected ServerConfig serverConfig; + + /** + * invoker数量 + */ + protected AtomicInteger invokerCnt = new AtomicInteger(); + + @Override + public void init(ServerConfig serverConfig) { + this.serverConfig = serverConfig; + } + + private SofaNettyJaxrsServer buildServer() { + // 生成Server对象 + SofaNettyJaxrsServer httpServer = new SofaNettyJaxrsServer(serverConfig); + + int bossThreads = serverConfig.getIoThreads(); + if (bossThreads > 0) { + httpServer.setIoWorkerCount(bossThreads); // 其实是boss+worker线程 默认cpu*2 + } + httpServer.setExecutorThreadCount(serverConfig.getMaxThreads()); // 业务线程 + httpServer.setMaxRequestSize(serverConfig.getPayload()); + httpServer.setHostname(serverConfig.getBoundHost()); + httpServer.setPort(serverConfig.getPort()); + + ResteasyDeployment resteasyDeployment = httpServer.getDeployment(); + resteasyDeployment.start(); + + ResteasyProviderFactory providerFactory = resteasyDeployment.getProviderFactory(); + registerProvider(providerFactory); + + return httpServer; + } + + private void registerProvider(ResteasyProviderFactory providerFactory) { + // 注册内置 + Set internalProviderClasses = JAXRSProviderManager.getInternalProviderClasses(); + if (CommonUtils.isNotEmpty(internalProviderClasses)) { + for (Class providerClass : internalProviderClasses) { + providerFactory.register(providerClass); + } + } + // 注册自定义 + Set customProviderInstances = JAXRSProviderManager.getCustomProviderInstances(); + if (CommonUtils.isNotEmpty(customProviderInstances)) { + for (Object provider : customProviderInstances) { + PropertyInjector propertyInjector = providerFactory.getInjectorFactory() + .createPropertyInjector( + JAXRSProviderManager.getTargetClass(provider), providerFactory); + propertyInjector.inject(provider); + providerFactory.registerProviderInstance(provider); + } + } + + if (LOGGER.isDebugEnabled()) { + Set pcs = providerFactory.getProviderClasses(); + StringBuilder sb = new StringBuilder(); + sb.append("\ndefault-providers:\n"); + + for (Object provider : pcs) { + sb.append(" ").append(provider).append("\n"); + } + LOGGER.debug(sb.toString()); + } + } + + @Override + public void start() { + if (started) { + return; + } + synchronized (this) { + if (started) { + return; + } + // 绑定到端口 + try { + httpServer = buildServer(); + httpServer.start(); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Start the http rest server at port {}", serverConfig.getPort()); + } + } catch (Exception e) { + throw new SofaRpcRuntimeException( + "Failed to start jetty server at port " + serverConfig.getPort() + ", cause: " + e.getMessage(), e); + } + started = true; + } + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public boolean hasNoEntry() { + return false; + } + + @Override + public void stop() { + if (!started) { + return; + } + try { + // 关闭端口,不关闭线程池 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort()); + } + httpServer.stop(); + httpServer = null; + } catch (Exception e) { + LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e); + } + started = false; + } + + @Override + public void registerProcessor(ProviderConfig providerConfig, Invoker instance) { + if (!isStarted()) { + start(); + } + // 在httpserver中注册此jaxrs服务 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Register jaxrs service to base url http://" + serverConfig.getHost() + ":" + + serverConfig.getPort() + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .addResourceFactory(new SofaResourceFactory(providerConfig), serverConfig.getContextPath()); + + invokerCnt.incrementAndGet(); + } catch (Exception e) { + LOGGER.error("Register jaxrs service error", e); + } + } + + @Override + public void unRegisterProcessor(ProviderConfig providerConfig, boolean closeIfNoEntry) { + if (!isStarted()) { + return; + } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Unregister jaxrs service to port {} and base path is {}", serverConfig.getPort(), + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .removeRegistrations(providerConfig.getRef().getClass(), serverConfig.getContextPath()); + invokerCnt.decrementAndGet(); + } catch (Exception e) { + LOGGER.error("Unregister jaxrs service error", e); + } + // 如果最后一个需要关闭,则关闭 + if (closeIfNoEntry && invokerCnt.get() == 0) { + stop(); + } + } + + @Override + public void destroy() { + stop(); + } + + @Override + public void destroy(DestroyHook hook) { + hook.preDestroy(); + destroy(); + hook.postDestroy(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.rpc.server.rest.RestServer.stop` writes to field `this.com.alipay.sofa.rpc.server.rest.RestServer.httpServer` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RestServer.stop() + +### Procedure Id: +com.alipay.sofa.rpc.server.rest.RestServer.stop():void.59af57e6e49148ca6857406346f94b27 + +### File: +extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/RestServer.java + +### Key: +RestServer.java|stop|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +705e0ffb0309353c9f4ab2b5468ab388 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9275/instruction.md b/inferredbugs-9275/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..66cb9f6f83a6f0dcd6cbfd21853c2df5f9237a16 --- /dev/null +++ b/inferredbugs-9275/instruction.md @@ -0,0 +1,268 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.bootstrap; + +import com.alipay.sofa.rpc.client.ClientProxyInvoker; +import com.alipay.sofa.rpc.client.Cluster; +import com.alipay.sofa.rpc.common.RemotingConstants; +import com.alipay.sofa.rpc.config.ConfigUniqueNameGenerator; +import com.alipay.sofa.rpc.context.BaggageResolver; +import com.alipay.sofa.rpc.context.RpcInternalContext; +import com.alipay.sofa.rpc.context.RpcInvokeContext; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.core.invoke.SendableResponseCallback; +import com.alipay.sofa.rpc.core.invoke.SofaResponseCallback; +import com.alipay.sofa.rpc.core.request.SofaRequest; +import com.alipay.sofa.rpc.core.response.SofaResponse; +import com.alipay.sofa.rpc.message.ResponseFuture; + +import static com.alipay.sofa.rpc.common.RpcConstants.HIDDEN_KEY_INVOKE_CONTEXT; +import static com.alipay.sofa.rpc.common.RpcConstants.HIDDEN_KEY_PINPOINT; +import static com.alipay.sofa.rpc.common.RpcConstants.INTERNAL_KEY_APP_NAME; +import static com.alipay.sofa.rpc.common.RpcConstants.INTERNAL_KEY_PROTOCOL_NAME; +import static com.alipay.sofa.rpc.common.RpcConstants.INTERNAL_KEY_RESULT_CODE; +import static com.alipay.sofa.rpc.common.RpcConstants.SERIALIZE_HESSIAN; +import static com.alipay.sofa.rpc.common.RpcConstants.SERIALIZE_HESSIAN2; +import static com.alipay.sofa.rpc.common.RpcConstants.SERIALIZE_JAVA; +import static com.alipay.sofa.rpc.common.RpcConstants.SERIALIZE_PROTOBUF; + +/** + * 默认调用端代理执行器 + * + * @author GengZhang + */ +public class DefaultClientProxyInvoker extends ClientProxyInvoker { + + /** + * 缓存接口名 + */ + private String serviceName; + + /** + * 缓存序列化类型 + */ + private Byte serializeType; + + /** + * 构造执行链 + * + * @param bootstrap 调用端配置 + */ + public DefaultClientProxyInvoker(ConsumerBootstrap bootstrap) { + super(bootstrap); + cacheCommonData(); + } + + private void cacheCommonData() { + // 缓存数据 + this.serviceName = ConfigUniqueNameGenerator.getUniqueName(consumerConfig); + this.serializeType = parseSerializeType(consumerConfig.getSerialization()); + } + + private Byte parseSerializeType(String serialization) { + Byte serializeType; + if (SERIALIZE_HESSIAN.equals(serialization) + || SERIALIZE_HESSIAN2.equals(serialization)) { + serializeType = RemotingConstants.SERIALIZE_CODE_HESSIAN; + } else if (SERIALIZE_PROTOBUF.equals(serialization)) { + serializeType = RemotingConstants.SERIALIZE_CODE_PROTOBUF; + } else if (SERIALIZE_JAVA.equals(serialization)) { + serializeType = RemotingConstants.SERIALIZE_CODE_JAVA; + } else { + throw new SofaRpcRuntimeException("Unsupported serialization type"); + } + return serializeType; + } + + @Override + protected void decorateRequest(SofaRequest request) { + // 公共的设置 + super.decorateRequest(request); + + // 缓存是为了加快速度 + request.setTargetServiceUniqueName(serviceName); + request.setSerializeType(serializeType); + + if (!consumerConfig.isGeneric()) { + // 找到调用类型, generic的时候类型在filter里进行判断 + request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName())); + } + + RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext(); + RpcInternalContext internalContext = RpcInternalContext.getContext(); + if (invokeCtx != null) { + // 如果用户设置了调用级别回调函数 + SofaResponseCallback responseCallback = invokeCtx.getResponseCallback(); + if (responseCallback != null) { + request.setSofaResponseCallback(responseCallback); + invokeCtx.setResponseCallback(null); // 一次性用完 + invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN, + isSendableResponseCallback(responseCallback)); + } + // 如果用户设置了调用级别超时时间 + Integer timeout = invokeCtx.getTimeout(); + if (timeout != null) { + request.setTimeout(timeout); + invokeCtx.setTimeout(null);// 一次性用完 + } + // 如果用户指定了调用的URL + String targetURL = invokeCtx.getTargetURL(); + if (targetURL != null) { + internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL); + invokeCtx.setTargetURL(null);// 一次性用完 + } + // 如果用户指定了透传数据 + if (RpcInvokeContext.isBaggageEnable()) { + // 需要透传 + BaggageResolver.carryWithRequest(invokeCtx, request); + internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx); + } + } + if (RpcInternalContext.isAttachmentEnable()) { + internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName()); + internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol()); + } + + // 额外属性通过HEAD传递给服务端 + request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName()); + request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol()); + } + + @Override + protected void decorateResponse(SofaResponse response) { + // 公共的设置 + super.decorateResponse(response); + // 上下文内转外 + RpcInternalContext context = RpcInternalContext.getContext(); + ResponseFuture future = context.getFuture(); + RpcInvokeContext invokeCtx = null; + if (future != null) { + invokeCtx = RpcInvokeContext.getContext(); + invokeCtx.setFuture(future); + } + if (RpcInvokeContext.isBaggageEnable()) { + BaggageResolver.pickupFromResponse(invokeCtx, response, true); + } + // bad code + if (RpcInternalContext.isAttachmentEnable()) { + String resultCode = (String) context.getAttachment(INTERNAL_KEY_RESULT_CODE); + if (resultCode != null) { + if (invokeCtx == null) { + invokeCtx = RpcInvokeContext.getContext(); + } + invokeCtx.put(RemotingConstants.INVOKE_CTX_RPC_RESULT_CODE, resultCode); + } + } + } + + /** + * 是否是异步Callback,如果跨classloader下不能直接使用instanceof + * + * @param callback SofaResponseCallback + * @return 是否异步Callback + */ + protected boolean isSendableResponseCallback(SofaResponseCallback callback) { + return callback instanceof SendableResponseCallback; + } + + @Override + public Cluster setCluster(Cluster newCluster) { + Cluster old = super.setCluster(newCluster); + cacheCommonData(); + return old; + } + + @Override + public String toString() { + return consumerConfig != null ? ConfigUniqueNameGenerator.getUniqueName(consumerConfig) : super.toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.rpc.bootstrap.DefaultClientProxyInvoker.decorateRequest` indirectly writes to field `request.com.alipay.sofa.rpc.core.request.SofaRequest.serializeType` outside of synchronization. + Reporting because a superclass `class com.alipay.sofa.rpc.client.ClientProxyInvoker` is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DefaultClientProxyInvoker.decorateRequest(SofaRequest) + +### Procedure Id: +com.alipay.sofa.rpc.bootstrap.DefaultClientProxyInvoker.decorateRequest(com.alipay.sofa.rpc.core.req.9bd94b5ca5bdd3525d0fd6a72d87f1cb + +### File: +extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/bootstrap/DefaultClientProxyInvoker.java + +### Key: +DefaultClientProxyInvoker.java|decorateRequest|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +510e720bfa5ec3f2f8185d612d2a5f13 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9280/instruction.md b/inferredbugs-9280/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13ac58fe1c404be2c25773c87a4b795c93c7a330 --- /dev/null +++ b/inferredbugs-9280/instruction.md @@ -0,0 +1,869 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.client; + +import com.alipay.sofa.rpc.bootstrap.ConsumerBootstrap; +import com.alipay.sofa.rpc.common.RpcConstants; +import com.alipay.sofa.rpc.common.utils.ClassUtils; +import com.alipay.sofa.rpc.common.utils.CommonUtils; +import com.alipay.sofa.rpc.common.utils.StringUtils; +import com.alipay.sofa.rpc.config.ConsumerConfig; +import com.alipay.sofa.rpc.context.AsyncRuntime; +import com.alipay.sofa.rpc.context.RpcInternalContext; +import com.alipay.sofa.rpc.context.RpcRuntimeContext; +import com.alipay.sofa.rpc.core.exception.RpcErrorType; +import com.alipay.sofa.rpc.core.exception.SofaRouteException; +import com.alipay.sofa.rpc.core.exception.SofaRpcException; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.core.invoke.SofaResponseCallback; +import com.alipay.sofa.rpc.core.request.SofaRequest; +import com.alipay.sofa.rpc.core.response.SofaResponse; +import com.alipay.sofa.rpc.event.EventBus; +import com.alipay.sofa.rpc.event.ProviderInfoAddEvent; +import com.alipay.sofa.rpc.event.ProviderInfoRemoveEvent; +import com.alipay.sofa.rpc.event.ProviderInfoUpdateAllEvent; +import com.alipay.sofa.rpc.event.ProviderInfoUpdateEvent; +import com.alipay.sofa.rpc.filter.ConsumerInvoker; +import com.alipay.sofa.rpc.filter.FilterChain; +import com.alipay.sofa.rpc.listener.ConsumerStateListener; +import com.alipay.sofa.rpc.log.LogCodes; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.message.ResponseFuture; +import com.alipay.sofa.rpc.transport.ClientTransport; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static com.alipay.sofa.rpc.client.ProviderInfoAttrs.ATTR_TIMEOUT; +import static com.alipay.sofa.rpc.common.RpcConfigs.getIntValue; +import static com.alipay.sofa.rpc.common.RpcOptions.CONSUMER_INVOKE_TIMEOUT; + +/** + * Abstract cluster, contains router chain, filter chain, address holder, connection holder and load balancer. + * + * @author GengZhang + */ +public abstract class AbstractCluster extends Cluster { + + /** + * slf4j Logger for this class + */ + private final static Logger LOGGER = LoggerFactory.getLogger(AbstractCluster.class); + + /** + * 构造函数 + * + * @param consumerBootstrap 服务端消费者启动器 + */ + public AbstractCluster(ConsumerBootstrap consumerBootstrap) { + super(consumerBootstrap); + } + + /** + * 是否已启动(已建立连接) + */ + protected volatile boolean initialized = false; + + /** + * 是否已经销毁(已经销毁不能再继续使用) + */ + protected volatile boolean destroyed = false; + + /** + * 当前Client正在发送的调用数量 + */ + protected AtomicInteger countOfInvoke = new AtomicInteger(0); + + /** + * 路由列表 + */ + protected RouterChain routerChain; + /** + * 负载均衡接口 + */ + protected LoadBalancer loadBalancer; + /** + * 地址保持器 + */ + protected AddressHolder addressHolder; + /** + * 连接管理器 + */ + protected ConnectionHolder connectionHolder; + /** + * 过滤器链 + */ + protected FilterChain filterChain; + + @Override + public synchronized void init() { + if (initialized) { // 已初始化 + return; + } + // 构造Router链 + routerChain = RouterChain.buildConsumerChain(consumerBootstrap); + // 负载均衡策略 考虑是否可动态替换? + loadBalancer = LoadBalancerFactory.getLoadBalancer(consumerBootstrap); + // 地址管理器 + addressHolder = AddressHolderFactory.getAddressHolder(consumerBootstrap); + // 连接管理器 + connectionHolder = ConnectionHolderFactory.getConnectionHolder(consumerBootstrap); + // 构造Filter链,最底层是调用过滤器 + this.filterChain = FilterChain.buildConsumerChain(this.consumerConfig, + new ConsumerInvoker(consumerBootstrap)); + + if (consumerConfig.isLazy()) { // 延迟连接 + if (LOGGER.isInfoEnabled(consumerConfig.getAppName())) { + LOGGER.infoWithApp(consumerConfig.getAppName(), "Connection will be initialized when first invoke."); + } + } + + // 启动重连线程 + connectionHolder.init(); + try { + // 得到服务端列表 + List all = consumerBootstrap.subscribe(); + if (CommonUtils.isNotEmpty(all)) { + // 初始化服务端连接(建立长连接) + updateAllProviders(all); + } + } catch (SofaRpcRuntimeException e) { + throw e; + } catch (Throwable e) { + throw new SofaRpcRuntimeException("Init provider's transport error!", e); + } + + // 启动成功 + initialized = true; + + // 如果check=true表示强依赖 + if (consumerConfig.isCheck() && !isAvailable()) { + throw new SofaRpcRuntimeException("The consumer is depend on alive provider " + + "and there is no alive provider, you can ignore it " + + "by ConsumerConfig.setCheck(boolean) (default is false)"); + } + } + + /** + * 检测状态 + */ + protected void checkClusterState() { + if (destroyed) { // 已销毁 + throw new SofaRpcRuntimeException("Client has been destroyed!"); + } + if (!initialized) { // 未初始化 + init(); + } + } + + @Override + public void addProvider(ProviderGroup providerGroup) { + // 包装了各个组件的操作 + addressHolder.addProvider(providerGroup); + connectionHolder.addProvider(providerGroup); + if (EventBus.isEnable(ProviderInfoAddEvent.class)) { + ProviderInfoAddEvent event = new ProviderInfoAddEvent(consumerConfig, providerGroup); + EventBus.post(event); + } + } + + @Override + public void removeProvider(ProviderGroup providerGroup) { + // 包装了各个组件的操作 + addressHolder.removeProvider(providerGroup); + connectionHolder.removeProvider(providerGroup); + if (EventBus.isEnable(ProviderInfoRemoveEvent.class)) { + ProviderInfoRemoveEvent event = new ProviderInfoRemoveEvent(consumerConfig, providerGroup); + EventBus.post(event); + } + } + + @Override + public void updateProviders(ProviderGroup providerGroup) { + checkProviderInfo(providerGroup); + ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName()); + if (ProviderHelper.isEmpty(providerGroup)) { + addressHolder.updateProviders(providerGroup); + if (CommonUtils.isNotEmpty(oldProviderGroup.getProviderInfos())) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + + "providers has been closed, or this consumer has been add to blacklist"); + closeTransports(); + } + } + } else { + addressHolder.updateProviders(providerGroup); + connectionHolder.updateProviders(providerGroup); + } + if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) { + ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup); + EventBus.post(event); + } + } + + @Override + public void updateAllProviders(List providerGroups) { + List oldProviderGroups = new ArrayList(addressHolder.getProviderGroups()); + int count = 0; + if (providerGroups != null) { + for (ProviderGroup providerGroup : providerGroups) { + checkProviderInfo(providerGroup); + count += providerGroup.size(); + } + } + if (count == 0) { + Collection currentProviderList = currentProviderList(); + addressHolder.updateAllProviders(providerGroups); + if (CommonUtils.isNotEmpty(currentProviderList)) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + + "providers has been closed, or this consumer has been add to blacklist"); + closeTransports(); + } + } + } else { + addressHolder.updateAllProviders(providerGroups); + connectionHolder.updateAllProviders(providerGroups); + } + if (EventBus.isEnable(ProviderInfoUpdateAllEvent.class)) { + ProviderInfoUpdateAllEvent event = new ProviderInfoUpdateAllEvent(consumerConfig, oldProviderGroups, + providerGroups); + EventBus.post(event); + } + } + + /** + * 检测服务节点的一些信息 + * + * @param providerGroup 服务列表分组 + */ + protected void checkProviderInfo(ProviderGroup providerGroup) { + List providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos(); + if (CommonUtils.isEmpty(providerInfos)) { + return; + } + Iterator iterator = providerInfos.iterator(); + while (iterator.hasNext()) { + ProviderInfo providerInfo = iterator.next(); + if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) { + if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { + LOGGER.warnWithApp(consumerConfig.getAppName(), + "Unmatched protocol between consumer [{}] and provider [{}].", + consumerConfig.getProtocol(), providerInfo.getProtocolType()); + } + } + if (StringUtils.isEmpty(providerInfo.getSerializationType())) { + providerInfo.setSerializationType(consumerConfig.getSerialization()); + } + } + } + + @Override + public SofaResponse invoke(SofaRequest request) throws SofaRpcException { + SofaResponse response = null; + try { + // 做一些初始化检查,例如未连接可以连接 + checkClusterState(); + // 开始调用 + countOfInvoke.incrementAndGet(); // 计数+1 + response = doInvoke(request); + return response; + } catch (SofaRpcException e) { + // 客户端收到异常(客户端自己的异常) + throw e; + } finally { + countOfInvoke.decrementAndGet(); // 计数-1 + } + } + + /** + * 子类实现各自逻辑的调用,例如重试等 + * + * @param msg Request对象 + * @return 调用结果 + * @throws SofaRpcException rpc异常 + */ + protected abstract SofaResponse doInvoke(SofaRequest msg) throws SofaRpcException; + + /** + * 检查服务端版本,特殊处理 + * + * @param providerInfo 服务端 + * @param request 请求对象 + */ + protected void checkProviderVersion(ProviderInfo providerInfo, SofaRequest request) { + + } + + /** + * 上一次连接,目前是记录整个接口的,是否需要方法级的?? + */ + private volatile ProviderInfo lastProviderInfo; + + /** + * 根据规则进行负载均衡 + * + * @param message 调用对象 + * @return 一个可用的provider + * @throws SofaRpcException rpc异常 + */ + protected ProviderInfo select(SofaRequest message) throws SofaRpcException { + return select(message, null); + } + + /** + * 根据规则进行负载均衡 + * + * @param message 调用对象 + * @param invokedProviderInfos 已调用列表 + * @return 一个可用的provider + * @throws SofaRpcException rpc异常 + */ + protected ProviderInfo select(SofaRequest message, List invokedProviderInfos) + throws SofaRpcException { + // 粘滞连接,当前连接可用 + if (consumerConfig.isSticky()) { + if (lastProviderInfo != null) { + ProviderInfo providerInfo = lastProviderInfo; + ClientTransport lastTransport = connectionHolder.getAvailableClientTransport(providerInfo); + if (lastTransport != null && lastTransport.isAvailable()) { + checkAlias(providerInfo, message); + return providerInfo; + } + } + } + // 原始服务列表数据 --> 路由结果 + List providerInfos = routerChain.route(message, null); + if (CommonUtils.isEmpty(providerInfos)) { + throw noAvailableProviderException(message.getTargetServiceUniqueName()); + } + if (CommonUtils.isNotEmpty(invokedProviderInfos) && providerInfos.size() > invokedProviderInfos.size()) { // 总数大于已调用数 + providerInfos.removeAll(invokedProviderInfos);// 已经调用异常的本次不再重试 + } + + String targetIP = null; + ProviderInfo providerInfo; + RpcInternalContext context = RpcInternalContext.peekContext(); + if (context != null) { + targetIP = (String) RpcInternalContext.getContext().getAttachment(RpcConstants.HIDDEN_KEY_PINPOINT); + } + if (StringUtils.isNotBlank(targetIP)) { + // 如果指定了调用地址 + providerInfo = selectPinpointProvider(targetIP, providerInfos); + if (providerInfo == null) { + // 指定的不存在 + throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP); + } + ClientTransport clientTransport = selectByProvider(message, providerInfo); + if (clientTransport == null) { + // 指定的不存在或已死,抛出异常 + throw unavailableProviderException(message.getTargetServiceUniqueName(), targetIP); + } + return providerInfo; + } else { + do { + // 再进行负载均衡筛选 + providerInfo = loadBalancer.select(message, providerInfos); + ClientTransport transport = selectByProvider(message, providerInfo); + if (transport != null) { + return providerInfo; + } + providerInfos.remove(providerInfo); + } while (!providerInfos.isEmpty()); + } + throw noAvailableProviderException(message.getTargetServiceUniqueName()); + } + + /** + * Select provider. + * + * @param targetIP the target ip + * @return the provider + */ + protected ProviderInfo selectPinpointProvider(String targetIP, List providerInfos) { + ProviderInfo tp = ProviderHelper.toProviderInfo(targetIP); + for (ProviderInfo providerInfo : providerInfos) { + if (providerInfo.getHost().equals(tp.getHost()) + && StringUtils.equals(providerInfo.getProtocolType(), tp.getProtocolType()) + && providerInfo.getPort() == tp.getPort()) { + return providerInfo; + } + } + return null; + } + + /** + * 找不到可用的服务列表的异常 + * + * @param serviceKey 服务关键字 + * @return 服务端 + */ + protected SofaRouteException noAvailableProviderException(String serviceKey) { + return new SofaRouteException(LogCodes.getLog(LogCodes.ERROR_NO_AVAILBLE_PROVIDER, serviceKey)); + } + + /** + * 指定地址不可用 + * + * @param serviceKey 服务关键字 + * @return 服务端 + */ + protected SofaRouteException unavailableProviderException(String serviceKey, String providerInfo) { + return new SofaRouteException(LogCodes.getLog(LogCodes.ERROR_TARGET_URL_INVALID, serviceKey, providerInfo)); + } + + /** + * 得到provider得到连接 + * + * @param message 调用对象 + * @param providerInfo 指定Provider + * @return 一个可用的transport或者null + */ + protected ClientTransport selectByProvider(SofaRequest message, ProviderInfo providerInfo) { + ClientTransport transport = connectionHolder.getAvailableClientTransport(providerInfo); + if (transport != null) { + if (transport.isAvailable()) { + lastProviderInfo = providerInfo; + checkAlias(providerInfo, message); //检查分组 + return transport; + } else { + connectionHolder.setUnavailable(providerInfo, transport); + } + } + return null; + } + + /** + * 检查分组映射 + * + * @param providerInfo 服务端 + * @param message 请求对象 + */ + protected void checkAlias(ProviderInfo providerInfo, SofaRequest message) { + + } + + /** + * 发起调用链 + * + * @param providerInfo 服务端信息 + * @param request 请求对象 + * @return 执行后返回的响应 + * @throws SofaRpcException 请求RPC异常 + */ + protected SofaResponse filterChain(ProviderInfo providerInfo, SofaRequest request) throws SofaRpcException { + RpcInternalContext context = RpcInternalContext.getContext(); + context.setProviderInfo(providerInfo); + return filterChain.invoke(request); + } + + @Override + public SofaResponse sendMsg(ProviderInfo providerInfo, SofaRequest request) throws SofaRpcException { + ClientTransport clientTransport = connectionHolder.getAvailableClientTransport(providerInfo); + if (clientTransport != null && clientTransport.isAvailable()) { + return doSendMsg(providerInfo, clientTransport, request); + } else { + throw unavailableProviderException(request.getTargetServiceUniqueName(), providerInfo.getOriginUrl()); + } + } + + /** + * 调用客户端 + * + * @param transport 客户端连接 + * @param request Request对象 + * @return 调用结果 + * @throws SofaRpcException rpc异常 + */ + protected SofaResponse doSendMsg(ProviderInfo providerInfo, ClientTransport transport, + SofaRequest request) throws SofaRpcException { + RpcInternalContext context = RpcInternalContext.getContext(); + // 添加调用的服务端远程地址 + RpcInternalContext.getContext().setRemoteAddress(providerInfo.getHost(), providerInfo.getPort()); + try { + checkProviderVersion(providerInfo, request); // 根据服务端版本特殊处理 + String invokeType = request.getInvokeType(); + int timeout = resolveTimeout(request, consumerConfig, providerInfo); + + SofaResponse response = null; + // 同步调用 + if (RpcConstants.INVOKER_TYPE_SYNC.equals(invokeType)) { + long start = RpcRuntimeContext.now(); + try { + response = transport.syncSend(request, timeout); + } finally { + if (RpcInternalContext.isAttachmentEnable()) { + long elapsed = RpcRuntimeContext.now() - start; + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed); + } + } + } + // 单向调用 + else if (RpcConstants.INVOKER_TYPE_ONEWAY.equals(invokeType)) { + long start = RpcRuntimeContext.now(); + try { + transport.oneWaySend(request, timeout); + response = buildEmptyResponse(request); + } finally { + if (RpcInternalContext.isAttachmentEnable()) { + long elapsed = RpcRuntimeContext.now() - start; + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_ELAPSE, elapsed); + } + } + } + // Callback调用 + else if (RpcConstants.INVOKER_TYPE_CALLBACK.equals(invokeType)) { + // 调用级别回调监听器 + SofaResponseCallback sofaResponseCallback = request.getSofaResponseCallback(); + if (sofaResponseCallback == null) { + SofaResponseCallback methodResponseCallback = consumerConfig + .getMethodOnreturn(request.getMethodName()); + if (methodResponseCallback != null) { // 方法的Callback + request.setSofaResponseCallback(methodResponseCallback); + } + } + // 记录发送开始时间 + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now()); + // 开始调用 + transport.asyncSend(request, timeout); + response = buildEmptyResponse(request); + } + // Future调用 + else if (RpcConstants.INVOKER_TYPE_FUTURE.equals(invokeType)) { + // 记录发送开始时间 + context.setAttachment(RpcConstants.INTERNAL_KEY_CLIENT_SEND_TIME, RpcRuntimeContext.now()); + // 开始调用 + ResponseFuture future = transport.asyncSend(request, timeout); + // 放入线程上下文 + RpcInternalContext.getContext().setFuture(future); + response = buildEmptyResponse(request); + } else { + throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, "Unknown invoke type:" + invokeType); + } + return response; + } catch (SofaRpcException e) { + throw e; + } catch (Throwable e) { // 客户端其它异常 + throw new SofaRpcException(RpcErrorType.CLIENT_UNDECLARED_ERROR, e); + } + } + + private SofaResponse buildEmptyResponse(SofaRequest request) { + SofaResponse response = new SofaResponse(); + Method method = request.getMethod(); + if (method != null) { + response.setAppResponse(ClassUtils.getDefaultPrimitiveValue(method.getReturnType())); + } + return response; + } + + /** + * 决定超时时间 + * + * @param request 请求 + * @param consumerConfig 客户端配置 + * @param providerInfo 服务提供者信息 + * @return 调用超时 + */ + private int resolveTimeout(SofaRequest request, ConsumerConfig consumerConfig, ProviderInfo providerInfo) { + // 先去调用级别配置 + Integer timeout = request.getTimeout(); + if (timeout == null) { + // 取客户端配置(先方法级别再接口级别) + timeout = consumerConfig.getMethodTimeout(request.getMethodName()); + if (timeout == null || timeout < 0) { + // 再取服务端配置 + timeout = (Integer) providerInfo.getDynamicAttr(ATTR_TIMEOUT); + if (timeout == null) { + // 取框架默认值 + timeout = getIntValue(CONSUMER_INVOKE_TIMEOUT); + } + } + } + return timeout; + } + + @Override + public void destroy() { + destroy(null); + } + + @Override + public void destroy(DestroyHook hook) { + if (destroyed) { + return; + } + if (hook != null) { + hook.postDestroy(); + } + if (connectionHolder != null) { + connectionHolder.destroy(new GracefulDestroyHook()); + } + destroyed = true; + initialized = false; + if (hook != null) { + hook.postDestroy(); + } + } + + /** + * 关闭连接
    + * 注意:关闭有风险,可能有正在调用的请求,建议判断下isAvailable() + */ + protected void closeTransports() { + if (connectionHolder != null) { + connectionHolder.closeAllClientTransports(new GracefulDestroyHook()); + } + } + + /** + * 优雅关闭的钩子 + */ + protected class GracefulDestroyHook implements DestroyHook { + @Override + public void preDestroy() { + // 准备关闭连接 + int count = countOfInvoke.get(); + final int timeout = consumerConfig.getDisconnectTimeout(); // 等待结果超时时间 + if (count > 0) { // 有正在调用的请求 + long start = RpcRuntimeContext.now(); + if (LOGGER.isWarnEnabled()) { + LOGGER.warn("There are {} outstanding call in client, will close transports util return", + count); + } + while (countOfInvoke.get() > 0 && RpcRuntimeContext.now() - start < timeout) { // 等待返回结果 + try { + Thread.sleep(10); + } catch (InterruptedException ignore) { + } + } + } + } + + @Override + public void postDestroy() { + } + } + + @Override + public boolean isAvailable() { + if (destroyed || !initialized) { + return false; + } + List providerGroups = addressHolder.getProviderGroups(); + if (CommonUtils.isEmpty(providerGroups)) { + return false; + } + for (ProviderGroup entry : providerGroups) { + List providerInfos = entry.getProviderInfos(); + for (ProviderInfo providerInfo : providerInfos) { + ClientTransport transport = connectionHolder.getAvailableClientTransport(providerInfo); + if (transport != null && transport.isAvailable()) { + return true; // 只有有1个可用 即可返回 + } else { + connectionHolder.setUnavailable(providerInfo, transport); + } + } + } + return false; + } + + @Override + public void checkStateChange(boolean originalState) { + if (originalState) { // 原来可以 + if (!isAvailable()) { // 变不可以 + notifyStateChangeToUnavailable(); + } + } else { // 原来不可用 + if (isAvailable()) { // 变成可用 + notifyStateChangeToAvailable(); + } + } + } + + /** + * 通知状态变成不可用,主要是:
    + * 1.注册中心删除,更新节点后变成不可用时
    + * 2.连接断线后(心跳+调用),如果是可用节点为空 + */ + public void notifyStateChangeToUnavailable() { + final List onprepear = consumerConfig.getOnAvailable(); + if (onprepear != null) { + AsyncRuntime.getAsyncThreadPool().execute(new Runnable() { + @Override + public void run() { + // 状态变化通知监听器 + for (ConsumerStateListener listener : onprepear) { + try { + listener.onUnavailable(consumerBootstrap.getProxyIns()); + } catch (Exception e) { + LOGGER.error("Failed to notify consumer state listener when state change to unavailable"); + } + } + } + }); + } + } + + /** + * 通知状态变成可用,主要是:
    + * 1.启动成功变成可用时
    + * 2.注册中心增加,更新节点后变成可用时
    + * 3.重连上从一个可用节点都没有-->有可用节点时 + */ + public void notifyStateChangeToAvailable() { + final List onprepear = consumerConfig.getOnAvailable(); + if (onprepear != null) { + AsyncRuntime.getAsyncThreadPool().execute(new Runnable() { + @Override + public void run() { + // 状态变化通知监听器 + for (ConsumerStateListener listener : onprepear) { + try { + listener.onAvailable(consumerBootstrap.getProxyIns()); + } catch (Exception e) { + LOGGER.error("Failed to notify consumer state listener when state change to available"); + } + } + } + }); + } + } + + /** + * 获取当前的Provider全部列表(包括连上和没连上的),比较费性能,慎用 + * + * @return 当前的Provider列表 + */ + public Collection currentProviderList() { + List providerInfos = new ArrayList(); + List providerGroups = addressHolder.getProviderGroups(); + if (CommonUtils.isNotEmpty(providerGroups)) { + for (ProviderGroup entry : providerGroups) { + providerInfos.addAll(entry.getProviderInfos()); + } + } + return providerInfos; + } + + /** + * @return the consumerConfig + */ + public ConsumerConfig getConsumerConfig() { + return consumerConfig; + } + + @Override + public AddressHolder getAddressHolder() { + return addressHolder; + } + + @Override + public ConnectionHolder getConnectionHolder() { + return connectionHolder; + } + + @Override + public FilterChain getFilterChain() { + return filterChain; + } + + @Override + public RouterChain getRouterChain() { + return routerChain; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.alipay.sofa.rpc.client.AbstractCluster.updateProviders` indirectly writes to field `providerInfo.com.alipay.sofa.rpc.client.ProviderInfo.serializationType` outside of synchronization. + Reporting because a superclass `class com.alipay.sofa.rpc.client.Cluster` is annotated `@ThreadSafe`, so we assume that this method can run in parallel with other non-private methods in the class (including itself). + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void AbstractCluster.updateProviders(ProviderGroup) + +### Procedure Id: +com.alipay.sofa.rpc.client.AbstractCluster.updateProviders(com.alipay.sofa.rpc.client.ProviderGroup).73cd86b43c8f6f580706c13ff0ba0685 + +### File: +core-impl/client/src/main/java/com/alipay/sofa/rpc/client/AbstractCluster.java + +### Key: +AbstractCluster.java|updateProviders|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +ab7376b5e822d4fe20ffdfa49083c963 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9281/instruction.md b/inferredbugs-9281/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fad317c8f38a46a5934b677ddb1f59665c826c9f --- /dev/null +++ b/inferredbugs-9281/instruction.md @@ -0,0 +1,308 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sofa-rpc +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alipay.sofa.rpc.server.rest; + +import com.alipay.sofa.rpc.common.utils.CommonUtils; +import com.alipay.sofa.rpc.config.JAXRSProviderManager; +import com.alipay.sofa.rpc.config.ProviderConfig; +import com.alipay.sofa.rpc.config.ServerConfig; +import com.alipay.sofa.rpc.core.exception.SofaRpcRuntimeException; +import com.alipay.sofa.rpc.ext.Extension; +import com.alipay.sofa.rpc.invoke.Invoker; +import com.alipay.sofa.rpc.log.Logger; +import com.alipay.sofa.rpc.log.LoggerFactory; +import com.alipay.sofa.rpc.server.Server; +import org.jboss.resteasy.spi.PropertyInjector; +import org.jboss.resteasy.spi.ResteasyDeployment; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Rest server base on resteasy. + * + * @author GengZhang + */ +@Extension("rest") +public class RestServer implements Server { + + /** + * Logger + */ + private static final Logger LOGGER = LoggerFactory.getLogger(RestServer.class); + + /** + * 是否已经启动 + */ + protected volatile boolean started; + + /** + * Bolt服务端 + */ + protected SofaNettyJaxrsServer httpServer; + + /** + * 服务端配置 + */ + protected ServerConfig serverConfig; + + /** + * invoker数量 + */ + protected AtomicInteger invokerCnt = new AtomicInteger(); + + @Override + public void init(ServerConfig serverConfig) { + this.serverConfig = serverConfig; + } + + private SofaNettyJaxrsServer buildServer() { + // 生成Server对象 + SofaNettyJaxrsServer httpServer = new SofaNettyJaxrsServer(serverConfig); + + int bossThreads = serverConfig.getIoThreads(); + if (bossThreads > 0) { + httpServer.setIoWorkerCount(bossThreads); // 其实是boss+worker线程 默认cpu*2 + } + httpServer.setExecutorThreadCount(serverConfig.getMaxThreads()); // 业务线程 + httpServer.setMaxRequestSize(serverConfig.getPayload()); + httpServer.setHostname(serverConfig.getBoundHost()); + httpServer.setPort(serverConfig.getPort()); + + ResteasyDeployment resteasyDeployment = httpServer.getDeployment(); + resteasyDeployment.start(); + + ResteasyProviderFactory providerFactory = resteasyDeployment.getProviderFactory(); + registerProvider(providerFactory); + + return httpServer; + } + + private void registerProvider(ResteasyProviderFactory providerFactory) { + // 注册内置 + Set internalProviderClasses = JAXRSProviderManager.getInternalProviderClasses(); + if (CommonUtils.isNotEmpty(internalProviderClasses)) { + for (Class providerClass : internalProviderClasses) { + providerFactory.register(providerClass); + } + } + // 注册自定义 + Set customProviderInstances = JAXRSProviderManager.getCustomProviderInstances(); + if (CommonUtils.isNotEmpty(customProviderInstances)) { + for (Object provider : customProviderInstances) { + PropertyInjector propertyInjector = providerFactory.getInjectorFactory() + .createPropertyInjector( + JAXRSProviderManager.getTargetClass(provider), providerFactory); + propertyInjector.inject(provider); + providerFactory.registerProviderInstance(provider); + } + } + + if (LOGGER.isDebugEnabled()) { + Set pcs = providerFactory.getProviderClasses(); + StringBuilder sb = new StringBuilder(); + sb.append("\ndefault-providers:\n"); + + for (Object provider : pcs) { + sb.append(" ").append(provider).append("\n"); + } + LOGGER.debug(sb.toString()); + } + } + + @Override + public void start() { + if (started) { + return; + } + synchronized (this) { + if (started) { + return; + } + // 绑定到端口 + try { + httpServer = buildServer(); + httpServer.start(); + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Start the http rest server at port {}", serverConfig.getPort()); + } + } catch (Exception e) { + throw new SofaRpcRuntimeException( + "Failed to start jetty server at port " + serverConfig.getPort() + ", cause: " + e.getMessage(), e); + } + started = true; + } + } + + @Override + public boolean isStarted() { + return started; + } + + @Override + public boolean hasNoEntry() { + return false; + } + + @Override + public void stop() { + if (!started) { + return; + } + try { + // 关闭端口,不关闭线程池 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort()); + } + httpServer.stop(); + httpServer = null; + } catch (Exception e) { + LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e); + } + started = false; + } + + @Override + public void registerProcessor(ProviderConfig providerConfig, Invoker instance) { + if (!isStarted()) { + start(); + } + // 在httpserver中注册此jaxrs服务 + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Register jaxrs service to base url http://" + serverConfig.getHost() + ":" + + serverConfig.getPort() + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .addResourceFactory(new SofaResourceFactory(providerConfig), serverConfig.getContextPath()); + + invokerCnt.incrementAndGet(); + } catch (Exception e) { + LOGGER.error("Register jaxrs service error", e); + } + } + + @Override + public void unRegisterProcessor(ProviderConfig providerConfig, boolean closeIfNoEntry) { + if (!isStarted()) { + return; + } + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Unregister jaxrs service to port {} and base path is {}", serverConfig.getPort(), + serverConfig.getContextPath()); + } + try { + httpServer.getDeployment().getRegistry() + .removeRegistrations(providerConfig.getRef().getClass(), serverConfig.getContextPath()); + invokerCnt.decrementAndGet(); + } catch (Exception e) { + LOGGER.error("Unregister jaxrs service error", e); + } + // 如果最后一个需要关闭,则关闭 + if (closeIfNoEntry && invokerCnt.get() == 0) { + stop(); + } + } + + @Override + public void destroy() { + stop(); + } + + @Override + public void destroy(DestroyHook hook) { + hook.preDestroy(); + destroy(); + hook.postDestroy(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.alipay.sofa.rpc.server.rest.RestServer.stop` reads without synchronization from `this.com.alipay.sofa.rpc.server.rest.RestServer.httpServer`. Potentially races with write in method `RestServer.start()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RestServer.stop() + +### Procedure Id: +com.alipay.sofa.rpc.server.rest.RestServer.stop():void.59af57e6e49148ca6857406346f94b27 + +### File: +extension-impl/remoting-resteasy/src/main/java/com/alipay/sofa/rpc/server/rest/RestServer.java + +### Key: +RestServer.java|stop|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +546f2346ff3e26df7cccd168bfa9ae4f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9287/instruction.md b/inferredbugs-9287/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..da06581383a529024e07fc04feed7ff9caa5916f --- /dev/null +++ b/inferredbugs-9287/instruction.md @@ -0,0 +1,3102 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javacpp +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2013,2014 Samuel Audet + * + * This file is part of JavaCPP. + * + * JavaCPP is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version (subject to the "Classpath" exception + * as provided in the LICENSE.txt file that accompanied this code). + * + * JavaCPP is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with JavaCPP. If not, see . + */ + +package com.googlecode.javacpp; + +import java.io.BufferedReader; +import java.io.Closeable; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.ListIterator; +import java.util.Map; +import java.util.Properties; +import java.util.Scanner; + +/** + * To do: + * - Inherit constructors from helper classes, if possible + * - etc. + * + * @author Samuel Audet + */ +public class Parser { + + public static class Exception extends java.lang.Exception { + public Exception(String message) { super(message); } + public Exception(String message, Throwable cause) { super(message, cause); } + } + + public static class Info { + public Info() { } + public Info(String ... cppNames) { this.cppNames = cppNames; } + public Info(Info i) { + cppNames = i.cppNames != null ? i.cppNames.clone() : null; + javaNames = i.javaNames != null ? i.javaNames.clone() : null; + annotations = i.annotations != null ? i.annotations.clone() : null; + cppTypes = i.cppTypes != null ? i.cppTypes.clone() : null; + valueTypes = i.valueTypes != null ? i.valueTypes.clone() : null; + pointerTypes = i.pointerTypes != null ? i.pointerTypes.clone() : null; + cast = i.cast; + define = i.define; + translate = i.translate; + skip = i.skip; + base = i.base; + cppText = i.cppText; + javaText = i.javaText; + } + + String[] cppNames = null, javaNames = null, annotations = null, + cppTypes = null, valueTypes = null, pointerTypes = null; + boolean cast = false, define = false, translate = false, skip = false; + String base = null, cppText = null, javaText = null; + + public Info cppNames(String ... cppNames) { this.cppNames = cppNames; return this; } + public Info javaNames(String ... javaNames) { this.javaNames = javaNames; return this; } + public Info annotations(String ... annotations) { this.annotations = annotations; return this; } + public Info cppTypes(String ... cppTypes) { this.cppTypes = cppTypes; return this; } + public Info valueTypes(String ... valueTypes) { this.valueTypes = valueTypes; return this; } + public Info pointerTypes(String ... pointerTypes) { this.pointerTypes = pointerTypes; return this; } + public Info cast(boolean cast) { this.cast = cast; return this; } + public Info define(boolean define) { this.define = define; return this; } + public Info translate(boolean translate) { this.translate = translate; return this; } + public Info skip(boolean skip) { this.skip = skip; return this; } + public Info base(String base) { this.base = base; return this; } + public Info cppText(String cppText) { this.cppText = cppText; return this; } + public Info javaText(String javaText) { this.javaText = javaText; return this; } + } + + public static class InfoMap extends HashMap> { + public InfoMap() { this.parent = defaults; } + public InfoMap(InfoMap parent) { this.parent = parent; } + + InfoMap parent = null; + static final String[] containers = { "std::deque", "std::list", "std::map", "std::queue", "std::set", "std::stack", "std::vector", "std::valarray" }; + static final String[] simpleTypes = { "signed", "unsigned", "char", "short", "int", "long", "bool", "float", "double" }; + static { Arrays.sort(simpleTypes); } + static final InfoMap defaults = new InfoMap(null) + .put(new Info("void").valueTypes("void").pointerTypes("Pointer")) + .put(new Info("va_list", "FILE", "std::exception", "std::istream", "std::ostream", "std::iostream", + "std::ifstream", "std::ofstream", "std::fstream").cast(true).pointerTypes("Pointer")) + + .put(new Info("int8_t", "jbyte", "signed char") + .valueTypes("byte").pointerTypes("BytePointer", "ByteBuffer", "byte[]")) + .put(new Info("uint8_t", "char", "unsigned char").cast(true) + .valueTypes("byte").pointerTypes("BytePointer", "ByteBuffer", "byte[]")) + + .put(new Info("int16_t", "jshort", "short", "signed short", "short int", "signed short int") + .valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]")) + .put(new Info("uint16_t", "unsigned short", "unsigned short int").cast(true) + .valueTypes("short").pointerTypes("ShortPointer", "ShortBuffer", "short[]")) + + .put(new Info("int32_t", "jint", "int", "signed int", "signed") + .valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]")) + .put(new Info("uint32_t", "unsigned int", "unsigned").cast(true) + .valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]")) + + .put(new Info("int64_t", "__int64", "jlong", "long long", "signed long long", "long long int", "signed long long int") + .valueTypes("long").pointerTypes("LongPointer", "LongBuffer", "long[]")) + .put(new Info("uint64_t", "__uint64", "unsigned long long", "unsigned long long int").cast(true) + .valueTypes("long").pointerTypes("LongPointer", "LongBuffer", "long[]")) + + .put(new Info("long", "signed long", "long int", "signed long int") + .valueTypes("long").pointerTypes("CLongPointer")) + .put(new Info("unsigned long", "unsigned long int").cast(true) + .valueTypes("long").pointerTypes("CLongPointer")) + + .put(new Info("size_t", "ptrdiff_t").cast(true).valueTypes("long").pointerTypes("SizeTPointer")) + .put(new Info("float", "jfloat").valueTypes("float").pointerTypes("FloatPointer", "FloatBuffer", "float[]")) + .put(new Info("double", "jdouble").valueTypes("double").pointerTypes("DoublePointer", "DoubleBuffer", "double[]")) + .put(new Info("std::complex").cast(true).pointerTypes("FloatPointer", "FloatBuffer", "float[]")) + .put(new Info("std::complex").cast(true).pointerTypes("DoublePointer", "DoubleBuffer", "double[]")) + .put(new Info("bool", "jboolean").cast(true).valueTypes("boolean").pointerTypes("BoolPointer")) + .put(new Info("wchar_t", "WCHAR").cast(true).valueTypes("char").pointerTypes("CharPointer")) + .put(new Info("const char").valueTypes("byte").pointerTypes("@Cast(\"const char*\") BytePointer", "String")) + .put(new Info("std::string").annotations("@StdString").valueTypes("BytePointer", "String")) + .put(new Info("std::vector").annotations("@StdVector")) + + .put(new Info("operator->").javaNames("access")) + .put(new Info("operator()").javaNames("apply")) + .put(new Info("operator[]").javaNames("get")) + .put(new Info("operator=").javaNames("put")) + .put(new Info("operator+").javaNames("add")) + .put(new Info("operator-").javaNames("subtract")) + .put(new Info("operator*").javaNames("multiply")) + .put(new Info("operator/").javaNames("divide")) + .put(new Info("operator%").javaNames("mod")) + .put(new Info("operator++").javaNames("increment")) + .put(new Info("operator--").javaNames("decrement")) + .put(new Info("operator==").javaNames("equals")) + .put(new Info("operator!=").javaNames("notEquals")) + .put(new Info("operator<").javaNames("lessThan")) + .put(new Info("operator>").javaNames("greaterThan")) + .put(new Info("operator<=").javaNames("lessThanEquals")) + .put(new Info("operator>=").javaNames("greaterThanEquals")) + .put(new Info("operator!").javaNames("not")) + .put(new Info("operator&&").javaNames("and")) + .put(new Info("operator||").javaNames("or")) + .put(new Info("operator&").javaNames("and")) + .put(new Info("operator|").javaNames("or")) + .put(new Info("operator^").javaNames("xor")) + .put(new Info("operator~").javaNames("not")) + .put(new Info("operator<<").javaNames("shiftLeft")) + .put(new Info("operator>>").javaNames("shiftRight")) + .put(new Info("operator+=").javaNames("addPut")) + .put(new Info("operator-=").javaNames("subtractPut")) + .put(new Info("operator*=").javaNames("multiplyPut")) + .put(new Info("operator/=").javaNames("dividePut")) + .put(new Info("operator%=").javaNames("modPut")) + .put(new Info("operator&=").javaNames("andPut")) + .put(new Info("operator|=").javaNames("orPut")) + .put(new Info("operator^=").javaNames("xorPut")) + .put(new Info("operator<<=").javaNames("shiftLeftPut")) + .put(new Info("operator>>=").javaNames("shiftRightPut")) + + .put(new Info("allocate").javaNames("_allocate")) + .put(new Info("deallocate").javaNames("_deallocate")) + .put(new Info("position").javaNames("_position")) + .put(new Info("limit").javaNames("_limit")) + .put(new Info("capacity").javaNames("_capacity")); + + static String normalize(String name, boolean unconst, boolean untemplate) { + if (name == null || name.length() == 0) { + return name; + } + boolean foundConst = false, simpleType = true; + Token[] tokens = new Tokenizer(name).tokenize(); + int n = tokens.length; + for (int i = 0; i < n; i++) { + if (tokens[i].match(Token.CONST)) { + foundConst = true; + for (int j = i + 1; j < n; j++) { + tokens[j - 1] = tokens[j]; + } + i--; n--; + } else if (Arrays.binarySearch(simpleTypes, tokens[i].value) < 0) { + simpleType = false; + break; + } + } + if (simpleType) { + Arrays.sort(tokens, 0, n); + name = (foundConst ? "const " : "") + tokens[0].value; + for (int i = 1; i < n; i++) { + name += " " + tokens[i].value; + } + } else if (untemplate) { + int count = 0, template = -1; + for (int i = 0; i < n; i++) { + if (tokens[i].match('<')) { + if (count == 0) { + template = i; + } + count++; + } else if (tokens[i].match('>')) { + count--; + if (count == 0 && i + 1 != n) { + template = -1; + } + } + } + if (template >= 0) { + name = foundConst ? "const " : ""; + for (int i = 0; i < template; i++) { + name += tokens[i].value; + } + } + } + if (unconst && foundConst) { + name = name.substring(name.indexOf("const") + 5); + } + return name.trim(); + } + + public LinkedList get(String cppName) { + return get(cppName, true); + } + public LinkedList get(String cppName, boolean partial) { + String key = normalize(cppName, false, false); + LinkedList infoList = super.get(key); + if (infoList == null) { + key = normalize(cppName, true, false); + infoList = super.get(key); + } + if (infoList == null && partial) { + key = normalize(cppName, true, true); + infoList = super.get(key); + } + if (infoList == null) { + infoList = new LinkedList(); + } + if (parent != null) { + LinkedList l = parent.get(cppName, partial); + if (l != null && l.size() > 0) { + infoList = new LinkedList(infoList); + infoList.addAll(l); + } + } + return infoList; + } + + public Info get(int index, String cppName) { + return get(index, cppName, true); + } + public Info get(int index, String cppName, boolean partial) { + LinkedList infoList = get(cppName, partial); + return infoList.size() > 0 ? infoList.get(index) : null; + } + + public Info getFirst(String cppName) { + return getFirst(cppName, true); + } + public Info getFirst(String cppName, boolean partial) { + LinkedList infoList = get(cppName, partial); + return infoList.size() > 0 ? infoList.getFirst() : null; + } + + public InfoMap put(int index, Info info) { + for (String cppName : info.cppNames != null ? info.cppNames : new String[] { null }) { + String[] keys = { normalize(cppName, false, false), + normalize(cppName, false, true) }; + for (String key : keys) { + LinkedList infoList = super.get(key); + if (infoList == null) { + super.put(key, infoList = new LinkedList()); + } + if (!infoList.contains(info)) { + switch (index) { + case -1: infoList.add(info); break; + case 0: infoList.addFirst(info); break; + default: infoList.add(index, info); break; + } + } + } + } + return this; + } + + public InfoMap put(Info info) { + return put(-1, info); + } + + public InfoMap putFirst(Info info) { + return put(0, info); + } + } + + public static interface InfoMapper { + void map(InfoMap infoMap); + } + + static class Token implements Comparable { + Token() { } + Token(int type, String value) { this.type = type; this.value = value; } + Token(Token t) { + file = t.file; + lineNumber = t.lineNumber; + type = t.type; + spacing = t.spacing; + value = t.value; + } + + static final int + INTEGER = 1, + FLOAT = 2, + STRING = 3, + COMMENT = 4, + IDENTIFIER = 5, + SYMBOL = 6; + + static final Token + EOF = new Token(), + CONST = new Token(IDENTIFIER, "const"), + DEFINE = new Token(IDENTIFIER, "define"), + IF = new Token(IDENTIFIER, "if"), + IFDEF = new Token(IDENTIFIER, "ifdef"), + IFNDEF = new Token(IDENTIFIER, "ifndef"), + ELIF = new Token(IDENTIFIER, "elif"), + ELSE = new Token(IDENTIFIER, "else"), + ENDIF = new Token(IDENTIFIER, "endif"), + ENUM = new Token(IDENTIFIER, "enum"), + EXPLICIT = new Token(IDENTIFIER, "explicit"), + EXTERN = new Token(IDENTIFIER, "extern"), + FRIEND = new Token(IDENTIFIER, "friend"), + INLINE = new Token(IDENTIFIER, "inline"), + STATIC = new Token(IDENTIFIER, "static"), + CLASS = new Token(IDENTIFIER, "class"), + STRUCT = new Token(IDENTIFIER, "struct"), + UNION = new Token(IDENTIFIER, "union"), + TEMPLATE = new Token(IDENTIFIER, "template"), + TYPEDEF = new Token(IDENTIFIER, "typedef"), + TYPENAME = new Token(IDENTIFIER, "typename"), + USING = new Token(IDENTIFIER, "using"), + NAMESPACE = new Token(IDENTIFIER, "namespace"), + OPERATOR = new Token(IDENTIFIER, "operator"), + PRIVATE = new Token(IDENTIFIER, "private"), + PROTECTED = new Token(IDENTIFIER, "protected"), + PUBLIC = new Token(IDENTIFIER, "public"), + VIRTUAL = new Token(IDENTIFIER, "virtual"); + + File file = null; + int lineNumber = 0, type = -1; + String spacing = "", value = ""; + + boolean match(Object ... tokens) { + boolean found = false; + for (Object t : tokens) { + found = found || equals(t); + } + return found; + } + + Token expect(Object ... tokens) throws Exception { + if (!match(tokens)) { + throw new Exception(file + ":" + lineNumber + ": Unexpected token '" + toString() + "'"); + } + return this; + } + + boolean isEmpty() { + return type == -1 && spacing.isEmpty(); + } + + @Override public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj == null) { + return false; + } else if (obj.getClass() == Integer.class) { + return type == (Integer)obj; + } else if (obj.getClass() == Character.class) { + return type == (Character)obj; + } else if (obj.getClass() == String.class) { + return obj.equals(value); + } else if (obj.getClass() == getClass()) { + Token other = (Token)obj; + return type == other.type && ((value == null && other.value == null) || + value != null && value.equals(other.value)); + } else { + return false; + } + } + + @Override public int hashCode() { + return type; + } + + @Override public String toString() { + return value != null && value.length() > 0 ? value : String.valueOf((char)type); + } + + public int compareTo(Token t) { + return toString().compareTo(t.toString()); + } + } + + static class Tokenizer implements Closeable { + Tokenizer(Reader reader) { + this.reader = reader; + } + Tokenizer(String string) { + this.reader = new StringReader(string); + } + Tokenizer(File file) throws FileNotFoundException { + this.file = file; + this.reader = new BufferedReader(new FileReader(file)); + } + + File file = null; + Reader reader = null; + String lineSeparator = null; + int lastChar = -1, lineNumber = 1; + StringBuilder buffer = new StringBuilder(); + + public void close() throws IOException { + reader.close(); + } + + int readChar() throws IOException { + if (lastChar != -1) { + int c = lastChar; + lastChar = -1; + return c; + } + int c = reader.read(); + if (c == '\r' || c == '\n') { + lineNumber++; + int c2 = c == '\r' ? reader.read() : -1; + if (lineSeparator == null) { + lineSeparator = c == '\r' && c2 == '\n' ? "\r\n" : + c == '\r' ? "\r" : "\n"; + } + if (c2 != '\n') { + lastChar = c2; + } + c = '\n'; + } + return c; + } + + public Token nextToken() throws IOException { + Token token = new Token(); + int c = readChar(); + + buffer.setLength(0); + if (Character.isWhitespace(c)) { + buffer.append((char)c); + while ((c = readChar()) != -1 && Character.isWhitespace(c)) { + buffer.append((char)c); + } + } + token.file = file; + token.lineNumber = lineNumber; + token.spacing = buffer.toString(); + + buffer.setLength(0); + if (Character.isLetter(c) || c == '_') { + token.type = Token.IDENTIFIER; + buffer.append((char)c); + while ((c = readChar()) != -1 && (Character.isDigit(c) || Character.isLetter(c) || c == '_')) { + buffer.append((char)c); + } + token.value = buffer.toString(); + lastChar = c; + } else if (Character.isDigit(c) || c == '.' || c == '-' || c == '+') { + token.type = c == '.' ? Token.FLOAT : Token.INTEGER; + buffer.append((char)c); + int prevc = 0; + boolean large = false, unsigned = false, hex = false; + while ((c = readChar()) != -1 && (Character.isDigit(c) || c == '.' || c == '-' || c == '+' || + (c >= 'a' && c <= 'f') || c == 'l' || c == 'u' || c == 'x' || + (c >= 'A' && c <= 'F') || c == 'L' || c == 'U' || c == 'X')) { + switch (c) { + case '.': token.type = Token.FLOAT; break; + case 'l': case 'L': large = true; break; + case 'u': case 'U': unsigned = true; break; + case 'x': case 'X': hex = true; break; + } + if (c != 'l' && c != 'L' && c != 'u' && c != 'U') { + buffer.append((char)c); + } + prevc = c; + } + if (!hex && (prevc == 'f' || prevc == 'F')) { + token.type = Token.FLOAT; + } + if (token.type == Token.INTEGER && (large || (unsigned && !hex))) { + buffer.append('L'); + } + token.value = buffer.toString(); + lastChar = c; + } else if (c == '"') { + token.type = Token.STRING; + buffer.append('"'); + int prevc = 0; + while ((c = readChar()) != -1 && (prevc == '\\' || c != '"')) { + buffer.append((char)c); + prevc = c; + } + buffer.append('"'); + token.value = buffer.toString(); + } else if (c == '/') { + c = readChar(); + if (c == '/') { + token.type = Token.COMMENT; + buffer.append('/').append('/'); + int prevc = 0; + while ((c = readChar()) != -1 && (prevc == '\\' || c != '\n')) { + buffer.append((char)c); + prevc = c; + } + token.value = buffer.toString(); + lastChar = c; + } else if (c == '*') { + token.type = Token.COMMENT; + buffer.append('/').append('*'); + int prevc = 0; + while ((c = readChar()) != -1 && (prevc != '*' || c != '/')) { + buffer.append((char)c); + prevc = c; + } + buffer.append('/'); + token.value = buffer.toString(); + } else { + lastChar = c; + token.type = '/'; + } + } else if (c == ':') { + int c2 = readChar(); + if (c2 == ':') { + token.type = Token.SYMBOL; + token.value = "::"; + } else { + token.type = c; + lastChar = c2; + } + } else { + if (c == '\\') { + int c2 = readChar(); + if (c2 == '\n') { + token.type = Token.COMMENT; + token.value = "\n"; + return token; + } else { + lastChar = c2; + } + } + token.type = c; + } + return token; + } + + Token[] tokenize() { + ArrayList tokens = new ArrayList(); + try { + Token token; + while (!(token = nextToken()).isEmpty()) { + tokens.add(token); + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } + return tokens.toArray(new Token[tokens.size()]); + } + } + + static class TokenIndexer { + TokenIndexer(InfoMap infoMap, Token[] array) { + this.infoMap = infoMap; + this.array = array; + } + + boolean raw = false; + InfoMap infoMap = null; + Token[] array = null; + int index = 0; + + void filter(int index) { + if (index + 1 < array.length && array[index].match('#') && + array[index + 1].match(Token.IF, Token.IFDEF, Token.IFNDEF)) { + ArrayList tokens = new ArrayList(); + for (int i = 0; i < index; i++) { + tokens.add(array[i]); + } + int count = 0; + Info info = null; + boolean define = true, defined = false; + while (index < array.length) { + Token keyword = null; + if (array[index].match('#')) { + if (count == 0 && array[index + 1].match(Token.IF, Token.IFDEF, Token.IFNDEF)) { + count++; + keyword = array[index + 1]; + } else if (count == 1 && array[index + 1].match(Token.ELIF, Token.ELSE, Token.ENDIF)) { + keyword = array[index + 1]; + } + } + if (keyword != null) { + tokens.add(array[index++]); + tokens.add(array[index++]); + if (keyword.match(Token.IF, Token.IFDEF, Token.IFNDEF, Token.ELIF)) { + String value = ""; + while (index < array.length) { + if (array[index].spacing.indexOf('\n') >= 0) { + break; + } + value += array[index].spacing + array[index]; + tokens.add(array[index++]); + } + define = info == null || !defined; + info = infoMap.getFirst(value); + if (info != null) { + define = keyword.match(Token.IFNDEF) ? !info.define : info.define; + } else try { + define = Integer.parseInt(value.trim()) != 0; + } catch (NumberFormatException e) { + /* default define */ + } + } else if (keyword.match(Token.ELSE)) { + define = info == null || !define; + } else if (keyword.match(Token.ENDIF)) { + count--; + if (count == 0) { + break; + } + } + } else if (define) { + tokens.add(array[index++]); + } else { + index++; + } + defined = define || defined; + } + while (index < array.length) { + tokens.add(array[index++]); + } + array = tokens.toArray(new Token[tokens.size()]); + } + } + + void expand(int index) { + if (index < array.length && infoMap.containsKey(array[index].value)) { + int startIndex = index; + Info info = infoMap.getFirst(array[index].value); + if (info != null && info.cppText != null) { + try { + Tokenizer tokenizer = new Tokenizer(info.cppText); + if (!tokenizer.nextToken().match('#') + || !tokenizer.nextToken().match(Token.DEFINE) + || !tokenizer.nextToken().match(info.cppNames[0]) + || !tokenizer.nextToken().match('(')) { + return; + } + ArrayList params = new ArrayList(); + Token token; + while (!(token = tokenizer.nextToken()).isEmpty()) { + if (token.match(Token.IDENTIFIER)) { + params.add(token.value); + } else if (token.match(')')) { + break; + } + } + if (params.size() > 0 && (index + 1 >= array.length + || !array[index + 1].match('('))) { + return; + } + ArrayList tokens = new ArrayList(); + for (int i = 0; i < index; i++) { + tokens.add(array[i]); + } + ArrayList[] args = new ArrayList[params.size()]; + int count = 0, count2 = 0; + for (index += 2; index < array.length; index++) { + token = array[index]; + if (count2 == 0 && token.match(')')) { + break; + } else if (count2 == 0 && token.match(',')) { + count++; + continue; + } else if (token.match('(','[','{')) { + count2++; + } else if (token.match(')',']','}')) { + count2--; + } + if (args[count] == null) { + args[count] = new ArrayList(); + } + args[count].add(token); + } + while (!(token = tokenizer.nextToken()).isEmpty()) { + boolean foundArg = false; + for (int i = 0; i < params.size(); i++) { + if (params.get(i).equals(token.value)) { + if (tokens.size() == startIndex) { + args[i].get(0).spacing = array[startIndex].spacing; + } + tokens.addAll(args[i]); + foundArg = true; + break; + } + } + if (!foundArg) { + if (tokens.size() == startIndex) { + token.spacing = array[startIndex].spacing; + } + tokens.add(token); + } + } + for (index += 1; index < array.length; index++) { + tokens.add(array[index]); + } + array = tokens.toArray(new Token[tokens.size()]); + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + } + } + + int preprocess(int index, int count) { + while (index < array.length) { + filter(index); + expand(index); + if (!array[index].match(Token.COMMENT) && --count < 0) { + break; + } + index++; + } + filter(index); + expand(index); + return index; + } + + Token get() { + return get(0); + } + Token get(int i) { + int k = raw ? index + i : preprocess(index, i); + return k < array.length ? array[k] : Token.EOF; + } + Token next() { + index = raw ? index + 1 : preprocess(index, 1); + return index < array.length ? array[index] : Token.EOF; + } + } + + static class Context { + Context() { + usingList = new LinkedList(); + } + Context(Context c) { + namespace = c.namespace; + group = c.group; + inaccessible = c.inaccessible; + variables = c.variables; + templateMap = c.templateMap; + usingList = c.usingList; + } + + String namespace = null; + Type group = null; + boolean inaccessible = false; + Declarator[] variables = null; + TemplateMap templateMap = null; + LinkedList usingList = null; + + String[] qualify(String cppName) { + if (cppName == null || cppName.length() == 0) { + return new String[0]; + } + ArrayList names = new ArrayList(); + String ns = namespace != null ? namespace : ""; + while (ns != null) { + String name = ns.length() > 0 ? ns + "::" + cppName : cppName; + TemplateMap map = templateMap; + while (map != null) { + if (name.equals(map.getName())) { + String args = ""; + char separator = '<'; + for (String s : map.values()) { + args += separator + s; + separator = ','; + } + args += args.endsWith(">") ? " >" : ">"; + names.add(name + args); + break; + } + map = map.parent; + } + names.add(name); + + ns = InfoMap.normalize(ns, false, true); + int i = ns.lastIndexOf("::"); + ns = i >= 0 ? ns.substring(0, i) : ns.length() > 0 ? "" : null; + } + for (String s : usingList) { + String prefix = InfoMap.normalize(cppName, false, true); + int i = s.lastIndexOf("::") + 2; + ns = s.substring(0, i); + String suffix = s.substring(i); + if (suffix.length() == 0 || prefix.equals(suffix)) { + names.add(ns + cppName); + } + } + return names.toArray(new String[names.size()]); + } + + String shorten(String javaName) { + if (group != null) { + int lastDot = 0; + String s1 = javaName, s2 = group.javaName + '.'; + for (int i = 0; i < s1.length() && i < s2.length(); i++) { + if (s1.charAt(i) != s2.charAt(i)) { + break; + } else if (s1.charAt(i) == '.') { + lastDot = i; + } + } + if (lastDot > 0) { + javaName = javaName.substring(lastDot + 1); + } + } + return javaName; + } + } + + + public Parser(Logger logger, Properties properties) { + this.logger = logger; + this.properties = properties; + } + Parser(Parser p, String text) { + this.logger = p.logger; + this.properties = p.properties; + this.infoMap = p.infoMap; + this.tokens = new TokenIndexer(infoMap, new Tokenizer(text).tokenize()); + } + + final Logger logger; + final Properties properties; + InfoMap infoMap = null, leafInfoMap = null; + TokenIndexer tokens = null; + + String translate(String text) { + int namespace = text.lastIndexOf("::"); + if (namespace >= 0) { + Info info2 = infoMap.getFirst(text.substring(0, namespace)); + text = text.substring(namespace + 2); + if (info2.pointerTypes != null) { + text = info2.pointerTypes[0] + "." + text; + } + } + return text; + } + + + void containers(Context context, DeclarationList declList) throws Exception { + for (String containerName : InfoMap.containers) { + LinkedList infoList = leafInfoMap.get(containerName); + for (Info info : infoList) { + Declaration decl = new Declaration(); + if (info == null || info.skip || !info.define) { + continue; + } + int dim = 1; + boolean resizable = true; + Type containerType = new Parser(this, info.cppNames[0]).type(context), + indexType, valueType, firstType = null, secondType = null; + if (containerType.arguments == null || containerType.arguments.length == 0) { + continue; + } else if (containerType.arguments.length > 1) { + resizable = false; + indexType = containerType.arguments[0]; + valueType = containerType.arguments[1]; + } else { + indexType = new Type(); + indexType.annotations = "@Cast(\"size_t\") "; + indexType.cppName = "size_t"; + indexType.javaName = "long"; + valueType = containerType.arguments[0]; + } + while (valueType.cppName.startsWith(containerName)) { + dim++; + valueType = valueType.arguments[0]; + } + if (valueType.cppName.startsWith("std::pair")) { + firstType = valueType.arguments[0]; + secondType = valueType.arguments[1]; + if (firstType.annotations == null || firstType.annotations.length() == 0) { + firstType.annotations = "@ByRef "; + } + if (secondType.annotations == null || secondType.annotations.length() == 0) { + secondType.annotations = "@ByRef "; + } + } + if (valueType.annotations == null || valueType.annotations.length() == 0) { + valueType.annotations = "@ByRef "; + } + String arrayBrackets = ""; + for (int i = 0; i < dim - 1; i++) { + arrayBrackets += "[]"; + } + decl.text += "\n" + + "@Name(\"" + containerType.cppName + "\") public static class " + containerType.javaName + " extends Pointer {\n" + + " static { Loader.load(); }\n" + + " public " + containerType.javaName + "(Pointer p) { super(p); }\n" + (!resizable || firstType != null || secondType != null ? "" + : " public " + containerType.javaName + "(" + valueType.javaName + arrayBrackets + " ... array) { this(array.length); put(array); }\n") + + " public " + containerType.javaName + "() { allocate(); }\n" + (!resizable ? "" + : " public " + containerType.javaName + "(long n) { allocate(n); }\n") + + " private native void allocate();\n" + (!resizable ? "\n" + : " private native void allocate(@Cast(\"size_t\") long n);\n\n"); + + for (int i = 0; i < dim; i++) { + String indexAnnotation = i > 0 ? ("@Index" + (i > 1 ? "(" + i + ") " : " " )) : ""; + String indices = ""; + String separator = ""; + for (int j = 0; j < i; j++) { + indices += separator + indexType.annotations + indexType.javaName + " " + (char)('i' + j); + separator = ", "; + } + + decl.text += " public native " + indexAnnotation + "long size(" + indices + ");\n" + (!resizable ? "" + : " public native " + indexAnnotation + "void resize(" + indices + separator + "@Cast(\"size_t\") long n);\n"); + } + + String params = ""; + String separator = ""; + for (int i = 0; i < dim; i++) { + params += separator + indexType.annotations + indexType.javaName + " " + (char)('i' + i); + separator = ", "; + } + + if (firstType != null && secondType != null) { + String indexAnnotation = "@Index" + (dim > 1 ? "(" + dim + ") " : " "); + decl.text += "\n" + + " " + indexAnnotation + "public native " + firstType.annotations + firstType.javaName + " first(" + params + ");" + + " public native " + containerType.javaName + " first(" + params + separator + firstType.javaName + " first);\n" + + " " + indexAnnotation + "public native " + secondType.annotations + secondType.javaName + " second(" + params + "); " + + " public native " + containerType.javaName + " second(" + params + separator + secondType.javaName + " second);\n"; + } else { + decl.text += "\n" + + " @Index public native " + valueType.annotations + valueType.javaName + " get(" + params + ");\n" + + " public native " + containerType.javaName + " put(" + params + separator + valueType.javaName + " value);\n"; + } + + if (resizable && firstType == null && secondType == null) { + decl.text += "\n" + + " public " + containerType.javaName + " put(" + valueType.javaName + arrayBrackets + " ... array) {\n"; + String indent = " "; + String indices = ""; + String args = ""; + separator = ""; + for (int i = 0; i < dim; i++) { + char c = (char)('i' + i); + decl.text += + indent + "if (size(" + args + ") != array" + indices + ".length) { resize(" + args + separator + "array" + indices + ".length); }\n" + + indent + "for (int " + c + " = 0; " + c + " < array" + indices + ".length; " + c + "++) {\n"; + indent += " "; + indices += "[" + c + "]"; + args += separator + c; + separator = ", "; + } + decl.text += indent + "put(" + args + separator + "array" + indices + ");\n"; + for (int i = 0; i < dim; i++) { + indent = indent.substring(4); + decl.text += indent + "}\n"; + } + decl.text += " return this;\n" + + " }\n"; + } + decl.text += "}\n"; + declList.add(decl); + } + } + } + + + static class TemplateMap extends LinkedHashMap { + TemplateMap(TemplateMap parent) { + this.parent = parent; + } + Type type = null; + Declarator declarator = null; + TemplateMap parent = null; + + String getName() { + return type != null ? type.cppName : declarator != null ? declarator.cppName : null; + } + + boolean full() { + for (String s : values()) { + if (s == null) { + return false; + } + } + return true; + } + + String get(String key) { + String value = super.get(key); + if (value == null && parent != null) { + return parent.get(key); + } else { + return value; + } + } + } + + TemplateMap template(Context context) throws Exception { + if (!tokens.get().match(Token.TEMPLATE)) { + return null; + } + TemplateMap map = new TemplateMap(context.templateMap); + + tokens.next().expect('<'); + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(Token.IDENTIFIER)) { + String key = tokens.next().expect(Token.IDENTIFIER).value; + map.put(key, map.get(key)); + token = tokens.next(); + } + if (!token.match(',', '>')) { + // ignore default argument + int count = 0; + for (token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (count == 0 && token.match(',', '>')) { + break; + } else if (token.match('<')) { + count++; + } else if (token.match('>')) { + count--; + } + } + } + if (token.expect(',', '>').match('>')) { + tokens.next(); + break; + } + } + return map; + } + + Type[] templateArguments(Context context) throws Exception { + if (!tokens.get().match('<')) { + return null; + } + ArrayList arguments = new ArrayList(); + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + Type type = type(context); + arguments.add(type); + token = tokens.get(); + if (!token.match(',', '>')) { + // may not actually be a type + int count = 0; + for (token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (count == 0 && token.match(',', '>')) { + break; + } else if (token.match('<')) { + count++; + } else if (token.match('>')) { + count--; + } + type.cppName += token; + } + if (type.cppName.endsWith("*")) { + type.javaName = "PointerPointer"; + type.annotations += "@Cast(\"" + type.cppName + "*\") "; + } + } + if (token.expect(',', '>').match('>')) { + break; + } + } + return arguments.toArray(new Type[arguments.size()]); + } + + + static class Type { + Type() { } + Type(String name) { cppName = javaName = name; } + + boolean anonymous = false, constValue = false, constructor = false, + destructor = false, operator = false, simple = false, staticMember = false; + String annotations = "", cppName = "", javaName = ""; + Type[] arguments = null; + Attribute[] attributes = null; + + @Override public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj == null) { + return false; + } else if (obj.getClass() == getClass()) { + Type other = (Type)obj; + return cppName.equals(other.cppName) && javaName.equals(other.javaName); + } else { + return false; + } + } + } + + Type type(Context context) throws Exception { + Type type = new Type(); + if (tokens.get().match(Token.OPERATOR)) { + type.operator = true; + tokens.next(); + } + ArrayList attributes = new ArrayList(); + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match("::")) { + type.cppName += token; + } else if (token.match('<')) { + type.arguments = templateArguments(context); + char separator = '<'; + for (Type t : type.arguments) { + type.cppName += separator; + Info info = infoMap.getFirst(t.cppName); + type.cppName += info != null && info.cppTypes != null ? info.cppTypes[0] : t.cppName; + separator = ','; + } + type.cppName += type.cppName.endsWith(">") ? " >" : ">"; + } else if (token.match(Token.CONST)) { + type.constValue = true; + } else if (token.match('~')) { + type.destructor = true; + } else if (token.match(Token.STATIC)) { + type.staticMember = true; + } else if (token.match(Token.OPERATOR)) { + break; + } else if (token.match(Token.ENUM, Token.EXPLICIT, Token.EXTERN, Token.INLINE, Token.CLASS, + Token.STRUCT, Token.UNION, Token.TYPEDEF, Token.TYPENAME, Token.USING, Token.VIRTUAL)) { + continue; + } else if (token.match((Object[])InfoMap.simpleTypes)) { + type.cppName += token.value + " "; + type.simple = true; + } else if (token.match(Token.IDENTIFIER)) { + int backIndex = tokens.index; + Attribute attr = attribute(); + if (attr != null && attr.annotation) { + tokens.index--; + type.annotations += attr.javaName; + attributes.add(attr); + } else { + tokens.index = backIndex; + if (type.cppName.length() == 0 || type.cppName.endsWith("::")) { + type.cppName += token.value; + } else { + Info info = infoMap.getFirst(tokens.get(1).value); + if ((info != null && info.annotations != null) || + !tokens.get(1).match('*', '&', Token.IDENTIFIER, Token.CONST)) { + // we probably reached a variable or function name identifier + break; + } + } + } + } else { + if (token.match('}')) { + type.anonymous = true; + tokens.next(); + } + break; + } + } + if (attributes.size() > 0) { + type.attributes = attributes.toArray(new Attribute[attributes.size()]); + } + type.cppName = type.cppName.trim(); + if ("...".equals(tokens.get().value)) { + tokens.next(); + return null; + } else if (type.operator) { + for (Token token = tokens.get(); !token.match(Token.EOF, '('); token = tokens.next()) { + type.cppName += token; + } + } + boolean pointer = type.cppName.endsWith("*"); + boolean reference = type.cppName.endsWith("&"); + if (pointer || reference) { + type.cppName = type.cppName.substring(0, type.cppName.length() - 1); + } + if (context.templateMap != null && context.templateMap.get(type.cppName) != null) { + type.cppName = context.templateMap.get(type.cppName); + } + int namespace = type.cppName.lastIndexOf("::"); + int template = type.cppName.indexOf('<'); + type.javaName = namespace >= 0 && template < 0 ? type.cppName.substring(namespace + 2) : type.cppName; + Info info = null; + for (String name : context.qualify(type.cppName)) { + if ((info = infoMap.getFirst(name, false)) != null) { + type.cppName = name; + break; + } else if (infoMap.getFirst(name) != null) { + type.cppName = name; + } + } + boolean valueType = false; + if (info != null) { + if (!pointer && !reference && info.valueTypes != null && info.valueTypes.length > 0) { + type.javaName = info.valueTypes[0]; + valueType = true; + } else if (info.pointerTypes != null && info.pointerTypes.length > 0) { + type.javaName = info.pointerTypes[0]; + } + } + if (type.operator) { + if (type.constValue) { + type.annotations += "@Const "; + } + if (!valueType && !pointer && !reference) { + type.annotations += "@ByVal "; + } else if (!valueType && !pointer && reference) { + type.annotations += "@ByRef "; + } + type.annotations += "@Name(\"operator " + (type.constValue ? "const " : "") + + type.cppName + (pointer ? "*" : reference ? "&" : "") + "\") "; + } + if (info != null && info.annotations != null) { + for (String s : info.annotations) { + type.annotations += s + " "; + } + } + if (context.group != null && type.javaName.length() > 0) { + if (type.cppName.equals(context.group.cppName)) { + type.constructor = !type.destructor && !type.operator && tokens.get().match('('); + } + type.javaName = context.shorten(type.javaName); + } + return type; + } + + static class Declarator { + Type type = null; + Parameters parameters = null; + Declaration definition = null; + int infoNumber = 0, indices = 0; + boolean constPointer = false; + String cppName = "", javaName = "", signature = ""; + } + + Declarator declarator(Context context, String defaultName, int infoNumber, boolean useDefaults, + int varNumber, boolean arrayAsPointer, boolean pointerAsArray) throws Exception { + boolean typedef = tokens.get().match(Token.TYPEDEF); + boolean using = tokens.get().match(Token.USING); + Declarator dcl = new Declarator(); + Type type = type(context); + if (type == null) { + return null; + } + Attribute attr = null; + if (type.attributes != null) { + for (Attribute a : type.attributes) { + if (a.arguments.length() > 0 && Character.isJavaIdentifierStart(a.arguments.charAt(0))) { + attr = a; + for (char c : a.arguments.toCharArray()) { + if (!Character.isJavaIdentifierPart(c)) { + attr = null; + break; + } + } + } + if (attr != null) { + break; + } + } + } + + int count = 0; + for (Token token = tokens.get(); varNumber > 0 && !token.match(Token.EOF); token = tokens.next()) { + if (token.match('(','[','{')) { + count++; + } else if (token.match(')',']','}')) { + count--; + } else if (count > 0) { + continue; + } else if (token.match(',')) { + varNumber--; + } else if (token.match(';')) { + tokens.next(); + return null; + } + } + + String cast = type.cppName; + int indirections = 0; + boolean reference = false; + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match('*')) { + indirections++; + } else if (token.match('&')) { + reference = true; + } else if (token.match(Token.CONST)) { + dcl.constPointer = true; + } else { + break; + } + cast += token; + } + if (indirections == 0 && reference) { + cast = cast.replace('&', '*'); + } + + int dims[] = new int[256]; + int indirections2 = 0; + dcl.cppName = ""; + Info groupInfo = null; + Declaration definition = new Declaration(); + boolean operator = false; + if (tokens.get().match('(')) { + // probably a function pointer declaration + while (tokens.get().match('(')) { + tokens.next(); + } + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(Token.IDENTIFIER, "::")) { + dcl.cppName += token; + } else if (token.match('*')) { + indirections2++; + if (dcl.cppName.endsWith("::")) { + dcl.cppName = dcl.cppName.substring(0, dcl.cppName.length() - 2); + for (String name : context.qualify(dcl.cppName)) { + if ((groupInfo = infoMap.getFirst(name, false)) != null) { + dcl.cppName = name; + break; + } else if (infoMap.getFirst(name) != null) { + dcl.cppName = name; + } + } + definition.text += "@Namespace(\"" + dcl.cppName + "\") "; + } else if (dcl.cppName.length() > 0) { + definition.text += "@Convention(\"" + dcl.cppName + "\") "; + } + dcl.cppName = ""; + } else if (token.match('[')) { + Token n = tokens.get(1); + dims[dcl.indices++] = n.match(Token.INTEGER) ? Integer.parseInt(n.value) : -1; + } else if (token.match(')')) { + tokens.next(); + break; + } + } + while (tokens.get().match(')')) { + tokens.next(); + } + } else if (tokens.get().match(Token.IDENTIFIER)) { + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match("::")) { + dcl.cppName += token; + } else if (token.match(Token.OPERATOR)) { + operator = true; + dcl.cppName += "operator" + tokens.next(); + for (token = tokens.next(); !token.match(Token.EOF, '('); token = tokens.next()) { + dcl.cppName += token; + } + break; + } else if (token.match('<')) { + // template argument + dcl.cppName += token; + int count2 = 0; + for (token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + dcl.cppName += token; + if (count2 == 0 && token.match(',', '>')) { + break; + } else if (token.match('<')) { + count2++; + } else if (token.match('>')) { + count2--; + } + } + } else if (token.match(Token.IDENTIFIER) && + (dcl.cppName.length() == 0 || dcl.cppName.endsWith("::"))) { + dcl.cppName += token; + } else { + break; + } + } + } + if (dcl.cppName.length() == 0) { + dcl.cppName = defaultName; + } + + boolean bracket = false; + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (!bracket && token.match('[')) { + bracket = true; + Token n = tokens.get(1); + dims[dcl.indices++] = n.match(Token.INTEGER) ? Integer.parseInt(n.value) : -1; + } else if (!bracket) { + break; + } else if (bracket && token.match(']')) { + bracket = false; + } + } + while (dcl.indices > 0 && indirections2 > 0) { + // treat complex combinations of arrays and pointers as multidimensional arrays + dims[dcl.indices++] = -1; + indirections2--; + } + if (arrayAsPointer && dcl.indices > 0) { + // treat array as an additional indirection + indirections++; + String dimCast = ""; + for (int i = 1; i < dcl.indices; i++) { + if (dims[i] > 0) { + dimCast += "[" + dims[i] + "]"; + } + } + //dcl.indices = 0; + cast += dimCast.length() > 0 ? "(*)" + dimCast : "*"; + } + if (pointerAsArray && indirections > (type.anonymous ? 0 : 1)) { + // treat second indirection as an array, unless anonymous + dims[dcl.indices++] = -1; + indirections--; + cast = cast.substring(0, cast.length() - 1); + } + + if (tokens.get().match(':')) { + // ignore bitfields + type.annotations += "@NoOffset "; + tokens.next().expect(Token.INTEGER); + tokens.next().expect(',', ';'); + } + + int infoLength = 1; + boolean valueType = false, needCast = arrayAsPointer && dcl.indices > 1, implicitConst = false; + String prefix = type.constValue && indirections < 2 && !reference ? "const " : ""; + Info info = infoMap.getFirst(prefix + type.cppName, false); + if (!typedef && (info == null || (info.cppTypes != null && info.cppTypes.length > 0))) { + // substitute template types that have no info with appropriate adapter annotation + Type type2 = type; + if (info != null) { + type2 = new Parser(this, info.cppTypes[0]).type(context); + } + LinkedList infoList = infoMap.get(type2.cppName); + for (Info info2 : infoList) { + if (type2.arguments != null && info2.annotations != null) { + indirections = 1; + reference = false; + type = type2.arguments[0]; + cast = type.cppName + "*"; + for (String s : info2.annotations) { + type.annotations += s + " "; + } + info = infoMap.getFirst(type.cppName, false); + break; + } + } + } + if (!using && info != null) { + valueType = info.valueTypes != null && ((type.constValue && reference) || + (indirections == 0 && !reference) || info.pointerTypes == null); + implicitConst = info.cppNames[0].startsWith("const "); + infoLength = valueType ? info.valueTypes.length : + info.pointerTypes != null ? info.pointerTypes.length : 1; + dcl.infoNumber = infoNumber < 0 ? 0 : infoNumber % infoLength; + type.javaName = valueType ? info.valueTypes[dcl.infoNumber] : + info.pointerTypes != null ? info.pointerTypes[dcl.infoNumber] : type.javaName; + type.javaName = context.shorten(type.javaName); + needCast |= info.cast && !type.cppName.equals(type.javaName); + } + + if (!valueType) { + if (indirections == 0 && !reference) { + type.annotations += "@ByVal "; + } else if (indirections == 0 && reference) { + type.annotations += "@ByRef "; + } else if (indirections == 1 && reference) { + type.annotations += "@ByPtrRef "; + } else if (indirections == 2 && !reference && infoNumber >= 0) { + type.annotations += "@ByPtrPtr "; + needCast |= type.cppName.equals("void"); + } else if (indirections >= 2) { + dcl.infoNumber += infoLength; + needCast = true; + type.javaName = "PointerPointer"; + if (reference) { + type.annotations += "@ByRef "; + } + } + + if (!needCast && type.constValue && !implicitConst) { + type.annotations = "@Const " + type.annotations; + } + } + if (needCast) { + if (type.constValue) { + cast = "const " + cast; + } + if (!valueType && indirections == 0 && !reference) { + type.annotations += "@Cast(\"" + cast + "*\") "; + } else { + type.annotations = "@Cast(\"" + cast + "\") " + type.annotations; + } + } + + dcl.javaName = attr != null ? attr.arguments : dcl.cppName; + for (String name : context.qualify(dcl.cppName)) { + if ((info = infoMap.getFirst(name, false)) != null) { + dcl.cppName = name; + break; + } else if (infoMap.getFirst(name) != null) { + dcl.cppName = name; + } + } + if (attr == null && defaultName == null && info != null && info.javaNames != null && info.javaNames.length > 0 + && (operator || !info.cppNames[0].contains("<") || (context.templateMap != null && context.templateMap.type == null))) { + dcl.javaName = info.javaNames[0]; + } + if (dcl.cppName != null) { + String localName = dcl.cppName; + if (localName.startsWith(context.namespace + "::")) { + localName = dcl.cppName.substring(context.namespace.length() + 2); + } + if (!localName.equals(dcl.javaName)) { + type.annotations += "@Name(\"" + localName + "\") "; + } + } + + dcl.signature = dcl.javaName; + dcl.parameters = parameters(context, infoNumber, useDefaults); + if (dcl.parameters != null) { + dcl.infoNumber = Math.max(dcl.infoNumber, dcl.parameters.infoNumber); + if (indirections2 == 0) { + dcl.signature += dcl.parameters.signature; + } else { + String functionType = Character.toUpperCase(dcl.javaName.charAt(0)) + dcl.javaName.substring(1); + if (typedef) { + functionType = dcl.javaName; + } else if (dcl.parameters.signature.length() > 0) { + functionType += dcl.parameters.signature; + } else if (!type.javaName.equals("void")) { + functionType = type.javaName + "_" + functionType; + } + definition.text += (tokens.get().match(Token.CONST) ? "@Const " : "") + + "public static class " + functionType + " extends FunctionPointer {\n" + + " static { Loader.load(); }\n" + + " public " + functionType + "(Pointer p) { super(p); }\n" + + (groupInfo != null ? "" : + " protected " + functionType + "() { allocate(); }\n" + + " private native void allocate();\n") + + " public native " + type.annotations + type.javaName + " call" + + (groupInfo != null ? "(" + groupInfo.pointerTypes[0] + " o" + (dcl.parameters.list.charAt(1) == ')' ? + ")" : ", " + dcl.parameters.list.substring(1)) : dcl.parameters.list) + ";\n" + + "}\n"; + definition.signature = functionType; + definition.declarator = new Declarator(); + definition.declarator.parameters = dcl.parameters; + dcl.definition = definition; + dcl.parameters = null; + type.annotations = ""; + type.javaName = functionType; + } + } + dcl.type = type; + return dcl; + } + + String commentBefore() throws Exception { + String comment = ""; + tokens.raw = true; + while (tokens.index > 0 && tokens.get(-1).match(Token.COMMENT)) { + tokens.index--; + } + boolean closeComment = false; + for (Token token = tokens.get(); token.match(Token.COMMENT); token = tokens.next()) { + String s = token.value; + if (s.startsWith("/**") || s.startsWith("/*!") || s.startsWith("///") || s.startsWith("//!")) { + if (s.charAt(3) == '<') { + continue; + } else if (s.startsWith("/// ") || s.startsWith("//!")) { + s = (comment.length() == 0 || comment.contains("*/") + || !comment.contains("/*") ? "/**" : " * ") + s.substring(3); + closeComment = true; + } else if (!s.startsWith("///")) { + s = "/**" + s.substring(3); + } + } + comment += token.spacing + s; + } + if (closeComment && !comment.endsWith("*/")) { + comment += " */"; + } + tokens.raw = false; + return comment; + } + + String commentAfter() throws Exception { + String comment = ""; + tokens.raw = true; + while (tokens.index > 0 && tokens.get(-1).match(Token.COMMENT)) { + tokens.index--; + } + boolean closeComment = false; + for (Token token = tokens.get(); token.match(Token.COMMENT); token = tokens.next()) { + String s = token.value; + if (s.startsWith("/**") || s.startsWith("/*!") || s.startsWith("///") || s.startsWith("//!")) { + if (s.charAt(3) != '<') { + continue; + } else if (s.startsWith("///") || s.startsWith("//!")) { + s = (comment.length() == 0 || comment.contains("*/") + || !comment.contains("/*") ? "/**" : " * ") + s.substring(4); + closeComment = true; + } else { + s = "/**" + s.substring(4); + } + comment += s; + } + } + if (closeComment && !comment.endsWith("*/")) { + comment += " */"; + } + if (comment.length() > 0) { + comment += "\n"; + } + tokens.raw = false; + return comment; + } + + + static class Attribute { + boolean annotation = false; + String cppName = "", javaName = "", arguments = ""; + } + + Attribute attribute() throws Exception { + if (!tokens.get().match(Token.IDENTIFIER)) { + return null; + } + Attribute attr = new Attribute(); + Info info = infoMap.getFirst(attr.cppName = tokens.get().value); + if (attr.annotation = info != null && info.annotations != null + && info.valueTypes == null && info.pointerTypes == null) { + for (String s : info.annotations) { + attr.javaName += s + " "; + } + } + if (!tokens.next().match('(')) { + return attr; + } + + int count = 1; + tokens.raw = true; + for (Token token = tokens.next(); !token.match(Token.EOF) && count > 0; token = tokens.next()) { + if (token.match('(')) { + count++; + } else if (token.match(')')) { + count--; + } else { + attr.arguments += token.value; + } + } + tokens.raw = false; + return attr; + } + + String body() throws Exception { + if (!tokens.get().match('{')) { + return null; + } + + int count = 1; + tokens.raw = true; + for (Token token = tokens.next(); !token.match(Token.EOF) && count > 0; token = tokens.next()) { + if (token.match('{')) { + count++; + } else if (token.match('}')) { + count--; + } + } + tokens.raw = false; + return ""; + } + + + static class Parameters { + Declarator[] declarators = null; + int infoNumber = 0; + String list = "", signature = "", names = ""; + } + + Parameters parameters(Context context, int infoNumber, boolean useDefaults) throws Exception { + if (!tokens.get().match('(')) { + return null; + } + + int count = 0; + Parameters params = new Parameters(); + ArrayList dcls = new ArrayList(); + params.list = "("; + params.names = "("; + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.get()) { + String spacing = token.spacing; + if (token.match(')')) { + params.list += spacing + ")"; + params.names += ")"; + tokens.next(); + break; + } + Declarator dcl = declarator(context, "arg" + count++, infoNumber, useDefaults, 0, true, false); + boolean hasDefault = !tokens.get().match(',', ')'); + if (dcl != null && !dcl.type.javaName.equals("void") && (!hasDefault || !useDefaults)) { + params.infoNumber = Math.max(params.infoNumber, dcl.infoNumber); + params.list += (count > 1 ? "," : "") + spacing + dcl.type.annotations + dcl.type.javaName + " " + dcl.javaName; + params.signature += '_'; + for (char c : dcl.type.javaName.substring(dcl.type.javaName.lastIndexOf(' ') + 1).toCharArray()) { + params.signature += Character.isJavaIdentifierPart(c) ? c : '_'; + } + params.names += (count > 1 ? ", " : "") + dcl.javaName; + if (dcl.javaName.startsWith("arg")) { + try { + count = Integer.parseInt(dcl.javaName.substring(3)) + 1; + } catch (NumberFormatException e) { /* don't care if not int */ } + } + } + if (!hasDefault || !useDefaults) { + dcls.add(dcl); + } + if (hasDefault) { + // output default argument as a comment + if (!useDefaults) { + params.list += "/*" + tokens.get(); + } + int count2 = 0; + for (token = tokens.next(), token.spacing = ""; !token.match(Token.EOF); token = tokens.next()) { + if (count2 == 0 && token.match(',', ')')) { + break; + } else if (token.match('(')) { + count2++; + } else if (token.match(')')) { + count2--; + } + if (!useDefaults) { + params.list += token.spacing + token; + } + } + if (!useDefaults) { + params.list += "*/"; + } + } + if (tokens.get().expect(',', ')').match(',')) { + tokens.next(); + } + } + params.declarators = dcls.toArray(new Declarator[dcls.size()]); + return params; + } + + boolean function(Context context, DeclarationList declList) throws Exception { + int backIndex = tokens.index; + String spacing = tokens.get().spacing; + String modifiers = "public native "; + Type type = type(context); + Parameters params = parameters(context, 0, false); + Declarator dcl = new Declarator(); + Declaration decl = new Declaration(); + if (type.javaName.length() == 0) { + // not a function, probably an attribute + tokens.index = backIndex; + return false; + } else if (context.group == null && params != null) { + // this is a constructor definition or specialization, skip over + if (tokens.get().match('{')) { + body(); + } else { + tokens.next(); + } + decl.text = spacing; + declList.add(decl); + return true; + } else if (type.constructor || type.destructor || type.operator) { + // this is a constructor, destructor, or cast operator + dcl.type = type; + dcl.parameters = params; + dcl.cppName = type.cppName; + dcl.javaName = type.javaName.substring(type.javaName.lastIndexOf(' ') + 1); + if (type.operator) { + dcl.cppName = "operator " + dcl.cppName; + dcl.javaName = "as" + Character.toUpperCase(dcl.javaName.charAt(0)) + dcl.javaName.substring(1); + } + dcl.signature = dcl.javaName + params.signature; + } else { + tokens.index = backIndex; + dcl = declarator(context, null, 0, false, 0, false, false); + type = dcl.type; + } + + int namespace = dcl.cppName.lastIndexOf("::"); + if (context.namespace != null && namespace < 0) { + dcl.cppName = context.namespace + "::" + dcl.cppName; + } + Info info = infoMap.getFirst(dcl.cppName); + String localName = dcl.cppName; + if (localName.startsWith(context.namespace + "::")) { + localName = dcl.cppName.substring(context.namespace.length() + 2); + } + if (type.javaName.length() == 0 || dcl.parameters == null) { + tokens.index = backIndex; + return false; + } else if ((context.group == null && localName.contains("::")) || (info != null && info.skip)) { + // this is a member function definition or specialization, skip over + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.get()) { + if (attribute() == null) { + break; + } + } + if (tokens.get().match('{')) { + body(); + } else { + tokens.next(); + } + decl.text = spacing; + declList.add(decl); + return true; + } else if (type.staticMember || context.group == null) { + modifiers = "public static native "; + } + + LinkedList prevDcl = new LinkedList(); + boolean first = true; + for (int n = -2; n < Integer.MAX_VALUE; n++) { + decl = new Declaration(); + tokens.index = backIndex; + if (type.constructor || type.destructor || type.operator) { + type = type(context); + params = parameters(context, n / 2, n % 2 != 0); + dcl = new Declarator(); + dcl.type = type; + dcl.parameters = params; + dcl.cppName = type.cppName; + dcl.javaName = type.javaName.substring(type.javaName.lastIndexOf(' ') + 1); + if (type.operator) { + dcl.cppName = "operator " + dcl.cppName; + dcl.javaName = "as" + Character.toUpperCase(dcl.javaName.charAt(0)) + dcl.javaName.substring(1); + } + dcl.signature = dcl.javaName + params.signature; + if (tokens.get().match(':')) { + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match('{', ';')) { + break; + } + } + } + } else { + dcl = declarator(context, null, n / 2, n % 2 != 0, 0, false, false); + type = dcl.type; + } + decl.declarator = dcl; + if (context.namespace != null && context.group == null) { + decl.text += "@Namespace(\"" + context.namespace + "\") "; + } + if (type.constructor) { + decl.text += "public " + dcl.javaName + dcl.parameters.list + " { allocate" + params.names + "; }\n" + + "private native void allocate" + dcl.parameters.list + ";\n"; + } else { + decl.text += modifiers + type.annotations + type.javaName + " " + dcl.javaName + dcl.parameters.list + ";\n"; + } + decl.signature = dcl.signature; + + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.get()) { + decl.constMember |= token.match(Token.CONST); + if (attribute() == null) { + break; + } + } + if (tokens.get().match('{')) { + body(); + } else { + if (tokens.get().match('=')) { + tokens.next().expect("0"); + tokens.next().expect(';'); + decl.abstractMember = true; + } + tokens.next(); + } + if (info != null && info.javaText != null) { + decl.text = info.javaText; + decl.declarator = null; + } + String comment = commentAfter(); + if (first) { + first = false; + declList.spacing = spacing; + decl.text = comment + decl.text; + } + + boolean found = false; + for (Declarator d : prevDcl) { + found |= dcl.signature.equals(d.signature); + } + if (dcl.javaName.length() > 0 && !found && !type.destructor) { + declList.add(decl); + } else if (found && n / 2 > 0 && n % 2 == 0) { + break; + } + prevDcl.add(dcl); + } + declList.spacing = null; + return true; + } + + boolean variable(Context context, DeclarationList declList) throws Exception { + int backIndex = tokens.index; + String spacing = tokens.get().spacing; + String modifiers = "public static native "; + String setterType = "void "; + Declarator dcl = declarator(context, null, 0, false, 0, false, true); + Declaration decl = new Declaration(); + String cppName = dcl.cppName; + String javaName = dcl.javaName; + if (javaName == null || !tokens.get().match('[', '=', ',', ':', ';')) { + tokens.index = backIndex; + return false; + } else if (!dcl.type.staticMember && context.group != null) { + modifiers = "public native "; + setterType = context.shorten(context.group.javaName) + " "; + } + + int namespace = cppName.lastIndexOf("::"); + if (context.namespace != null && namespace < 0) { + cppName = context.namespace + "::" + cppName; + } + Info info = infoMap.getFirst(cppName); + if (info != null && info.skip) { + decl.text = spacing; + declList.add(decl); + return true; + } + boolean first = true; + for (Declarator metadcl : context.variables != null ? context.variables : new Declarator[] { null }) { + for (int n = 0; n < Integer.MAX_VALUE; n++) { + decl = new Declaration(); + tokens.index = backIndex; + dcl = declarator(context, null, -1, false, n, false, true); + if (dcl == null) { + break; + } + decl.declarator = dcl; + javaName = dcl.javaName; + if (metadcl == null || metadcl.indices == 0 || dcl.indices == 0) { + // arrays are currently not supported for both metadcl and dcl at the same time + String indices = ""; + for (int i = 0; i < (metadcl == null || metadcl.indices == 0 ? dcl.indices : metadcl.indices); i++) { + if (i > 0) { + indices += ", "; + } + indices += "int " + (char)('i' + i); + } + if (context.namespace != null && context.group == null) { + decl.text += "@Namespace(\"" + context.namespace + "\") "; + } + if (metadcl != null && metadcl.cppName.length() > 0) { + decl.text += metadcl.indices == 0 + ? "@Name(\"" + metadcl.cppName + "." + dcl.cppName + "\") " + : "@Name({\"" + metadcl.cppName + "\", \"." + dcl.cppName + "\"}) "; + javaName = metadcl.javaName + "_" + dcl.javaName; + } + if (dcl.type.constValue) { + decl.text += "@MemberGetter "; + } + decl.text += modifiers + dcl.type.annotations.replace("@ByVal ", "@ByRef ") + + dcl.type.javaName + " " + javaName + "(" + indices + ");"; + if (!dcl.type.constValue) { + if (indices.length() > 0) { + indices += ", "; + } + decl.text += " " + modifiers + setterType + javaName + "(" + indices + dcl.type.javaName + " " + javaName + ");"; + } + decl.text += "\n"; + } + if (dcl.indices > 0) { + // in the case of arrays, also add a pointer accessor + tokens.index = backIndex; + dcl = declarator(context, null, -1, false, n, true, false); + String indices = ""; + for (int i = 0; i < (metadcl == null ? 0 : metadcl.indices); i++) { + if (i > 0) { + indices += ", "; + } + indices += "int " + (char)('i' + i); + } + if (context.namespace != null && context.group == null) { + decl.text += "@Namespace(\"" + context.namespace + "\") "; + } + if (metadcl != null && metadcl.cppName.length() > 0) { + decl.text += metadcl.indices == 0 + ? "@Name(\"" + metadcl.cppName + "." + dcl.cppName + "\") " + : "@Name({\"" + metadcl.cppName + "\", \"." + dcl.cppName + "\"}) "; + javaName = metadcl.javaName + "_" + dcl.javaName; + } + decl.text += "@MemberGetter " + modifiers + dcl.type.annotations.replace("@ByVal ", "@ByRef ") + + dcl.type.javaName + " " + javaName + "(" + indices + ");\n"; + } + decl.signature = dcl.signature; + if (info != null && info.javaText != null) { + decl.text = info.javaText; + decl.declarator = null; + } + while (!tokens.get().match(Token.EOF, ';')) { + tokens.next(); + } + tokens.next(); + String comment = commentAfter(); + if (first) { + first = false; + declList.spacing = spacing; + decl.text = comment + decl.text; + } + decl.variable = true; + declList.add(decl); + } + } + declList.spacing = null; + return true; + } + + boolean macro(Context context, DeclarationList declList) throws Exception { + int backIndex = tokens.index; + if (!tokens.get().match('#')) { + return false; + } + tokens.raw = true; + String spacing = tokens.get().spacing; + Token keyword = tokens.next(); + + tokens.next(); + int beginIndex = tokens.index; + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.spacing.indexOf('\n') >= 0) { + break; + } + } + int endIndex = tokens.index; + while (tokens.get(-1).match(Token.COMMENT)) { + tokens.index--; + } + int lastIndex = tokens.index; + + Declaration decl = new Declaration(); + if (keyword.match(Token.DEFINE) && beginIndex + 1 < endIndex) { + tokens.index = beginIndex; + String macroName = tokens.get().value; + Token first = tokens.next(); + boolean hasArgs = first.spacing.length() == 0 && first.match('('); + LinkedList infoList = infoMap.get(macroName); + for (Info info : infoList.size() > 0 ? infoList : Arrays.asList(new Info[] { null })) { + if (hasArgs && info == null) { + // save declaration for expansion + info = new Info(macroName).cppText(""); + tokens.index = backIndex; + for (Token token = tokens.get(); tokens.index < endIndex; token = tokens.next()) { + info.cppText += token.spacing + token; + } + infoMap.put(info); + } else if (info != null && info.cppText == null && + info.cppTypes != null && info.cppTypes.length > (hasArgs ? 0 : 1)) { + // declare as a static native method + LinkedList prevDcl = new LinkedList(); + for (int n = -1; n < Integer.MAX_VALUE; n++) { + int count = 1; + tokens.index = beginIndex + 2; + String params = "("; + for (Token token = tokens.get(); hasArgs && tokens.index < lastIndex + && count < info.cppTypes.length; token = tokens.next()) { + if (token.match(Token.IDENTIFIER)) { + String type = info.cppTypes[count]; + String name = token.value; + if (name.equals("...")) { + name = "arg" + count; + } + params += type + " " + name; + if (++count < info.cppTypes.length) { + params += ", "; + } + } else if (token.match(')')) { + break; + } + } + while (count < info.cppTypes.length) { + String type = info.cppTypes[count]; + String name = "arg" + count; + params += type + " " + name; + if (++count < info.cppTypes.length) { + params += ", "; + } + } + params += ")"; + + Declarator dcl = new Parser(this, info.cppTypes[0] + " " + macroName + params).declarator(context, null, n, false, 0, false, false); + for (int i = 0; i < info.cppNames.length; i++) { + if (macroName.equals(info.cppNames[i]) && info.javaNames != null) { + macroName = "@Name(\"" + info.cppNames[0] + "\") " + info.javaNames[i]; + break; + } + } + + boolean found = false; + for (Declarator d : prevDcl) { + found |= dcl.signature.equals(d.signature); + } + if (!found) { + decl.text += "public static native " + dcl.type.annotations + dcl.type.javaName + " " + macroName + dcl.parameters.list + ";\n"; + } else if (found && n > 0) { + break; + } + prevDcl.add(dcl); + } + } else if (info == null || (info.cppText == null && + (info.cppTypes == null || info.cppTypes.length == 1))) { + // declare as a static final variable + String value = ""; + String type = "int"; + String cat = ""; + tokens.index = beginIndex + 1; + Token prevToken = new Token(); + boolean translate = true; + for (Token token = tokens.get(); tokens.index < lastIndex; token = tokens.next()) { + if (token.match(Token.STRING)) { + type = "String"; cat = " + "; break; + } else if (token.match(Token.FLOAT)) { + type = "double"; cat = ""; break; + } else if (token.match(Token.INTEGER) && token.value.endsWith("L")) { + type = "long"; cat = ""; break; + } else if ((prevToken.match(Token.IDENTIFIER) && token.match('(')) || token.match('{', '}')) { + translate = false; + } + prevToken = token; + } + if (info != null) { + if (info.cppTypes != null) { + Declarator dcl = new Parser(this, info.cppTypes[0]).declarator(context, null, -1, false, 0, false, true); + type = dcl.type.annotations + dcl.type.javaName; + } + for (int i = 0; i < info.cppNames.length; i++) { + if (macroName.equals(info.cppNames[i]) && info.javaNames != null) { + macroName = "@Name(\"" + info.cppNames[0] + "\") " + info.javaNames[i]; + break; + } + } + translate = info.translate; + } + tokens.index = beginIndex + 1; + if (translate) { + for (Token token = tokens.get(); tokens.index < lastIndex; token = tokens.next()) { + value += token.spacing + token + (tokens.index + 1 < lastIndex ? cat : ""); + } + value = translate(value); + } else { + decl.text += "public static native @MemberGetter " + type + " " + macroName + "();\n"; + value = " " + macroName + "()"; + } + int i = type.lastIndexOf(' '); + if (i >= 0) { + type = type.substring(i + 1); + } + if (value.length() > 0) { + decl.text += "public static final " + type + " " + macroName + " =" + value + ";\n"; + } + } + } + } + + if (decl.text.length() == 0) { + // output whatever we did not process as comment + tokens.index = beginIndex; + int n = spacing.lastIndexOf('\n') + 1; + decl.text += "// " + spacing.substring(n) + "#" + keyword.spacing + keyword; + for (Token token = tokens.get(); tokens.index < lastIndex; token = tokens.next()) { + decl.text += token.match("\n") ? "\n// " : token.spacing + token; + } + spacing = spacing.substring(0, n); + } + if (decl.text.length() > 0) { + tokens.index = lastIndex; + String comment = commentAfter(); + decl.text = comment + decl.text; + } + tokens.raw = false; + declList.spacing = spacing; + declList.add(decl); + declList.spacing = null; + return true; + } + + boolean typedef(Context context, DeclarationList declList) throws Exception { + String spacing = tokens.get().spacing; + if (!tokens.get().match(Token.TYPEDEF)) { + return false; + } + Declaration decl = new Declaration(); + Declarator dcl = declarator(context, null, 0, false, 0, true, false); + tokens.next(); + + String typeName = dcl.type.cppName, defName = dcl.cppName; + if (context.namespace != null) { + defName = context.namespace + "::" + defName; + } + if (dcl.definition != null) { + // a function pointer or something + decl = dcl.definition; + if (dcl.javaName.length() > 0 && context.group != null) { + dcl.javaName = context.group.javaName + "." + dcl.javaName; + } + infoMap.put(new Info(defName).valueTypes(dcl.javaName)); + } else if (typeName.equals("void")) { + // some opaque data type + Info info = infoMap.getFirst(defName); + if (info == null || !info.skip) { + decl.text = "@Opaque public static class " + dcl.javaName + " extends Pointer {\n" + + " public " + dcl.javaName + "() { }\n" + + " public " + dcl.javaName + "(Pointer p) { super(p); }\n" + + "}"; + } + } else { + // point back to original type + Info info = infoMap.getFirst(typeName); + if (info == null || !info.skip) { + info = info != null ? new Info(info).cppNames(defName) : new Info(defName); + if (info.cppTypes == null) { + info.cppTypes(typeName); + } + if (info.pointerTypes == null) { + info.pointerTypes(typeName); + } + if (info.annotations == null) { + info.cast(!dcl.cppName.equals(info.pointerTypes[0])); + } + infoMap.put(info); + } + } + + String comment = commentAfter(); + decl.text = comment + decl.text; + declList.spacing = spacing; + declList.add(decl); + declList.spacing = null; + return true; + } + + boolean using(Context context, DeclarationList declList) throws Exception { + if (!tokens.get().match(Token.USING)) { + return false; + } + String spacing = tokens.get().spacing; + boolean namespace = tokens.get(1).match(Token.NAMESPACE); + Declarator dcl = declarator(context, null, 0, false, 0, true, false); + tokens.next(); + + context.usingList.add(dcl.type.cppName + (namespace ? "::" : "")); + + Declaration decl = new Declaration(); + if (dcl.definition != null) { + decl = dcl.definition; + } + String comment = commentAfter(); + decl.text = comment + decl.text; + declList.spacing = spacing; + declList.add(decl); + declList.spacing = null; + return true; + } + + boolean group(Context context, DeclarationList declList) throws Exception { + int backIndex = tokens.index; + String spacing = tokens.get().spacing; + boolean typedef = tokens.get().match(Token.TYPEDEF); + boolean foundGroup = false, friend = false; + Context ctx = new Context(context); + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(Token.CLASS, Token.STRUCT, Token.UNION)) { + foundGroup = true; + ctx.inaccessible = token.match(Token.CLASS); + break; + } else if (token.match(Token.FRIEND)) { + friend = true; + } else if (!token.match(Token.IDENTIFIER)) { + break; + } + } + if (!foundGroup) { + tokens.index = backIndex; + return false; + } + + tokens.next().expect(Token.IDENTIFIER, '{'); + if (typedef && tokens.get(1).match('*')) { + tokens.next(); + } + if (!tokens.get().match('{') && tokens.get(1).match(Token.IDENTIFIER) + && (typedef || !tokens.get(2).match(';'))) { + tokens.next(); + } + Type type = type(context); + ArrayList baseClasses = new ArrayList(); + Declaration decl = new Declaration(); + decl.text = type.annotations; + String name = type.javaName; + boolean anonymous = !typedef && type.cppName.length() == 0, derivedClass = false; + if (type.cppName.length() > 0 && tokens.get().match(':')) { + derivedClass = true; + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + boolean accessible = false; + if (token.match(Token.VIRTUAL)) { + continue; + } else if (token.match(Token.PRIVATE, Token.PROTECTED, Token.PUBLIC)) { + accessible = token.match(Token.PUBLIC); + tokens.next(); + } + Type t = type(context); + if (accessible) { + baseClasses.add(t); + } + if (tokens.get().expect(',', '{').match('{')) { + break; + } + } + } + if (!tokens.get().match('{', ';')) { + tokens.index = backIndex; + return false; + } + int startIndex = tokens.index; + ArrayList variables = new ArrayList(); + if (body() != null && !tokens.get().match(';')) { + if (typedef) { + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(';')) { + decl.text += token.spacing; + break; + } else { + name = type.javaName = type.cppName = token.value; + } + } + } else { + int index = tokens.index - 1; + for (int n = 0; n < Integer.MAX_VALUE; n++) { + tokens.index = index; + Declarator dcl = declarator(context, null, -1, false, n, false, true); + if (dcl == null) { + break; + } else { + variables.add(dcl); + } + } + int n = spacing.lastIndexOf('\n'); + if (n >= 0) { + decl.text += spacing.substring(0, n); + } + } + } + int namespace = type.cppName.lastIndexOf("::"); + if (context.namespace != null && namespace < 0) { + type.cppName = context.namespace + "::" + type.cppName; + } + Info info = infoMap.getFirst(type.cppName); + if (info != null && info.skip) { + decl.text = ""; + declList.add(decl); + return true; + } else if (info != null && info.pointerTypes != null && info.pointerTypes.length > 0) { + name = type.javaName = info.pointerTypes[0]; + } else if (info == null) { + if (type.javaName.length() > 0 && context.group != null) { + type.javaName = context.group.javaName + "." + type.javaName; + } + infoMap.put(info = new Info(type.cppName).pointerTypes(type.javaName)); + } + Type base = new Type("Pointer"); + if (baseClasses.size() > 0) { + base = baseClasses.remove(0); + } + String casts = ""; + if (baseClasses.size() > 0) { + for (Type t : baseClasses) { + casts += " public " + t.javaName + " as" + t.javaName + "() { return as" + t.javaName + "(this); }\n" + + " @Namespace public static native @Name(\"static_cast<" + t.cppName + "*>\") " + + t.javaName + " as" + t.javaName + "(" + type.javaName + " pointer);\n"; + } + } + decl.signature = type.javaName; + tokens.index = startIndex; + if (name.length() > 0 && tokens.get().match(';')) { + // incomplete type (forward or friend declaration) + tokens.next(); + if (friend) { + decl.text = ""; + declList.add(decl); + return true; + } else if (info != null && info.base != null) { + base.javaName = info.base; + } + String fullName = context.namespace != null ? context.namespace + "::" + name : name; + if (!fullName.equals(type.cppName)) { + decl.text += "@Name(\"" + type.cppName + "\") "; + } else if (context.namespace != null && context.group == null) { + decl.text += "@Namespace(\"" + context.namespace + "\") "; + } + decl.text += "@Opaque public static class " + name + " extends " + base.javaName + " {\n" + + " public " + name + "() { }\n" + + " public " + name + "(Pointer p) { super(p); }\n" + + "}"; + decl.type = type; + decl.incomplete = true; + String comment = commentAfter(); + decl.text = comment + decl.text; + declList.spacing = spacing; + declList.add(decl); + declList.spacing = null; + return true; + } else if (tokens.get().match('{')) { + tokens.next(); + } + + if (!anonymous) { + ctx.namespace = type.cppName; + ctx.group = type; + } + if (variables.size() > 0) { + ctx.variables = variables.toArray(new Declarator[variables.size()]); + } + DeclarationList declList2 = new DeclarationList(); + declarations(ctx, declList2); + boolean implicitConstructor = true, defaultConstructor = false, intConstructor = false, abstractClass = false, haveVariables = false; + for (Declaration d : declList2) { + if (d.declarator != null && d.declarator.type != null && d.declarator.type.constructor) { + implicitConstructor = false; + Declarator[] paramDcls = d.declarator.parameters.declarators; + defaultConstructor |= paramDcls.length == 0 && !d.inaccessible; + intConstructor |= paramDcls.length == 1 && paramDcls[0].type.javaName.equals("int") && !d.inaccessible; + } else if (d.abstractMember) { + implicitConstructor = false; + abstractClass = true; + } + haveVariables |= d.variable; + } + if (!anonymous) { + String fullName = context.namespace != null ? context.namespace + "::" + name : name; + if (!fullName.equals(type.cppName)) { + decl.text += "@Name(\"" + type.cppName + "\") "; + } else if (context.namespace != null && context.group == null) { + decl.text += "@Namespace(\"" + context.namespace + "\") "; + } + if ((!implicitConstructor || derivedClass) && haveVariables) { + decl.text += "@NoOffset "; + } + if (info != null && info.base != null) { + base.javaName = info.base; + } + decl.text += "public static class " + name + " extends " + base.javaName + " {\n" + + " static { Loader.load(); }\n"; + + if (implicitConstructor) { + decl.text += " public " + name + "() { allocate(); }\n" + + " public " + name + "(int size) { allocateArray(size); }\n" + + " public " + name + "(Pointer p) { super(p); }\n" + + " private native void allocate();\n" + + " private native void allocateArray(int size);\n" + + " @Override public " + name + " position(int position) {\n" + + " return (" + name + ")super.position(position);\n" + + " }\n"; + } else { + if (!defaultConstructor || abstractClass) { + decl.text += " public " + name + "() { }\n"; + } + decl.text += " public " + name + "(Pointer p) { super(p); }\n"; + if (defaultConstructor && !abstractClass && !intConstructor) { + decl.text += " public " + name + "(int size) { allocateArray(size); }\n" + + " private native void allocateArray(int size);\n" + + " @Override public " + name + " position(int position) {\n" + + " return (" + name + ")super.position(position);\n" + + " }\n"; + } + } + declList.spacing = spacing; + decl.text = declList.rescan(decl.text + casts + "\n"); + declList.spacing = null; + } + for (Declaration d : declList2) { + if (!d.inaccessible && (d.declarator == null || d.declarator.type == null || !d.declarator.type.constructor || !abstractClass)) { + decl.text += d.text; + } + } + decl.text += commentBefore(); // for comments at the end without declarations + if (!anonymous) { + decl.text += tokens.get().spacing + '}'; + } + for (Token token = tokens.next(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(';')) { + decl.text += token.spacing; + break; + } + } + tokens.next(); + decl.type = type; + if (info != null && info.javaText != null) { + decl.text = info.javaText; + } + declList.add(decl); + return true; + } + + boolean enumeration(Context context, DeclarationList declList) throws Exception { + int backIndex = tokens.index; + String enumSpacing = tokens.get().spacing; + boolean typedef = tokens.get().match(Token.TYPEDEF); + boolean foundEnum = false; + for (Token token = tokens.get(); !token.match(Token.EOF); token = tokens.next()) { + if (token.match(Token.ENUM)) { + foundEnum = true; + break; + } else if (!token.match(Token.IDENTIFIER)) { + break; + } + } + if (!foundEnum) { + tokens.index = backIndex; + return false; + } + + if (typedef && !tokens.get(1).match('{') && tokens.get(2).match(Token.IDENTIFIER)) { + tokens.next(); + } + boolean first = true; + int count = 0; + String countPrefix = " "; + String enumerators = ""; + String macroText = ""; + String name = tokens.next().expect(Token.IDENTIFIER, '{').value; + if (!tokens.get().match('{') && !tokens.next().match('{')) { + tokens.index = backIndex; + return false; + } + for (Token token = tokens.next(); !token.match(Token.EOF, '}'); token = tokens.get()) { + if (macro(context, declList)) { + Declaration macroDecl = declList.removeLast(); + macroText += macroDecl.text; + if (!first && !macroDecl.text.trim().startsWith("//")) { + enumerators += ";\n"; + macroText += "\npublic static final int"; + first = true; + } + continue; + } + String comment = commentBefore(); + Token enumerator = tokens.get(); + String spacing2 = " "; + String separator = first ? "" : ","; + if (tokens.next().match('=')) { + spacing2 = tokens.get().spacing; + countPrefix = " "; + int count2 = 0; + Token prevToken = new Token(); + boolean translate = true; + for (token = tokens.next(); !token.match(Token.EOF, ',', '}') || count2 > 0; token = tokens.next()) { + countPrefix += token.spacing + token; + if (token.match('(')) { + count2++; + } else if (token.match(')')) { + count2--; + } + if (prevToken.match(Token.IDENTIFIER) && token.match('(')) { + translate = false; + } + prevToken = token; + } + try { + count = Integer.parseInt(countPrefix.trim()); + countPrefix = " "; + } catch (NumberFormatException e) { + count = 0; + if (translate) { + countPrefix = translate(countPrefix); + } else { + if (!first) { + separator = ";\n"; + first = true; + } + separator += "public static native @MemberGetter int " + enumerator.value + "();\npublic static final int"; + countPrefix = " " + enumerator.value + "()"; + } + } + } + first = false; + enumerators += separator + macroText + comment; + macroText = ""; + comment = commentAfter(); + if (comment.length() == 0 && tokens.get().match(',')) { + tokens.next(); + comment = commentAfter(); + } + String spacing = enumerator.spacing; + if (comment.length() > 0) { + enumerators += spacing + comment; + int newline = spacing.lastIndexOf('\n'); + if (newline >= 0) { + spacing = spacing.substring(newline + 1); + } + } + enumerators += spacing + enumerator.value + spacing2 + "=" + countPrefix; + if (countPrefix.trim().length() > 0) { + if (count > 0) { + enumerators += " + " + count; + } + } else { + enumerators += count; + } + count++; + } + String comment = commentBefore(); + Declaration decl = new Declaration(); + Token token = tokens.next(); + if (token.match(Token.IDENTIFIER)) { + // XXX: If !isTypedef, this is a variable declaration with anonymous type + name = token.value; + token = tokens.next(); + } + if (context.namespace != null) { + name = context.namespace + "::" + name; + } + decl.text += enumSpacing + "/** enum " + name + " */\n"; + int newline = enumSpacing.lastIndexOf('\n'); + if (newline >= 0) { + enumSpacing = enumSpacing.substring(newline + 1); + } + if (!Character.isWhitespace(enumerators.charAt(0))) { + enumerators = " " + enumerators; + } + decl.text += enumSpacing + "public static final int" + enumerators + token.expect(';').spacing + ";"; + if (name.length() > 0) { + infoMap.put(new Info(name).cast(true).valueTypes("int").pointerTypes("IntPointer", "IntBuffer", "int[]")); + } + tokens.next(); + decl.text += macroText + comment; + declList.add(decl); + return true; + } + + boolean namespace(Context context, DeclarationList declList) throws Exception { + if (!tokens.get().match(Token.NAMESPACE)) { + return false; + } + Declaration decl = new Declaration(); + String name = tokens.next().expect(Token.IDENTIFIER).value; + tokens.next().expect('{'); + tokens.next(); + + context = new Context(context); + context.namespace = context.namespace != null ? context.namespace + "::" + name : name; + declarations(context, declList); + decl.text += tokens.get().expect('}').spacing; + tokens.next(); + declList.add(decl); + return true; + } + + boolean extern(Context context, DeclarationList declList) throws Exception { + if (!tokens.get().match(Token.EXTERN) || !tokens.get(1).match(Token.STRING)) { + return false; + } + Declaration decl = new Declaration(); + tokens.next().expect("\"C\""); + if (!tokens.next().match('{')) { + declList.add(decl); + return true; + } + tokens.next(); + + declarations(context, declList); + tokens.get().expect('}'); + tokens.next(); + declList.add(decl); + return true; + } + + + static class Declaration { + Type type = null; + Declarator declarator = null; + boolean abstractMember = false, constMember = false, inaccessible = false, incomplete = false, variable = false; + String signature = "", text = ""; + } + + static class DeclarationList extends LinkedList { + InfoMap infoMap = null; + Context context = null; + TemplateMap templateMap = null; + ListIterator infoIterator = null; + String spacing = null; + + String rescan(String lines) { + if (spacing == null) { + return lines; + } + String text = ""; + Scanner scanner = new Scanner(lines); + while (scanner.hasNextLine()) { + text += spacing + scanner.nextLine(); + int newline = spacing.lastIndexOf('\n'); + spacing = newline >= 0 ? spacing.substring(newline) : "\n"; + } + return text; + } + + @Override public boolean add(Declaration decl) { + boolean add = true; + if (templateMap != null && !templateMap.full() && (decl.type != null || decl.declarator != null)) { + Type type = templateMap.type = decl.type; + Declarator dcl = templateMap.declarator = decl.declarator; + LinkedList infoList = infoMap.get(dcl != null ? dcl.cppName : type.cppName); + infoIterator = infoList.size() > 0 ? infoList.listIterator() : null; + add = false; + } else if (decl.declarator != null && decl.declarator.type != null) { + Info info = infoMap.getFirst(decl.declarator.type.cppName); + if (info != null && info.skip && info.valueTypes == null && info.pointerTypes == null) { + add = false; + } else if (decl.declarator.parameters != null) { + for (Declarator d : decl.declarator.parameters.declarators) { + if (d != null && d.type != null) { + info = infoMap.getFirst(d.type.cppName); + if (info != null && info.skip && info.valueTypes == null && info.pointerTypes == null) { + add = false; + break; + } + } + } + } + } + if (!add) { + return false; + } + + LinkedList stack = new LinkedList(); + ListIterator it = stack.listIterator(); + it.add(decl); it.previous(); + while (it.hasNext()) { + decl = it.next(); + Declarator dcl = decl.declarator; + if (dcl != null && dcl.definition != null) { + it.add(dcl.definition); it.previous(); + } + if (dcl != null && dcl.parameters != null && dcl.parameters.declarators != null) { + for (Declarator d : dcl.parameters.declarators) { + if (d != null && d.definition != null) { + it.add(d.definition); it.previous(); + } + } + } + } + + while (!stack.isEmpty()) { + decl = stack.removeLast(); + if (context != null) { + decl.inaccessible = context.inaccessible; + } + it = listIterator(); + boolean found = false; + while (it.hasNext()) { + Declaration d = it.next(); + if (d.signature.length() > 0 && d.signature.equals(decl.signature)) { + if ((d.constMember && !decl.constMember) || (d.inaccessible && !decl.inaccessible) || (d.incomplete && !decl.incomplete)) { + // add preferably non-const accessible complete versions of functions and types + it.remove(); + } else { + found = true; + } + } + } + if (!found) { + decl.text = rescan(decl.text); + super.add(decl); + } + } + return true; + } + } + + void declarations(Context context, DeclarationList declList) throws Exception { + for (Token token = tokens.get(); !token.match(Token.EOF, '}'); token = tokens.get()) { + if (token.match(Token.PRIVATE, Token.PROTECTED, Token.PUBLIC) && tokens.next().match(':')) { + context.inaccessible = !token.match(Token.PUBLIC); + tokens.next(); + } + Context ctx = context; + String comment = commentBefore(); + token = tokens.get(); + String spacing = token.spacing; + TemplateMap map = template(ctx); + if (map != null) { + token = tokens.get(); + token.spacing = spacing; + ctx = new Context(ctx); + ctx.templateMap = map; + } + Declaration decl = new Declaration(); + if (comment != null && comment.length() > 0) { + decl.inaccessible = ctx.inaccessible; + decl.text = comment; + declList.add(decl); + } + int startIndex = tokens.index; + declList.infoMap = infoMap; + declList.context = ctx; + declList.templateMap = map; + declList.infoIterator = null; + declList.spacing = null; + do { + if (map != null && declList.infoIterator != null && declList.infoIterator.hasNext()) { + Info info = declList.infoIterator.next(); + if (info == null) { + continue; + } + Type type = new Parser(this, info.cppNames[0]).type(context); + if (type.arguments == null) { + continue; + } + int count = 0; + for (Map.Entry e : map.entrySet()) { + if (count < type.arguments.length) { + e.setValue(type.arguments[count++].cppName); + } + } + tokens.index = startIndex; + } + + if (!macro(ctx, declList) && !extern(ctx, declList) && !namespace(ctx, declList) + && !enumeration(ctx, declList) && !group(ctx, declList) && !typedef(ctx, declList) + && !using(ctx, declList) && !function(ctx, declList) && !variable(ctx, declList)) { + spacing = tokens.get().spacing; + if (attribute() != null) { + tokens.get().spacing = spacing; + } else { + throw new Exception(token.file + ":" + token.lineNumber + ": Could not parse declaration at '" + token + "'"); + } + } + while (tokens.get().match(';') && !tokens.get().match(Token.EOF)) { + tokens.next(); + } + } while (declList.infoIterator != null && declList.infoIterator.hasNext()); + } + } + + void parse(String outputFilename, Context context, String[] includePath, String ... inputFilenames) throws IOException, Exception { + File[] files = new File[inputFilenames.length]; + for (int i = 0; i < files.length; i++) { + files[i] = new File(inputFilenames[i]); + } + parse(new File(outputFilename), context, includePath, files); + } + void parse(File outputFile, Context context, String[] includePath, File ... inputFiles) throws IOException, Exception { + ArrayList tokenList = new ArrayList(); + String lineSeparator = null; + for (File file : inputFiles) { + if (!file.exists()) { + for (String s : includePath) { + File f = new File(s, file.getPath()); + if (f.exists()) { + file = f; + break; + } + } + } + Info info = infoMap.getFirst(file.getName()); + if (info != null && info.skip) { + continue; + } + logger.info("Parsing " + file); + Token token = new Token(); + token.type = Token.COMMENT; + token.value = "\n// Parsed from " + file + "\n\n"; + tokenList.add(token); + Tokenizer tokenizer = new Tokenizer(file); + while (!(token = tokenizer.nextToken()).isEmpty()) { + if (token.type == -1) { + token.type = Token.COMMENT; + } + tokenList.add(token); + } + if (lineSeparator == null) { + lineSeparator = tokenizer.lineSeparator; + } + tokenizer.close(); + token = new Token(); + token.type = Token.COMMENT; + token.spacing = "\n"; + tokenList.add(token); + } + tokens = new TokenIndexer(infoMap, tokenList.toArray(new Token[tokenList.size()])); + + final String newline = lineSeparator != null ? lineSeparator : "\n"; + Writer out = outputFile != null ? new FileWriter(outputFile) { + @Override public Writer append(CharSequence text) throws IOException { + return super.append(((String)text).replace("\n", newline).replace("\\u", "\\u005Cu")); + }} : new Writer() { + @Override public void write(char[] cbuf, int off, int len) { } + @Override public void flush() { } + @Override public void close() { } + }; + LinkedList infoList = leafInfoMap.get(null); + for (Info info : infoList) { + if (info.javaText != null && !info.javaText.startsWith("import")) { + out.append(info.javaText + "\n"); + } + } + out.append(" static { Loader.load(); }\n"); + + DeclarationList declList = new DeclarationList(); + containers(context, declList); + declarations(context, declList); + for (Declaration d : declList) { + out.append(d.text); + } + String comment = commentBefore(); + if (comment != null) { + out.append(comment); + } + out.append("\n}\n").close(); + } + + public File parse(String outputDirectory, String[] classPath, Class cls) throws IOException, Exception { + return parse(new File(outputDirectory), classPath, cls); + } + public File parse(File outputDirectory, String[] classPath, Class cls) throws IOException, Exception { + Loader.ClassProperties allProperties = Loader.loadProperties(cls, properties, true); + Loader.ClassProperties clsProperties = Loader.loadProperties(cls, properties, false); + LinkedList allFiles = allProperties.getHeaderFiles(); + LinkedList clsFiles = clsProperties.getHeaderFiles(); + LinkedList allTargets = allProperties.get("target"); + LinkedList clsTargets = clsProperties.get("target"); + LinkedList clsHelpers = clsProperties.get("helper"); + String target = clsTargets.getFirst(); // there can only be one + LinkedList allInherited = allProperties.getInheritedClasses(); + + infoMap = new Parser.InfoMap(); + for (Class c : allInherited) { + try { + ((InfoMapper)c.newInstance()).map(infoMap); + } catch (ClassCastException e) { + } catch (InstantiationException e) { + } catch (IllegalAccessException e) { + // fail silently as if the interface wasn't implemented + } + } + leafInfoMap = new Parser.InfoMap(); + try { + ((InfoMapper)cls.newInstance()).map(leafInfoMap); + } catch (ClassCastException e) { + } catch (InstantiationException e) { + } catch (IllegalAccessException e) { + // fail silently as if the interface wasn't implemented + } + infoMap.putAll(leafInfoMap); + + String version = Generator.class.getPackage().getImplementationVersion(); + if (version == null) { + version = "unknown"; + } + String text = "// Targeted by JavaCPP version " + version + "\n\n"; + int n = target.lastIndexOf('.'); + if (n >= 0) { + text += "package " + target.substring(0, n) + ";\n\n"; + } + LinkedList infoList = leafInfoMap.get(null); + for (Info info : infoList) { + if (info.javaText != null && info.javaText.startsWith("import")) { + text += info.javaText + "\n"; + } + } + text += "import com.googlecode.javacpp.*;\n" + + "import com.googlecode.javacpp.annotation.*;\n" + + "import java.nio.*;\n\n"; + for (String s : allTargets) { + if (!target.equals(s)) { + text += "import static " + s + ".*;\n"; + } + } + if (allTargets.size() > 1) { + text += "\n"; + } + text += "public class " + target.substring(n + 1) + " extends " + + (clsHelpers.size() > 0 ? clsHelpers.getFirst() : cls.getCanonicalName()) + " {"; + leafInfoMap.putFirst(new Info().javaText(text)); + + String targetPath = target.replace('.', File.separatorChar); + File targetFile = new File(outputDirectory, targetPath + ".java"); + logger.info("Targeting " + targetFile); + Context context = new Context(); + String[] includePath = classPath; + n = targetPath.lastIndexOf(File.separatorChar); + if (n >= 0) { + includePath = classPath.clone(); + for (int i = 0; i < includePath.length; i++) { + includePath[i] += File.separator + targetPath.substring(0, n); + } + } + for (File f : allFiles) { + if (!clsFiles.contains(f)) { + parse(null, context, includePath, f); + } + } + parse(targetFile, context, includePath, clsFiles.toArray(new File[clsFiles.size()])); + return targetFile; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `allInherited` last assigned on line 2956 could be null and is dereferenced at line 2959. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +File Parser.parse(File,java.lang.String[],Class) + +### Procedure Id: +com.googlecode.javacpp.Parser.parse(java.io.File,java.lang.String[],java.lang.Class):java.io.File.f175143f1a72d531678ca157edc5215d + +### File: +src/main/java/com/googlecode/javacpp/Parser.java + +### Key: +Parser.java|parse|NULL_DEREFERENCE + +### Node Key: +508fe65944aede45ae4405e1858c9447 + +### Hash: +1b0e0b8cafff477145a73e32e4d9ae26 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9288/instruction.md b/inferredbugs-9288/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..933c05cf9335eae101bde23c0f980b712bdf22cc --- /dev/null +++ b/inferredbugs-9288/instruction.md @@ -0,0 +1,967 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javacpp +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2011-2016 Samuel Audet + * + * Licensed either under the Apache License, Version 2.0, or (at your option) + * under the terms of the GNU General Public License as published by + * the Free Software Foundation (subject to the "Classpath" exception), + * either version 2, or any later version (collectively, the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.gnu.org/licenses/ + * http://www.gnu.org/software/classpath/license.html + * + * or as provided in the LICENSE.txt file that accompanied this code. + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.bytedeco.javacpp; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.JarURLConnection; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLConnection; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.WeakHashMap; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import org.bytedeco.javacpp.annotation.Platform; +import org.bytedeco.javacpp.tools.Builder; +import org.bytedeco.javacpp.tools.Logger; + +/** + * The Loader contains functionality to load native libraries, but also has a bit + * of everything that does not fit anywhere else. In addition to its library loading + * features, it also has utility methods to get the platform name, to load properties + * from Java resources and from Class annotations, to extract file resources to the + * temporary directory, and to get the {@code offsetof()} or {@code sizeof()} a native + * {@code struct}, {@code class}, or {@code union} with its {@link Pointer} peer class + * and a {@link HashMap} initialized by the native libraries inside {@code JNI_OnLoad()}. + * + * @author Samuel Audet + */ +public class Loader { + + private static final Logger logger = Logger.create(Loader.class); + + /** Value created out of "java.vm.name", "os.name", and "os.arch" system properties. + * Returned by {@link #getPlatform()} as default. */ + private static final String PLATFORM; + /** Default platform properties loaded and returned by {@link #loadProperties()}. */ + private static Properties platformProperties = null; + + static { + String jvmName = System.getProperty("java.vm.name", "").toLowerCase(); + String osName = System.getProperty("os.name", "").toLowerCase(); + String osArch = System.getProperty("os.arch", "").toLowerCase(); + String abiType = System.getProperty("sun.arch.abi", "").toLowerCase(); + String libPath = System.getProperty("sun.boot.library.path", "").toLowerCase(); + if (jvmName.startsWith("dalvik") && osName.startsWith("linux")) { + osName = "android"; + } else if (jvmName.startsWith("robovm") && osName.startsWith("darwin")) { + osName = "ios"; + osArch = "arm"; + } else if (osName.startsWith("mac os x") || osName.startsWith("darwin")) { + osName = "macosx"; + } else { + int spaceIndex = osName.indexOf(' '); + if (spaceIndex > 0) { + osName = osName.substring(0, spaceIndex); + } + } + if (osArch.equals("i386") || osArch.equals("i486") || osArch.equals("i586") || osArch.equals("i686")) { + osArch = "x86"; + } else if (osArch.equals("amd64") || osArch.equals("x86-64") || osArch.equals("x64")) { + osArch = "x86_64"; + } else if (osArch.startsWith("aarch64") || osArch.startsWith("armv8") || osArch.startsWith("arm64")) { + osArch = "arm64"; + } else if ((osArch.startsWith("arm")) && ((abiType.equals("gnueabihf")) || (libPath.contains("openjdk-armhf")))) { + osArch = "armhf"; + } else if (osArch.startsWith("arm")) { + osArch = "arm"; + } + PLATFORM = osName + "-" + osArch; + } + + /** + * Returns either the value of the "org.bytedeco.javacpp.platform" + * system property, or {@link #PLATFORM} when the former is not set. + * + * @return {@code System.getProperty("org.bytedeco.javacpp.platform", platform)} + * @see #PLATFORM + */ + public static String getPlatform() { + return System.getProperty("org.bytedeco.javacpp.platform", PLATFORM); + } + + /** + * Loads the {@link Properties} associated with the default {@link #getPlatform()}. + * + * @return {@code loadProperties(getPlatform(), null)} + * @see #loadProperties(String, String) + */ + public static Properties loadProperties() { + String name = getPlatform(); + if (platformProperties != null && name.equals(platformProperties.getProperty("platform"))) { + return platformProperties; + } + return platformProperties = loadProperties(name, null); + } + /** + * Loads from resources the default {@link Properties} of the specified platform name. + * The resource must be at {@code "org/bytedeco/javacpp/properties/" + name + ".properties"}. + * + * @param name the platform name + * @param defaults the fallback platform name (null == "generic") + * @return the Properties from resources + */ + public static Properties loadProperties(String name, String defaults) { + if (defaults == null) { + defaults = "generic"; + } + Properties p = new Properties(); + p.put("platform", name); + p.put("platform.path.separator", File.pathSeparator); + String s = System.mapLibraryName("/"); + int i = s.indexOf('/'); + p.put("platform.library.prefix", s.substring(0, i)); + p.put("platform.library.suffix", s.substring(i + 1)); + name = "properties/" + name + ".properties"; + InputStream is = Loader.class.getResourceAsStream(name); + try { + try { + p.load(new InputStreamReader(is)); + } catch (NoSuchMethodError e) { + p.load(is); + } + } catch (Exception e) { + name = "properties/" + defaults + ".properties"; + InputStream is2 = Loader.class.getResourceAsStream(name); + try { + try { + p.load(new InputStreamReader(is2)); + } catch (NoSuchMethodError e2) { + p.load(is2); + } + } catch (Exception e2) { + // give up and return defaults + } finally { + try { + if (is2 != null) { + is2.close(); + } + } catch (IOException ex) { + logger.error("Unable to close resource : " + ex.getMessage()); + } + } + } finally { + try { + if (is != null) { + is.close(); + } + } catch (IOException ex) { + logger.error("Unable to close resource : " + ex.getMessage()); + } + } + return p; + } + + /** + * If annotated with properties, returns the argument as "enclosing Class". + * If no properties are found on the Class, makes a search for the first Class + * with properties that we can use, and returns it as the enclosing Class found. + * + * @param cls the Class to start the search from + * @return the enclosing Class + * @see org.bytedeco.javacpp.annotation.Platform + * @see org.bytedeco.javacpp.annotation.Properties + */ + public static Class getEnclosingClass(Class cls) { + Class c = cls; + // Find first enclosing declaring class with some properties to use + while (c.getDeclaringClass() != null) { + if (c.isAnnotationPresent(org.bytedeco.javacpp.annotation.Properties.class)) { + break; + } + if (c.isAnnotationPresent(Platform.class)) { + Platform p = c.getAnnotation(Platform.class); + if (p.pragma().length > 0 || p.define().length > 0 || p.include().length > 0 || p.cinclude().length > 0 || + p.includepath().length > 0 || p.compiler().length > 0 || p.linkpath().length > 0 || + p.link().length > 0 || p.frameworkpath().length > 0 || p.framework().length > 0 || + p.preloadpath().length > 0 || p.preload().length > 0 || p.library().length() > 0) { + break; + } + } + c = c.getDeclaringClass(); + } + return c; + } + + + /** + * For all the classes, loads all properties from each Class annotations for the given platform. + * @see #loadProperties(Class, java.util.Properties, boolean) + */ + public static ClassProperties loadProperties(Class[] cls, Properties properties, boolean inherit) { + ClassProperties cp = new ClassProperties(properties); + for (Class c : cls) { + cp.load(c, inherit); + } + return cp; + } + /** + * Loads all properties from Class annotations for the given platform. The platform + * of interest needs to be specified as the value of the "platform" key in the + * properties argument. It is also possible to indicate whether to load all the classes + * specified in the {@link org.bytedeco.javacpp.annotation.Properties#inherit()} + * annotation recursively via the inherit argument. + * + * @param cls the Class of which to return Properties + * @param properties the platform Properties to inherit + * @param inherit indicates whether or not to inherit properties from other classes + * @return all the properties associated with the Class for the given platform + */ + public static ClassProperties loadProperties(Class cls, Properties properties, boolean inherit) { + ClassProperties cp = new ClassProperties(properties); + cp.load(cls, inherit); + return cp; + } + + /** + * Returns the {@link Class} object that contains a caller's method. + * + * @param i the offset on the call stack of the method of interest + * @return the Class found from the calling context, or {@code null} if not found + */ + public static Class getCallerClass(int i) { + Class[] classContext = null; + try { + new SecurityManager() { + @Override public Class[] getClassContext() { + return super.getClassContext(); + } + }.getClassContext(); + } catch (NoSuchMethodError e) { + logger.error("No definition of this method : " + e.getMessage()); + } + if (classContext != null) { + for (int j = 0; j < classContext.length; j++) { + if (classContext[j] == Loader.class) { + return classContext[i+j]; + } + } + } else { + // SecurityManager.getClassContext() returns null on Android 4.0 + try { + StackTraceElement[] classNames = Thread.currentThread().getStackTrace(); + for (int j = 0; j < classNames.length; j++) { + if (Class.forName(classNames[j].getClassName()) == Loader.class) { + return Class.forName(classNames[i+j].getClassName()); + } + } + } catch (ClassNotFoundException e) { + logger.error("No definition for the class found : " + e.getMessage()); + } + } + return null; + } + + /** + * Extracts a resource using the {@link ClassLoader} of the caller class, + * and returns the cached {@link File}. + * + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #cacheResource(Class, String) + */ + public static File cacheResource(String name) throws IOException { + Class cls = getCallerClass(2); + return cacheResource(cls, name); + } + /** + * Extracts a resource using the {@link ClassLoader} of the specified {@link Class}, + * and returns the cached {@link File}. + * + * @param cls the Class from which to load resources + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #cacheResource(URL) + */ + public static File cacheResource(Class cls, String name) throws IOException { + return cacheResource(cls.getResource(name)); + } + /** Returns {@code cacheResource(resourceUrl, null)} */ + public static File cacheResource(URL resourceURL) throws IOException { + return cacheResource(resourceURL, null); + } + /** + * Extracts a resource, if the size or last modified timestamp differs from what is in cache, + * and returns the cached {@link File}. If target is not null, creates instead a symbolic link + * where the resource would have been extracted. + * + * @param resourceURL the URL of the resource to extract and cache + * @param target of the symbolic link to create (must be null to have the resource actually extracted) + * @return the File object representing the extracted file from the cache + * @throws IOException if fails to extract resource properly + * @see #extractResource(URL, File, String, String) + * @see #cacheDir + */ + public static File cacheResource(URL resourceURL, String target) throws IOException { + // Find appropriate subdirectory in cache for the resource ... + File urlFile = new File(resourceURL.getPath()); + String name = urlFile.getName(); + long size, timestamp; + File cacheSubdir = getCacheDir().getCanonicalFile(); + URLConnection urlConnection = resourceURL.openConnection(); + if (urlConnection instanceof JarURLConnection) { + JarFile jarFile = ((JarURLConnection)urlConnection).getJarFile(); + JarEntry jarEntry = ((JarURLConnection)urlConnection).getJarEntry(); + File jarFileFile = new File(jarFile.getName()); + File jarEntryFile = new File(jarEntry.getName()); + size = jarEntry.getSize(); + timestamp = jarEntry.getTime(); + cacheSubdir = new File(cacheSubdir, jarFileFile.getName() + File.separator + jarEntryFile.getParent()); + } else { + size = urlFile.length(); + timestamp = urlFile.lastModified(); + cacheSubdir = new File(cacheSubdir, name); + } + if (resourceURL.getRef() != null) { + // ... get the URL fragment to let users rename library files ... + name = resourceURL.getRef(); + } + // ... then check if it has not already been extracted, and if not ... + File file = new File(cacheSubdir, name); + if (target != null && target.length() > 0) { + // ... create symbolic link to already extracted library or ... + try { + if (logger.isDebugEnabled()) { + logger.debug("Creating symbolic link to " + target); + } + Path path = file.toPath(), targetPath = Paths.get(target); + if ((!file.exists() || !Files.isSymbolicLink(path)) + && targetPath.isAbsolute() && !targetPath.equals(path)) { + file.delete(); + Files.createSymbolicLink(path, targetPath); + } + } catch (IOException e) { + // ... (probably an unsupported operation on Windows, but DLLs never need links) ... + return null; + } + } else if (!file.exists() || file.length() != size || file.lastModified() != timestamp + || !cacheSubdir.equals(file.getCanonicalFile().getParentFile())) { + // ... then extract it from our resources ... + if (logger.isDebugEnabled()) { + logger.debug("Extracting " + resourceURL); + } + file.delete(); + extractResource(resourceURL, file, null, null); + file.setLastModified(timestamp); + } else while (System.currentTimeMillis() - file.lastModified() >= 0 + && System.currentTimeMillis() - file.lastModified() < 1000) { + // ... else wait until the file is at least 1 second old ... + try { + Thread.sleep(1000); + } catch (InterruptedException ex) { + // ... and reset interrupt to be nice. + Thread.currentThread().interrupt(); + } + } + return file; + } + + /** + * Extracts by name a resource using the {@link ClassLoader} of the caller. + * + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #extractResource(URL, File, String, String) + */ + public static File extractResource(String name, File directory, + String prefix, String suffix) throws IOException { + Class cls = getCallerClass(2); + return extractResource(cls, name, directory, prefix, suffix); + } + /** + * Extracts by name a resource using the {@link ClassLoader} of the specified {@link Class}. + * + * @param cls the Class from which to load resources + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #extractResource(URL, File, String, String) + */ + public static File extractResource(Class cls, String name, File directory, + String prefix, String suffix) throws IOException { + return extractResource(cls.getResource(name), directory, prefix, suffix); + } + /** + * Extracts a resource into the specified directory and with the specified + * prefix and suffix for the filename. If both prefix and suffix are {@code null}, + * the original filename is used, so directoryOrFile must not be {@code null}. + * + * @param resourceURL the URL of the resource to extract + * @param directoryOrFile the output directory or file ({@code null == System.getProperty("java.io.tmpdir")}) + * @param prefix the prefix of the temporary filename to use + * @param suffix the suffix of the temporary filename to use + * @return the File object representing the extracted file + * @throws IOException if fails to extract resource properly + */ + public static File extractResource(URL resourceURL, File directoryOrFile, + String prefix, String suffix) throws IOException { + InputStream is = resourceURL != null ? resourceURL.openStream() : null; + OutputStream os = null; + if (is == null) { + return null; + } + File file = null; + boolean fileExisted = false; + try { + if (prefix == null && suffix == null) { + if (directoryOrFile == null) { + directoryOrFile = new File(System.getProperty("java.io.tmpdir")); + } + File directory; + if (directoryOrFile.isDirectory()) { + directory = directoryOrFile; + file = new File(directoryOrFile, new File(resourceURL.getPath()).getName()); + } else { + directory = directoryOrFile.getParentFile(); + file = directoryOrFile; + } + if (directory != null) { + directory.mkdirs(); + } + fileExisted = file.exists(); + } else { + file = File.createTempFile(prefix, suffix, directoryOrFile); + } + os = new FileOutputStream(file); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) != -1) { + os.write(buffer, 0, length); + } + is.close(); + os.close(); + } catch (IOException e) { + if (file != null && !fileExisted) { + file.delete(); + } + throw e; + } finally { + is.close(); + if (os != null) { + os.close(); + } + } + return file; + } + + /** User-specified cache directory set and returned by {@link #getCacheDir()}. */ + static File cacheDir = null; + /** Temporary directory set and returned by {@link #getTempDir()}. */ + static File tempDir = null; + /** Contains all the native libraries that we have loaded to avoid reloading them. */ + static Map loadedLibraries = Collections.synchronizedMap(new HashMap()); + + /** Creates and returns {@code System.getProperty("org.bytedeco.javacpp.cachedir")} or {@code ~/.javacpp/cache/} when not set. */ + public static File getCacheDir() { + if (cacheDir == null) { + String dirName = System.getProperty("org.bytedeco.javacpp.cachedir", System.getProperty("user.home") + "/.javacpp/cache/"); + if (dirName != null) { + File f = new File(dirName); + if (f.exists() || f.mkdirs()) { + cacheDir = f; + } + } + } + return cacheDir; + } + + /** + * Creates a unique name for {@link #tempDir} out of + * {@code System.getProperty("java.io.tmpdir")} and {@code System.nanoTime()}. + * + * @return {@link #tempDir} + */ + public static File getTempDir() { + if (tempDir == null) { + File tmpdir = new File(System.getProperty("java.io.tmpdir")); + File f; + for (int i = 0; i < 1000; i++) { + f = new File(tmpdir, "javacpp" + System.nanoTime()); + if (f.mkdir()) { + tempDir = f; + tempDir.deleteOnExit(); + break; + } + } + } + return tempDir; + } + + /** Returns {@code System.getProperty("org.bytedeco.javacpp.loadlibraries")}. + * Flag set by the {@link Builder} to tell us not to try to load anything. */ + public static boolean isLoadLibraries() { + String s = System.getProperty("org.bytedeco.javacpp.loadlibraries", "true").toLowerCase(); + return s.equals("true") || s.equals("t") || s.equals(""); + } + + /** Returns {@code load(getCallerClass(2), loadProperties(), false)}. */ + public static String load() { + return load(getCallerClass(2), loadProperties(), false); + } + /** + * Loads native libraries associated with the {@link Class} of the caller. + * + * @param pathsFirst search the paths first before bundled resources + * @return {@code load(getCallerClass(2), loadProperties(), pathsFirst) } + * @see #getCallerClass(int) + * @see #load(Class, Properties, boolean) + */ + public static String load(boolean pathsFirst) { + Class cls = getCallerClass(2); + return load(cls, loadProperties(), pathsFirst); + } + /** Returns {@code load(cls, loadProperties(), false)}. */ + public static String load(Class cls) { + return load(cls, loadProperties(), false); + } + /** + * Loads native libraries associated with the given {@link Class}. + * + * @param cls the Class to get native library information from + * @param properties the platform Properties to inherit + * @param pathsFirst search the paths first before bundled resources + * @return the full path to the main file loaded, or the library name if unknown + * (but {@code if (!isLoadLibraries() || cls == null) { return null; }}) + * @throws NoClassDefFoundError on Class initialization failure + * @throws UnsatisfiedLinkError on native library loading failure + * @see #findLibrary(Class, ClassProperties, String, boolean) + * @see #loadLibrary(URL[], String) + */ + public static String load(Class cls, Properties properties, boolean pathsFirst) { + if (!isLoadLibraries() || cls == null) { + return null; + } + + // Find the top enclosing class, to match the library filename + cls = getEnclosingClass(cls); + ClassProperties p = loadProperties(cls, properties, true); + + // Force initialization of all the target classes in case they need it + List targets = p.get("target"); + if (targets.isEmpty()) { + if (p.getInheritedClasses() != null) { + for (Class c : p.getInheritedClasses()) { + targets.add(c.getName()); + } + } + targets.add(cls.getName()); + } + for (String s : targets) { + try { + if (logger.isDebugEnabled()) { + logger.debug("Loading class " + s); + } + Class.forName(s, true, cls.getClassLoader()); + } catch (ClassNotFoundException ex) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to load class " + s + ": " + ex); + } + Error e = new NoClassDefFoundError(ex.toString()); + e.initCause(ex); + throw e; + } + } + + // Preload native libraries desired by our class + List preloads = new ArrayList(); + preloads.addAll(p.get("platform.preload")); + preloads.addAll(p.get("platform.link")); + UnsatisfiedLinkError preloadError = null; + for (String preload : preloads) { + try { + URL[] urls = findLibrary(cls, p, preload, pathsFirst); + loadLibrary(urls, preload); + } catch (UnsatisfiedLinkError e) { + preloadError = e; + } + } + + try { + String library = p.getProperty("platform.library"); + URL[] urls = findLibrary(cls, p, library, pathsFirst); + return loadLibrary(urls, library); + } catch (UnsatisfiedLinkError e) { + if (preloadError != null && e.getCause() == null) { + e.initCause(preloadError); + } + throw e; + } + } + + /** + * Finds from where the library may be extracted and loaded among the {@link Class} + * resources. But in case that fails, and depending on the value of {@code pathsFirst}, + * either as a fallback or in priority over bundled resources, also searches the paths + * found in the "platform.preloadpath" and "platform.linkpath" class properties as well as + * the "java.library.path" system property, in that order. + * + * @param cls the Class whose package name and {@link ClassLoader} are used to extract from resources + * @param properties contains the directories to scan for if we fail to extract the library from resources + * @param libnameversion the name of the library + "@" + optional version tag + * + "#" + a second optional name used at extraction (or empty to prevent it) + * @param pathsFirst search the paths first before bundled resources + * @return URLs that point to potential locations of the library + */ + public static URL[] findLibrary(Class cls, ClassProperties properties, String libnameversion, boolean pathsFirst) { + if (libnameversion.trim().endsWith("#")) { + return new URL[0]; + } + String[] split = libnameversion.split("#"); + String[] s = split[0].split("@"); + String[] s2 = (split.length > 1 ? split[1] : split[0]).split("@"); + String libname = s[0]; + String libname2 = s2[0]; + String version = s.length > 1 ? s[s.length-1] : ""; + String version2 = s2.length > 1 ? s2[s2.length-1] : ""; + + // If we do not already have the native library file ... + String subdir = properties.getProperty("platform") + '/'; + String prefix = properties.getProperty("platform.library.prefix", ""); + String suffix = properties.getProperty("platform.library.suffix", ""); + String[] styles = { + prefix + libname + suffix + version, // Linux style + prefix + libname + version + suffix, // Mac OS X style + prefix + libname + suffix // without version + }; + String[] styles2 = { + prefix + libname2 + suffix + version2, // Linux style + prefix + libname2 + version2 + suffix, // Mac OS X style + prefix + libname2 + suffix // without version + }; + + String[] suffixes = properties.get("platform.library.suffix").toArray(new String[0]); + if (suffixes.length > 1) { + styles = new String[3 * suffixes.length]; + styles2 = new String[3 * suffixes.length]; + for (int i = 0; i < suffixes.length; i++) { + styles[3 * i ] = prefix + libname + suffixes[i] + version; // Linux style + styles[3 * i + 1] = prefix + libname + version + suffixes[i]; // Mac OS X style + styles[3 * i + 2] = prefix + libname + suffixes[i]; // without version + styles2[3 * i ] = prefix + libname2 + suffixes[i] + version2; // Linux style + styles2[3 * i + 1] = prefix + libname2 + version2 + suffixes[i]; // Mac OS X style + styles2[3 * i + 2] = prefix + libname2 + suffixes[i]; // without version + } + } + + List paths = new ArrayList(); + paths.addAll(properties.get("platform.preloadpath")); + paths.addAll(properties.get("platform.linkpath")); + String libpath = System.getProperty("java.library.path", ""); + if (libpath.length() > 0) { + paths.addAll(Arrays.asList(libpath.split(File.pathSeparator))); + } + ArrayList urls = new ArrayList(styles.length * (1 + paths.size())); + for (int i = 0; cls != null && i < styles.length; i++) { + // ... then find it from in our resources ... + URL u = cls.getResource(subdir + styles[i]); + if (u != null) { + if (!styles[i].equals(styles2[i])) { + try { + u = new URL(u + "#" + styles2[i]); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + urls.add(u); + } + } + // ... and in case of bad resources search the paths last, or first on user request. + int k = pathsFirst ? 0 : urls.size(); + for (int i = 0; paths.size() > 0 && i < styles.length; i++) { + for (String path : paths) { + File file = new File(path, styles[i]); + if (file.exists()) { + try { + URL u = file.toURI().toURL(); + if (!styles[i].equals(styles2[i])) { + u = new URL(u + "#" + styles2[i]); + } + urls.add(k++, u); + } catch (MalformedURLException ex) { + throw new RuntimeException(ex); + } + } + } + } + return urls.toArray(new URL[urls.size()]); + } + + /** + * Tries to load the library from the URLs in order, extracting resources as necessary. + * Finally, if all fails, falls back on {@link System#loadLibrary(String)}. + * + * @param urls the URLs to try loading the library from + * @param libnameversion the name of the library + "@" + optional version tag + * + "#" + a second optional name used at extraction + * @return the full path of the file loaded, or the library name if unknown + * (but {@code if (!isLoadLibraries) { return null; }}) + * @throws UnsatisfiedLinkError on failure + */ + public static String loadLibrary(URL[] urls, String libnameversion) { + if (!isLoadLibraries()) { + return null; + } + String[] split = libnameversion.split("#"); + String libnameversion2 = split[0]; + if (split.length > 1) { + libnameversion2 = split[1]; + } + + // If we do not already have the native library file ... + String filename = loadedLibraries.get(libnameversion2); + UnsatisfiedLinkError loadError = null; + try { + for (URL url : urls) { + URI uri = url.toURI(); + File file; + try { + // ... and if the URL is not already a file without fragments, etc ... + file = new File(uri); + } catch (Exception exc) { + try { + file = new File(uri.getPath()); + if (file.exists()) { + // ... else preload it as some libraries do not like being renamed ... + String filename2 = file.getAbsolutePath(); + if (logger.isDebugEnabled()) { + logger.debug("Preloading " + filename2); + } + try { + System.load(filename2); + } catch (UnsatisfiedLinkError e) { + if (logger.isDebugEnabled()) { + logger.debug("Failed to preload " + filename2 + ": " + e); + } + } + } + } catch (Exception exc2) { + /// ... or give up and ... + } + // ... extract it from resources into the cache, if necessary ... + file = cacheResource(url, filename); + } + if (filename != null) { + return filename; + } else if (file != null && file.exists()) { + String filename2 = file.getAbsolutePath(); + try { + // ... and load it! + if (logger.isDebugEnabled()) { + logger.debug("Loading " + filename2); + } + loadedLibraries.put(libnameversion2, filename2); + System.load(filename2); + return filename2; + } catch (UnsatisfiedLinkError e) { + loadError = e; + loadedLibraries.remove(libnameversion2); + if (logger.isDebugEnabled()) { + logger.debug("Failed to load " + filename2 + ": " + e); + } + } + } + } + if (filename != null) { + return filename; + } else { + // ... or as last resort, try to load it via the system. + String libname = libnameversion.split("#")[0].split("@")[0]; + if (logger.isDebugEnabled()) { + logger.debug("Loading library " + libname); + } + loadedLibraries.put(libnameversion2, libname); + System.loadLibrary(libname); + return libname; + } + } catch (UnsatisfiedLinkError e) { + loadedLibraries.remove(libnameversion2); + if (loadError != null && e.getCause() == null) { + e.initCause(loadError); + } + if (logger.isDebugEnabled()) { + logger.debug("Failed to load for " + libnameversion + ": " + e); + } + throw e; + } catch (IOException | URISyntaxException ex) { + loadedLibraries.remove(libnameversion2); + if (loadError != null && ex.getCause() == null) { + ex.initCause(loadError); + } + Error e = new UnsatisfiedLinkError(ex.toString()); + e.initCause(ex); + if (logger.isDebugEnabled()) { + logger.debug("Failed to extract for " + libnameversion + ": " + e); + } + throw e; + } + } + + /** + * Contains {@code offsetof()} and {@code sizeof()} values of native types + * of {@code struct}, {@code class}, and {@code union}. A {@link WeakHashMap} + * is used to prevent the Loader from hanging onto Class objects the user may + * be trying to unload. + */ + static WeakHashMap,HashMap> memberOffsets = + new WeakHashMap,HashMap>(); + + /** + * Called by native libraries to put {@code offsetof()} and {@code sizeof()} values in {@link #memberOffsets}. + * Tries to load the Class object for typeName using the {@link ClassLoader} of the Loader. + * + * @param typeName the name of the peer Class acting as interface to the native type + * @param member the name of the native member variable (can be null to retrieve the Class object only) + * @param offset the value of {@code offsetof()} (or {@code sizeof()} when {@code member.equals("sizeof")}) + * @return {@code Class.forName(typeName, false)} + * @throws ClassNotFoundException on Class initialization failure + */ + static Class putMemberOffset(String typeName, String member, int offset) throws ClassNotFoundException { + Class c = Class.forName(typeName.replace('/', '.'), false, Loader.class.getClassLoader()); + if (member != null) { + putMemberOffset(c.asSubclass(Pointer.class), member, offset); + } + return c; + } + /** + * Called by native libraries to put {@code offsetof()} and {@code sizeof()} values in {@link #memberOffsets}. + * + * @param type the peer Class acting as interface to the native type + * @param member the name of the native member variable + * @param offset the value of {@code offsetof()} (or {@code sizeof()} when {@code member.equals("sizeof")}) + */ + static synchronized void putMemberOffset(Class type, String member, int offset) { + HashMap offsets = memberOffsets.get(type); + if (offsets == null) { + memberOffsets.put(type, offsets = new HashMap()); + } + offsets.put(member, offset); + } + + /** + * Gets {@code offsetof()} values from {@link #memberOffsets} filled by native libraries. + * + * @param type the peer Class acting as interface to the native type + * @param member the name of the native member variable + * @return {@code memberOffsets.get(type).get(member)} + */ + public static int offsetof(Class type, String member) { + // Should we synchronize that? + return memberOffsets.get(type).get(member); + } + + /** + * Gets {@code sizeof()} values from {@link #memberOffsets} filled by native libraries. + * + * @param type the peer Class acting as interface to the native type + * @return {@code memberOffsets.get(type).get("sizeof")} + */ + public static int sizeof(Class type) { + // Should we synchronize that? + return memberOffsets.get(type).get("sizeof"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getCacheDir()` could be null and is dereferenced at line 334. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +File Loader.cacheResource(URL,String) + +### Procedure Id: +org.bytedeco.javacpp.Loader.cacheResource(java.net.URL,java.lang.String):java.io.File.1db15ef41d1c8fd0fba2a3808458641b + +### File: +src/main/java/org/bytedeco/javacpp/Loader.java + +### Key: +Loader.java|cacheResource|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +05c6bfc6feb2d3dfcf91ac8ac1b0d013 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9289/instruction.md b/inferredbugs-9289/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..118fc20e35af24adfbadc857522370c46a8221ba --- /dev/null +++ b/inferredbugs-9289/instruction.md @@ -0,0 +1,794 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** javacpp +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (C) 2011,2012,2013 Samuel Audet + * + * This file is part of JavaCPP. + * + * JavaCPP is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version (subject to the "Classpath" exception + * as provided in the LICENSE.txt file that accompanied this code). + * + * JavaCPP is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with JavaCPP. If not, see . + */ + +package com.googlecode.javacpp; + +import com.googlecode.javacpp.annotation.Platform; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Map; +import java.util.MissingResourceException; +import java.util.Properties; +import java.util.WeakHashMap; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * The Loader contains functionality to load native libraries, but also has a bit + * of everything that does not fit anywhere else. In addition to its loading features, + * it also has utility methods to get the platform name and its properties from Java + * resources, to append to them properties from Class annotations, to extract file + * resources to the temporary directory, and to get the {@code offsetof()} or + * {@code sizeof()} a native {@code struct}, {@code class}, or {@code union} with + * its {@link Pointer} peer class and a {@link HashMap} initialized by the native libraries. + * + * @author Samuel Audet + */ +public class Loader { + + private static final Logger logger = Logger.getLogger(Loader.class.getName()); + + /** Platform name set and returned by {@link #getPlatformName()} and {@link #setPlatformName(String)}. */ + private static String platformName = null; + /** Default platform properties loaded and returned by {@link #getProperties()}. */ + private static Properties platformProperties = null; + + /** + * Creates a {@link #platformName} out of {@link System#getProperty(String)} if {@code null}. + * + * @return {@link #platformName} + */ + public static String getPlatformName() { + if (platformName != null) { + return platformName; + } + String jvmName = System.getProperty("java.vm.name").toLowerCase(); + String osName = System.getProperty("os.name").toLowerCase(); + String osArch = System.getProperty("os.arch").toLowerCase(); + if (jvmName.startsWith("dalvik") && osName.startsWith("linux")) { + osName = "android"; + } else if (osName.startsWith("mac os x")) { + osName = "macosx"; + } else { + int spaceIndex = osName.indexOf(' '); + if (spaceIndex > 0) { + osName = osName.substring(0, spaceIndex); + } + } + if (osArch.equals("i386") || osArch.equals("i486") || osArch.equals("i586") || osArch.equals("i686")) { + osArch = "x86"; + } else if (osArch.equals("amd64") || osArch.equals("x86-64")) { + osArch = "x86_64"; + } else if (osArch.startsWith("arm")) { + osArch = "arm"; + } + return platformName = osName + "-" + osArch; + } + /** + * Lets the user set {@link #platformName} in case {@link #getPlatformName()} gets it wrong. + * + * @param platformName value of the platformName + */ + public static void setPlatformName(String platformName) { + Loader.platformName = platformName; + Loader.platformProperties = null; + } + + /** + * Get the {@link Properties} associated with the default {@link #platformName}. + * + * @see #getProperties(String) + */ + public static Properties getProperties() { + if (platformProperties != null) { + return platformProperties; + } + return platformProperties = getProperties(getPlatformName()); + } + /** + * Get from resources the default {@link Properties} of the specified platform name. + * + * @param name the platform name + * @return the Properties from resources + */ + public static Properties getProperties(String name) { + Properties p = new Properties(); + p.put("platform.name", name); + name = "properties/" + name + ".properties"; + InputStream is = Loader.class.getResourceAsStream(name); + try { + try { + p.load(new InputStreamReader(is)); + } catch (NoSuchMethodError e) { + p.load(is); + } + } catch (Exception e) { + name = "properties/generic.properties"; + is = Loader.class.getResourceAsStream(name); + try { + try { + p.load(new InputStreamReader(is)); + } catch (NoSuchMethodError e2) { + p.load(is); + } + } catch (Exception e2) { + throw new MissingResourceException("Could not even get generic properties: " + + e2.getMessage(), Loader.class.getName(), name); + } + } + return p; + } + + /** + * Appends to properties the ones from Class annotations. If no properties are + * found on the class, makes a search for the first enclosing class with properties + * that we can use, appends those properties, and returns the enclosing Class used. + * + * @param properties the Properties to update + * @param cls the Class from which to take new Properties + * @return the actual enclosing Class on which we found the Properties + */ + public static Class appendProperties(Properties properties, Class cls) { + Class c = cls; + // Find first enclosing declaring class with some properties to use + while (c.getDeclaringClass() != null) { + if (c.isAnnotationPresent(com.googlecode.javacpp.annotation.Properties.class)) { + break; + } + if (c.isAnnotationPresent(Platform.class)) { + Platform p = c.getAnnotation(Platform.class); + if (p.define().length > 0 || p.include().length > 0 || p.cinclude().length > 0 || + p.includepath().length > 0 || p.options().length > 0 || p.linkpath().length > 0 || + p.link().length > 0 || p.framework().length > 0 || p.preloadpath().length > 0 || + p.preload().length > 0 || p.library().length() > 0) { + break; + } + } + c = c.getDeclaringClass(); + } + String platformName = properties.getProperty("platform.name"); + com.googlecode.javacpp.annotation.Properties classProperties = + c.getAnnotation(com.googlecode.javacpp.annotation.Properties.class); + Platform[] platforms; + if (classProperties == null) { + try { + Platform platform = c.getAnnotation(Platform.class); + if (platform == null) { + return c; + } else { + platforms = new Platform[] { platform }; + } + } catch (Throwable t) { + logger.log(Level.WARNING, "Could not append properties for " + c.getCanonicalName() + ": " + t); + return c; + } + } else { + platforms = classProperties.value(); + } + + String[] define = {}, include = {}, cinclude = {}, includepath = {}, options = {}, + linkpath = {}, link = {}, framework = {}, preloadpath = {}, preload = {}; + String library = "jni" + c.getSimpleName(); + for (Platform p : platforms) { + String[][] names = { p.value(), p.not() }; + boolean[] matches = { false, false }; + for (int i = 0; i < names.length; i++) { + for (String s : names[i]) { + if (platformName.startsWith(s)) { + matches[i] = true; + break; + } + } + } + if ((names[0].length == 0 || matches[0]) && (names[1].length == 0 || !matches[1])) { + if (p.define() .length > 0) { define = p.define(); } + if (p.include() .length > 0) { include = p.include(); } + if (p.cinclude() .length > 0) { cinclude = p.cinclude(); } + if (p.includepath().length > 0) { includepath = p.includepath(); } + if (p.options() .length > 0) { options = p.options(); } + if (p.linkpath() .length > 0) { linkpath = p.linkpath(); } + if (p.link() .length > 0) { link = p.link(); } + if (p.framework() .length > 0) { framework = p.framework(); } + if (p.preloadpath().length > 0) { preloadpath = p.preloadpath(); } + if (p.preload() .length > 0) { preload = p.preload(); } + if (p.library().length() > 0) { library = p.library(); } + } + } + + String s = properties.getProperty("path.separator"); + appendProperty(properties, "generator.define", "\u0000", define); + appendProperty(properties, "generator.include", "\u0000", include); + appendProperty(properties, "generator.cinclude", "\u0000", cinclude); + appendProperty(properties, "compiler.includepath", s, includepath); + if (options.length > 0) { + String defaultOptions = properties.getProperty("compiler.options"); + properties.setProperty("compiler.options", ""); + for (int i = 0; i < options.length; i++) { + String o = defaultOptions; + if (options[i].length() > 0 && ((o = properties.getProperty("compiler.options." + options[i])) == null)) { + logger.log(Level.WARNING, "Could not find a property name \"compiler.options." + options[i] + "\"."); + } else { + appendProperty(properties, "compiler.options", " ", o); + } + } + } + appendProperty(properties, "compiler.linkpath", s, linkpath); + appendProperty(properties, "compiler.link", s, link); + appendProperty(properties, "compiler.framework", s, framework); + appendProperty(properties, "loader.preloadpath", s, linkpath); + appendProperty(properties, "loader.preloadpath", s, preloadpath); + appendProperty(properties, "loader.preload", s, link); + appendProperty(properties, "loader.preload", s, preload); + properties.setProperty("loader.library", library); + return c; + } + + /** + * Appends new property values to a given key name of the properties. + * + * @param properties the Properties to update + * @param name the key name of the property to update + * @param separator the separator character to use for splitting and merging values + * @param values the property values to append, either an array or merged with separators + */ + public static void appendProperty(Properties properties, String name, + String separator, String ... values) { + if (values == null || values.length == 0) { + return; + } else if (values.length == 1 && values[0] != null) { + values = values[0].split(separator); + } + String oldValue = properties.getProperty(name, ""); + String[] oldValues = oldValue.split(separator); + String value = ""; + next: + for (String v : values) { + if (v == null || v.length() == 0) { + continue; + } + for (String ov : oldValues) { + if (v.equals(ov)) { + continue next; + } + } + if (value.length() > 0 && !value.endsWith(separator)) { + value += separator; + } + value += v; + } + if (value.length() > 0 && oldValue.length() > 0) { + value += separator; + } + properties.setProperty(name, value + oldValue); + } + + /** + * Returns the {@link Class} object that contains a caller's method. + * + * @param i the offset on the call stack of the method of interest + * @return the Class found from the calling context, or {@code null} if not found + */ + public static Class getCallerClass(int i) { + Class[] classContext = new SecurityManager() { + @Override public Class[] getClassContext() { + return super.getClassContext(); + } + }.getClassContext(); + if (classContext != null) { + for (int j = 0; j < classContext.length; j++) { + if (classContext[j] == Loader.class) { + return classContext[i+j]; + } + } + } else { + // SecurityManager.getClassContext() returns null on Android 4.0 + try { + StackTraceElement[] classNames = Thread.currentThread().getStackTrace(); + for (int j = 0; j < classNames.length; j++) { + if (Class.forName(classNames[j].getClassName()) == Loader.class) { + return Class.forName(classNames[i+j].getClassName()); + } + } + } catch (ClassNotFoundException e) { } + } + return null; + } + + /** + * Extracts by name a resource using the {@link ClassLoader} of the caller. + * + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #extractResource(URL, File, String, String) + */ + public static File extractResource(String name, File directory, + String prefix, String suffix) throws IOException { + Class cls = getCallerClass(2); + return extractResource(cls, name, directory, prefix, suffix); + } + /** + * Extracts by name a resource using the {@link ClassLoader} of the specified {@link Class}. + * + * @param cls the Class from which to load resources + * @param name the name of the resource passed to {@link Class#getResource(String)} + * @see #extractResource(URL, File, String, String) + */ + public static File extractResource(Class cls, String name, File directory, + String prefix, String suffix) throws IOException { + return extractResource(cls.getResource(name), directory, prefix, suffix); + } + /** + * Extracts a resource into the specified directory and with the specified + * prefix and suffix for the filename. If both prefix and suffix are {@code null}, + * the original filename is used, so the directory must not be {@code null}. + * + * @param resourceURL the URL of the resource to extract + * @param directory the output directory ({@code null == System.getProperty("java.io.tmpdir")}) + * @param prefix the prefix of the temporary filename to use + * @param suffix the suffix of the temporary filename to use + * @return the File object representing the extracted file + * @throws IOException if fails to extract resource properly + */ + public static File extractResource(URL resourceURL, File directory, + String prefix, String suffix) throws IOException { + InputStream is = resourceURL != null ? resourceURL.openStream() : null; + if (is == null) { + return null; + } + File file = null; + boolean fileExisted = false; + try { + if (prefix == null && suffix == null) { + if (directory == null) { + directory = new File(System.getProperty("java.io.tmpdir")); + } + file = new File(directory, new File(resourceURL.getPath()).getName()); + fileExisted = file.exists(); + } else { + file = File.createTempFile(prefix, suffix, directory); + } + FileOutputStream os = new FileOutputStream(file); + byte[] buffer = new byte[1024]; + int length; + while ((length = is.read(buffer)) != -1) { + os.write(buffer, 0, length); + } + is.close(); + os.close(); + } catch (IOException e) { + if (file != null && !fileExisted) { + file.delete(); + } + throw e; + } + return file; + } + + + /** Temporary directory set and returned by {@link #getTempDir()}. */ + static File tempDir = null; + /** Flag set by the {@link Builder} to tell us not to try to load anything. */ + static boolean loadLibraries = true; + /** Contains all the native libraries that we have loaded to avoid reloading them. */ + static Map loadedLibraries = Collections.synchronizedMap(new HashMap()); + + /** + * Creates a unique name for {@link #tempDir} out of + * {@code System.getProperty("java.io.tmpdir")} and {@code System.nanoTime()}. + * + * @return {@link #tempDir} + */ + public static File getTempDir() { + if (tempDir == null) { + File tmpdir = new File(System.getProperty("java.io.tmpdir")); + File f = null; + for (int i = 0; i < 1000; i++) { + f = new File(tmpdir, "javacpp" + System.nanoTime()); + if (f.mkdir()) { + tempDir = f; + tempDir.deleteOnExit(); + break; + } + } + } + return tempDir; + } + + /** @return {@link #loadLibraries} */ + public static boolean isLoadLibraries() { + return loadLibraries; + } + + /** + * Loads native libraries associated with the {@link Class} of the caller. + * @see #load(Class) + */ + public static String load() { + Class cls = getCallerClass(2); + return load(cls); + } + /** + * Loads native libraries associated with the given {@link Class}. + * + * @param cls the Class to get native library information from + * @return the full path of the file, or the library name, loaded + * (but {@code if (!loadLibraries || cls == null) { return null; }}) + * @throws NoClassDefFoundError on Class initialization failure + * @throws UnsatisfiedLinkError on native library loading failure + */ + public static String load(Class cls) { + if (!loadLibraries || cls == null) { + return null; + } + + // Find the top enclosing class, to match the library filename + Properties p = (Properties)getProperties().clone(); + cls = appendProperties(p, cls); + + // Force initialization of the class in case it needs it + try { + cls = Class.forName(cls.getName(), true, cls.getClassLoader()); + } catch (ClassNotFoundException ex) { + Error e = new NoClassDefFoundError(ex.toString()); + e.initCause(ex); + throw e; + } + + // Preload native libraries desired by our class + String pathSeparator = p.getProperty("path.separator"); + String platformRoot = p.getProperty("platform.root"); + if (platformRoot != null && !platformRoot.endsWith(File.separator)) { + platformRoot += File.separator; + } + String preloadPath = p.getProperty("loader.preloadpath"); + String preloadLibraries = p.getProperty("loader.preload"); + UnsatisfiedLinkError preloadError = null; + if (preloadLibraries != null) { + String[] preloadPaths = preloadPath == null ? null : preloadPath.split(pathSeparator); + if (preloadPaths != null && platformRoot != null) { + for (int i = 0; i < preloadPaths.length; i++) { + if (!new File(preloadPaths[i]).isAbsolute()) { + preloadPaths[i] = platformRoot + preloadPaths[i]; + } + } + } + String[] libnames = preloadLibraries.split(pathSeparator); + for (int i = 0; i < libnames.length; i++) { + try { + loadLibrary(cls, preloadPaths, libnames[i]); + } catch (UnsatisfiedLinkError e) { + preloadError = e; + } + } + } + + try { + return loadLibrary(cls, null, p.getProperty("loader.library")); + } catch (UnsatisfiedLinkError e) { + if (preloadError != null) { + e.initCause(preloadError); + } + throw e; + } + } + + /** + * Tries to load library from the caller's {@link Class} resources or {@link System#loadLibrary(String)}. + * @see #loadLibrary(Class, String[], String) + */ + public static String loadLibrary(String libnameversion) { + Class cls = getCallerClass(2); + return loadLibrary(cls, null, libnameversion); + } + /** + * Tries to load library from the caller's {@link Class} resources, the paths, or {@link System#loadLibrary(String)}. + * @see #loadLibrary(Class, String[], String) + */ + public static String loadLibrary(String[] paths, String libnameversion) { + Class cls = getCallerClass(2); + return loadLibrary(cls, paths, libnameversion); + } + /** + * First tries to extract and load the library from the {@link Class} resources, + * but if fails, continues to try loading from the paths (if not {@code null}), + * and finally {@link System#loadLibrary(String)}. + * + * @param cls the Class whose package name and {@link ClassLoader} are used to extract from resources + * @param paths the directories to scan for if we fail to extract the library from resources + * @param libnameversion the name of the library + "@" + optional version tag + * @return the full path of the file, or the library name, loaded + * (but {@code if (!loadLibraries || cls == null) { return null; }}) + * @throws UnsatisfiedLinkError on failure + */ + public static String loadLibrary(Class cls, String[] paths, String libnameversion) { + if (!loadLibraries || cls == null) { + return null; + } + String className = cls.getName(); + int packageIndex = className.lastIndexOf('.'); + String packageName = packageIndex != -1 ? className.substring(0, packageIndex + 1) : ""; + String hashkey = packageName + libnameversion; + + // If we do not already have the native library file ... + String filename = loadedLibraries.get(hashkey); + if (filename != null) { + return filename; + } + + String[] s = libnameversion.split("@"); + String libname = s[0]; + String version = s.length > 1 ? s[s.length-1] : ""; + + Properties p = getProperties(); + String subdir = p.getProperty("platform.name") + '/'; + String prefix = p.getProperty("library.prefix") + libname; + String suffix = p.getProperty("library.suffix"); + URL resourceURL = cls.getResource(subdir + prefix + suffix + version); // Linux style + if (resourceURL == null) { + resourceURL = cls.getResource(subdir + prefix + version + suffix); // Mac OS X style + } + if (resourceURL == null) { + resourceURL = cls.getResource(subdir + prefix + suffix); // without version + } + + File tempFile = null; + UnsatisfiedLinkError loadError = null; + try { + if (resourceURL != null) { + // ... then extract it from our resources ... + tempFile = extractResource(resourceURL, getTempDir(), null, null); + // ... and load it! + String tempFilename = tempFile.getAbsolutePath(); + loadedLibraries.put(hashkey, tempFilename); + System.load(tempFilename); + return tempFilename; + } else { + // throw new UnsatisfiedLinkError("Could not find library resource: " + resourceName); + // If not found in resources, search the paths instead ... + for (int j = 0; paths != null && j < paths.length; j++) { + File file = new File(paths[j], prefix + suffix + version); // Linux style + if (!file.exists()) { + file = new File(paths[j], prefix + version + suffix); // Mac OS X style + } + if (!file.exists()) { + file = new File(paths[j], prefix + suffix); // without version + } + if (file.exists()) { + filename = file.getPath(); + try { + loadedLibraries.put(hashkey, filename); + System.load(filename); + return filename; + } catch (UnsatisfiedLinkError e) { + loadError = e; + loadedLibraries.remove(hashkey); + } + } + } + // ... or as last resort, try to load it via the system. + loadedLibraries.put(hashkey, libname); + System.loadLibrary(libname); + return libname; + } + } catch (UnsatisfiedLinkError e) { + loadedLibraries.remove(hashkey); + if (loadError != null) { + throw loadError; + } else { + throw e; + } + } catch (IOException ex) { + loadedLibraries.remove(hashkey); + Error e = new UnsatisfiedLinkError(ex.toString()); + e.initCause(ex); + throw e; + } finally { + if (tempFile != null && tempFile.exists()) { + tempFile.deleteOnExit(); + } + // But under Windows, it won't get deleted! + } + } + + // So, let's use a shutdown hook... + static { + if (getPlatformName().startsWith("windows")) { + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override public void run() { + if (tempDir == null) { + return; + } + try { + // ... to launch a separate process ... + LinkedList command = new LinkedList(); + command.add(System.getProperty("java.home") + "/bin/java"); + command.add("-classpath"); + command.add(System.getProperty("java.class.path")); + command.add(Loader.class.getName()); + command.add(tempDir.getAbsolutePath()); + new ProcessBuilder(command).start(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + }); + } + } + + // ... that makes sure to delete all our files. + public static void main(String[] args) { + File tmpdir = new File(System.getProperty("java.io.tmpdir")); + File tempDir = new File(args[0]); + if (!tmpdir.equals(tempDir.getParentFile()) || + !tempDir.getName().startsWith("javacpp")) { + // Someone is trying to break us ... ? + return; + } + for (File file : tempDir.listFiles()) { + while (file.exists() && !file.delete()) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { } + } + } + tempDir.delete(); + } + + + /** + * Contains {@code offsetof()} and {@code sizeof()} values of native types + * of {@code struct}, {@code class}, and {@code union}. A {@link WeakHashMap} + * is used to prevent the Loader from hanging onto Class objects the user may + * be trying to unload. + */ + static WeakHashMap,HashMap> memberOffsets = + new WeakHashMap,HashMap>(); + + /** + * Called by native libraries to put {@code offsetof()} and {@code sizeof()} values in {@link #memberOffsets}. + * Tries to load the Class object for typeName using the {@link ClassLoader} of the Loader. + * + * @param typeName the name of the peer Class acting as interface to the native type + * @param member the name of the native member variable + * @param offset the value of {@code offsetof()} (or {@code sizeof()} when {@code member.equals("sizeof")}) + * @throws ClassNotFoundException on Class initialization failure + */ + static void putMemberOffset(String typeName, String member, int offset) throws ClassNotFoundException { + Class c = Class.forName(typeName.replace('/', '.'), false, Loader.class.getClassLoader()); + putMemberOffset(c.asSubclass(Pointer.class), member, offset); + } + /** + * Called by native libraries to put {@code offsetof()} and {@code sizeof()} values in {@link #memberOffsets}. + * + * @param type the peer Class acting as interface to the native type + * @param member the name of the native member variable + * @param offset the value of {@code offsetof()} (or {@code sizeof()} when {@code member.equals("sizeof")}) + */ + static synchronized void putMemberOffset(Class type, String member, int offset) { + HashMap offsets = memberOffsets.get(type); + if (offsets == null) { + memberOffsets.put(type, offsets = new HashMap()); + } + offsets.put(member, offset); + } + + /** + * Gets {@code offsetof()} values from {@link #memberOffsets} filled by native libraries. + * + * @param type the peer Class acting as interface to the native type + * @param member the name of the native member variable + * @return {@code memberOffsets.get(type).get(member)} + */ + public static int offsetof(Class type, String member) { + // Should we synchronize that? + return memberOffsets.get(type).get(member); + } + + /** + * Gets {@code sizeof()} values from {@link #memberOffsets} filled by native libraries. + * + * @param type the peer Class acting as interface to the native type + * @return {@code memberOffsets.get(type).get("sizeof")} + */ + public static int sizeof(Class type) { + // Should we synchronize that? + return memberOffsets.get(type).get("sizeof"); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `libnames` last assigned on line 478 could be null and is dereferenced at line 479. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String Loader.load(Class) + +### Procedure Id: +com.googlecode.javacpp.Loader.load(java.lang.Class):java.lang.String.a5dffc349e316731f3aa2cac3cf0f4a4 + +### File: +src/main/java/com/googlecode/javacpp/Loader.java + +### Key: +Loader.java|load|NULL_DEREFERENCE + +### Node Key: +57a86cabad769b98ba4bb221beb4a196 + +### Hash: +ad71967a5de3a1142e593725e57f1241 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9331/instruction.md b/inferredbugs-9331/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d480d77bf77c026d1257d1162a0da5bcf12e81c --- /dev/null +++ b/inferredbugs-9331/instruction.md @@ -0,0 +1,158 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** HaloDB +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package amannaly; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.List; + +/** + * @author Arjun Mannaly + */ +public class DBRepairTest extends TestBase { + + @Test + public void testRepairDB() throws IOException { + String directory = Paths.get("tmp", "DBRepairTest", "testRepairDB").toString(); + + HaloDBOptions options = new HaloDBOptions(); + options.maxFileSize = 1024 * 1024; + + HaloDB db = getTestDB(directory, options); + int noOfRecords = 5 * 1024 + 512; + + List records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE); + + File latestDataFile = TestUtils.getLatestDataFile(directory); + + db.close(); + + // trick the db to think that there was an unclean shutdown. + DBMetaData dbMetaData = new DBMetaData(directory); + dbMetaData.setOpen(true); + dbMetaData.storeToFile(); + + db = getTestDBWithoutDeletingFiles(directory, options); + + // latest file should have been repaired and deleted. + Assert.assertFalse(latestDataFile.exists()); + + Assert.assertEquals(db.size(), noOfRecords); + for (Record r : records) { + Assert.assertEquals(db.get(r.getKey()), r.getValue()); + } + } + + @Test + public void testRepairDBWithCompaction() throws IOException, InterruptedException { + String directory = Paths.get("tmp", "DBRepairTest", "testRepairDBWithCompaction").toString(); + + HaloDBOptions options = new HaloDBOptions(); + options.maxFileSize = 1024 * 1024; + + HaloDB db = getTestDB(directory, options); + int noOfRecords = 5 * 1024 + 512; + + List records = TestUtils.insertRandomRecordsOfSize(db, noOfRecords, 1024-Record.Header.HEADER_SIZE); + records = TestUtils.updateRecords(db, records); + + TestUtils.waitForMergeToComplete(db); + + File latestDataFile = TestUtils.getLatestDataFile(directory); + File latestCompactionFile = TestUtils.getLatestCompactionFile(directory); + + db.close(); + + // trick the db to think that there was an unclean shutdown. + DBMetaData dbMetaData = new DBMetaData(directory); + dbMetaData.setOpen(true); + dbMetaData.storeToFile(); + + db = getTestDBWithoutDeletingFiles(directory, options); + + // latest file should have been repaired and deleted. + Assert.assertFalse(latestDataFile.exists()); + Assert.assertFalse(latestCompactionFile.exists()); + + Assert.assertEquals(db.size(), noOfRecords); + for (Record r : records) { + Assert.assertEquals(db.get(r.getKey()), r.getValue()); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `amannaly.cache.linked.OHCacheLinkedImpl` acquired by call to `getTestDB(...)` at line 23 is not released after line 37. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DBRepairTest.testRepairDB() + +### Procedure Id: +amannaly.DBRepairTest.testRepairDB():void.1e005b506a960a4d20d7e069dc4ebf7a + +### File: +src/test/java/amannaly/DBRepairTest.java + +### Key: +DBRepairTest.java|testRepairDB|RESOURCE_LEAK + +### Node Key: +d91afdc43fc8c30da782b7736b1a7f25 + +### Hash: +1745fbef088ed8981aa2d319cdae6b8a + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9412/instruction.md b/inferredbugs-9412/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a4b31aa2a9390d16e9c8fa108fad97c024ffd23 --- /dev/null +++ b/inferredbugs-9412/instruction.md @@ -0,0 +1,273 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** SonarTsPlugin +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.pablissimo.sonar; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.sonar.api.utils.System2; +import org.sonar.api.utils.TempFolder; +import org.sonar.api.utils.command.Command; +import org.sonar.api.utils.command.CommandExecutor; +import org.sonar.api.utils.command.StreamConsumer; +import org.sonar.api.utils.command.StringStreamConsumer; + +public class TsLintExecutorImpl implements TsLintExecutor { + public static final int MAX_COMMAND_LENGTH = 4096; + private static final Logger LOG = LoggerFactory.getLogger(TsLintExecutorImpl.class); + + private boolean mustQuoteSpaceContainingPaths = false; + private TempFolder tempFolder; + + public TsLintExecutorImpl(System2 system, TempFolder tempFolder) { + this.mustQuoteSpaceContainingPaths = system.isOsWindows(); + this.tempFolder = tempFolder; + } + + private String preparePath(String path) { + if (path == null) { + return null; + } + else if (path.contains(" ") && this.mustQuoteSpaceContainingPaths) { + return '"' + path + '"'; + } + else { + return path; + } + } + + private Command getBaseCommand(TsLintExecutorConfig config, String tempPath) { + Command command = + Command + .create("node") + .addArgument(this.preparePath(config.getPathToTsLint())) + .addArgument("--format") + .addArgument("json"); + + String rulesDir = config.getRulesDir(); + if (rulesDir != null && rulesDir.length() > 0) { + command + .addArgument("--rules-dir") + .addArgument(this.preparePath(rulesDir)); + } + + if (tempPath != null && tempPath.length() > 0) { + command + .addArgument("--out") + .addArgument(this.preparePath(tempPath)); + } + + command + .addArgument("--config") + .addArgument(this.preparePath(config.getConfigFile())); + + if (config.useTsConfigInsteadOfFileList()) { + command + .addArgument("--project") + .addArgument(this.preparePath(config.getPathToTsConfig())); + } + + if (config.shouldPerformTypeCheck()) { + command + .addArgument("--type-check"); + } + + command.setNewShell(false); + + return command; + } + + public List execute(TsLintExecutorConfig config, List files) { + if (config == null) { + throw new IllegalArgumentException("config"); + } + else if (files == null) { + throw new IllegalArgumentException("files"); + } + + // New up a command that's everything we need except the files to process + // We'll use this as our reference for chunking up files, if we need to + File tslintOutputFile = this.tempFolder.newFile(); + String tslintOutputFilePath = tslintOutputFile.getAbsolutePath(); + Command baseCommand = getBaseCommand(config, tslintOutputFilePath); + + LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath); + + StringStreamConsumer stdOutConsumer = new StringStreamConsumer(); + StringStreamConsumer stdErrConsumer = new StringStreamConsumer(); + + List toReturn = new ArrayList(); + + if (config.useTsConfigInsteadOfFileList()) { + LOG.debug("Running against a single project JSON file"); + + // If we're being asked to use a tsconfig.json file, it'll contain + // the file list to lint - so don't batch, and just run with it + toReturn.add(this.getCommandOutput(baseCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs())); + } + else { + int baseCommandLength = baseCommand.toCommandLine().length(); + int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength; + + List> batches = new ArrayList>(); + List currentBatch = new ArrayList(); + batches.add(currentBatch); + + int currentBatchLength = 0; + for (int i = 0; i < files.size(); i++) { + String nextPath = this.preparePath(files.get(i).trim()); + + // +1 for the space we'll be adding between filenames + if (currentBatchLength + nextPath.length() + 1 > availableForBatching) { + // Too long to add to this batch, create new + currentBatch = new ArrayList(); + currentBatchLength = 0; + batches.add(currentBatch); + } + + currentBatch.add(nextPath); + currentBatchLength += nextPath.length() + 1; + } + + LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing"); + + for (int i = 0; i < batches.size(); i++) { + StringBuilder outputBuilder = new StringBuilder(); + + List thisBatch = batches.get(i); + + Command thisCommand = getBaseCommand(config, tslintOutputFilePath); + + for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) { + thisCommand.addArgument(thisBatch.get(fileIndex)); + } + + LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); + + // Timeout is specified per file, not per batch (which can vary a lot) + // so multiply it up + toReturn.add(this.getCommandOutput(thisCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs() * thisBatch.size())); + } + } + + return toReturn; + } + + private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) { + LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine()); + + // Timeout is specified per file, not per batch (which can vary a lot) + // so multiply it up + this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs); + + StringBuilder outputBuilder = new StringBuilder(); + + try { + BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile); + + String str; + while ((str = reader.readLine()) != null) { + outputBuilder.append(str); + } + + reader.close(); + + return outputBuilder.toString(); + } + catch (IOException ex) { + LOG.error("Failed to re-read TsLint output", ex); + } + + return ""; + } + + protected BufferedReader getBufferedReaderForFile(File file) throws IOException { + return new BufferedReader( + new InputStreamReader( + new FileInputStream(file), "UTF8")); + } + + protected CommandExecutor createExecutor() { + return CommandExecutor.create(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `getBufferedReaderForFile(...)` at line 171 is not released after line 182. +**Note**: potential exception at line 174 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String TsLintExecutorImpl.getCommandOutput(Command,StreamConsumer,StreamConsumer,File,Integer) + +### Procedure Id: +com.pablissimo.sonar.TsLintExecutorImpl.getCommandOutput(org.sonar.api.utils.command.Command,org.son.ede58b405c239f2dedb3f9021019eff8 + +### File: +src/main/java/com/pablissimo/sonar/TsLintExecutorImpl.java + +### Key: +TsLintExecutorImpl.java|getCommandOutput|RESOURCE_LEAK + +### Node Key: +d54375129813b1c5d9f10eb00e12d6a9 + +### Hash: +7e40a9b9f79262bcaa75c1bdc11cd6c4 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9413/instruction.md b/inferredbugs-9413/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db5aa53a88b364b954198cda55b9ca04d92b4967 --- /dev/null +++ b/inferredbugs-9413/instruction.md @@ -0,0 +1,592 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.metrics.impl.MemoryCounterService; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.NbAppEventListener; +import org.nutz.boot.tools.NbAppEventListener.EventType; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.Mvcs; +import org.nutz.mvc.annotation.IocBy; +import org.nutz.resource.Scans; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock; + + protected List listeners = new LinkedList<>(); + + protected boolean started; + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + if (execute()) { + lock = new Object(); + synchronized (lock) { + lock.wait(); + } + } + // 收尾 + _shutdown(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + public boolean execute() { + Stopwatch sw = Stopwatch.begin(); + try { + // 各种预备操作 + listeners.forEach((listener)->listener.whenPrepare(this, EventType.before)); + this.prepare(); + listeners.forEach((listener)->listener.whenPrepare(this, EventType.after)); + + // 依次启动 + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.before)); + ctx.init(); + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.after)); + + listeners.forEach((listener)->listener.whenStartServers(this, EventType.before)); + ctx.startServers(); + listeners.forEach((listener)->listener.whenStartServers(this, EventType.after)); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + listeners.forEach((listener)->listener.afterAppStated(this)); + + sw.stop(); + log.infof("%s started : %sms", ctx.getConf().get("nutz.application.name", "NB"), sw.du()); + started = true; + return true; + } + catch (Throwable e) { + log.error("something happen!!", e); + return false; + } + } + + public void _shutdown() { + try { + ctx.stopServers(); + ctx.depose(); + } + catch (Exception e) { + throw Lang.wrapThrow(e); + } + } + + public void shutdown() { + log.info("ok, shutting down ..."); + if (lock == null) { + _shutdown(); + } + else { + synchronized (lock) { + lock.notify(); + } + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); + this.prepareBasic(); + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); + this.prepareConfigureLoader(); + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); + + // 创建IocLoader体系 + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); + prepareIocLoader(); + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); + + // 加载各种starter + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); + prepareStarterClassList(); + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); + + // 打印配置文档 + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(); + docReader.load(starterClasses); + if (getAppContext().getConf().get("nutz.propdoc.packages") != null) { + for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) { + for (Class klass : Scans.me().scanPackage(pkg)) { + if (klass.isInterface()) + continue; + docReader.addClass(klass); + } + } + } + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 创建Ioc容器 + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); + prepareIoc(); + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); + + // 生成Starter实例 + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); + prepareStarterInstance(); + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); + + // 从Ioc容器检索Listener + listeners.addAll(ctx.getBeans(NbAppEventListener.class)); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + ConfigureLoader configureLoader = null; + InputStream ins = ctx.getResourceLoader().get("META-INF/nutz/org.nutz.boot.config.ConfigureLoader"); + if (ins != null) { + String cnfLoader = new String(Streams.readBytes(ins)).trim(); + if (!Strings.isBlank(cnfLoader)) { + log.debugf("using %s as ConfigureLoader", cnfLoader); + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + } + if (configureLoader == null) { + configureLoader = new PropertiesConfigureLoader(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + ctx.ioc.addBean("appContext", ctx); + ctx.ioc.addBean("conf", ctx.getConf()); + ctx.ioc.addBean("nbApp", this); + // 添加更多扩展bean + ctx.ioc.addBean("counterService", new MemoryCounterService()); + } + Mvcs.ctx().iocs.put("nutz", ctx.getIoc()); + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + continue; + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + continue; + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + + public void setListener(NbAppEventListener listener) { + this.listeners.clear(); + addListener(listener); + } + + public void addListener(NbAppEventListener listener) { + this.listeners.add(listener); + } + + public boolean isStarted() { + return started; + } + + public NbApp setMainPackage(String mainPackage) { + getAppContext().setMainPackage(mainPackage); + return this; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepareStarterClassList` reads without synchronization from `this.org.nutz.boot.NbApp.starterClasses`. Potentially races with write in method `NbApp.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareStarterClassList() + +### Procedure Id: +org.nutz.boot.NbApp.prepareStarterClassList():void.13b0567fe7050a0853d221c42bbf6e2a + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareStarterClassList|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e728747110b6203aaab2c3800c50ca91 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9414/instruction.md b/inferredbugs-9414/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5bb448c5393aeafee5d41b2dc31bce82bd20e8c --- /dev/null +++ b/inferredbugs-9414/instruction.md @@ -0,0 +1,601 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 33 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.metrics.impl.MemoryCounterService; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.NbAppEventListener; +import org.nutz.boot.tools.NbAppEventListener.EventType; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.Mvcs; +import org.nutz.mvc.annotation.IocBy; +import org.nutz.resource.Scans; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses = new LinkedList<>(); + + protected boolean prepared; + + protected Object lock; + + protected List listeners = new LinkedList<>(); + + protected boolean started; + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + if (execute()) { + lock = new Object(); + synchronized (lock) { + lock.wait(); + } + } + // 收尾 + _shutdown(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + public boolean execute() { + Stopwatch sw = Stopwatch.begin(); + try { + // 各种预备操作 + listeners.forEach((listener)->listener.whenPrepare(this, EventType.before)); + this.prepare(); + listeners.forEach((listener)->listener.whenPrepare(this, EventType.after)); + + // 依次启动 + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.before)); + ctx.init(); + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.after)); + + listeners.forEach((listener)->listener.whenStartServers(this, EventType.before)); + ctx.startServers(); + listeners.forEach((listener)->listener.whenStartServers(this, EventType.after)); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + listeners.forEach((listener)->listener.afterAppStated(this)); + + sw.stop(); + log.infof("%s started : %sms", ctx.getConf().get("nutz.application.name", "NB"), sw.du()); + started = true; + return true; + } + catch (Throwable e) { + log.error("something happen!!", e); + return false; + } + } + + public void _shutdown() { + try { + ctx.stopServers(); + ctx.depose(); + } + catch (Exception e) { + throw Lang.wrapThrow(e); + } + } + + public void shutdown() { + log.info("ok, shutting down ..."); + if (lock == null) { + _shutdown(); + } + else { + synchronized (lock) { + lock.notify(); + } + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); + this.prepareBasic(); + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); + this.prepareConfigureLoader(); + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); + + // 创建IocLoader体系 + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); + prepareIocLoader(); + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); + + // 加载各种starter + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); + prepareStarterClassList(); + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); + + // 打印配置文档 + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(); + docReader.load(starterClasses); + if (getAppContext().getConf().get("nutz.propdoc.packages") != null) { + for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) { + for (Class klass : Scans.me().scanPackage(pkg)) { + if (klass.isInterface()) + continue; + docReader.addClass(klass); + } + } + } + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 创建Ioc容器 + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); + prepareIoc(); + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); + + // 生成Starter实例 + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); + prepareStarterInstance(); + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); + + // 从Ioc容器检索Listener + listeners.addAll(ctx.getBeans(NbAppEventListener.class)); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + ConfigureLoader configureLoader = null; + InputStream ins = ctx.getResourceLoader().get("META-INF/nutz/org.nutz.boot.config.ConfigureLoader"); + if (ins != null) { + String cnfLoader = new String(Streams.readBytes(ins)).trim(); + if (!Strings.isBlank(cnfLoader)) { + log.debugf("using %s as ConfigureLoader", cnfLoader); + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + } + if (configureLoader == null) { + configureLoader = new PropertiesConfigureLoader(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + ctx.ioc.addBean("appContext", ctx); + ctx.ioc.addBean("conf", ctx.getConf()); + ctx.ioc.addBean("nbApp", this); + // 添加更多扩展bean + ctx.ioc.addBean("counterService", new MemoryCounterService()); + } + Mvcs.ctx().iocs.put("nutz", ctx.getIoc()); + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + continue; + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + continue; + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + + public void setListener(NbAppEventListener listener) { + this.listeners.clear(); + addListener(listener); + } + + public void addListener(NbAppEventListener listener) { + this.listeners.add(listener); + } + + public boolean isStarted() { + return started; + } + + public NbApp setMainPackage(String mainPackage) { + getAppContext().setMainPackage(mainPackage); + return this; + } + + public List> getStarterClasses() { + return starterClasses; + } + + public NbApp addStarterClass(Class klass) { + if (klass != null) + starterClasses.add(klass); + return this; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp.prepare` indirectly reads without synchronization from `boot.NbApp.org.nutz.boot.NbApp.log`. Potentially races with write in method `NbApp.run()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepare() + +### Procedure Id: +org.nutz.boot.NbApp.prepare():void.3497bd920679b1a589201156049c849c + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepare|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e880f8ca93929122c5fb749e626a653c + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9415/instruction.md b/inferredbugs-9415/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eaf229634b0d659e6d320a24c752d22c37e66b00 --- /dev/null +++ b/inferredbugs-9415/instruction.md @@ -0,0 +1,497 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 20 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建IocLoader体系 + prepareIocLoader(); + + // 加载各种starter + prepareStarterClassList(); + + // 创建Ioc容器 + prepareIoc(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + Ioc2 ioc2 = (Ioc2) ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf())); + ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this)); + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.nutz.boot.NbApp._run` reads without synchronization from `boot.NbApp.org.nutz.boot.NbApp.log`. Potentially races with write in method `NbApp.run()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp._run() + +### Procedure Id: +org.nutz.boot.NbApp._run():void.3641f60336c24c77461f31b034e2a838 + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|_run|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +db6b06d34e5b43713e8ec8650d4485c7 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9422/instruction.md b/inferredbugs-9422/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..01976671a806a2e308689abd61fb1e329c72333b --- /dev/null +++ b/inferredbugs-9422/instruction.md @@ -0,0 +1,485 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 16 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf())); + ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this)); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.nutz.boot.NbApp.prepareIoc` indirectly writes to field `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.comboIocLoader` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareIoc() + +### Procedure Id: +org.nutz.boot.NbApp.prepareIoc():void.674739fecc4139c35432600c7c9226d8 + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareIoc|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +bc6681f20569d4b864442a1f7f5d1860 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9423/instruction.md b/inferredbugs-9423/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49f5146f6927ad7b19744173aff6d09f62b2b2aa --- /dev/null +++ b/inferredbugs-9423/instruction.md @@ -0,0 +1,481 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.Ioc2; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.ObjectProxy; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 主启动器类,必须设置 + */ + protected Class mainClass; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * @param mainClass 主启动类 + */ + public NbApp(Class mainClass) { + this.mainClass = mainClass; + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.mainClass = mainClass; + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * @param flag 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + _run(); + } catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + /** + * 启动整个NbApp + */ + public void _run() throws Exception { + Stopwatch sw = Stopwatch.begin(); + + // 各种预备操作 + this.prepare(); + + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(ctx); + docReader.load(); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 依次启动 + try { + ctx.init(); + + ctx.startServers(); + + if (mainClass.getAnnotation(IocBean.class) != null) + ctx.getIoc().get(mainClass); + + sw.stop(); + log.infof("NB started : %sms", sw.du()); + synchronized (lock) { + lock.wait(); + } + } + catch (Throwable e) { + log.error("something happen!!", e); + } + // 收尾 + ctx.stopServers(); + ctx.depose(); + } + + public void shutdown() { + log.info("ok, shutting down ..."); + synchronized (lock) { + lock.notify(); + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + this.prepareBasic(); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + this.prepareConfigureLoader(); + + // 创建Ioc容器 + prepareIoc(); + + // 加载各种starter + prepareStarterClassList(); + + // 生成Starter实例 + prepareStarterInstance(); + + prepared = true; + } + + public void prepareBasic() throws Exception { + if (this.ctx == null) { + ctx = AppContext.getDefault(); + } + if (ctx.getMainClass() == null && mainClass != null) + ctx.setMainClass(mainClass); + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + String cnfLoader = ctx.getEnvHolder().get("nutz.boot.base.ConfigureLoader"); + ConfigureLoader configureLoader; + if (Strings.isBlank(cnfLoader)) { + configureLoader = new PropertiesConfigureLoader(); + } else { + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIoc() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add(""+asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i=0;i 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")){ + Ioc2 ioc2 = (Ioc2)ctx.getIoc(); + ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); + ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); + } + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } + else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.nutz.boot.NbApp.prepareBasic` indirectly writes to field `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.classLoader` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +Note that the prefix path this.org.nutz.boot.NbApp.ctx has been contaminated during the execution, so the reported race on this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.classLoader might be a false positive. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepareBasic() + +### Procedure Id: +org.nutz.boot.NbApp.prepareBasic():void.dd6da23e2d20c27b6fe908f129d9169b + +### File: +nutzboot-starter/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepareBasic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +276ba1e8cf34b1e75c5a1aef27bfaa7f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9424/instruction.md b/inferredbugs-9424/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..60ac347860d53c3f8aa903bd7df472d5fb2f24ac --- /dev/null +++ b/inferredbugs-9424/instruction.md @@ -0,0 +1,580 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** nutzboot +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.nutz.boot; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; + +import org.nutz.boot.aware.AppContextAware; +import org.nutz.boot.aware.ClassLoaderAware; +import org.nutz.boot.aware.EnvHolderAware; +import org.nutz.boot.aware.IocAware; +import org.nutz.boot.aware.ResourceLoaderAware; +import org.nutz.boot.banner.SimpleBannerPrinter; +import org.nutz.boot.config.ConfigureLoader; +import org.nutz.boot.config.impl.PropertiesConfigureLoader; +import org.nutz.boot.env.SystemPropertiesEnvHolder; +import org.nutz.boot.ioc.IocLoaderProvider; +import org.nutz.boot.metrics.impl.MemoryCounterService; +import org.nutz.boot.resource.ResourceLoader; +import org.nutz.boot.resource.impl.SimpleResourceLoader; +import org.nutz.boot.tools.NbAppEventListener; +import org.nutz.boot.tools.NbAppEventListener.EventType; +import org.nutz.boot.tools.PropDocReader; +import org.nutz.ioc.IocLoader; +import org.nutz.ioc.impl.NutIoc; +import org.nutz.ioc.loader.annotation.AnnotationIocLoader; +import org.nutz.ioc.loader.annotation.IocBean; +import org.nutz.ioc.loader.combo.ComboIocLoader; +import org.nutz.lang.Lang; +import org.nutz.lang.Mirror; +import org.nutz.lang.Stopwatch; +import org.nutz.lang.Streams; +import org.nutz.lang.Strings; +import org.nutz.lang.util.LifeCycle; +import org.nutz.log.Log; +import org.nutz.log.LogAdapter; +import org.nutz.log.Logs; +import org.nutz.mvc.Mvcs; +import org.nutz.mvc.annotation.IocBy; + +/** + * NutzBoot的主体 + * + * @author wendal + * + */ +public class NbApp extends Thread { + + /** + * 日志属性要等日志适配器准备好了才能加载,这里不可以使用Logs.get(); + */ + protected static Log log; + + /** + * 命令行参数 + */ + protected String[] args; + + /** + * 是否允许命令行下的 -Dxxx.xxx.xxx=转为配置参数 + */ + protected boolean allowCommandLineProperties = true; + + /** + * 是否打印配置文档 + */ + protected boolean printProcDoc; + + /** + * 主上下文 + */ + protected AppContext ctx; + + /** + * Starter共享的IocLoader + */ + protected AnnotationIocLoader starterIocLoader; + + /** + * Starter类列表 + */ + protected List> starterClasses; + + protected boolean prepared; + + protected Object lock = new Object(); + + protected List listeners = new LinkedList<>(); + + protected boolean started; + + /** + * 创建一个NbApp,把调用本构造方法的类作为mainClass + */ + public NbApp() { + ctx = AppContext.getDefault(); + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + /** + * 基于mainClass创建一个NbApp + * + * @param mainClass + * 主启动类 + */ + public NbApp(Class mainClass) { + ctx = AppContext.getDefault(); + setMainClass(mainClass); + } + + public NbApp(AppContext ctx) { + this.ctx = ctx; + StackTraceElement[] ts = Thread.currentThread().getStackTrace(); + if (ts.length > 2) { + setMainClass(Lang.loadClassQuite(ts[2].getClassName())); + } + } + + public NbApp(AppContext ctx, Class mainClass) { + this.ctx = ctx; + setMainClass(mainClass); + } + + /** + * 设置命令行参数,可选 + */ + public NbApp setArgs(String[] args) { + this.args = args; + return this; + } + + /** + * 设置主启动类 + */ + public NbApp setMainClass(Class mainClass) { + this.ctx.setMainClass(mainClass); + return this; + } + + /** + * 是否允许从命令行读取配置信息, 例如 java -Dnutz.ioc.async.poolSize=128 xxx.jar + * + * @param flag + * 默认允许 + */ + public NbApp setAllowCommandLineProperties(boolean flag) { + this.allowCommandLineProperties = flag; + return this; + } + + /** + * 是否打印配置文档 + */ + public NbApp setPrintProcDoc(boolean printProcDoc) { + this.printProcDoc = printProcDoc; + return this; + } + + /** + * 获取全局上下文 + * + * @return + */ + public AppContext getAppContext() { + return ctx; + } + + public void run() { + try { + if (execute()) { + synchronized (lock) { + lock.wait(); + } + } + // 收尾 + _shutdown(); + } + catch (Throwable e) { + Logs.get().error("something happen", e); + } + } + + public boolean execute() { + Stopwatch sw = Stopwatch.begin(); + try { + // 各种预备操作 + listeners.forEach((listener)->listener.whenPrepare(this, EventType.before)); + this.prepare(); + listeners.forEach((listener)->listener.whenPrepare(this, EventType.after)); + + // 依次启动 + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.before)); + ctx.init(); + listeners.forEach((listener)->listener.whenInitAppContext(this, EventType.after)); + + listeners.forEach((listener)->listener.whenStartServers(this, EventType.before)); + ctx.startServers(); + listeners.forEach((listener)->listener.whenStartServers(this, EventType.after)); + + if (ctx.getMainClass().getAnnotation(IocBean.class) != null) + ctx.getIoc().get(ctx.getMainClass()); + + listeners.forEach((listener)->listener.afterAppStated(this)); + + sw.stop(); + log.infof("%s started : %sms", ctx.getConf().get("nutz.application.name", "NB"), sw.du()); + started = true; + return true; + } + catch (Throwable e) { + log.error("something happen!!", e); + return false; + } + } + + public void _shutdown() { + try { + ctx.stopServers(); + ctx.depose(); + } + catch (Exception e) { + throw Lang.wrapThrow(e); + } + } + + public void shutdown() { + log.info("ok, shutting down ..."); + if (lock == null) { + _shutdown(); + } + else { + synchronized (lock) { + lock.notify(); + } + } + } + + /** + * 执行预备操作 + */ + public void prepare() throws Exception { + if (prepared) + return; + // 初始化上下文 + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); + this.prepareBasic(); + listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); + + // 打印Banner,暂时不可配置具体的类 + new SimpleBannerPrinter().printBanner(ctx); + + // 配置信息要准备好 + + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); + this.prepareConfigureLoader(); + listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); + + // 创建IocLoader体系 + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); + prepareIocLoader(); + listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); + + // 加载各种starter + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); + prepareStarterClassList(); + listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); + + // 打印配置文档 + if (printProcDoc) { + PropDocReader docReader = new PropDocReader(); + docReader.load(starterClasses); + Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); + } + + // 创建Ioc容器 + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); + prepareIoc(); + listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); + + // 生成Starter实例 + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); + prepareStarterInstance(); + listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); + + // 从Ioc容器检索Listener + listeners.addAll(ctx.getBeans(NbAppEventListener.class)); + + prepared = true; + } + + public void prepareBasic() throws Exception { + // 检查ClassLoader的情况 + if (ctx.getClassLoader() == null) + ctx.setClassLoader(NbApp.class.getClassLoader()); + + if (ctx.getEnvHolder() == null) { + ctx.setEnvHolder(new SystemPropertiesEnvHolder()); + } + + // 看看日志应该用哪个 + String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); + if (!Strings.isBlank(logAdapter)) { + Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); + } + log = Logs.get(); + // 资源加载器 + if (ctx.getResourceLoader() == null) { + ResourceLoader resourceLoader = new SimpleResourceLoader(); + aware(resourceLoader); + ctx.setResourceLoader(resourceLoader); + } + } + + public void prepareConfigureLoader() throws Exception { + if (ctx.getConfigureLoader() == null) { + ConfigureLoader configureLoader = null; + InputStream ins = ctx.getResourceLoader().get("META-INF/nutz/org.nutz.boot.config.ConfigureLoader"); + if (ins != null) { + String cnfLoader = new String(Streams.readBytes(ins)).trim(); + if (!Strings.isBlank(cnfLoader)) { + log.debugf("using %s as ConfigureLoader", cnfLoader); + configureLoader = (ConfigureLoader) ctx.getClassLoader().loadClass(cnfLoader).newInstance(); + } + } + if (configureLoader == null) { + configureLoader = new PropertiesConfigureLoader(); + } + configureLoader.setCommandLineProperties(allowCommandLineProperties, args); + aware(configureLoader); + ctx.setConfigureLoader(configureLoader); + if (configureLoader instanceof LifeCycle) + ((LifeCycle) configureLoader).init(); + } + } + + public void prepareIocLoader() throws Exception { + if (ctx.getComboIocLoader() == null) { + int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); + List args = new ArrayList<>(); + args.add("*js"); + args.add("ioc/"); + args.add("*tx"); + args.add("*async"); + args.add("" + asyncPoolSize); + args.add("*anno"); + args.add(ctx.getPackage()); + IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); + if (iocBy != null) { + String[] tmp = iocBy.args(); + ArrayList _args = new ArrayList<>(); + for (int i = 0; i < tmp.length; i++) { + if (tmp[i].startsWith("*")) { + if (!_args.isEmpty()) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + _args.clear(); + } + } + _args.add(tmp[i]); + } + if (_args.size() > 0) { + switch (_args.get(0)) { + case "*tx": + case "*async": + case "*anno": + case "*js": + break; + default: + args.addAll(_args); + } + } + } + ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); + } + // 用于加载Starter的IocLoader + starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); + ctx.getComboIocLoader().addLoader(starterIocLoader); + } + + public void prepareStarterClassList() throws Exception { + starterClasses = new ArrayList<>(); + HashSet classNames = new HashSet<>(); + Enumeration _en = ctx.getClassLoader().getResources("META-INF/nutz/org.nutz.boot.starter.NbStarter"); + while (_en.hasMoreElements()) { + URL url = _en.nextElement(); + log.debug("Found " + url); + try (InputStream ins = url.openStream()) { + InputStreamReader reader = new InputStreamReader(ins); + String tmp = Streams.readAndClose(reader); + if (!Strings.isBlank(tmp)) { + for (String _tmp : Strings.splitIgnoreBlank(tmp, "[\n]")) { + String className = _tmp.trim(); + if (!classNames.add(className)) + continue; + Class klass = ctx.getClassLoader().loadClass(className); + if (!klass.getPackage().getName().startsWith(NbApp.class.getPackage().getName()) && klass.getAnnotation(IocBean.class) != null) { + starterIocLoader.addClass(klass); + } + starterClasses.add(klass); + } + } + } + } + } + + public void prepareIoc() { + if (ctx.getIoc() == null) { + ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); + } + // 把核心对象放进ioc容器 + if (!ctx.ioc.has("appContext")) { + ctx.ioc.addBean("appContext", ctx); + ctx.ioc.addBean("conf", ctx.getConf()); + ctx.ioc.addBean("nbApp", this); + // 添加更多扩展bean + ctx.ioc.addBean("counterService", new MemoryCounterService()); + } + Mvcs.ctx().iocs.put("nutz", ctx.getIoc()); + } + + public void prepareStarterInstance() { + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + obj = Mirror.me(klass).born(); + } else { + continue; + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + for (Class klass : starterClasses) { + Object obj; + if (klass.getAnnotation(IocBean.class) == null) { + continue; + } else { + obj = ctx.getIoc().get(klass); + } + aware(obj); + if (obj instanceof IocLoaderProvider) { + IocLoader loader = ((IocLoaderProvider) obj).getIocLoader(); + ctx.getComboIocLoader().addLoader(loader); + } + ctx.addStarter(obj); + } + } + + protected void aware(Object obj) { + // 需要注入AppContext + if (obj instanceof AppContextAware) { + ((AppContextAware) obj).setAppContext(ctx); + } + // 需要注入ClassLoader + if (obj instanceof ClassLoaderAware) { + ((ClassLoaderAware) obj).setClassLoader(ctx.getClassLoader()); + } + // 需要注入EnvHolder + if (obj instanceof EnvHolderAware) { + ((EnvHolderAware) obj).setEnvHolder(ctx.getEnvHolder()); + } + // 需要注入ResourceLoader + if (obj instanceof ResourceLoaderAware) { + ((ResourceLoaderAware) obj).setResourceLoader(ctx.getResourceLoader()); + } + // 需要注入Ioc + if (obj instanceof IocAware) { + ((IocAware) obj).setIoc(ctx.getIoc()); + } + } + + public void setListener(NbAppEventListener listener) { + this.listeners.clear(); + addListener(listener); + } + + public void addListener(NbAppEventListener listener) { + this.listeners.add(listener); + } + + public boolean isStarted() { + return started; + } + + public void setMainPackage(String mainPackage) { + getAppContext().setMainPackage(mainPackage); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.nutz.boot.NbApp.prepare` indirectly writes to field `this.org.nutz.boot.NbApp.ctx.org.nutz.boot.AppContext.ioc` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void NbApp.prepare() + +### Procedure Id: +org.nutz.boot.NbApp.prepare():void.3497bd920679b1a589201156049c849c + +### File: +nutzboot-core/src/main/java/org/nutz/boot/NbApp.java + +### Key: +NbApp.java|prepare|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +10c3497f8bed4598cf88f6d86ede25d6 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9446/instruction.md b/inferredbugs-9446/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41c77e7fa6b48cda4eb1308ded5ac089be69f2db --- /dev/null +++ b/inferredbugs-9446/instruction.md @@ -0,0 +1,576 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** tesb-rt-se +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.talend.esb.locator; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.namespace.QName; + +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.KeeperException.Code; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.apache.zookeeper.ZooDefs.Ids; + +/** + * This is the entry point for clients of the Service Locator. To access the + * Service Locator clients have to first {@link #connect() connect} to the + * Service Locator to get a session assigned. Once the connection is established + * the client will periodically send heart beats to the server to keep the + * session alive. + *

    + * The Service Locator provides the following operations. + *

      + *
    • An endpoint for a specific service can be registered. + *
    • All endpoints for a specific service that were registered before by other + * clients can be looked up. + *
    + * + */ +public class ServiceLocator { + + private static final Logger LOG = Logger.getLogger(ServiceLocator.class + .getName()); + + public static final NodePath LOCATOR_ROOT_PATH = new NodePath("cxf-locator"); + + public static final byte[] EMPTY_CONTENT = new byte[0]; + + // Count of register() and lookup() methods which performed in parallel in + // this moment + private int businessOperations = 0; + + // Is blocked by connect() or disconnect() method + private boolean blockedByRunUpOperation = false; + + public static final PostConnectAction DO_NOTHING_ACTION = new PostConnectAction() { + + @Override + public void process(ServiceLocator lc) { + } + }; + + /** + * Callback interface to define actions that must be executed after a + * successful connect or reconnect. + */ + static interface PostConnectAction { + /** + * Execute this after the connection to the Service Locator is + * established or re-established. + * + * @param lc + * the Service Locator client that just successfully + * connected to the server, must not be null + */ + void process(ServiceLocator lc); + } + + private String locatorEndpoints = "localhost:2181"; + + private int sessionTimeout = 5000; + + private int connectionTimeout = 5000; + + private int waitingTimeout = 3000; + + private PostConnectAction pca = DO_NOTHING_ACTION; + + private volatile ZooKeeper zk; + + /** + * Establish a connection to the Service Locator. After successful + * connection the specified {@link PostConnectAction} is run. If the session + * to the server expires because the server could not be reached within the + * {@link #setSessionTimeout(int) specified time}, a reconnect is + * automatically executed as soon as the server can be reached again. + * Because after a session time out all registered endpoints are removed it + * is important to specify a {@link PostConnectAction} that re-registers all + * endpoints. + * + * @throws IOException + * At least one of the endpoints does not represent a valid + * address + * @throws InterruptedException + * the current Thread was interrupted when waiting + * for a successful connection to the ServiceLocator + * @throws ServiceLocatorException + * the connect operation failed + */ + public void connect() throws IOException, InterruptedException, + ServiceLocatorException { + connect(false); + } + + synchronized public void connect(boolean immediately) throws IOException, + InterruptedException, ServiceLocatorException { + if (LOG.isLoggable(Level.FINE)) { + LOG.log(Level.FINE, "Start connect session"); + } + blockedByRunUpOperation = true; + disconnect(false, immediately); + + CountDownLatch connectionLatch = new CountDownLatch(1); + zk = createZooKeeper(connectionLatch); + boolean connected = connectionLatch.await(connectionTimeout, + TimeUnit.MILLISECONDS); + + if (!connected) { + throw new ServiceLocatorException( + "Connection to Service Locator failed."); + } else { + pca.process(this); + } + blockedByRunUpOperation = false; + + if (LOG.isLoggable(Level.FINER)) { + LOG.log(Level.FINER, "End connect session"); + } + + } + + /** + * Disconnects from a Service Locator server. All endpoints that were + * registered before are removed from the server. To be able to communicate + * with a Service Locator server again the client has to {@link #connect() + * connect} again. + * + * @throws InterruptedException + * the current Thread was interrupted when waiting + * for the disconnect to happen + * @throws ServiceLocatorException + */ + public void disconnect() throws InterruptedException, + ServiceLocatorException { + disconnect(true, false); + } + + synchronized public void disconnect(boolean notify, boolean immediately) + throws InterruptedException, ServiceLocatorException { + if (LOG.isLoggable(Level.FINE)) { + LOG.log(Level.FINE, "Start disconnect session"); + } + blockedByRunUpOperation = true; + if (!immediately) { + try { + int waiting = 0; + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Waiting " + + waitingTimeout + + " ms for some business operations to complete its work"); + } + while (businessOperations != 0 && waiting < waitingTimeout) { + Thread.sleep(1); + waiting++; + } + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("In fact waiting was " + waiting + " ms ;)"); + } + businessOperations = 0; + } catch (InterruptedException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "Thread sleeping, and the thread is interrupted, either before or during the activity: " + + e.getMessage()); + } + throw new ServiceLocatorException("Thread is interrupted.", e); + } + } else { + businessOperations = 0; + } + + if (zk != null) { + zk.close(); + zk = null; + } + if (notify) { + blockedByRunUpOperation = false; + } + if (LOG.isLoggable(Level.FINER)) { + LOG.log(Level.FINER, "End disconnect session"); + } + + } + + /** + * For a given service register the endpoint of a concrete provider of this + * service. If the client is destroyed, disconnected, or fails to + * successfully send the heartbeat for a period of time defined by the + * {@link #setSessionTimeout(int) session timeout parameter} the endpoint is + * removed from the Service Locator. To ensure that all available endpoints + * are re-registered when the client reconnects after a session expired a + * {@link PostConnectAction} should be + * {@link #setPostConnectAction(PostConnectAction) set} that registers all + * endpoints. + * + * @param serviceName + * the name of the service the endpoint is registered for, must + * not be null + * @param endpoint + * the endpoint to register, must not be null + * @throws ServiceLocatorException + * the server returned an error + * @throws InterruptedException + * the current Thread was interrupted when waiting + * for a response of the ServiceLocator + */ + public void register(QName serviceName, String endpoint) + throws ServiceLocatorException, InterruptedException { + if (blockedByRunUpOperation) { + if (LOG.isLoggable(Level.INFO)) { + LOG.info("It seems that Service Locator performs connection operation. We are waiting for completion."); + } + synchronized (this) { + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Entering into synchronization block"); + } + } + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Leaving the synchronization block"); + } + } + businessOperations++; + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, "Register endpoint " + endpoint + + " for service " + serviceName + "."); + } + NodePath serviceNodePath = LOCATOR_ROOT_PATH.child(serviceName + .toString()); + ensurePathExists(serviceNodePath, CreateMode.PERSISTENT); + + NodePath endpointNodePath = serviceNodePath.child(endpoint); + ensurePathExists(endpointNodePath, CreateMode.EPHEMERAL); + if (businessOperations > 0) + businessOperations--; + } + + public void unregister(QName serviceName, String endpoint) + throws ServiceLocatorException, InterruptedException { + if (blockedByRunUpOperation) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, + "It seems that Service Locator performs connection operation. We are waiting for completion."); + } + synchronized (this) { + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Entering into synchronization block"); + } + } + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Leaving the synchronization block"); + } + } + businessOperations++; + if (LOG.isLoggable(Level.INFO)) { + LOG.info("Unregister endpoint " + endpoint + " for service " + + serviceName + "."); + } + + NodePath serviceNodePath = LOCATOR_ROOT_PATH.child(serviceName + .toString()); + NodePath endpointNodePath = serviceNodePath.child(endpoint); + + try { + deleteNode(endpointNodePath); + deleteNode(serviceNodePath); + } catch (KeeperException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "The service locator server signaled an error: " + + e.getMessage()); + } + throw new ServiceLocatorException( + "The service locator server signaled an error.", e); + + } + + if (businessOperations > 0) + businessOperations--; + } + + /** + * For the given service return all endpoints that currently registered at + * the Service Locator Service. + * + * @param serviceName + * the name of the service for which to get the endpoints, must + * not be null + * @return a possibly empty list of endpoints + * @throws ServiceLocatorException + * the server returned an error + * @throws InterruptedException + * the current Thread was interrupted when waiting + * for a response of the ServiceLocator + */ + public List lookup(QName serviceName) + throws ServiceLocatorException, InterruptedException { + if (blockedByRunUpOperation) { + if (LOG.isLoggable(Level.INFO)) { + LOG.log(Level.INFO, + "It seems that Service Locator performs connection operation. We are waiting for completion."); + } + synchronized (this) { + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Entering into synchronization block"); + } + } + if (LOG.isLoggable(Level.FINEST)) { + LOG.log(Level.FINEST, "Leaving the synchronization block"); + } + } + businessOperations++; + if (LOG.isLoggable(Level.INFO)) { + LOG.info("Lookup endpoints of " + serviceName + " service."); + } + try { + NodePath providerPath = LOCATOR_ROOT_PATH.child(serviceName + .toString()); + List children; + if (nodeExists(providerPath)) { + children = decode(getChildren(providerPath)); + } else { + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Lookup for provider" + serviceName + + " failed, provider not known."); + } + children = Collections.emptyList(); + } + if (businessOperations > 0) + businessOperations--; + + return children; + + } catch (KeeperException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "The service locator server signaled an error: " + + e.getMessage()); + } + throw new ServiceLocatorException( + "The service locator server signaled an error.", e); + } + + } + + public void setLocatorEndpoints(String endpoints) { + locatorEndpoints = endpoints; + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Locator endpoints set to " + locatorEndpoints); + } + } + + public void setSessionTimeout(int timeout) { + sessionTimeout = timeout; + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Locator session timeout set to: " + sessionTimeout); + } + } + + public void setConnectionTimeout(int timeout) { + connectionTimeout = timeout; + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Locator connection timeout set to: " + connectionTimeout); + } + } + + public void setPostConnectAction(PostConnectAction pca) { + this.pca = pca; + } + + public void setWaitingTimeout(int waitingTimeout) { + this.waitingTimeout = waitingTimeout; + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Locator wating timeout set to: " + waitingTimeout); + } + + } + + private void ensurePathExists(NodePath path, CreateMode mode) + throws ServiceLocatorException, InterruptedException { + try { + if (!nodeExists(path)) { + createNode(path, mode); + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Node " + path + " created."); + } + } else { + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Node " + path + " already exists."); + } + } + } catch (KeeperException e) { + if (!e.code().equals(Code.NODEEXISTS)) { + throw new ServiceLocatorException( + "The service locator server signaled an error.", e); + } else { + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Some other client created node" + path + + " concurrently."); + } + } + } + } + + private boolean nodeExists(NodePath path) throws KeeperException, + InterruptedException { + return zk.exists(path.toString(), false) != null; + } + + private void createNode(NodePath path, CreateMode mode) + throws KeeperException, InterruptedException { + zk.create(path.toString(), EMPTY_CONTENT, Ids.OPEN_ACL_UNSAFE, mode); + } + + private void deleteNode(NodePath path) throws KeeperException, + InterruptedException { + if (getChildren(path).isEmpty()) + zk.delete(path.toString(), -1); + } + + private List getChildren(NodePath path) throws KeeperException, + InterruptedException { + return zk.getChildren(path.toString(), false); + } + + private List decode(List encoded) { + List raw = new ArrayList(); + + for (String oneEncoded : encoded) { + raw.add(NodePath.decode(oneEncoded)); + } + return raw; + } + + protected ZooKeeper createZooKeeper(CountDownLatch connectionLatch) + throws IOException { + return new ZooKeeper(locatorEndpoints, sessionTimeout, new WatcherImpl( + connectionLatch)); + } + + public class WatcherImpl implements Watcher { + + private CountDownLatch connectionLatch; + + public WatcherImpl(CountDownLatch connectionLatch) { + this.connectionLatch = connectionLatch; + } + + @Override + public void process(WatchedEvent event) { + if (LOG.isLoggable(Level.FINE)) { + LOG.fine("Event with state " + event.getState() + " sent."); + } + + KeeperState eventState = event.getState(); + try { + if (eventState == KeeperState.SyncConnected) { + ensurePathExists(LOCATOR_ROOT_PATH, CreateMode.PERSISTENT); + connectionLatch.countDown(); + } else if (eventState == KeeperState.Expired) { + connect(); + } + } catch (IOException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "An IOException was thrown when trying to connect to the ServiceLocator", + e); + } + } catch (InterruptedException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "An InterruptedException was thrown while waiting for an answer from the Service Locator", + e); + } + } catch (ServiceLocatorException e) { + if (LOG.isLoggable(Level.SEVERE)) { + LOG.log(Level.SEVERE, + "Failed to execute an request to Service Locator.", + e); + } + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.talend.esb.locator.ServiceLocator.connect` indirectly reads with synchronization from `this.org.talend.esb.locator.ServiceLocator.businessOperations`. Potentially races with unsynchronized write in method `ServiceLocator.unregister(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ServiceLocator.connect() + +### Procedure Id: +org.talend.esb.locator.ServiceLocator.connect():void.0568b7dccb583a903ed4a3bdeb577702 + +### File: +locator/src/main/java/org/talend/esb/locator/ServiceLocator.java + +### Key: +ServiceLocator.java|connect|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +1a0797ed22dd4d85cd1d953838633e37 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9448/instruction.md b/inferredbugs-9448/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e99dcb8415b235764775c076ad58c68c8ea190c6 --- /dev/null +++ b/inferredbugs-9448/instruction.md @@ -0,0 +1,180 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** async-google-pubsub-client +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright (c) 2011-2015 Spotify AB + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.spotify.google.cloud.pubsub.client.integration; + +import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; +import com.google.api.services.pubsub.PubsubScopes; + +import com.spotify.google.cloud.pubsub.client.Message; +import com.spotify.google.cloud.pubsub.client.Pubsub; +import com.spotify.google.cloud.pubsub.client.Puller; +import com.spotify.logging.LoggingConfigurator; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.zip.Deflater; + +import static com.spotify.logging.LoggingConfigurator.Level.WARN; + +public class PullerBenchmark { + + private static final int PULLER_CONCURRENCY = 128; + + public static void main(final String... args) throws IOException, ExecutionException, InterruptedException { + + final String project = Util.defaultProject(); + + GoogleCredential credential; + + // Use credentials from file if available + try { + credential = GoogleCredential + .fromStream(new FileInputStream("credentials.json")) + .createScoped(PubsubScopes.all()); + } catch (IOException e) { + credential = GoogleCredential.getApplicationDefault() + .createScoped(PubsubScopes.all()); + } + + final Pubsub pubsub = Pubsub.builder() + .credential(credential) + .compressionLevel(Deflater.BEST_SPEED) + .enabledCipherSuites(Util.nonGcmCiphers()) + .build(); + + LoggingConfigurator.configureDefaults("benchmark", WARN); + + final String subscription = System.getenv("GOOGLE_PUBSUB_SUBSCRIPTION"); + if (subscription == null) { + System.err.println("Please specify a subscription using the GOOGLE_PUBSUB_SUBSCRIPTION environment variable."); + System.exit(1); + } + + System.out.println("Consuming from GOOGLE_PUBSUB_SUBSCRIPTION='" + subscription + "'"); + + final ProgressMeter meter = new ProgressMeter(); + final ProgressMeter.Metric receives = meter.group("operations").metric("receives", "messages"); + + final Puller puller = Puller.builder() + .pubsub(pubsub) + .batchSize(1000) + .concurrency(PULLER_CONCURRENCY) + .project(project) + .subscription(subscription) + .messageHandler(new Handler(receives)) + .build(); + + while (true) { + Thread.sleep(1000); + } + } + + + private static class Handler implements Puller.MessageHandler { + + private final ProgressMeter.Metric receives; + + public Handler(final ProgressMeter.Metric receives) { + + this.receives = receives; + } + + @Override + public CompletionStage handleMessage(final Puller puller, final String subscription, + final Message message, final String ackId) { + receives.inc(0); + return CompletableFuture.completedFuture(ackId); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.spotify.google.cloud.pubsub.client.Puller` acquired to `puller` by call to `build()` at line 82 is not released after line 82. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PullerBenchmark.main(java.lang.String[]) + +### Procedure Id: +com.spotify.google.cloud.pubsub.client.integration.PullerBenchmark.main(java.lang.String[]):void.fb5e140660e540f9cac1c0e45a8367f2 + +### File: +src/test/java/com/spotify/google/cloud/pubsub/client/integration/PullerBenchmark.java + +### Key: +PullerBenchmark.java|main|RESOURCE_LEAK + +### Node Key: +dc2539c4f7b57372dedb2b3889714f63 + +### Hash: +555a40c5129b38e5af39a66365cd825b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9470/instruction.md b/inferredbugs-9470/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a074696c6201787dfa3ace28f9b4d6d24988e750 --- /dev/null +++ b/inferredbugs-9470/instruction.md @@ -0,0 +1,624 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zalenium +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package de.zalando.ep.zalenium.container.swarm; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; +import com.spotify.docker.client.AnsiProgressHandler; +import com.spotify.docker.client.DefaultDockerClient; +import com.spotify.docker.client.DockerClient; +import com.spotify.docker.client.exceptions.DockerException; +import com.spotify.docker.client.messages.*; +import com.spotify.docker.client.messages.mount.Mount; +import com.spotify.docker.client.messages.swarm.*; +import de.zalando.ep.zalenium.container.ContainerClient; +import de.zalando.ep.zalenium.container.ContainerClientRegistration; +import de.zalando.ep.zalenium.container.ContainerCreationStatus; +import de.zalando.ep.zalenium.proxy.DockeredSeleniumStarter; +import de.zalando.ep.zalenium.util.Environment; +import de.zalando.ep.zalenium.util.GoogleAnalyticsApi; +import de.zalando.ep.zalenium.util.ZaleniumConfiguration; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.RandomStringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.stream.Collectors; + +import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusCreated; +import static com.spotify.docker.client.DockerClient.ListContainersParam.withStatusRunning; + +@SuppressWarnings("ConstantConditions") +public class SwarmContainerClient implements ContainerClient { + + private static final String ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT = "ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT"; + private static final String ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT = "ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT"; + + private static final String SWARM_EXEC_IMAGE = "datagridsys/skopos-plugin-swarm-exec:latest"; + + private static final Environment defaultEnvironment = new Environment(); + + private static Environment env = defaultEnvironment; + private static String seleniumContainerCpuLimit; + private static String seleniumContainerMemoryLimit; + private static String dockerHost; + private static AtomicBoolean environmentInitialised = new AtomicBoolean(false); + + static { + readConfigurationFromEnvVariables(); + } + + private final Logger logger = LoggerFactory.getLogger(SwarmContainerClient.class.getName()); + private final GoogleAnalyticsApi ga = new GoogleAnalyticsApi(); + private DockerClient dockerClient = new DefaultDockerClient(dockerHost); + private String nodeId; + private Map seleniumContainerLabels = new HashMap<>(); + private AtomicBoolean seleniumContainerLabelsChecked = new AtomicBoolean(false); + + private static void readConfigurationFromEnvVariables() { + + String cpuLimit = env.getEnvVariable(ZALENIUM_SELENIUM_CONTAINER_CPU_LIMIT); + setSeleniumContainerCpuLimit(cpuLimit); + + String memoryLimit = env.getEnvVariable(ZALENIUM_SELENIUM_CONTAINER_MEMORY_LIMIT); + setSeleniumContainerMemoryLimit(memoryLimit); + + String dockerHost = env.getStringEnvVariable("DOCKER_HOST", "unix:///var/run/docker.sock"); + setDockerHost(dockerHost); + } + + @VisibleForTesting + protected static void setEnv(final Environment env) { + SwarmContainerClient.env = env; + } + + private static void setDockerHost(String dockerHost) { + // https://github.com/spotify/docker-client/issues/946 + SwarmContainerClient.dockerHost = dockerHost.replace("tcp", "http"); + } + + private static String getSeleniumContainerCpuLimit() { + return seleniumContainerCpuLimit; + } + + private static void setSeleniumContainerCpuLimit(String seleniumContainerCpuLimit) { + SwarmContainerClient.seleniumContainerCpuLimit = seleniumContainerCpuLimit; + } + + private static String getSeleniumContainerMemoryLimit() { + return seleniumContainerMemoryLimit; + } + + private static void setSeleniumContainerMemoryLimit(String seleniumContainerMemoryLimit) { + SwarmContainerClient.seleniumContainerMemoryLimit = seleniumContainerMemoryLimit; + } + + public void setNodeId(String nodeId) { + this.nodeId = nodeId; + } + + private String getContainerId(URL remoteUrl) { + try { + List tasks = dockerClient.listTasks(); + for (Task task : tasks) { + for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) { + for (String address : networkAttachment.addresses()) { + if (address.startsWith(remoteUrl.getHost())) { + return task.status().containerStatus().containerId(); + } + } + } + } + } catch (DockerException | InterruptedException e) { + e.printStackTrace(); + } + + return null; + } + + private String getContainerId(String containerName) { + final String containerNameSearch = containerName.contains("/") ? + containerName : String.format("/%s", containerName); + + List containerList = null; + try { + containerList = dockerClient.listContainers(withStatusRunning(), withStatusCreated()); + } catch (DockerException | InterruptedException e) { + logger.debug(nodeId + " Error while getting containerId", e); + ga.trackException(e); + } + + if (containerList != null) { + String containerByName = containerList.stream() + .filter(container -> containerNameSearch.equalsIgnoreCase(container.names().get(0))) + .findFirst().map(Container::id).orElse(containerName); + return containerByName != null ? containerByName : containerList.stream() + .filter(container -> container.names().get(0).contains(containerName)) + .findFirst().map(Container::id).orElse(containerName); + } else { + return containerName; + } + } + + public InputStream copyFiles(String containerId, String folderName) { + // TODO: Implement behaviour + return null; + } + + public void stopContainer(String containerId) { + try { + List tasks = dockerClient.listTasks(); + for (Task task : tasks) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null && containerStatus.containerId().equals(containerId)) { + String serviceId = task.serviceId(); + Service.Criteria criteria = Service.Criteria.builder() + .serviceId(serviceId) + .build(); + List services = dockerClient.listServices(criteria); + if (!CollectionUtils.isEmpty(services)) { + dockerClient.removeService(serviceId); + } + } + } + } catch (DockerException | InterruptedException e) { + logger.warn(nodeId + " Error while stopping the container", e); + ga.trackException(e); + } + } + + public void executeCommand(String containerId, String[] command, boolean waitForExecution) { + try { + List tasks = dockerClient.listTasks(); + + pullSwarmExecImage(); + + for (Task task : CollectionUtils.emptyIfNull(tasks)) { + ContainerStatus containerStatus = task.status().containerStatus(); + + if (containerStatus != null && containerStatus.containerId().equals(containerId)) { + startSwarmExecContainer(task, command, containerId); + return; + } + } + } catch (DockerException | InterruptedException e) { + logger.warn("Error while executing comman on container {}", containerId); + ga.trackException(e); + } + + logger.warn("Couldn't execute command on container {}", containerId); + } + + private void pullSwarmExecImage() { + try { + List images = dockerClient.listImages(DockerClient.ListImagesParam.byName(SWARM_EXEC_IMAGE)); + if (CollectionUtils.isEmpty(images)) { + dockerClient.pull(SWARM_EXEC_IMAGE, new AnsiProgressHandler()); + } + } catch (DockerException | InterruptedException e) { + logger.warn(nodeId + " Error while checking (and pulling) if the image is present", e); + ga.trackException(e); + } + } + + private void startSwarmExecContainer(Task task, String[] command, String containerId) throws DockerException, InterruptedException { + String taskId = task.id(); + + List binds = new ArrayList<>(); + binds.add("/var/run/docker.sock:/var/run/docker.sock"); + + HostConfig.Builder hostConfigBuilder = HostConfig.builder() + .autoRemove(true) + .appendBinds(binds); + + HostConfig hostConfig = hostConfigBuilder.build(); + + command[0] = "task-exec"; + command[1] = taskId; + + logger.debug("Executing command: {} - on Container: {}", + Arrays.toString(command), + containerId); + + ContainerConfig containerConfig = ContainerConfig.builder() + .image(SWARM_EXEC_IMAGE) + .hostConfig(hostConfig) + .cmd(command) + .build(); + + ContainerCreation containerCreation = dockerClient.createContainer(containerConfig); + + dockerClient.startContainer(containerCreation.id()); + } + + public String getLatestDownloadedImage(String imageName) { + // TODO: verify this is handled by docker + return imageName; + } + + public ContainerCreationStatus createContainer(String zaleniumContainerName, String image, Map envVars, + String nodePort) { + // TODO: is it meaningful to add labels to identify services/containers in the swarm? + + List flattenedEnvVars = envVars.entrySet().stream() + .map(e -> e.getKey() + "=" + e.getValue()) + .collect(Collectors.toList()); + final ContainerSpec containerSpec = buildContainerSpec(flattenedEnvVars, image); + + final TaskSpec taskSpec = buildTaskSpec(containerSpec); + + String noVncPort = envVars.get("NOVNC_PORT"); + final ServiceSpec serviceSpec = buildServiceSpec(taskSpec, nodePort, noVncPort); + + try { + ServiceCreateResponse service = dockerClient.createService(serviceSpec); + + TaskStatus taskStatus = waitForTaskStatus(service.id()); + + if (taskStatus != null) { + return getContainerCreationStatus(service.id(), nodePort); + } + } catch (DockerException | InterruptedException e) { + e.printStackTrace(); + } + + logger.debug("Something went wrong while creating service"); + return null; + } + + private ContainerSpec buildContainerSpec(List flattenedEnvVars, String image) { + final Mount.Builder mountBuilder = Mount.builder() + .source("/dev/shm") + .target("/dev/shm") + .type("bind"); + + final ContainerSpec.Builder containerSpecBuilder = ContainerSpec.builder() + .env(flattenedEnvVars) + .image(image) + .mounts(mountBuilder.build()); + + loadSeleniumContainerLabels(); + + if (seleniumContainerLabels.size() > 0) { + containerSpecBuilder.labels(seleniumContainerLabels); + } + + return containerSpecBuilder.build(); + } + + private TaskSpec buildTaskSpec(ContainerSpec containerSpec) { + final RestartPolicy restartPolicy = RestartPolicy.builder() + .condition("on-failure") + .build(); + + final List placementList = new ArrayList<>(); + + placementList.add("node.role==worker"); + + final Placement placement = Placement.create(placementList); + + Resources.Builder resourceBuilder = Resources.builder(); + String cpuLimit = getSeleniumContainerCpuLimit(); + String memLimit = getSeleniumContainerMemoryLimit(); + + if (!Strings.isNullOrEmpty(cpuLimit)) { + resourceBuilder.nanoCpus(Long.valueOf(cpuLimit)); + } + + if (!Strings.isNullOrEmpty(memLimit)) { + resourceBuilder.memoryBytes(Long.valueOf(memLimit)); + } + + ResourceRequirements resourceRequirements = ResourceRequirements.builder() + .limits(resourceBuilder.build()) + .build(); + + final TaskSpec.Builder taskSpecBuilder = TaskSpec.builder() + .resources(resourceRequirements) + .restartPolicy(restartPolicy) + .placement(placement) + .containerSpec(containerSpec); + + return taskSpecBuilder.build(); + } + + private ServiceSpec buildServiceSpec(TaskSpec taskSpec, String nodePort, String noVncPort) { + final PortConfig nodePortConfig = PortConfig.builder() + .targetPort(Integer.valueOf(nodePort)) + .publishedPort(Integer.valueOf(nodePort)) + .build(); + + final PortConfig noVncPortConfig = PortConfig.builder() + .targetPort(Integer.valueOf(noVncPort)) + .publishedPort(Integer.valueOf(noVncPort)) + .build(); + + final EndpointSpec.Builder endpointSpecBuilder = EndpointSpec.builder() + .addPort(nodePortConfig) + .addPort(noVncPortConfig); + + final NetworkAttachmentConfig networkAttachmentConfig = NetworkAttachmentConfig.builder() + .target(ZaleniumConfiguration.getSwarmOverlayNetwork()) + .build(); + + return ServiceSpec.builder() + .name(generateServiceName()) + .endpointSpec(endpointSpecBuilder.build()) + .networks(networkAttachmentConfig) + .taskTemplate(taskSpec) + .build(); + } + + private TaskStatus waitForTaskStatus(String serviceId) throws DockerException, InterruptedException { + return waitForTaskStatus(serviceId, 0); + } + + private TaskStatus waitForTaskStatus(String serviceId, int attempts) throws DockerException, InterruptedException { + int attemptsLimit = 100; + Thread.sleep(100); + String serviceName = dockerClient.inspectService(serviceId).spec().name(); + Task.Criteria criteria = Task.Criteria.builder().serviceName(serviceName).build(); + List tasks = dockerClient.listTasks(criteria); + Task task = null; + + if (!CollectionUtils.isEmpty(tasks)) { + task = tasks.get(0); + } + + if (task == null && attempts < attemptsLimit) { + return waitForTaskStatus(serviceId, attempts + 1); + } else { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus == null) { + return waitForTaskStatus(serviceId, attempts + 1); + } + + logger.debug("container {} is ready", containerStatus.containerId()); + + return task.status(); + } + } + + private ContainerCreationStatus getContainerCreationStatus(String serviceId, String nodePort) throws DockerException, InterruptedException { + Service service = dockerClient.inspectService(serviceId); + Task.Criteria criteria = Task.Criteria.builder() + .serviceName(service.spec().name()) + .build(); + List tasks = dockerClient.listTasks(criteria); + for (Task task : tasks) { + if (task.serviceId().equals(serviceId)) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null) { + String containerId = containerStatus.containerId(); + String containerName = containerStatus.containerId(); + return new ContainerCreationStatus(true, containerName, containerId, nodePort); + } + } + } + + return null; + } + + private String generateServiceName() { + final String suffix = RandomStringUtils.randomAlphanumeric(6); + return String.format("node_%s", suffix); + } + + private void loadSeleniumContainerLabels() { + if (!this.seleniumContainerLabelsChecked.getAndSet(true)) { + String containerLabels = env.getStringEnvVariable("SELENIUM_CONTAINER_LABELS", ""); + if (containerLabels.length() == 0) { + return; + } + try { + for (String label : containerLabels.split(";")) { + String[] split = label.split("="); + seleniumContainerLabels.put(split[0], split[1]); + } + } catch (Exception e) { + logger.warn(nodeId + " Error while retrieving the added labels for the Selenium containers.", e); + ga.trackException(e); + } + } + } + + @Override + public void initialiseContainerEnvironment() { + if (!environmentInitialised.getAndSet(true)) { + // Delete any leftover services from a previous time + deleteSwarmServices(); + // Register a shutdown hook to cleanup pods + Runtime.getRuntime().addShutdownHook(new Thread(this::deleteSwarmServices, "SwarmContainerClient shutdown hook")); + } + } + + private void deleteSwarmServices() { + // TODO: Implement functionality + } + + @Override + public ContainerClientRegistration registerNode(String zaleniumContainerName, URL remoteHost) { + ContainerClientRegistration registration = new ContainerClientRegistration(); + + Integer noVncPort = remoteHost.getPort() + DockeredSeleniumStarter.NO_VNC_PORT_GAP; + + String containerId = this.getContainerId(remoteHost); + + if (containerId == null) { + logger.warn("No container id for {} - {}, can't register.", zaleniumContainerName, remoteHost.toExternalForm()); + } + + registration.setNoVncPort(noVncPort); + registration.setContainerId(containerId); + registration.setIpAddress(remoteHost.getHost()); + return registration; + } + + @Override + public String getContainerIp(String containerName) { + String containerId = this.getContainerId(containerName); + + if (containerId == null) { + logger.warn("Failed to get id of container: {} ", containerName); + return null; + } + + try { + List tasks = dockerClient.listTasks(); + String swarmOverlayNetwork = ZaleniumConfiguration.getSwarmOverlayNetwork(); + for (Task task : tasks) { + ContainerStatus containerStatus = task.status().containerStatus(); + if (containerStatus != null) { + if (containerStatus.containerId().equals(containerId)) { + for (NetworkAttachment networkAttachment : CollectionUtils.emptyIfNull(task.networkAttachments())) { + if (networkAttachment.network().spec().name().equals(swarmOverlayNetwork)) { + String cidrSuffix = "/\\d+$"; + return networkAttachment.addresses().get(0).replaceAll(cidrSuffix, ""); + } + } + } + } + } + } catch (DockerException | InterruptedException e) { + logger.debug(nodeId + " Error while getting the container IP.", e); + ga.trackException(e); + } + + logger.warn("Failed to get ip of container: {}", containerName); + return null; + } + + @Override + public boolean isReady(ContainerCreationStatus container) { + String containerIp = this.getContainerIp(container.getContainerName()); + if (containerIp != null) { + try { + URL statusUrl = new URL(String.format("http://%s:%s/wd/hub/status", containerIp, container.getNodePort())); + String status = IOUtils.toString(statusUrl, StandardCharsets.UTF_8); + String successMessage = "\"Node is running\""; + if (status.contains(successMessage)) { + return true; + } + } catch (IOException e) { + logger.debug("Error while getting node status, probably the node is still starting up...", e); + } + } + return false; + } + + @Override + public boolean isTerminated(ContainerCreationStatus container) { + try { + List termStates = Arrays.asList("complete", "failed", "shutdown", "rejected", "orphaned", "removed"); + String containerId = container.getContainerId(); + List tasks = dockerClient.listTasks(); + boolean containerExists = tasks.stream().anyMatch(task -> { + ContainerStatus containerStatus = task.status().containerStatus(); + return containerStatus != null && containerStatus.containerId().equals(containerId); + }); + + if (!containerExists) { + logger.info("Container {} has no corresponding task - flagging it as terminated", container); + return true; + } else { + return tasks.stream().anyMatch(task -> { + ContainerStatus containerStatus = task.status().containerStatus(); + boolean hasTerminalState = termStates.contains(task.status().state()); + boolean isContainer = containerStatus != null && containerStatus.containerId().equals(containerId); + boolean isTerminated = isContainer && hasTerminalState; + + if (isTerminated) { + logger.info("State of Container {} is {} - flagging it as terminated", + container.getContainerId(), + task.status().state()); + } + + return isTerminated; + }); + } + } catch (DockerException | InterruptedException e) { + logger.warn("Failed to fetch container status [" + container.getContainerId() + "].", e); + return false; + } + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `containerStatus.containerId()` at line 184. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SwarmContainerClient.executeCommand(String,java.lang.String[],boolean) + +### Procedure Id: +de.zalando.ep.zalenium.container.swarm.SwarmContainerClient.executeCommand(java.lang.String,java.lan.afcb3f092d3d38a657a9cc9ed25346c9 + +### File: +src/main/java/de/zalando/ep/zalenium/container/swarm/SwarmContainerClient.java + +### Key: +SwarmContainerClient.java|executeCommand|NULL_DEREFERENCE + +### Node Key: +7e9fc31bc469440d6384630f8b346526 + +### Hash: +1e338541d43e899672d95a215bc5ed1c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9477/instruction.md b/inferredbugs-9477/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c9dcb28994c70533f6e4c2af4f8f2292867905f3 --- /dev/null +++ b/inferredbugs-9477/instruction.md @@ -0,0 +1,114 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** niubi-job +**Bug ID:** 4 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2002-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.zuoxiaolong.niubi.job.example; + +import com.zuoxiaolong.niubi.job.cluster.node.Node; +import com.zuoxiaolong.niubi.job.cluster.node.StandbyNode; +import com.zuoxiaolong.niubi.job.core.config.Configuration; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author Xiaolong Zuo + * @since 16/1/9 15:08 + */ +public class StandbyNodeTest { + + @org.junit.Test + public void test() throws InterruptedException, IOException { + Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); + node.join(); + new BufferedReader(new InputStreamReader(System.in)).readLine(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 37 is not released after line 37. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void StandbyNodeTest.test() + +### Procedure Id: +com.zuoxiaolong.niubi.job.example.StandbyNodeTest.test():void.6475d7c222e20c0f50268785ebc24813 + +### File: +niubi-job-examples/src/test/java/com/zuoxiaolong/niubi/job/example/StandbyNodeTest.java + +### Key: +StandbyNodeTest.java|test|RESOURCE_LEAK + +### Node Key: +fb177ebc5befa9bb46909e04282ac8ca + +### Hash: +d51e825d0be554689f15587338f19c6d + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9479/instruction.md b/inferredbugs-9479/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75f1ff15d2f0e0a73d42a2d680641518a60d3fb9 --- /dev/null +++ b/inferredbugs-9479/instruction.md @@ -0,0 +1,114 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** niubi-job +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2002-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.zuoxiaolong.niubi.job.example; + +import com.zuoxiaolong.niubi.job.cluster.node.MasterSlaveNode; +import com.zuoxiaolong.niubi.job.cluster.node.Node; +import com.zuoxiaolong.niubi.job.core.config.Configuration; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/** + * @author Xiaolong Zuo + * @since 16/1/9 15:08 + */ +public class MasterSlaveNodeTest { + + @org.junit.Test + public void test() throws InterruptedException, IOException { + Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); + node.join(); + new BufferedReader(new InputStreamReader(System.in)).readLine(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.InputStreamReader` acquired by call to `new()` at line 37 is not released after line 37. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void MasterSlaveNodeTest.test() + +### Procedure Id: +com.zuoxiaolong.niubi.job.example.MasterSlaveNodeTest.test():void.79d778479ee7ec9c743868f680e0d5bd + +### File: +niubi-job-examples/src/test/java/com/zuoxiaolong/niubi/job/example/MasterSlaveNodeTest.java + +### Key: +MasterSlaveNodeTest.java|test|RESOURCE_LEAK + +### Node Key: +fb177ebc5befa9bb46909e04282ac8ca + +### Hash: +37a2a9a3e13bb842d456c92f98fa42de + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9483/instruction.md b/inferredbugs-9483/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37aec1bd9f526c61c70375f8fd3b09c9c1c9a26b --- /dev/null +++ b/inferredbugs-9483/instruction.md @@ -0,0 +1,716 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** craft-atom +**Bug ID:** 3 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.craft.atom.protocol.http; + +import static org.craft.atom.protocol.http.model.HttpConstants.COLON; +import static org.craft.atom.protocol.http.model.HttpConstants.CONTENT_ENCODING_DEFLATE; +import static org.craft.atom.protocol.http.model.HttpConstants.CONTENT_ENCODING_GZIP; +import static org.craft.atom.protocol.http.model.HttpConstants.CONTENT_ENCODING_IDENTITY; +import static org.craft.atom.protocol.http.model.HttpConstants.CR; +import static org.craft.atom.protocol.http.model.HttpConstants.EQUAL_SIGN; +import static org.craft.atom.protocol.http.model.HttpConstants.HT; +import static org.craft.atom.protocol.http.model.HttpConstants.LF; +import static org.craft.atom.protocol.http.model.HttpConstants.NUL; +import static org.craft.atom.protocol.http.model.HttpConstants.SEMICOLON; +import static org.craft.atom.protocol.http.model.HttpConstants.SP; +import static org.craft.atom.protocol.http.model.HttpConstants.TRANSFER_ENCODING_CHUNKED; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.List; + +import org.craft.atom.protocol.AbstractProtocolDecoder; +import org.craft.atom.protocol.ProtocolException; +import org.craft.atom.protocol.ProtocolExceptionType; +import org.craft.atom.protocol.http.model.HttpChunk; +import org.craft.atom.protocol.http.model.HttpChunkEntity; +import org.craft.atom.protocol.http.model.HttpConstants; +import org.craft.atom.protocol.http.model.HttpEntity; +import org.craft.atom.protocol.http.model.HttpHeader; +import org.craft.atom.protocol.http.model.HttpHeaderValueElement; +import org.craft.atom.protocol.http.model.HttpHeaders; +import org.craft.atom.protocol.http.model.HttpMessage; +import org.craft.atom.util.ByteUtil; +import org.craft.atom.util.GzipUtil; + +/** + * A http decoder for {@code HttpRequest} and {@code HttpResponse} + * + * @author mindwind + * @version 1.0, Feb 3, 2013 + * @param + * @see HttpRequestDecoder + * @see HttpResponseDecoder + */ +abstract public class HttpDecoder extends AbstractProtocolDecoder { + + protected static final int START = 0; + protected static final int METHOD = 11; + protected static final int REQUEST_URI = 12; + protected static final int STATUS_CODE = 21; + protected static final int REASON_PHRASE = 22; + protected static final int VERSION = 30; + protected static final int HEADER_NAME = 40; + protected static final int HEADER_VALUE_PREFIX = 41; + protected static final int HEADER_VALUE = 42; + protected static final int HEADER_VALUE_SUFFIX = 43; + protected static final int ENTITY = 50; + protected static final int ENTITY_LENGTH = 51; + protected static final int ENTITY_CHUNKED_SIZE = 52; + protected static final int ENTITY_CHUNKED_EXTENSION_NAME = 53; + protected static final int ENTITY_CHUNKED_EXTENSION_VALUE = 54; + protected static final int ENTITY_CHUNKED_DATA = 55; + protected static final int ENTITY_CHUNKED_TRAILER_NAME = 56; + protected static final int ENTITY_CHUNKED_TRAILER_VALUE = 57; + protected static final int ENTITY_ENCODING = 58; + protected static final int END = -1; + + protected int stateIndex = 0; + protected int state = START; + protected int maxLineLength = defaultBufferSize; + + protected Charset contentCharset; + protected HttpHeader header; + protected HttpEntity entity; + protected HttpChunk chunk; + protected String chunkExtName; + protected int trailerSize; + protected T httpMessage; + + // ~ ------------------------------------------------------------------------------------------------------------ + + protected void state4END(List httpMessages) throws ProtocolException { + // enter END state means search index stay for the last byte of the HttpMessage, move to next + slide(1); + + httpMessages.add(httpMessage); + splitIndex = stateIndex = searchIndex; + clear(); + state = START; + } + + protected void state4ENTITY_ENCODING() throws ProtocolException, IOException { + HttpHeader ceh = httpMessage.getFirstHeader(HttpHeaders.CONTENT_ENCODING.getName()); + String coding = null; + if (ceh == null){ + coding = CONTENT_ENCODING_IDENTITY; + } else { + coding = ceh.getValue(); + } + + // none or identity + if (coding == null || CONTENT_ENCODING_IDENTITY.equals(coding)) { + // if content is chunked, getContent() will restructure chunked content to a complete content. + httpMessage.getEntity().setContent(httpMessage.getEntity().getContent()); + } + // gzip + else if (CONTENT_ENCODING_GZIP.equals(coding)) { + byte[] content = GzipUtil.ungzip(httpMessage.getEntity().getContent()); + httpMessage.getEntity().setContent(content); + } + // deflate + else if (CONTENT_ENCODING_DEFLATE.equals(coding)) { + /* + * A zlib stream will have a header. + * + * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 | + * + * * CMF is one byte. + * + * * FLG is one byte. + * + * * DICTID is four bytes, and only present if FLG.FDICT is set. + * + * Sniff the content. Does it look like a zlib stream, with a CMF, etc? + * c.f. RFC1950, section 2.2. http://tools.ietf.org/html/rfc1950#page-4 + * + * We need to see if it looks like a proper zlib stream, or whether it + * is just a deflate stream. RFC2616 calls zlib streams deflate. + * Confusing, isn't it? That's why some servers implement deflate + * Content-Encoding using deflate streams, rather than zlib streams. + * + * We could start looking at the bytes, but to be honest, someone else + * has already read the RFCs and implemented that for us. So we'll just + * use the JDK libraries and exception handling to do this. If that + * proves slow, then we could potentially change this to check the first + * byte - does it look like a CMF? What about the second byte - does it + * look like a FLG, etc. + * + * Many browsers over the years implemented an incorrect deflate algorithm, + * For example: deflate works in Safari 4.0 but is broken in Safari 5.1, it also always has issues on IE. + * So, we don't support deflate encoding now. + */ + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "unsupported content encoding=" + coding); + } + // compress or others encoding is unsupported + else { + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "unsupported content encoding=" + coding); + } + + // next state + httpMessage.setEntity(entity); + state = END; + } + + protected void state4ENTITY_CHUNKED_TRAILER_NAME() throws ProtocolException { + boolean done = skip(CR, LF); + if (!done) { + return; + } + + // slice header name + String name = sliceBySeparators(0, COLON); + if (name == null) { + return; + } + + header = new HttpHeader(); + header.setName(name); + + // to next state + trailerSize--; + state = ENTITY_CHUNKED_TRAILER_VALUE; + } + + protected void state4ENTITY_CHUNKED_TRAILER_VALUE() throws ProtocolException { + // skip SP or HT + boolean done = skip(SP, HT); + if (!done) { + return; + } + + // slice header value + String value = sliceBySeparators(-1, LF); + if (value == null) { + return; + } + + header.appendValue(value); + ((HttpChunkEntity) entity).addTrailer(header); + + // to next state + if (trailerSize == 0) { + slide(-1); + state = END; + } else { + state = ENTITY_CHUNKED_TRAILER_NAME; + } + } + + protected void state4ENTITY_CHUNKED_DATA() throws ProtocolException { + boolean done = skip(CR, LF); + if (!done) { + return; + } + + // slice content value + int clen = chunk.getSize(); + byte[] chunkData = sliceByLength(clen); + if (chunkData == null) { + return; + } + + chunk.setData(chunkData); + ((HttpChunkEntity) entity).addChunk(chunk); + + // skip CRLF + slide(2); + state = ENTITY_CHUNKED_SIZE; + } + + protected void state4ENTITY_CHUNKED_EXTENSION_VALUE() throws ProtocolException { + // slice chunk extension value + String chunkExtValue = sliceBySeparators(0, SEMICOLON, CR); + if (chunkExtValue == null) { + return; + } + + chunk.addExtension(chunkExtName, chunkExtValue); + + byte pb = previousByte(); + if (SEMICOLON == pb) { + state = ENTITY_CHUNKED_EXTENSION_NAME; + } else { + state = ENTITY_CHUNKED_DATA; + } + } + + protected void state4ENTITY_CHUNKED_EXTENSION_NAME() throws ProtocolException { + // slice chunk extension name + String name = sliceBySeparators(0, EQUAL_SIGN, CR); + if (name == null) { + return; + } + + this.chunkExtName = name; + + byte pb = previousByte(); + if (EQUAL_SIGN == pb) { + state = ENTITY_CHUNKED_EXTENSION_VALUE; + } else { + chunk.addExtension(chunkExtName, null); + state = ENTITY_CHUNKED_DATA; + } + } + + protected void state4ENTITY_CHUNKED_SIZE() throws ProtocolException { + boolean done = skip(LF); + if (!done) { + return; + } + + // slice chunk size + String sizeStr = sliceBySeparators(0, SEMICOLON, CR); + if (sizeStr == null) { + return; + } + + int size = Integer.parseInt(sizeStr, 16); + if (size < 0) { + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "chunked size < 0"); + } + + chunk = new HttpChunk(); + chunk.setSize(size); + + byte pb = previousByte(); + if (SEMICOLON == pb) { + state = ENTITY_CHUNKED_EXTENSION_NAME; + } else if (size > 0){ + state = ENTITY_CHUNKED_DATA; + } else if (size == 0) { + HttpHeader trailerHeader = httpMessage.getFirstHeader(HttpHeaders.TRAILER.getName()); + httpMessage.setEntity(entity); + if (trailerHeader != null) { + trailerSize = trailerHeader.getValue().split(",").length; + if (trailerSize <= 0) { + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "trailer size ilegal=" + trailerSize); + } + state = ENTITY_CHUNKED_TRAILER_NAME; + } else { + state = ENTITY_ENCODING; + } + } + } + + protected void state4ENTITY_LENGTH() throws ProtocolException { + // get content length + int clen = Integer.parseInt(httpMessage.getFirstHeader(HttpHeaders.CONTENT_LENGTH.getName()).getValue()); + if (clen < 0) { + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "content length < 0"); + } + + // slice content value + byte[] content = sliceByLength(clen); + if (content == null) { + return; + } + + // render current request with entity + entity.setContent(content); + httpMessage.setEntity(entity); + + // to next state + state = ENTITY_ENCODING; + } + + protected void state4ENTITY() throws ProtocolException { + boolean done = skip(CR, LF); + if (!done) { + return; + } + + // content length + if (httpMessage.getFirstHeader(HttpHeaders.CONTENT_LENGTH.getName()) != null) { + entity = new HttpEntity(); + entity.setCharset(getContentCharset(httpMessage)); + state = ENTITY_LENGTH; + } + // chunked + else if (TRANSFER_ENCODING_CHUNKED.equals(httpMessage.getFirstHeader(HttpHeaders.TRANSFER_ENCODING.getName()).getValue())) { + entity = new HttpChunkEntity(); + entity.setCharset(getContentCharset(httpMessage)); + state = ENTITY_CHUNKED_SIZE; + } + // no entity + else { + state = END; + } + } + + protected void state4HEADER_VALUE_SUFFIX() throws ProtocolException { + byte cb = currentByte(); + + // folded header + if (SP == cb || HT == cb) { + state = HEADER_VALUE_PREFIX; + } + // header end + else if (CR == cb) { + httpMessage.addHeader(header); + state = hasEntity(httpMessage) ? ENTITY : END; + slide(1); + } + // next header + else { + httpMessage.addHeader(header); + state = HEADER_NAME; + } + } + + protected void state4HEADER_VALUE() throws ProtocolException { + // slice header value + String value = sliceBySeparators(-1, LF); + if (value == null) { + return; + } + + header.appendValue(value); + + // to next state + byte cb = currentByte(); + // has no next byte in buffer + if (NUL == cb) { + state = HEADER_VALUE_SUFFIX; + } + // folded header + else if (SP == cb || HT == cb) { + state = HEADER_VALUE_PREFIX; + } + // header end + else if (CR == cb) { + httpMessage.addHeader(header); + state = hasEntity(httpMessage) ? ENTITY : END; + slide(1); + } + // next header + else { + httpMessage.addHeader(header); + state = HEADER_NAME; + } + } + + protected void state4HEADER_VALUE_PREFIX() throws ProtocolException { + // skip SP or HT + boolean done = skip(SP, HT); + if (!done) { + return; + } + + // to next state + state = HEADER_VALUE; + } + + protected void state4HEADER_NAME() throws ProtocolException { + // slice header name + String name = sliceBySeparators(0, COLON); + if (name == null) { + return; + } + + header = new HttpHeader(); + header.setName(name); + + // to next state + state = HEADER_VALUE_PREFIX; + } + + protected void reset() { + if (splitIndex > 0 && splitIndex < buf.length()) { + byte[] tailBytes = buf.array(splitIndex, buf.length()); + buf.clear(); + buf.append(tailBytes); + stateIndex -= splitIndex; + searchIndex = buf.length(); + splitIndex = 0; + } + + if (splitIndex > 0 && splitIndex == buf.length()) { + buf.clear(); + stateIndex = splitIndex = searchIndex = 0; + } + + if (buf.length() == 0 && buf.capacity() > maxSize * 2) { + buf.reset(defaultBufferSize); + } + } + + protected Charset getContentCharset(HttpMessage httpMessage) { + if (contentCharset != null) { + return contentCharset; + } + + HttpHeader contentTypeHeader = httpMessage.getFirstHeader(HttpHeaders.CONTENT_TYPE.getName()); + if (contentTypeHeader == null) { + contentCharset = charset; + return contentCharset; + } + + List elements = contentTypeHeader.getValueElements(); + if (elements.isEmpty()) { + contentCharset = charset; + return contentCharset; + } + + String charsetName = elements.get(0).getParamValue(HttpConstants.CONTENT_TYPE_CHARSET); + if (charsetName == null) { + contentCharset = charset; + return contentCharset; + } + + contentCharset = Charset.forName(charsetName); + return contentCharset; + } + + protected byte previousByte() { + int i = searchIndex - 1; + if ( i < buf.length()) { + return buf.byteAt(i); + } else { + return NUL; + } + } + + protected byte currentByte() { + int i = searchIndex; + if ( i < buf.length()) { + return buf.byteAt(i); + } else { + return NUL; + } + } + + protected byte nextByte() { + int i = searchIndex + 1; + if (i < buf.length()) { + return buf.byteAt(i); + } else { + return NUL; + } + } + + protected byte[] sliceByLength(int len) throws ProtocolException { + boolean done = false; + int offset = stateIndex; + int length = searchIndex - stateIndex; + if (len < length) { + throw new ProtocolException(ProtocolExceptionType.UNEXPECTED, "slice len=" + len + "< length=" + length); + } + + int tailIndex = offset + len - 1; + if (tailIndex < buf.length()) { + stateIndex = searchIndex = tailIndex; + done = true; + } else { + searchIndex = buf.length(); + } + + if (searchIndex > maxSize) { throw new ProtocolException(ProtocolExceptionType.MAX_SIZE_LIMIT, maxSize); } + + if (done) { + byte[] bytes = new byte[len]; + System.arraycopy(buf.buffer(), offset, bytes, 0, len); + return bytes; + } else { + return null; + } + } + + protected String sliceBySeparators(int shift, byte... separators) throws ProtocolException { + boolean done = false; + int offset = stateIndex; + int length = searchIndex - stateIndex; + for (int i = searchIndex; i < buf.length(); length++) { + if (length > maxLineLength) { throw new ProtocolException(ProtocolExceptionType.LINE_LENGTH_LIMIT, maxLineLength); } + + byte b = buf.byteAt(i); + searchIndex = ++i; + if (ByteUtil.indexOf(separators, b) >= 0) { + length = searchIndex - stateIndex - 1; + stateIndex = searchIndex; + done = true; + break; + } + } + + if (searchIndex > maxSize) { throw new ProtocolException(ProtocolExceptionType.MAX_SIZE_LIMIT, maxSize); } + + if (done) { + return new String(buf.buffer(), offset, length + shift, charset); + } else { + return null; + } + } + + protected boolean skip(byte... bytes) throws ProtocolException { + boolean done = false; + int length = searchIndex - stateIndex; + while (searchIndex < buf.length()) { + byte cb = currentByte(); + if (ByteUtil.indexOf(bytes, cb) < 0 && NUL != cb) { + done = true; + break; + } + slide(1); + length++; + if (length > maxSize) { throw new ProtocolException(ProtocolExceptionType.MAX_SIZE_LIMIT, maxSize); } + } + return done; + } + + protected void slide(int shift) throws ProtocolException { + stateIndex = searchIndex += shift; + if (searchIndex > maxSize) { + throw new ProtocolException(ProtocolExceptionType.MAX_SIZE_LIMIT, maxSize); + } + } + + protected void clear() { + contentCharset = null; + header = null; + entity = null; + chunk = null; + chunkExtName = null; + trailerSize = 0; + httpMessage = null; + } + + protected void resetIndex() { + searchIndex = splitIndex = stateIndex = 0; + } + + abstract boolean hasEntity(T httpMessage); + + // ~ ------------------------------------------------------------------------------------------------------------ + + public int getMaxLineLength() { + return maxLineLength; + } + + public void setMaxLineLength(int maxLineLength) { + this.maxLineLength = maxLineLength; + } + + public int getState() { + return state; + } + + public void setState(int state) { + this.state = state; + } + + public HttpHeader getHeader() { + return header; + } + + public void setHeader(HttpHeader header) { + this.header = header; + } + + public HttpEntity getEntity() { + return entity; + } + + public void setEntity(HttpEntity entity) { + this.entity = entity; + } + + public HttpChunk getChunk() { + return chunk; + } + + public void setChunk(HttpChunk chunk) { + this.chunk = chunk; + } + + public String getChunkExtName() { + return chunkExtName; + } + + public void setChunkExtName(String chunkExtName) { + this.chunkExtName = chunkExtName; + } + + @Override + public String toString() { + return String + .format("HttpDecoder [stateIndex=%s, state=%s, maxLineLength=%s, contentCharset=%s, header=%s, entity=%s, chunk=%s, chunkExtName=%s, trailerSize=%s, httpMessage=%s, defaultBufferSize=%s, buf=%s, splitIndex=%s, searchIndex=%s, maxSize=%s, charset=%s]", + stateIndex, state, maxLineLength, contentCharset, + header, entity, chunk, chunkExtName, trailerSize, + httpMessage, defaultBufferSize, buf, splitIndex, + searchIndex, maxSize, charset); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `HttpDecoder.httpMessage.getFirstHeader(org.craft.atom.protocol.http.model.HttpHeaders.CONTENT_LENGTH.getName())` could be null and is dereferenced at line 296. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HttpDecoder.state4ENTITY_LENGTH() + +### Procedure Id: +org.craft.atom.protocol.http.HttpDecoder.state4ENTITY_LENGTH():void.c4a8df0455a2d5af1ab1c7fccb0746d1 + +### File: +craft-atom-protocol-http/src/main/java/org/craft/atom/protocol/http/HttpDecoder.java + +### Key: +HttpDecoder.java|state4ENTITY_LENGTH|NULL_DEREFERENCE + +### Node Key: +9140dff8bf7cd03886d368c0c0c52aa5 + +### Hash: +81814cecd0968bdd6ef0df8ad7ada9ea + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9558/instruction.md b/inferredbugs-9558/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a43eeab5312506028a4f1a311aa50e4944eeb43 --- /dev/null +++ b/inferredbugs-9558/instruction.md @@ -0,0 +1,739 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** excel-streaming-reader +**Bug ID:** 10 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.monitorjbl.xlsx; + +import com.monitorjbl.xlsx.exceptions.MissingSheetException; +import org.apache.poi.openxml4j.opc.OPCPackage; +import org.apache.poi.openxml4j.opc.PackageAccess; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.DateUtil; +import org.apache.poi.ss.usermodel.Row; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.nullValue; +import static org.hamcrest.core.Is.is; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +public class StreamingReaderTest { + @BeforeClass + public static void init() { + Locale.setDefault(Locale.ENGLISH); + } + + @Test + public void testTypes() throws Exception { + SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy"); + try( + InputStream is = new FileInputStream(new File("src/test/resources/data_types.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(7, obj.size()); + List row; + + row = obj.get(0); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(1).getCellType()); + assertEquals("Type", row.get(0).getStringCellValue()); + assertEquals("Type", row.get(0).getRichStringCellValue().getString()); + assertEquals("Value", row.get(1).getStringCellValue()); + assertEquals("Value", row.get(1).getRichStringCellValue().getString()); + + row = obj.get(1); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(1).getCellType()); + assertEquals("string", row.get(0).getStringCellValue()); + assertEquals("string", row.get(0).getRichStringCellValue().getString()); + assertEquals("jib-jab", row.get(1).getStringCellValue()); + assertEquals("jib-jab", row.get(1).getRichStringCellValue().getString()); + + row = obj.get(2); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_NUMERIC, row.get(1).getCellType()); + assertEquals("int", row.get(0).getStringCellValue()); + assertEquals("int", row.get(0).getRichStringCellValue().getString()); + assertEquals(10, row.get(1).getNumericCellValue(), 0); + + row = obj.get(3); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_NUMERIC, row.get(1).getCellType()); + assertEquals("double", row.get(0).getStringCellValue()); + assertEquals("double", row.get(0).getRichStringCellValue().getString()); + assertEquals(3.14, row.get(1).getNumericCellValue(), 0); + + row = obj.get(4); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_NUMERIC, row.get(1).getCellType()); + assertEquals("date", row.get(0).getStringCellValue()); + assertEquals("date", row.get(0).getRichStringCellValue().getString()); + assertEquals(df.parse("1/1/2014"), row.get(1).getDateCellValue()); + assertTrue(DateUtil.isCellDateFormatted(row.get(1))); + + row = obj.get(5); + assertEquals(7, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(1).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(2).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(3).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(4).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(5).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(6).getCellType()); + assertEquals("long", row.get(0).getStringCellValue()); + assertEquals("long", row.get(0).getRichStringCellValue().getString()); + assertEquals("ass", row.get(1).getStringCellValue()); + assertEquals("ass", row.get(1).getRichStringCellValue().getString()); + assertEquals("row", row.get(2).getStringCellValue()); + assertEquals("row", row.get(2).getRichStringCellValue().getString()); + assertEquals("look", row.get(3).getStringCellValue()); + assertEquals("look", row.get(3).getRichStringCellValue().getString()); + assertEquals("at", row.get(4).getStringCellValue()); + assertEquals("at", row.get(4).getRichStringCellValue().getString()); + assertEquals("it", row.get(5).getStringCellValue()); + assertEquals("it", row.get(5).getRichStringCellValue().getString()); + assertEquals("go", row.get(6).getStringCellValue()); + assertEquals("go", row.get(6).getRichStringCellValue().getString()); + + row = obj.get(6); + assertEquals(3, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_BOOLEAN, row.get(1).getCellType()); + assertEquals(Cell.CELL_TYPE_BOOLEAN, row.get(2).getCellType()); + assertEquals("boolean", row.get(0).getStringCellValue()); + assertEquals("boolean", row.get(0).getRichStringCellValue().getString()); + assertEquals(true, row.get(1).getBooleanCellValue()); + assertEquals(false, row.get(2).getBooleanCellValue()); + } + } + + @Test + public void testGetDateCellValue() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/data_types.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + Date dt = obj.get(4).get(1).getDateCellValue(); + assertNotNull(dt); + final GregorianCalendar cal = new GregorianCalendar(); + cal.setTime(dt ); + assertEquals(cal.get(Calendar.YEAR), 2014); + + try { + obj.get(0).get(0).getDateCellValue(); + fail("Should have thrown IllegalStateException"); + } catch(IllegalStateException e) { } + } + } + @Test + public void testGetDateCellValue1904() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/1904Dates.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + Date dt = obj.get(1).get(5).getDateCellValue(); + assertNotNull(dt); + final GregorianCalendar cal = new GregorianCalendar(); + cal.setTime(dt ); + assertEquals(cal.get(Calendar.YEAR), 1991); + + try { + obj.get(0).get(0).getDateCellValue(); + fail("Should have thrown IllegalStateException"); + } catch(IllegalStateException e) { } + } + } + + @Test + public void testGetFirstCellNum() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/gaps.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + + List> obj = new ArrayList<>(); + List rows = new ArrayList<>(); + for(Row r : reader) { + rows.add(r); + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(3, rows.size()); + assertEquals(3, rows.get(2).getFirstCellNum()); + } + } + + @Test + public void testGaps() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/gaps.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(3, obj.size()); + List row; + + row = obj.get(0); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(1).getCellType()); + assertEquals("Dat", row.get(0).getStringCellValue()); + assertEquals("Dat", row.get(0).getRichStringCellValue().getString()); + assertEquals(0, row.get(0).getColumnIndex()); + assertEquals(0, row.get(0).getRowIndex()); + assertEquals("gap", row.get(1).getStringCellValue()); + assertEquals("gap", row.get(1).getRichStringCellValue().getString()); + assertEquals(2, row.get(1).getColumnIndex()); + assertEquals(0, row.get(1).getRowIndex()); + + row = obj.get(1); + assertEquals(2, row.size()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(0).getCellType()); + assertEquals(Cell.CELL_TYPE_STRING, row.get(1).getCellType()); + assertEquals("guuurrrrrl", row.get(0).getStringCellValue()); + assertEquals("guuurrrrrl", row.get(0).getRichStringCellValue().getString()); + assertEquals(0, row.get(0).getColumnIndex()); + assertEquals(6, row.get(0).getRowIndex()); + assertEquals("!", row.get(1).getStringCellValue()); + assertEquals("!", row.get(1).getRichStringCellValue().getString()); + assertEquals(6, row.get(1).getColumnIndex()); + assertEquals(6, row.get(1).getRowIndex()); + } + } + + @Test + public void testMultipleSheets_alpha() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/sheets.xlsx")); + StreamingReader reader = StreamingReader.builder() + .sheetIndex(0) + .read(is); + ) { + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(1, obj.size()); + List row; + + row = obj.get(0); + assertEquals(1, row.size()); + assertEquals("stuff", row.get(0).getStringCellValue()); + assertEquals("stuff", row.get(0).getRichStringCellValue().getString()); + } + } + + @Test + public void testMultipleSheets_zulu() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/sheets.xlsx")); + StreamingReader reader = StreamingReader.builder() + .sheetIndex(1) + .read(is); + ) { + + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(1, obj.size()); + List row; + + row = obj.get(0); + assertEquals(1, row.size()); + assertEquals("yeah", row.get(0).getStringCellValue()); + assertEquals("yeah", row.get(0).getRichStringCellValue().getString()); + } + } + + @Test + public void testSheetName_zulu() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/sheets.xlsx")); + StreamingReader reader = StreamingReader.builder() + .sheetName("SheetZulu") + .read(is); + ) { + + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(1, obj.size()); + List row; + + row = obj.get(0); + assertEquals(1, row.size()); + assertEquals("yeah", row.get(0).getStringCellValue()); + assertEquals("yeah", row.get(0).getRichStringCellValue().getString()); + } + } + + @Test + public void testSheetName_alpha() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/sheets.xlsx")); + StreamingReader reader = StreamingReader.builder() + .sheetName("SheetAlpha") + .read(is); + ) { + List> obj = new ArrayList<>(); + + for(Row r : reader) { + List o = new ArrayList<>(); + for(Cell c : r) { + o.add(c); + } + obj.add(o); + } + + assertEquals(1, obj.size()); + List row; + + row = obj.get(0); + assertEquals(1, row.size()); + assertEquals("stuff", row.get(0).getStringCellValue()); + assertEquals("stuff", row.get(0).getRichStringCellValue().getString()); + } + } + + @Test(expected = MissingSheetException.class) + public void testSheetName_missingInStream() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/sheets.xlsx")); + StreamingReader reader = StreamingReader.builder() + .sheetName("adsfasdfasdfasdf") + .read(is); + ) { + fail("Should have failed"); + } + } + + @Test + public void testSheetName_missingInFile() throws Exception { + File f = new File("src/test/resources/sheets.xlsx"); + try( + StreamingReader reader = StreamingReader.builder() + .sheetName("adsfasdfasdfasdf") + .read(f); + ) { + fail("Should have failed"); + } catch(MissingSheetException e) { + assertTrue(f.exists()); + } + } + + @Test + public void testIteration() throws Exception { + File f = new File("src/test/resources/large.xlsx"); + try( + StreamingReader reader = StreamingReader.builder() + .rowCacheSize(5) + .read(f)) { + int i = 1; + for(Row r : reader) { + assertEquals(i, r.getCell(0).getNumericCellValue(), 0); + assertEquals("#" + i, r.getCell(1).getStringCellValue()); + assertEquals("#" + i, r.getCell(1).getRichStringCellValue().getString()); + i++; + } + } + } + + @Test + public void testLeadingZeroes() throws Exception { + File f = new File("src/test/resources/leadingZeroes.xlsx"); + + try(StreamingReader reader = StreamingReader.builder().read(f)) { + Iterator iter = reader.iterator(); + iter.hasNext(); + + Row r1 = iter.next(); + assertEquals(1, r1.getCell(0).getNumericCellValue(), 0); + assertEquals("1", r1.getCell(0).getStringCellValue()); + assertEquals(Cell.CELL_TYPE_NUMERIC, r1.getCell(0).getCellType()); + + Row r2 = iter.next(); + assertEquals(2, r2.getCell(0).getNumericCellValue(), 0); + assertEquals("0002", r2.getCell(0).getStringCellValue()); + assertEquals("0002", r2.getCell(0).getRichStringCellValue().getString()); + assertEquals(Cell.CELL_TYPE_STRING, r2.getCell(0).getCellType()); + } + } + + @Test + public void testReadingEmptyFile() throws Exception { + File f = new File("src/test/resources/empty_sheet.xlsx"); + + try(StreamingReader reader = StreamingReader.builder().read(f)) { + Iterator iter = reader.iterator(); + assertThat(iter.hasNext(), is(false)); + } + } + + @Test + public void testSpecialStyles() throws Exception { + File f = new File("src/test/resources/special_types.xlsx"); + + Map> contents = new HashMap<>(); + try(StreamingReader reader = StreamingReader.builder().read(f)) { + for(Row row : reader) { + contents.put(row.getRowNum(), new ArrayList()); + for(Cell c : row) { + if(c.getColumnIndex() > 0) { + contents.get(row.getRowNum()).add(c); + } + } + } + } + + SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); + + assertThat(contents.size(), equalTo(2)); + assertThat(contents.get(0).size(), equalTo(4)); + assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14")); + assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014"))); + assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15")); + assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015"))); + assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015")); + assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015"))); + assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05")); + assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015"))); + + assertThat(contents.get(1).size(), equalTo(4)); + assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12")); + assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312)); + assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042")); + assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0)); + assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12")); + assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145)); + assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)")); + assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0)); + } + + @Test + public void testBlankNumerics() throws Exception { + File f = new File("src/test/resources/blank_cells.xlsx"); + try(StreamingReader reader = StreamingReader.builder().read(f)) { + Row row = reader.iterator().next(); + assertThat(row.getCell(1).getStringCellValue(), equalTo("")); + assertThat(row.getCell(1).getRichStringCellValue().getString(), equalTo("")); + assertThat(row.getCell(1).getDateCellValue(), is(nullValue())); + assertThat(row.getCell(1).getNumericCellValue(), equalTo(0.0)); + } + } + + @Test + public void testFirstRowNumIs0() throws Exception { + File f = new File("src/test/resources/data_types.xlsx"); + try(StreamingReader reader = StreamingReader.builder().read(f)) { + Row row = reader.iterator().next(); + assertThat(row.getRowNum(), equalTo(0)); + } + } + + @Test + public void testNoTypeCell() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/no_type_cell.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is);) { + for(Row r : reader) { + for(Cell c : r) { + assertEquals("1", c.getStringCellValue()); + } + } + } + } + + @Test + public void testEncryption() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/encrypted.xlsx")); + StreamingReader reader = StreamingReader.builder().password("test").read(is);) { + OUTER: + for(Row r : reader) { + for(Cell c : r) { + assertEquals("Demo", c.getStringCellValue()); + assertEquals("Demo", c.getRichStringCellValue().getString()); + break OUTER; + } + } + } + } + + @Test + public void testStringCellValue() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/blank_cell_StringCellValue.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + for(Row r : reader) { + if(r.getRowNum() == 1) { + assertEquals("", r.getCell(1).getStringCellValue()); + assertEquals("", r.getCell(1).getRichStringCellValue().getString()); + } + } + } + } + + @Test + public void testNullValueType() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/null_celltype.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + for(Row r : reader) { + for(Cell cell : r) { + if(r.getRowNum() == 0 && cell.getColumnIndex() == 8) { + assertEquals(0, cell.getCellType()); + assertEquals("8:00:00", cell.getStringCellValue()); + } + } + } + } + } + + @Test + public void testInlineCells() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/inline.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + Row row = reader.iterator().next(); + assertEquals("First inline cell", row.getCell(0).getStringCellValue()); + assertEquals("First inline cell", row.getCell(0).getRichStringCellValue().getString()); + assertEquals("Second inline cell", row.getCell(1).getStringCellValue()); + assertEquals("Second inline cell", row.getCell(1).getRichStringCellValue().getString()); + } + } + + @Test + public void testMissingRattrs() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/missing-r-attrs.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + Row row = reader.iterator().next(); + assertEquals(0, row.getRowNum()); + assertEquals("1", row.getCell(0).getStringCellValue()); + assertEquals("5", row.getCell(4).getStringCellValue()); + row = reader.iterator().next(); + assertEquals(1, row.getRowNum()); + assertEquals("6", row.getCell(0).getStringCellValue()); + assertEquals("10", row.getCell(4).getStringCellValue()); + row = reader.iterator().next(); + assertEquals(6, row.getRowNum()); + assertEquals("11", row.getCell(0).getStringCellValue()); + assertEquals("15", row.getCell(4).getStringCellValue()); + + assertFalse(reader.iterator().hasNext()); + } + } + + @Test + public void testClosingFiles() throws Exception { + OPCPackage o = OPCPackage.open(new File("src/test/resources/blank_cell_StringCellValue.xlsx"), PackageAccess.READ); + o.close(); + } + + @Test + public void shouldIgnoreSpreadsheetDrawingRows() throws Exception { + try( + InputStream is = new FileInputStream(new File("src/test/resources/has_spreadsheetdrawing.xlsx")); + StreamingReader reader = StreamingReader.builder().read(is); + ) { + Iterator iterator = reader.iterator(); + while(iterator.hasNext()) { + iterator.next(); + } + } + } + + @Test + public void testShouldReturnNullForMissingCellPolicy_RETURN_BLANK_AS_NULL() throws Exception { + try ( + InputStream is = new FileInputStream(new File("src/test/resources/blank_cells.xlsx")); + StreamingReader reader = StreamingReader.builder() + .read(is); + ) { + Row row = reader.iterator().next(); + assertNotNull(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //Remain unchanged + assertNull(row.getCell(1, Row.RETURN_BLANK_AS_NULL)); + } + } + + @Test + public void testShouldReturnBlankForMissingCellPolicy_CREATE_NULL_AS_BLANK() throws Exception { + try ( + InputStream is = new FileInputStream(new File("src/test/resources/null_cell.xlsx")); + StreamingReader reader = StreamingReader.builder() + .read(is); + ) { + Row row = reader.iterator().next(); + assertEquals("B1 is Null ->", row.getCell(0, Row.CREATE_NULL_AS_BLANK).getStringCellValue()); //Remain unchanged + assertEquals("B1 is Null ->", row.getCell(0, Row.CREATE_NULL_AS_BLANK).getRichStringCellValue().getString()); //Remain unchanged + assertThat(row.getCell(1), is(nullValue())); + assertNotNull(row.getCell(1, Row.CREATE_NULL_AS_BLANK)); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `contents.get(valueOf(1))` could be null and is dereferenced at line 489. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void StreamingReaderTest.testSpecialStyles() + +### Procedure Id: +com.monitorjbl.xlsx.StreamingReaderTest.testSpecialStyles():void.c7d60781c8a19dd7d3651b5e77b5e80a + +### File: +src/test/java/com/monitorjbl/xlsx/StreamingReaderTest.java + +### Key: +StreamingReaderTest.java|testSpecialStyles|NULL_DEREFERENCE + +### Node Key: +82bc4705d6466a0b8509dff7973fc602 + +### Hash: +fa7b7da17623c8cc43d09d1a3343800c + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9567/instruction.md b/inferredbugs-9567/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1b77cd35e54b7b846cf2533f23b42e7249b6eba --- /dev/null +++ b/inferredbugs-9567/instruction.md @@ -0,0 +1,415 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 50 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.integration.task; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.PropertyKey; +import org.apache.helix.TestHelper; +import org.apache.helix.task.JobConfig; +import org.apache.helix.task.JobContext; +import org.apache.helix.task.JobQueue; +import org.apache.helix.task.TargetState; +import org.apache.helix.task.TaskState; +import org.apache.helix.task.WorkflowConfig; +import org.apache.helix.task.WorkflowContext; +import org.apache.log4j.Logger; +import org.testng.Assert; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Sets; + +public class TestRecurringJobQueue extends TaskTestBase { + private static final Logger LOG = Logger.getLogger(TestRecurringJobQueue.class); + + @Test + public void deleteRecreateRecurrentQueue() throws Exception { + String queueName = TestHelper.getTestMethodName(); + + // Create a queue + LOG.info("Starting job-queue: " + queueName); + JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName); + List currentJobNames = createAndEnqueueJob(queueBuild, 2); + + _driver.start(queueBuild.build()); + + WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + + // ensure job 1 is started before stop it + String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + String namedSpaceJob1 = String.format("%s_%s", scheduledQueue, currentJobNames.get(0)); + _driver.pollForJobState(scheduledQueue, namedSpaceJob1, TaskState.IN_PROGRESS); + + _driver.stop(queueName); + _driver.delete(queueName); + Thread.sleep(500); + + JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName, 5); + currentJobNames.clear(); + currentJobNames = createAndEnqueueJob(queueBuilder, 2); + + _driver.createQueue(queueBuilder.build()); + + + wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + + // ensure jobs are started and completed + scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + namedSpaceJob1 = String.format("%s_%s", scheduledQueue, currentJobNames.get(0)); + _driver.pollForJobState(scheduledQueue, namedSpaceJob1, TaskState.COMPLETED); + + scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + String namedSpaceJob2 = String.format("%s_%s", scheduledQueue, currentJobNames.get(1)); + _driver.pollForJobState(scheduledQueue, namedSpaceJob2, TaskState.COMPLETED); + } + + @Test + public void stopDeleteJobAndResumeRecurrentQueue() throws Exception { + String queueName = TestHelper.getTestMethodName(); + + // Create a queue + LOG.info("Starting job-queue: " + queueName); + JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName, 5); + + // Create and Enqueue jobs + Map commandConfig = ImmutableMap.of(MockTask.TIMEOUT_CONFIG, String.valueOf(500)); + Thread.sleep(100); + List currentJobNames = createAndEnqueueJob(queueBuilder, 5); + _driver.createQueue(queueBuilder.build()); + + WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + + // ensure job 1 is started before deleting it + String deletedJob1 = currentJobNames.get(0); + String namedSpaceDeletedJob1 = String.format("%s_%s", scheduledQueue, deletedJob1); + _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.IN_PROGRESS, + TaskState.COMPLETED); + + // stop the queue + LOG.info("Pausing job-queue: " + scheduledQueue); + _driver.stop(queueName); + _driver.pollForJobState(scheduledQueue, namedSpaceDeletedJob1, TaskState.STOPPED); + _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); + + // delete the in-progress job (job 1) and verify it being deleted + _driver.deleteJob(queueName, deletedJob1); + verifyJobDeleted(queueName, namedSpaceDeletedJob1); + verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob1); + + LOG.info("Resuming job-queue: " + queueName); + _driver.resume(queueName); + + // ensure job 2 is started + _driver.pollForJobState(scheduledQueue, + String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.IN_PROGRESS, + TaskState.COMPLETED); + + // stop the queue + LOG.info("Pausing job-queue: " + queueName); + _driver.stop(queueName); + _driver.pollForJobState(scheduledQueue, + String.format("%s_%s", scheduledQueue, currentJobNames.get(1)), TaskState.STOPPED); + _driver.pollForWorkflowState(scheduledQueue, TaskState.STOPPED); + + // Ensure job 3 is not started before deleting it + String deletedJob2 = currentJobNames.get(2); + String namedSpaceDeletedJob2 = String.format("%s_%s", scheduledQueue, deletedJob2); + TaskTestUtil.pollForEmptyJobState(_driver, scheduledQueue, namedSpaceDeletedJob2); + + // delete not-started job (job 3) and verify it being deleted + _driver.deleteJob(queueName, deletedJob2); + verifyJobDeleted(queueName, namedSpaceDeletedJob2); + verifyJobDeleted(scheduledQueue, namedSpaceDeletedJob2); + + LOG.info("Resuming job-queue: " + queueName); + _driver.resume(queueName); + + // Ensure the jobs left are successful completed in the correct order + currentJobNames.remove(deletedJob1); + currentJobNames.remove(deletedJob2); + long preJobFinish = 0; + for (int i = 0; i < currentJobNames.size(); i++) { + String namedSpaceJobName = String.format("%s_%s", scheduledQueue, currentJobNames.get(i)); + _driver.pollForJobState(scheduledQueue, namedSpaceJobName, TaskState.COMPLETED); + + JobContext jobContext = _driver.getJobContext(namedSpaceJobName); + long jobStart = jobContext.getStartTime(); + Assert.assertTrue(jobStart >= preJobFinish); + preJobFinish = jobContext.getFinishTime(); + } + // verify the job is not there for the next recurrence of queue schedule + } + + @Test + public void deleteJobFromRecurrentQueueNotStarted() throws Exception { + String queueName = TestHelper.getTestMethodName(); + + // Create a queue + LOG.info("Starting job-queue: " + queueName); + JobQueue.Builder queueBuilder = TaskTestUtil.buildRecurrentJobQueue(queueName); + + // create jobs + List jobs = new ArrayList(); + List jobNames = new ArrayList(); + Map commandConfig = ImmutableMap.of(MockTask.TIMEOUT_CONFIG, String.valueOf(500)); + + final int JOB_COUNTS = 3; + for (int i = 0; i < JOB_COUNTS; i++) { + String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; + + JobConfig.Builder job = new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) + .setJobCommandConfigMap(commandConfig).setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) + .setTargetPartitionStates(Sets.newHashSet(targetPartition)); + jobs.add(job); + jobNames.add(targetPartition.toLowerCase() + "Job" + i); + } + + // enqueue all jobs except last one + for (int i = 0; i < JOB_COUNTS - 1; ++i) { + LOG.info("Enqueuing job: " + jobNames.get(i)); + queueBuilder.enqueueJob(jobNames.get(i), jobs.get(i)); + } + + _driver.createQueue(queueBuilder.build()); + + String currentLastJob = jobNames.get(JOB_COUNTS - 2); + + WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + + // ensure all jobs are finished + String namedSpaceJob = String.format("%s_%s", scheduledQueue, currentLastJob); + _driver.pollForJobState(scheduledQueue, namedSpaceJob, TaskState.COMPLETED); + + // enqueue the last job + LOG.info("Enqueuing job: " + jobNames.get(JOB_COUNTS - 1)); + _driver.enqueueJob(queueName, jobNames.get(JOB_COUNTS - 1), jobs.get(JOB_COUNTS - 1)); + _driver.stop(queueName); + + // remove the last job + _driver.deleteJob(queueName, jobNames.get(JOB_COUNTS - 1)); + + // verify + verifyJobDeleted(queueName, + String.format("%s_%s", scheduledQueue, jobNames.get(JOB_COUNTS - 1))); + } + + @Test + public void testCreateStoppedQueue() throws InterruptedException { + String queueName = TestHelper.getTestMethodName(); + + // Create a queue + LOG.info("Starting job-queue: " + queueName); + JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 600000, + TargetState.STOP); + createAndEnqueueJob(queueBuild, 2); + + _driver.createQueue(queueBuild.build()); + WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); + Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); + + _driver.resume(queueName); + + //TaskTestUtil.pollForWorkflowState(_driver, queueName, ); + WorkflowContext wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + + // ensure current schedule is started + String scheduledQueue = wCtx.getLastScheduledSingleWorkflow(); + _driver.pollForWorkflowState(scheduledQueue, TaskState.COMPLETED); + } + + @Test + public void testDeletingRecurrentQueueWithHistory() throws Exception { + final String queueName = TestHelper.getTestMethodName(); + int intervalSeconds = 3; + + // Create a queue + LOG.info("Starting job-queue: " + queueName); + JobQueue.Builder queueBuild = TaskTestUtil.buildRecurrentJobQueue(queueName, 0, 60, + TargetState.STOP); + createAndEnqueueJob(queueBuild, 2); + + _driver.createQueue(queueBuild.build()); + WorkflowConfig workflowConfig = _driver.getWorkflowConfig(queueName); + Assert.assertEquals(workflowConfig.getTargetState(), TargetState.STOP); + + // reset interval to a smaller number so as to accelerate test + workflowConfig.putSimpleConfig(WorkflowConfig.WorkflowConfigProperty.RecurrenceInterval.name(), + "" + intervalSeconds); + _driver.updateWorkflow(queueName, workflowConfig); + + _driver.resume(queueName); + + WorkflowContext wCtx; + // wait until at least 2 workflows are scheduled based on template queue + do { + Thread.sleep(intervalSeconds); + wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + } while (wCtx.getScheduledWorkflows().size() < 2); + + // Stop recurring workflow + _driver.stop(queueName); + _driver.pollForWorkflowState(queueName, TaskState.STOPPED); + + // Record all scheduled workflows + wCtx = TaskTestUtil.pollForWorkflowContext(_driver, queueName); + List scheduledWorkflows = new ArrayList(wCtx.getScheduledWorkflows()); + final String lastScheduledWorkflow = wCtx.getLastScheduledSingleWorkflow(); + + // Delete recurrent workflow + _driver.delete(queueName); + + // Wait until recurrent workflow and the last scheduled workflow are cleaned up + boolean result = TestHelper.verify(new TestHelper.Verifier() { + @Override public boolean verify() throws Exception { + WorkflowContext wCtx = _driver.getWorkflowContext(queueName); + WorkflowContext lastWfCtx = _driver.getWorkflowContext(lastScheduledWorkflow); + return (wCtx == null && lastWfCtx == null); + } + }, 5 * 1000); + Assert.assertTrue(result); + + for (String scheduledWorkflow : scheduledWorkflows) { + WorkflowContext scheduledWorkflowCtx = _driver.getWorkflowContext(scheduledWorkflow); + WorkflowConfig scheduledWorkflowCfg = _driver.getWorkflowConfig(scheduledWorkflow); + Assert.assertNull(scheduledWorkflowCtx); + Assert.assertNull(scheduledWorkflowCfg); + } + } + + @Test + public void testGetNoExistWorkflowConfig() { + String randomName = "randomJob"; + WorkflowConfig workflowConfig = _driver.getWorkflowConfig(randomName); + Assert.assertNull(workflowConfig); + JobConfig jobConfig = _driver.getJobConfig(randomName); + Assert.assertNull(jobConfig); + WorkflowContext workflowContext = _driver.getWorkflowContext(randomName); + Assert.assertNull(workflowContext); + JobContext jobContext = _driver.getJobContext(randomName); + Assert.assertNull(jobContext); + } + + private void verifyJobDeleted(String queueName, String jobName) throws Exception { + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + PropertyKey.Builder keyBuilder = accessor.keyBuilder(); + + Assert.assertNull(accessor.getProperty(keyBuilder.idealStates(jobName))); + Assert.assertNull(accessor.getProperty(keyBuilder.resourceConfig(jobName))); + TaskTestUtil.pollForEmptyJobState(_driver, queueName, jobName); + } + + private List createAndEnqueueJob(JobQueue.Builder queueBuild, int jobCount) { + List currentJobNames = new ArrayList(); + for (int i = 0; i < jobCount; i++) { + String targetPartition = (i == 0) ? "MASTER" : "SLAVE"; + + JobConfig.Builder jobConfig = + new JobConfig.Builder().setCommand(MockTask.TASK_COMMAND) + .setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) + .setTargetPartitionStates(Sets.newHashSet(targetPartition)); + String jobName = targetPartition.toLowerCase() + "Job" + i; + queueBuild.enqueueJob(jobName, jobConfig); + currentJobNames.add(jobName); + } + Assert.assertEquals(currentJobNames.size(), jobCount); + return currentJobNames; + } +} + + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `workflowConfig` last assigned on line 255 could be null and is dereferenced at line 256. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestRecurringJobQueue.testDeletingRecurrentQueueWithHistory() + +### Procedure Id: +org.apache.helix.integration.task.TestRecurringJobQueue.testDeletingRecurrentQueueWithHistory():void.9096ca5f7eec2684cc626fade56c18b4 + +### File: +helix-core/src/test/java/org/apache/helix/integration/task/TestRecurringJobQueue.java + +### Key: +TestRecurringJobQueue.java|testDeletingRecurrentQueueWithHistory|NULL_DEREFERENCE + +### Node Key: +7da37724fa80369a9d8bdb2726ece453 + +### Hash: +06ba81848cce7e3db58768a155f2e208 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9593/instruction.md b/inferredbugs-9593/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fafc2cd56d870a56987eeec56bcdbd33e2b819de --- /dev/null +++ b/inferredbugs-9593/instruction.md @@ -0,0 +1,1473 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 80 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.concurrent.TimeUnit; +import javax.management.JMException; + +import com.google.common.collect.Sets; + +import org.apache.helix.BaseDataAccessor; +import org.apache.helix.ClusterMessagingService; +import org.apache.helix.ConfigAccessor; +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixConstants.ChangeType; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixException; +import org.apache.helix.HelixManager; +import org.apache.helix.HelixManagerProperties; +import org.apache.helix.HelixManagerProperty; +import org.apache.helix.HelixPropertyFactory; +import org.apache.helix.HelixTimerTask; +import org.apache.helix.InstanceType; +import org.apache.helix.LiveInstanceInfoProvider; +import org.apache.helix.PreConnectCallback; +import org.apache.helix.PropertyKey; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.PropertyPathBuilder; +import org.apache.helix.PropertyType; +import org.apache.helix.SystemPropertyKeys; +import org.apache.helix.api.listeners.ClusterConfigChangeListener; +import org.apache.helix.api.listeners.ConfigChangeListener; +import org.apache.helix.api.listeners.ControllerChangeListener; +import org.apache.helix.api.listeners.CurrentStateChangeListener; +import org.apache.helix.api.listeners.CustomizedStateChangeListener; +import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener; +import org.apache.helix.api.listeners.CustomizedStateRootChangeListener; +import org.apache.helix.api.listeners.CustomizedViewChangeListener; +import org.apache.helix.api.listeners.CustomizedViewRootChangeListener; +import org.apache.helix.api.listeners.ExternalViewChangeListener; +import org.apache.helix.api.listeners.IdealStateChangeListener; +import org.apache.helix.api.listeners.InstanceConfigChangeListener; +import org.apache.helix.api.listeners.LiveInstanceChangeListener; +import org.apache.helix.api.listeners.MessageListener; +import org.apache.helix.api.listeners.ResourceConfigChangeListener; +import org.apache.helix.api.listeners.ScopedConfigChangeListener; +import org.apache.helix.controller.GenericHelixController; +import org.apache.helix.controller.pipeline.Pipeline; +import org.apache.helix.healthcheck.ParticipantHealthReportCollector; +import org.apache.helix.healthcheck.ParticipantHealthReportCollectorImpl; +import org.apache.helix.healthcheck.ParticipantHealthReportTask; +import org.apache.helix.messaging.DefaultMessagingService; +import org.apache.helix.model.BuiltInStateModelDefinitions; +import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.monitoring.ZKPathDataDumpTask; +import org.apache.helix.monitoring.mbeans.HelixCallbackMonitor; +import org.apache.helix.monitoring.mbeans.MonitorLevel; +import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; +import org.apache.helix.participant.HelixStateMachineEngine; +import org.apache.helix.participant.StateMachineEngine; +import org.apache.helix.store.zk.AutoFallbackPropertyStore; +import org.apache.helix.store.zk.ZkHelixPropertyStore; +import org.apache.helix.util.HelixUtil; +import org.apache.helix.zookeeper.api.client.HelixZkClient; +import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.HelixZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory; +import org.apache.helix.zookeeper.zkclient.IZkStateListener; +import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException; +import org.apache.helix.zookeeper.zkclient.serialize.PathBasedZkSerializer; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.helix.zookeeper.datamodel.serializer.ChainedPathZkSerializer; +import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; + +public class ZKHelixManager implements HelixManager, IZkStateListener { + private static Logger LOG = LoggerFactory.getLogger(ZKHelixManager.class); + + public static final String ALLOW_PARTICIPANT_AUTO_JOIN = "allowParticipantAutoJoin"; + private static final int FLAPPING_TIME_WINDOW = 300000; // Default to 300 sec + public static final int DEFAULT_MAX_DISCONNECT_THRESHOLD = 600; // Default to be a large number + private static final int DEFAULT_WAIT_CONNECTED_TIMEOUT = 10 * 1000; // wait until connected for up to 10 seconds. + + protected final String _zkAddress; + private final String _clusterName; + private final String _instanceName; + private final InstanceType _instanceType; + private final int _waitForConnectedTimeout; // wait time for testing connect + private final int _sessionTimeout; // client side session timeout, will be overridden by server timeout. Disconnect after timeout + private final int _connectionInitTimeout; // client timeout to init connect + private final List _preConnectCallbacks; + protected final List _handlers; + private final HelixManagerProperties _properties; + private final HelixManagerProperty _helixManagerProperty; + private final HelixManagerStateListener _stateListener; + + /** + * helix version# + */ + private final String _version; + private int _reportLatency; + + protected RealmAwareZkClient _zkclient; + private final DefaultMessagingService _messagingService; + private Map _callbackMonitors; + + private final MonitorLevel _monitorLevel; + + private BaseDataAccessor _baseDataAccessor; + private ZKHelixDataAccessor _dataAccessor; + private final Builder _keyBuilder; + private ConfigAccessor _configAccessor; + private ZkHelixPropertyStore _helixPropertyStore; + protected LiveInstanceInfoProvider _liveInstanceInfoProvider = null; + + private volatile String _sessionId; + + /** + * Keep track of timestamps that zk State has become Disconnected If in a _timeWindowLengthMs + * window zk State has become Disconnected for more than_maxDisconnectThreshold times disconnect + * the zkHelixManager + */ + private final List _disconnectTimeHistory = new ArrayList(); + private final int _flappingTimeWindowMs; + private final int _maxDisconnectThreshold; + + /** + * participant fields + */ + private final StateMachineEngine _stateMachineEngine; + private final List _timerTasks = new ArrayList<>(); + + private final ParticipantHealthReportCollectorImpl _participantHealthInfoCollector; + private Long _sessionStartTime; + private ParticipantManager _participantManager; + + /** + * controller fields + */ + private GenericHelixController _controller; + private Set _enabledPipelineTypes; + private CallbackHandler _leaderElectionHandler = null; + protected final List _controllerTimerTasks = new ArrayList<>(); + + /** + * status dump timer-task + */ + protected static class StatusDumpTask extends HelixTimerTask { + final HelixManager helixController; + + public StatusDumpTask(HelixManager helixController) { + this.helixController = helixController; + } + + @Override + public synchronized void start() { + long initialDelay = 0; + long period = 15 * 60 * 1000; + long timeThresholdNoChangeForStatusUpdates = 15 * 60 * 1000; // 15 minutes + long timeThresholdNoChangeForErrors = 24 * 60 * 60 * 1000; // 1 day + int maximumNumberOfLeafNodesAllowed = 100; + + if (_timer == null) { + LOG.info("Start StatusDumpTask"); + _timer = new Timer("StatusDumpTimerTask", true); + _timer.scheduleAtFixedRate( + new ZKPathDataDumpTask(helixController, timeThresholdNoChangeForStatusUpdates, + timeThresholdNoChangeForErrors, maximumNumberOfLeafNodesAllowed), initialDelay, + period); + } + } + + @Override + public synchronized void stop() { + if (_timer != null) { + LOG.info("Stop StatusDumpTask"); + _timer.cancel(); + _timer = null; + } + } + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress) { + this(clusterName, instanceName, instanceType, zkAddress, null); + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress, HelixManagerStateListener stateListener) { + this(clusterName, instanceName, instanceType, zkAddress, stateListener, + HelixPropertyFactory.getInstance().getHelixManagerProperty(zkAddress, clusterName)); + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress, HelixManagerStateListener stateListener, + HelixManagerProperty helixManagerProperty) { + + LOG.info("Create a zk-based cluster manager. zkSvr: " + zkAddress + ", clusterName: " + + clusterName + ", instanceName: " + instanceName + ", type: " + instanceType); + + _zkAddress = zkAddress; + _clusterName = clusterName; + _instanceType = instanceType; + + if (instanceName == null) { + try { + instanceName = + InetAddress.getLocalHost().getCanonicalHostName() + "-" + instanceType.toString(); + } catch (UnknownHostException e) { + // can ignore it + LOG.info("Unable to get host name. Will set it to UNKNOWN, mostly ignorable", e); + instanceName = "UNKNOWN"; + } + } + + _instanceName = instanceName; + _enabledPipelineTypes = + Sets.newHashSet(Pipeline.Type.DEFAULT, Pipeline.Type.TASK); + _preConnectCallbacks = new ArrayList<>(); + _handlers = new ArrayList<>(); + _properties = new HelixManagerProperties(SystemPropertyKeys.CLUSTER_MANAGER_VERSION); + _version = _properties.getVersion(); + + _keyBuilder = new Builder(clusterName); + _messagingService = new DefaultMessagingService(this); + try { + _callbackMonitors = new HashMap<>(); + for (ChangeType changeType : ChangeType.values()) { + HelixCallbackMonitor callbackMonitor = + new HelixCallbackMonitor(instanceType, clusterName, instanceName, changeType); + callbackMonitor.register(); + _callbackMonitors.put(changeType, callbackMonitor); + } + } catch (JMException e) { + LOG.error("Error in creating callback monitor.", e); + } + + _stateListener = stateListener; + _helixManagerProperty = helixManagerProperty; + + /** + * use system property if available + */ + _flappingTimeWindowMs = HelixUtil.getSystemPropertyAsInt(SystemPropertyKeys.FLAPPING_TIME_WINDOW, + ZKHelixManager.FLAPPING_TIME_WINDOW); + + _maxDisconnectThreshold = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.MAX_DISCONNECT_THRESHOLD, + ZKHelixManager.DEFAULT_MAX_DISCONNECT_THRESHOLD); + + _sessionTimeout = HelixUtil.getSystemPropertyAsInt(SystemPropertyKeys.ZK_SESSION_TIMEOUT, + HelixZkClient.DEFAULT_SESSION_TIMEOUT); + + _connectionInitTimeout = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.ZK_CONNECTION_TIMEOUT, + HelixZkClient.DEFAULT_CONNECTION_TIMEOUT); + + _waitForConnectedTimeout = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT, + DEFAULT_WAIT_CONNECTED_TIMEOUT); + + _reportLatency = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.PARTICIPANT_HEALTH_REPORT_LATENCY, + ParticipantHealthReportTask.DEFAULT_REPORT_LATENCY); + + MonitorLevel configuredMonitorLevel; + try { + configuredMonitorLevel = MonitorLevel.valueOf( + System.getProperty(SystemPropertyKeys.MONITOR_LEVEL, MonitorLevel.DEFAULT.name())); + } catch (IllegalArgumentException ex) { + LOG.warn("Unrecognizable Monitor Level configuration. Use DEFAULT monitor level.", ex); + configuredMonitorLevel = MonitorLevel.DEFAULT; + } + _monitorLevel = configuredMonitorLevel; + + /** + * instance type specific init + */ + switch (instanceType) { + case PARTICIPANT: + _stateMachineEngine = new HelixStateMachineEngine(this); + _participantHealthInfoCollector = + new ParticipantHealthReportCollectorImpl(this, _instanceName); + _timerTasks + .add(new ParticipantHealthReportTask(_participantHealthInfoCollector, _reportLatency)); + break; + case CONTROLLER: + _stateMachineEngine = null; + _participantHealthInfoCollector = null; + _controllerTimerTasks.add(new StatusDumpTask(this)); + + break; + case CONTROLLER_PARTICIPANT: + _stateMachineEngine = new HelixStateMachineEngine(this); + _participantHealthInfoCollector = + new ParticipantHealthReportCollectorImpl(this, _instanceName); + + _timerTasks + .add(new ParticipantHealthReportTask(_participantHealthInfoCollector, _reportLatency)); + _controllerTimerTasks.add(new StatusDumpTask(this)); + break; + case ADMINISTRATOR: + case SPECTATOR: + _stateMachineEngine = null; + _participantHealthInfoCollector = null; + break; + default: + throw new IllegalArgumentException("unrecognized type: " + instanceType); + } + } + + public void setEnabledControlPipelineTypes(Set types) { + if (!InstanceType.CONTROLLER.equals(_instanceType) && !InstanceType.CONTROLLER_PARTICIPANT + .equals(_instanceType)) { + throw new IllegalStateException( + String.format("Cannot enable control pipeline for instance type %s", _instanceType)); + } + _enabledPipelineTypes = types; + } + + @Override public boolean removeListener(PropertyKey key, Object listener) { + LOG.info("Removing listener: " + listener + " on path: " + key.getPath() + " from cluster: " + + _clusterName + " by instance: " + _instanceName); + + synchronized (this) { + List toRemove = new ArrayList<>(); + for (CallbackHandler handler : _handlers) { + // compare property-key path and listener reference + if (handler.getPath().equals(key.getPath()) && handler.getListener().equals(listener)) { + toRemove.add(handler); + } + } + + _handlers.removeAll(toRemove); + + // handler.reset() may modify the handlers list, so do it outside the iteration + for (CallbackHandler handler : toRemove) { + handler.reset(true); + } + } + + return true; + } + + void checkConnected() { + checkConnected(-1); + } + + /** + * Check if HelixManager is connected, if it is not connected, + * wait for the specified timeout and check again before return. + * + * @param timeout + */ + void checkConnected(long timeout) { + if (_zkclient == null || _zkclient.isClosed()) { + throw new HelixException( + "HelixManager (ZkClient) is not connected. Call HelixManager#connect()"); + } + + boolean isConnected = isConnected(); + if (!isConnected && timeout > 0) { + LOG.warn( + "zkClient to " + _zkAddress + " is not connected, wait for " + _waitForConnectedTimeout + + "ms."); + isConnected = _zkclient.waitUntilConnected(_waitForConnectedTimeout, TimeUnit.MILLISECONDS); + } + + if (!isConnected) { + LOG.error("zkClient is not connected after waiting " + timeout + "ms." + + ", clusterName: " + _clusterName + ", zkAddress: " + _zkAddress); + throw new HelixException( + "HelixManager is not connected within retry timeout for cluster " + _clusterName); + } + } + + void addListener(Object listener, PropertyKey propertyKey, ChangeType changeType, + EventType[] eventType) { + checkConnected(_waitForConnectedTimeout); + + PropertyType type = propertyKey.getType(); + + synchronized (this) { + for (CallbackHandler handler : _handlers) { + // compare property-key path and listener reference + if (handler.getPath().equals(propertyKey.getPath()) + && handler.getListener().equals(listener)) { + LOG.info("Listener: " + listener + " on path: " + propertyKey.getPath() + + " already exists. skip add"); + + return; + } + } + + CallbackHandler newHandler = + new CallbackHandler(this, _zkclient, propertyKey, listener, eventType, changeType, + _callbackMonitors.get(changeType)); + + _handlers.add(newHandler); + LOG.info("Added listener: " + listener + " for type: " + type + " to path: " + + newHandler.getPath()); + } + } + + @Override + public void addIdealStateChangeListener(final IdealStateChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addIdealStateChangeListener(final org.apache.helix.IdealStateChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).liveInstances(), ChangeType.LIVE_INSTANCE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addLiveInstanceChangeListener(org.apache.helix.LiveInstanceChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).liveInstances(), ChangeType.LIVE_INSTANCE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addConfigChangeListener(ConfigChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addInstanceConfigChangeListener(InstanceConfigChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Deprecated + @Override + public void addInstanceConfigChangeListener(org.apache.helix.InstanceConfigChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addResourceConfigChangeListener(ResourceConfigChangeListener listener) throws Exception{ + addListener(listener, new Builder(_clusterName).resourceConfigs(), ChangeType.RESOURCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedStateConfigChangeListener( + CustomizedStateConfigChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).customizedStateConfig(), + ChangeType.CUSTOMIZED_STATE_CONFIG, new EventType[] { + EventType.NodeDataChanged + }); + } + + @Override + public void addClusterfigChangeListener(ClusterConfigChangeListener listener) throws Exception{ + addListener(listener, new Builder(_clusterName).clusterConfig(), ChangeType.CLUSTER_CONFIG, + new EventType[] { EventType.NodeDataChanged + }); + } + + @Override + public void addConfigChangeListener(ScopedConfigChangeListener listener, ConfigScopeProperty scope) + throws Exception { + Builder keyBuilder = new Builder(_clusterName); + + PropertyKey propertyKey = null; + switch (scope) { + case CLUSTER: + propertyKey = keyBuilder.clusterConfigs(); + break; + case PARTICIPANT: + propertyKey = keyBuilder.instanceConfigs(); + break; + case RESOURCE: + propertyKey = keyBuilder.resourceConfigs(); + break; + default: + break; + } + + if (propertyKey != null) { + addListener(listener, propertyKey, ChangeType.CONFIG, new EventType[] { + EventType.NodeChildrenChanged + }); + } else { + LOG.error("Can't add listener to config scope: " + scope); + } + } + + + @Deprecated + @Override + public void addConfigChangeListener(org.apache.helix.ScopedConfigChangeListener listener, ConfigScopeProperty scope) + throws Exception { + addConfigChangeListener((ScopedConfigChangeListener) listener, scope); + } + + // TODO: Decide if do we still need this since we are exposing + // ClusterMessagingService + @Override + public void addMessageListener(MessageListener listener, String instanceName) { + addListener(listener, new Builder(_clusterName).messages(instanceName), ChangeType.MESSAGE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addMessageListener(org.apache.helix.MessageListener listener, String instanceName) { + addListener(listener, new Builder(_clusterName).messages(instanceName), ChangeType.MESSAGE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addControllerMessageListener(MessageListener listener) { + addListener(listener, new Builder(_clusterName).controllerMessages(), + ChangeType.MESSAGES_CONTROLLER, new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addControllerMessageListener(org.apache.helix.MessageListener listener) { + addListener(listener, new Builder(_clusterName).controllerMessages(), + ChangeType.MESSAGES_CONTROLLER, new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addCurrentStateChangeListener(CurrentStateChangeListener listener, + String instanceName, String sessionId) throws Exception { + addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId), + ChangeType.CURRENT_STATE, new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Deprecated + @Override + public void addCurrentStateChangeListener(org.apache.helix.CurrentStateChangeListener listener, + String instanceName, String sessionId) throws Exception { + addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId), + ChangeType.CURRENT_STATE, new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener, + String instanceName) throws Exception { + addListener(listener, new Builder(_clusterName).customizedStatesRoot(instanceName), + ChangeType.CUSTOMIZED_STATE_ROOT, new EventType[]{EventType.NodeChildrenChanged}); + } + + @Override + public void addCustomizedStateChangeListener(CustomizedStateChangeListener listener, + String instanceName, String customizedStateType) throws Exception { + addListener(listener, + new Builder(_clusterName).customizedStates(instanceName, customizedStateType), + ChangeType.CUSTOMIZED_STATE, new EventType[]{EventType.NodeChildrenChanged}); + } + + @Override + public void addExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addCustomizedViewChangeListener(CustomizedViewChangeListener listener, String customizedStateType) + throws Exception { + addListener(listener, new Builder(_clusterName).customizedView(customizedStateType), + ChangeType.CUSTOMIZED_VIEW, new EventType[] { + EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedViewRootChangeListener(CustomizedViewRootChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).customizedViews(), + ChangeType.CUSTOMIZED_VIEW_ROOT, new EventType[] { + EventType.NodeChildrenChanged + }); + } + + @Override + public void addTargetExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.TARGET_EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addExternalViewChangeListener(org.apache.helix.ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addControllerListener(ControllerChangeListener listener) { + addListener(listener, new Builder(_clusterName).controller(), ChangeType.CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addControllerListener(org.apache.helix.ControllerChangeListener listener) { + addListener(listener, new Builder(_clusterName).controller(), ChangeType.CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public HelixDataAccessor getHelixDataAccessor() { + checkConnected(_waitForConnectedTimeout); + return _dataAccessor; + } + + @Override + public ConfigAccessor getConfigAccessor() { + checkConnected(_waitForConnectedTimeout); + return _configAccessor; + } + + @Override + public String getClusterName() { + return _clusterName; + } + + /** + * Returns a string that can be used to connect to metadata store for this HelixManager instance + * i.e. for ZkHelixManager, this will have format "{zookeeper-address}:{port}" + * @return a string used to connect to metadata store + */ + @Override + public String getMetadataStoreConnectionString() { + return _zkAddress; + } + + @Override + public String getInstanceName() { + return _instanceName; + } + + BaseDataAccessor createBaseDataAccessor() { + ZkBaseDataAccessor baseDataAccessor = new ZkBaseDataAccessor<>(_zkclient); + return baseDataAccessor; + } + + /** + * Add Helix built-in state model definitions if not exist + */ + private void addBuiltInStateModelDefinitions() { + for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) { + // creation succeeds only if not exist + _dataAccessor.createStateModelDef(def.getStateModelDefinition()); + } + } + + private boolean isMonitorRootPathOnly() { + switch (_monitorLevel) { + case ALL: + return false; + case AGGREGATED_ONLY: + return true; + default: + // Otherwise, apply the default policy. Emitting full metrics for controllers only. + return !_instanceType.equals(InstanceType.CONTROLLER) && !_instanceType + .equals(InstanceType.CONTROLLER_PARTICIPANT); + } + } + + void createClient() throws Exception { + final RealmAwareZkClient newClient = createSingleRealmZkClient(); + + synchronized (this) { + if (_zkclient != null) { + _zkclient.close(); + } + _zkclient = newClient; + + _baseDataAccessor = createBaseDataAccessor(); + + _dataAccessor = new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor); + _configAccessor = new ConfigAccessor(_zkclient); + + if (_instanceType == InstanceType.CONTROLLER + || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { + addBuiltInStateModelDefinitions(); + } + } + + // subscribe to state change + _zkclient.subscribeStateChanges(this); + int retryCount = 0; + while (retryCount < 3) { + try { + final long sessionId = + _zkclient.waitForEstablishedSession(_connectionInitTimeout, TimeUnit.MILLISECONDS); + handleStateChanged(KeeperState.SyncConnected); + /* + * This listener is subscribed after SyncConnected and firing new session events, + * which means this listener has not yet handled new session, so we have to handle new + * session here just for this listener. + */ + handleNewSession(ZKUtil.toHexSessionId(sessionId)); + break; + } catch (HelixException e) { + LOG.error("fail to createClient.", e); + throw e; + } catch (Exception e) { + retryCount++; + LOG.error("fail to createClient. retry " + retryCount, e); + if (retryCount == 3) { + throw e; + } + } + } + } + + @Override + public void connect() throws Exception { + LOG.info("ClusterManager.connect()"); + if (isConnected()) { + LOG.warn("Cluster manager: " + _instanceName + " for cluster: " + _clusterName + + " already connected. skip connect"); + return; + } + + switch (_instanceType) { + case CONTROLLER: + case CONTROLLER_PARTICIPANT: + if (_controller == null) { + _controller = new GenericHelixController(_clusterName, _enabledPipelineTypes); + _messagingService.getExecutor().setController(_controller); + } + break; + default: + break; + } + + try { + createClient(); + _messagingService.onConnected(); + } catch (Exception e) { + LOG.error("fail to connect " + _instanceName, e); + try { + disconnect(); + } catch (Exception ex) { + // if zk connection fails to be created, disconnect may throw exception about reporting disconnect to ZK. + } + throw e; + } + } + + @Override + public void disconnect() { + if (_zkclient == null || _zkclient.isClosed()) { + LOG.info("instanceName: " + _instanceName + " already disconnected"); + return; + } + + LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); + + try { + /** + * stop all timer tasks + */ + stopTimerTasks(); + + /** + * shutdown thread pool first to avoid reset() being invoked in the middle of state + * transition + */ + _messagingService.getExecutor().shutdown(); + + // TODO reset user defined handlers only + // TODO Fix the issue that when connection disconnected, reset handlers will be blocked. -- JJ + // This is because reset logic contains ZK operations. + resetHandlers(true); + + if (_leaderElectionHandler != null) { + _leaderElectionHandler.reset(true); + } + + } finally { + GenericHelixController controller = _controller; + if (controller != null) { + try { + controller.shutdown(); + } catch (InterruptedException e) { + LOG.info("Interrupted shutting down GenericHelixController", e); + } + } + + ParticipantManager participantManager = _participantManager; + if (participantManager != null) { + participantManager.disconnect(); + } + + for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) { + callbackMonitor.unregister(); + } + + _helixPropertyStore = null; + + synchronized (this) { + if (_controller != null) { + _controller = null; + _leaderElectionHandler = null; + } + + if (_participantManager != null) { + _participantManager = null; + } + + if (_zkclient != null) { + _zkclient.close(); + } + } + _sessionStartTime = null; + LOG.info("Cluster manager: " + _instanceName + " disconnected"); + } + } + + @Override + public String getSessionId() { + checkConnected(_waitForConnectedTimeout); + // TODO: session id should be updated after zk client is connected. + // Otherwise, this session id might be an expired one. + return _sessionId; + } + + @Override + public boolean isConnected() { + if (_zkclient == null || _zkclient.isClosed()) { + return false; + } + // Don't check ZkConnection state, which is different from ZkClient's watcher state. + // ZkConnection state is the internal state of the connection, which can be different from the + // ZkClient state due to internal thread/retry logic. + try { + return _zkclient.waitUntilConnected(0, TimeUnit.MILLISECONDS); + } catch (ZkInterruptedException ex) { + return false; + } + } + + @Override + public long getLastNotificationTime() { + return 0; + } + + @Override + public void addPreConnectCallback(PreConnectCallback callback) { + LOG.info("Adding preconnect callback: " + callback); + _preConnectCallbacks.add(callback); + } + + @Override + public boolean isLeader() { + String warnLogPrefix = String + .format("Instance %s is not leader of cluster %s due to", _instanceName, _clusterName); + if (_instanceType != InstanceType.CONTROLLER + && _instanceType != InstanceType.CONTROLLER_PARTICIPANT) { + LOG.warn(String + .format("%s instance type %s does not match to CONTROLLER/CONTROLLER_PARTICIPANT", + warnLogPrefix, _instanceType.name())); + return false; + } + + if (!isConnected()) { + LOG.warn(String.format("%s HelixManager is not connected", warnLogPrefix)); + return false; + } + + try { + LiveInstance leader = _dataAccessor.getProperty(_keyBuilder.controllerLeader()); + if (leader != null) { + String leaderName = leader.getInstanceName(); + String sessionId = leader.getEphemeralOwner(); + if (leaderName != null && leaderName.equals(_instanceName) && sessionId + .equals(_sessionId)) { + return true; + } + LOG.warn(String + .format("%s current session %s does not match leader session %s", warnLogPrefix, + _sessionId, sessionId)); + } else { + LOG.warn(String.format("%s leader ZNode is null", warnLogPrefix)); + } + } catch (Exception e) { + LOG.warn(String.format("%s exception happen when session check", warnLogPrefix), e); + } + return false; + } + + @Override + public synchronized ZkHelixPropertyStore getHelixPropertyStore() { + checkConnected(_waitForConnectedTimeout); + + if (_helixPropertyStore == null) { + String path = PropertyPathBuilder.propertyStore(_clusterName); + String fallbackPath = String.format("/%s/%s", _clusterName, "HELIX_PROPERTYSTORE"); + _helixPropertyStore = + new AutoFallbackPropertyStore<>(new ZkBaseDataAccessor<>(_zkclient), + path, fallbackPath); + } + + return _helixPropertyStore; + } + + @Override + public synchronized HelixAdmin getClusterManagmentTool() { + checkConnected(_waitForConnectedTimeout); + if (_zkclient != null && !_zkclient.isClosed()) { + return new ZKHelixAdmin(_zkclient); + } + + LOG.error("Couldn't get ZKClusterManagementTool because zkclient is null"); + return null; + } + + @Override + public ClusterMessagingService getMessagingService() { + // The caller can register message handler factories on messaging service before the + // helix manager is connected. Thus we do not do connected check here. + return _messagingService; + } + + @Override + public InstanceType getInstanceType() { + return _instanceType; + } + + @Override + public String getVersion() { + return _version; + } + + @Override + public HelixManagerProperties getProperties() { + return _properties; + } + + @Override + public StateMachineEngine getStateMachineEngine() { + return _stateMachineEngine; + } + + // TODO: rename this and not expose this function as part of interface + @Override + public void startTimerTasks() { + for (HelixTimerTask task : _timerTasks) { + task.start(); + } + } + + @Override + public void stopTimerTasks() { + for (HelixTimerTask task : _timerTasks) { + task.stop(); + } + } + + @Override + public void setLiveInstanceInfoProvider(LiveInstanceInfoProvider liveInstanceInfoProvider) { + _liveInstanceInfoProvider = liveInstanceInfoProvider; + } + + /** + * wait until we get a non-zero session-id. note that we might lose zkconnection + * right after we read session-id. but it's ok to get stale session-id and we will have + * another handle-new-session callback to correct this. + */ + void waitUntilConnected() { + boolean isConnected; + do { + isConnected = + _zkclient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); + if (!isConnected) { + LOG.error("fail to connect zkserver: " + _zkAddress + " in " + + HelixZkClient.DEFAULT_CONNECTION_TIMEOUT + "ms. expiredSessionId: " + _sessionId + + ", clusterName: " + _clusterName); + continue; + } + + _sessionId = ZKUtil.toHexSessionId(_zkclient.getSessionId()); + + /** + * at the time we read session-id, zkconnection might be lost again + * wait until we get a non-zero session-id + */ + } while (!isConnected || "0".equals(_sessionId)); + + LOG.info("Handling new session, session id: " + _sessionId + ", instance: " + _instanceName + + ", instanceTye: " + _instanceType + ", cluster: " + _clusterName); + } + + void initHandlers(List handlers) { + synchronized (this) { + if (handlers != null) { + // get a copy of the list and iterate over the copy list + // in case handler.init() modifies the original handler list + List tmpHandlers = new ArrayList<>(handlers); + for (CallbackHandler handler : tmpHandlers) { + handler.init(); + LOG.info("init handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + void resetHandlers(boolean isShutdown) { + synchronized (this) { + if (_handlers != null) { + // get a copy of the list and iterate over the copy list + // in case handler.reset() modifies the original handler list + List tmpHandlers = new ArrayList<>(_handlers); + for (CallbackHandler handler : tmpHandlers) { + handler.reset(isShutdown); + LOG.info("reset handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + /** + * If zk state has changed into Disconnected for maxDisconnectThreshold times during previous + * timeWindowLengthMs Ms + * time window, we think that there are something wrong going on and disconnect the zkHelixManager + * from zk. + */ + boolean isFlapping() { + if (_disconnectTimeHistory.size() == 0) { + return false; + } + long mostRecentTimestamp = _disconnectTimeHistory.get(_disconnectTimeHistory.size() - 1); + + // Remove disconnect history timestamp that are older than flappingTimeWindowMs ago + while ((_disconnectTimeHistory.get(0) + _flappingTimeWindowMs) < mostRecentTimestamp) { + _disconnectTimeHistory.remove(0); + } + return _disconnectTimeHistory.size() > _maxDisconnectThreshold; + } + + @Override + public void handleStateChanged(KeeperState state) { + switch (state) { + case SyncConnected: + LOG.info("KeeperState: " + state + ", instance: " + _instanceName + ", type: " + _instanceType); + break; + case Disconnected: + /** + * Track the time stamp that the disconnected happens, then check history and see if + * we should disconnect the helix-manager + */ + _disconnectTimeHistory.add(System.currentTimeMillis()); + if (isFlapping()) { + String errorMsg = "instanceName: " + _instanceName + " is flapping. disconnect it. " + + " maxDisconnectThreshold: " + _maxDisconnectThreshold + " disconnects in " + + _flappingTimeWindowMs + "ms."; + LOG.error(errorMsg); + + // Only disable the instance when it's instance type is PARTICIPANT + if (_instanceType.equals(InstanceType.PARTICIPANT)) { + LOG.warn("instanceName: " + _instanceName + + " is flapping. Since it is a participant, disable it."); + try { + getClusterManagmentTool().enableInstance(_clusterName, _instanceName, false); + } catch (Exception e) { + LOG.error("Failed to disable participant before disconnecting participant.", e); + } + } + + try { + // TODO Call disconnect in another thread. + // handleStateChanged is triggered in ZkClient eventThread. The disconnect logic will + // interrupt this thread. This issue prevents the ZkClient.close() from complete. So the + // client is left in a strange state. + disconnect(); + } catch (Exception ex) { + LOG.error("Disconnect HelixManager is not completely done.", ex); + } + + if (_stateListener != null) { + try { + _stateListener.onDisconnected(this, new HelixException(errorMsg)); + } catch (Exception e) { + LOG.warn("stateListener.onDisconnected callback fails", e); + } + } + break; + } + // if not flapping, share the continuous logic with Expired case + case Expired: + LOG.warn("KeeperState:" + state + ", SessionId: " + _sessionId + ", instance: " + + _instanceName + ", type: " + _instanceType); + break; + default: + LOG.info("KeeperState:" + state + ", currentSessionId: " + _sessionId + ", instance: " + + _instanceName + ", type: " + _instanceType); + break; + } + } + + /** + * Called after zookeeper session has expired and a new session has been established. This method + * may cause session race condition when creating ephemeral nodes. Internally, this method calls + * {@link #handleNewSession(String)} with a null value as the sessionId parameter, which results + * in later creating the ephemeral node in the session of the latest zk connection. + * But please note that the session of the latest zk connection might not be the expected session. + * This is the session race condition issue. + * + * To avoid the race condition issue, please use {@link #handleNewSession(String)}. + * + * @deprecated + * This method is deprecated, because it may cause session race condition when creating ephemeral + * nodes. It is kept for backward compatibility in case a user class extends this class. + * + * Please use {@link #handleNewSession(String)} instead, which takes care of race condition. + * + * @throws Exception If any error occurs. + */ + @Deprecated + public void handleNewSession() throws Exception { + handleNewSession(null); + } + + /** + * Called after the zookeeper session has expired and a new session has been established. This + * methods handles a new session with its session id passed in. Before handling, this method + * waits until zk client is connected to zk service and gets a non-zero session id(current actual + * session id). If the passed-in(expected) session id does not match current actual session id, + * the expected session id is expired and will NOT be handled. + * + * @param sessionId the new session's id. The ephemeral nodes are expected to be created in this + * session. If this session id is expired, ephemeral nodes should not be created. + * @throws Exception if any error occurs during handling new session + */ + @Override + public void handleNewSession(String sessionId) throws Exception { + /* + * TODO: after removing I0ItecIZkStateListenerImpl, null session should be checked and + * discarded. + * Null session is still a special case here, which is treated as non-session aware operation. + * This special case could still potentially cause race condition, so null session should NOT + * be acceptable, once I0ItecIZkStateListenerImpl is removed. Currently this special case + * is kept for backward compatibility. + */ + + // Wait until we get a non-zero session id. Otherwise, getSessionId() might be null. + waitUntilConnected(); + + /* + * Filter out stale sessions. If a session id is not null and not the same as current session + * id, this session is expired. With this filtering, expired sessions are NOT handled, + * so performance is expected to improve. + */ + if (sessionId != null && !getSessionId().equals(sessionId)) { + LOG.warn("Session is expired and not handled. Expected: {}. Actual: {}.", sessionId, + getSessionId()); + return; + } + + /* + * When a null session id is passed in, we will take current session's id for following + * operations. Please note that current session might not be the one we expect to handle, + * because the one we expect might be already expired when the zk event is waiting in the + * event queue. Why we use current session here is for backward compatibility with the old + * method handleNewSession(). + */ + if (sessionId == null) { + sessionId = getSessionId(); + LOG.debug("Session id: is passed in. Current session id: {} will be used.", sessionId); + } + + LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, + _instanceType, sessionId); + + /** + * stop all timer tasks, reset all handlers, make sure cleanup completed for previous session + * disconnect if fail to cleanup + */ + stopTimerTasks(); + if (_leaderElectionHandler != null) { + _leaderElectionHandler.reset(false); + } + resetHandlers(false); + + /** + * clean up write-through cache + */ + _baseDataAccessor.reset(); + + /** + * from here on, we are dealing with new session + */ + if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { + throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); + } + + _sessionStartTime = System.currentTimeMillis(); + + switch (_instanceType) { + case PARTICIPANT: + handleNewSessionAsParticipant(sessionId); + break; + case CONTROLLER: + handleNewSessionAsController(); + break; + case CONTROLLER_PARTICIPANT: + handleNewSessionAsParticipant(sessionId); + handleNewSessionAsController(); + break; + case ADMINISTRATOR: + case SPECTATOR: + default: + break; + } + + startTimerTasks(); + + /** + * init handlers + * ok to init message handler and data-accessor twice + * the second init will be skipped (see CallbackHandler) + */ + initHandlers(_handlers); + + if (_stateListener != null) { + try { + _stateListener.onConnected(this); + } catch (Exception e) { + LOG.warn("stateListener.onConnected callback fails", e); + } + } + } + + void handleNewSessionAsParticipant(final String sessionId) throws Exception { + if (_participantManager != null) { + _participantManager.reset(); + } + _participantManager = + new ParticipantManager(this, _zkclient, _sessionTimeout, _liveInstanceInfoProvider, + _preConnectCallbacks, sessionId, _helixManagerProperty); + _participantManager.handleNewSession(); + } + + // TODO: pass in session id and make this method session aware to avoid potential session race + // condition. + void handleNewSessionAsController() { + if (_leaderElectionHandler != null) { + _leaderElectionHandler.init(); + } else { + _leaderElectionHandler = + new CallbackHandler(this, _zkclient, _keyBuilder.controller(), + new DistributedLeaderElection(this, _controller, _controllerTimerTasks), + new EventType[] { + EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated + }, ChangeType.CONTROLLER, _callbackMonitors.get(ChangeType.CONTROLLER)); + } + } + + @Override + public ParticipantHealthReportCollector getHealthReportCollector() { + return _participantHealthInfoCollector; + } + + @Override + public void handleSessionEstablishmentError(Throwable error) throws Exception { + LOG.warn("Handling Session Establishment Error. Disconnect Helix Manager.", error); + disconnect(); + + if (_stateListener != null) { + _stateListener.onDisconnected(this, error); + } + } + + @Override + public Long getSessionStartTime() { + return _sessionStartTime; + } + + /* + * Prepares connection config and client config based on the internal parameters given to + * HelixManager in order to create a ZkClient instance to use. Note that a shared ZkClient + * instance will be created if connecting as an ADMINISTRATOR to minimize the cost of creating + * ZkConnections. + */ + private RealmAwareZkClient createSingleRealmZkClient() { + final String shardingKey = buildShardingKey(); + PathBasedZkSerializer zkSerializer = + ChainedPathZkSerializer.builder(new ZNRecordSerializer()).build(); + + RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig = + new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() + .setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) + .setZkRealmShardingKey(shardingKey) + .setSessionTimeout(_sessionTimeout).build(); + + RealmAwareZkClient.RealmAwareZkClientConfig clientConfig = + new RealmAwareZkClient.RealmAwareZkClientConfig(); + + clientConfig.setZkSerializer(zkSerializer) + .setConnectInitTimeout(_connectionInitTimeout) + .setMonitorType(_instanceType.name()) + .setMonitorKey(_clusterName) + .setMonitorInstanceName(_instanceName) + .setMonitorRootPathOnly(isMonitorRootPathOnly()); + + if (_instanceType == InstanceType.ADMINISTRATOR) { + return resolveZkClient(SharedZkClientFactory.getInstance(), connectionConfig, + clientConfig); + } + + return resolveZkClient(DedicatedZkClientFactory.getInstance(), connectionConfig, + clientConfig); + } + + /* + * Resolves what type of ZkClient this HelixManager should use based on whether MULTI_ZK_ENABLED + * System config is set or not. Two types of ZkClients are available: + * 1) If MULTI_ZK_ENABLED is set to true, we create a dedicated RealmAwareZkClient + * that provides full ZkClient functionalities and connects to the correct ZK by querying + * MetadataStoreDirectoryService. + * 2) Otherwise, we create a dedicated HelixZkClient which plainly connects to + * the ZK address given. + */ + private RealmAwareZkClient resolveZkClient(HelixZkClientFactory zkClientFactory, + RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, + RealmAwareZkClient.RealmAwareZkClientConfig clientConfig) { + if (Boolean.getBoolean(SystemPropertyKeys.MULTI_ZK_ENABLED)) { + try { + // Create realm-aware ZkClient. + return zkClientFactory.buildZkClient(connectionConfig, clientConfig); + } catch (IllegalArgumentException | IOException | InvalidRoutingDataException e) { + throw new HelixException("Not able to connect on realm-aware mode for sharding key: " + + connectionConfig.getZkRealmShardingKey(), e); + } + } + + // If multi-zk mode is not enabled, create HelixZkClient with the provided zk address. + HelixZkClient.ZkClientConfig helixZkClientConfig = clientConfig.createHelixZkClientConfig(); + HelixZkClient.ZkConnectionConfig helixZkConnectionConfig = + new HelixZkClient.ZkConnectionConfig(_zkAddress) + .setSessionTimeout(connectionConfig.getSessionTimeout()); + + return zkClientFactory.buildZkClient(helixZkConnectionConfig, helixZkClientConfig); + } + + private String buildShardingKey() { + return _clusterName.charAt(0) == '/' ? _clusterName : "/" + _clusterName; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.manager.zk.ZKHelixManager.disconnect` reads without synchronization from `this.org.apache.helix.manager.zk.ZKHelixManager._leaderElectionHandler`. Potentially races with write in method `ZKHelixManager.handleStateChanged(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZKHelixManager.disconnect() + +### Procedure Id: +org.apache.helix.manager.zk.ZKHelixManager.disconnect():void.0716666aec749e0a4d5d805dbaf9f743 + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZKHelixManager.java + +### Key: +ZKHelixManager.java|disconnect|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +dac2fcc22241745671a0b5db65b0b107 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9610/instruction.md b/inferredbugs-9610/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0fb5d30ac8d007c7fb17a18e36068f49bb75c65 --- /dev/null +++ b/inferredbugs-9610/instruction.md @@ -0,0 +1,423 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 88 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.rest.server; + + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.helix.BaseDataAccessor; +import org.apache.helix.ConfigAccessor; +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixException; +import org.apache.helix.InstanceType; +import org.apache.helix.SystemPropertyKeys; +import org.apache.helix.manager.zk.ByteArraySerializer; +import org.apache.helix.manager.zk.ZKHelixAdmin; +import org.apache.helix.manager.zk.ZKHelixDataAccessor; +import org.apache.helix.manager.zk.ZkBaseDataAccessor; +import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; +import org.apache.helix.rest.metadatastore.ZkMetadataStoreDirectory; +import org.apache.helix.task.TaskDriver; +import org.apache.helix.tools.ClusterSetup; +import org.apache.helix.zookeeper.api.client.HelixZkClient; +import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; +import org.apache.helix.zookeeper.constant.RoutingDataReaderType; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; +import org.apache.helix.zookeeper.impl.client.FederatedZkClient; +import org.apache.helix.zookeeper.impl.client.ZkClient; +import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory; +import org.apache.helix.zookeeper.routing.RoutingDataManager; +import org.apache.helix.zookeeper.zkclient.IZkChildListener; +import org.apache.helix.zookeeper.zkclient.IZkDataListener; +import org.apache.helix.zookeeper.zkclient.IZkStateListener; +import org.apache.zookeeper.Watcher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +public class ServerContext implements IZkDataListener, IZkChildListener, IZkStateListener { + private static final Logger LOG = LoggerFactory.getLogger(ServerContext.class); + + private final String _zkAddr; + private boolean _isMultiZkEnabled; + private final String _msdsEndpoint; + private volatile RealmAwareZkClient _zkClient; + + private volatile ZKHelixAdmin _zkHelixAdmin; + private volatile ClusterSetup _clusterSetup; + private volatile ConfigAccessor _configAccessor; + // A lazily-initialized base data accessor that reads/writes byte array to ZK + // TODO: Only read (deserialize) is supported at this time. This baseDataAccessor should support write (serialize) as needs arise + private volatile ZkBaseDataAccessor _byteArrayZkBaseDataAccessor; + // 1 Cluster name will correspond to 1 helix data accessor + private final Map _helixDataAccessorPool; + // 1 Cluster name will correspond to 1 task driver + private final Map _taskDriverPool; + + /** + * Multi-ZK support + */ + private ZkMetadataStoreDirectory _zkMetadataStoreDirectory; + // Create a dedicated ZkClient for listening to data changes in routing data + private RealmAwareZkClient _zkClientForListener; + + public ServerContext(String zkAddr) { + this(zkAddr, false, null); + } + + /** + * Initializes a ServerContext for this namespace. + * @param zkAddr routing ZK address (on multi-zk mode) + * @param isMultiZkEnabled boolean flag for whether multi-zk mode is enabled + * @param msdsEndpoint if given, this server context will try to read routing data from this MSDS. + */ + public ServerContext(String zkAddr, boolean isMultiZkEnabled, String msdsEndpoint) { + _zkAddr = zkAddr; + _isMultiZkEnabled = isMultiZkEnabled; + _msdsEndpoint = msdsEndpoint; // only applicable on multi-zk mode + + // We should NOT initiate _zkClient and anything that depends on _zkClient in + // constructor, as it is reasonable to start up HelixRestServer first and then + // ZooKeeper. In this case, initializing _zkClient will fail and HelixRestServer + // cannot be started correctly. + _helixDataAccessorPool = new ConcurrentHashMap<>(); + _taskDriverPool = new ConcurrentHashMap<>(); + + // Initialize the singleton ZkMetadataStoreDirectory instance to allow it to be closed later + _zkMetadataStoreDirectory = ZkMetadataStoreDirectory.getInstance(); + } + + public RealmAwareZkClient getRealmAwareZkClient() { + if (_zkClient == null) { + synchronized (this) { + if (_zkClient == null) { + // If the multi ZK config is enabled, use FederatedZkClient on multi-realm mode + if (_isMultiZkEnabled || Boolean + .parseBoolean(System.getProperty(SystemPropertyKeys.MULTI_ZK_ENABLED))) { + try { + // Make sure the ServerContext is subscribed to routing data change so that it knows + // when to reset ZkClient and Helix APIs + if (_zkClientForListener == null) { + _zkClientForListener = DedicatedZkClientFactory.getInstance() + .buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddr), + new HelixZkClient.ZkClientConfig() + .setZkSerializer(new ZNRecordSerializer())); + } + // Refresh data subscription + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + LOG.info("ServerContext: subscribed to routing data in routing ZK at {}!", _zkAddr); + + RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder connectionConfigBuilder = + new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder(); + // If MSDS endpoint is set for this namespace, use that instead. + if (_msdsEndpoint != null && !_msdsEndpoint.isEmpty()) { + connectionConfigBuilder.setRoutingDataSourceEndpoint(_msdsEndpoint) + .setRoutingDataSourceType(RoutingDataReaderType.HTTP.name()); + } + _zkClient = new FederatedZkClient(connectionConfigBuilder.build(), + new RealmAwareZkClient.RealmAwareZkClientConfig() + .setZkSerializer(new ZNRecordSerializer())); + LOG.info("ServerContext: FederatedZkClient created successfully!"); + } catch (InvalidRoutingDataException | IllegalStateException e) { + throw new HelixException("Failed to create FederatedZkClient!", e); + } + } else { + // If multi ZK config is not set, just connect to the ZK address given + HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig(); + clientConfig.setZkSerializer(new ZNRecordSerializer()); + _zkClient = SharedZkClientFactory.getInstance() + .buildZkClient(new HelixZkClient.ZkConnectionConfig(_zkAddr), clientConfig); + } + } + } + } + return _zkClient; + } + + @Deprecated + public ZkClient getZkClient() { + return (ZkClient) getRealmAwareZkClient(); + } + + public HelixAdmin getHelixAdmin() { + if (_zkHelixAdmin == null) { + synchronized (this) { + if (_zkHelixAdmin == null) { + _zkHelixAdmin = new ZKHelixAdmin(getRealmAwareZkClient()); + } + } + } + return _zkHelixAdmin; + } + + public ClusterSetup getClusterSetup() { + if (_clusterSetup == null) { + synchronized (this) { + if (_clusterSetup == null) { + _clusterSetup = new ClusterSetup(getRealmAwareZkClient(), getHelixAdmin()); + } + } + } + return _clusterSetup; + } + + public TaskDriver getTaskDriver(String clusterName) { + TaskDriver taskDriver = _taskDriverPool.get(clusterName); + if (taskDriver == null) { + synchronized (this) { + if (!_taskDriverPool.containsKey(clusterName)) { + _taskDriverPool.put(clusterName, new TaskDriver(getRealmAwareZkClient(), clusterName)); + } + taskDriver = _taskDriverPool.get(clusterName); + } + } + return taskDriver; + } + + public ConfigAccessor getConfigAccessor() { + if (_configAccessor == null) { + synchronized (this) { + if (_configAccessor == null) { + _configAccessor = new ConfigAccessor(getRealmAwareZkClient()); + } + } + } + return _configAccessor; + } + + public HelixDataAccessor getDataAccessor(String clusterName) { + HelixDataAccessor dataAccessor = _helixDataAccessorPool.get(clusterName); + if (dataAccessor == null) { + synchronized (this) { + if (!_helixDataAccessorPool.containsKey(clusterName)) { + ZkBaseDataAccessor baseDataAccessor = + new ZkBaseDataAccessor<>(getRealmAwareZkClient()); + _helixDataAccessorPool.put(clusterName, + new ZKHelixDataAccessor(clusterName, InstanceType.ADMINISTRATOR, baseDataAccessor)); + } + dataAccessor = _helixDataAccessorPool.get(clusterName); + } + } + return dataAccessor; + } + + /** + * Returns a lazily-instantiated ZkBaseDataAccessor for the byte array type. + * @return + */ + public BaseDataAccessor getByteArrayZkBaseDataAccessor() { + if (_byteArrayZkBaseDataAccessor == null) { + synchronized (this) { + if (_byteArrayZkBaseDataAccessor == null) { + _byteArrayZkBaseDataAccessor = + new ZkBaseDataAccessor<>(_zkAddr, new ByteArraySerializer()); + } + } + } + return _byteArrayZkBaseDataAccessor; + } + + public void close() { + if (_zkClient != null) { + _zkClient.close(); + } + if (_zkMetadataStoreDirectory != null) { + _zkMetadataStoreDirectory.close(); + } + if (_zkClientForListener != null) { + _zkClientForListener.close(); + } + } + + @Override + public void handleChildChange(String parentPath, List currentChilds) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleDataChange(String dataPath, Object data) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + resetZkResources(); + } + + @Override + public void handleDataDeleted(String dataPath) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleStateChanged(Watcher.Event.KeeperState state) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleNewSession(String sessionId) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + @Override + public void handleSessionEstablishmentError(Throwable error) { + if (_zkClientForListener == null || _zkClientForListener.isClosed()) { + return; + } + // Resubscribe + _zkClientForListener.unsubscribeAll(); + _zkClientForListener.subscribeRoutingDataChanges(this, this); + resetZkResources(); + } + + /** + * Resets all internally cached routing data by closing and nullifying the ZkClient and Helix APIs. + * This is okay because routing data update should be infrequent. + */ + private void resetZkResources() { + synchronized (this) { + LOG.info("ServerContext: Resetting ZK resources due to routing data change! Routing ZK: {}", + _zkAddr); + try { + // Reset RoutingDataManager's cache + RoutingDataManager.getInstance().reset(); + // All Helix APIs will be closed implicitly because ZkClient is closed + if (_zkClient != null && !_zkClient.isClosed()) { + _zkClient.close(); + } + if (_byteArrayZkBaseDataAccessor != null) { + _byteArrayZkBaseDataAccessor.close(); + } + _zkClient = null; + _zkHelixAdmin = null; + _clusterSetup = null; + _configAccessor = null; + _byteArrayZkBaseDataAccessor = null; + _helixDataAccessorPool.clear(); + _taskDriverPool.clear(); + } catch (Exception e) { + LOG.error("Failed to reset ZkClient and Helix APIs in ServerContext!", e); + } + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.rest.server.ServerContext.handleStateChanged` reads without synchronization from `this.org.apache.helix.rest.server.ServerContext._zkClientForListener`. Potentially races with write in method `ServerContext.getTaskDriver(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ServerContext.handleStateChanged(Watcher$Event$KeeperState) + +### Procedure Id: +org.apache.helix.rest.server.ServerContext.handleStateChanged(org.apache.zookeeper.Watcher$Event$Kee.8892db998a0da0acc867462f50ffe40b + +### File: +helix-rest/src/main/java/org/apache/helix/rest/server/ServerContext.java + +### Key: +ServerContext.java|handleStateChanged|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e458c79b61949ee263e5671654c7c267 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9611/instruction.md b/inferredbugs-9611/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3ad0fdc1bb5fb5d72f6f0f8acc35bee795b453f --- /dev/null +++ b/inferredbugs-9611/instruction.md @@ -0,0 +1,486 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 38 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.task; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.I0Itec.zkclient.DataUpdater; +import org.apache.helix.*; +import org.apache.helix.controller.stages.ClusterDataCache; +import org.apache.helix.controller.stages.CurrentStateOutput; +import org.apache.helix.model.*; +import org.apache.helix.model.builder.CustomModeISBuilder; +import org.apache.log4j.Logger; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * Custom rebalancer implementation for the {@code Workflow} in task state model. + */ +public class WorkflowRebalancer extends TaskRebalancer { + private static final Logger LOG = Logger.getLogger(WorkflowRebalancer.class); + + @Override + public ResourceAssignment computeBestPossiblePartitionState(ClusterDataCache clusterData, + IdealState taskIs, Resource resource, CurrentStateOutput currStateOutput) { + final String workflow = resource.getResourceName(); + LOG.debug("Computer Best Partition for workflow: " + workflow); + + // Fetch workflow configuration and context + WorkflowConfig workflowCfg = TaskUtil.getWorkflowCfg(_manager, workflow); + if (workflowCfg == null) { + LOG.warn("Workflow configuration is NULL for " + workflow); + return buildEmptyAssignment(workflow, currStateOutput); + } + + WorkflowContext workflowCtx = TaskUtil.getWorkflowContext(_manager, workflow); + // Initialize workflow context if needed + if (workflowCtx == null) { + workflowCtx = new WorkflowContext(new ZNRecord("WorkflowContext")); + workflowCtx.setStartTime(System.currentTimeMillis()); + LOG.debug("Workflow context is created for " + workflow); + } + + // Clean up if workflow marked for deletion + TargetState targetState = workflowCfg.getTargetState(); + if (targetState == TargetState.DELETE) { + LOG.info("Workflow is marked as deleted " + workflow + " cleaning up the workflow context."); + cleanupWorkflow(workflow, workflowCfg, workflowCtx); + return buildEmptyAssignment(workflow, currStateOutput); + } + + if (targetState == TargetState.STOP) { + LOG.info("Workflow " + workflow + "is marked as stopped."); + // Workflow has been stopped if all jobs are stopped + // TODO: what should we do if workflowCtx is not set yet? + if (workflowCtx != null && isWorkflowStopped(workflowCtx, workflowCfg)) { + workflowCtx.setWorkflowState(TaskState.STOPPED); + } + return buildEmptyAssignment(workflow, currStateOutput); + } + + long currentTime = System.currentTimeMillis(); + // Check if workflow is completed and mark it if it is completed. + if (workflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + if (isWorkflowComplete(workflowCtx, workflowCfg)) { + workflowCtx.setWorkflowState(TaskState.COMPLETED); + workflowCtx.setFinishTime(currentTime); + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + } + } + + if (workflowCtx.getFinishTime() != WorkflowContext.UNFINISHED) { + LOG.info("Workflow " + workflow + " is completed."); + long expiryTime = workflowCfg.getExpiry(); + // Check if this workflow has been finished past its expiry. + if (workflowCtx.getFinishTime() + expiryTime <= currentTime) { + LOG.info("Workflow " + workflow + " passed expiry time, cleaning up the workflow context."); + cleanupWorkflow(workflow, workflowCfg, workflowCtx); + } else { + // schedule future cleanup work + long cleanupTime = workflowCtx.getFinishTime() + expiryTime; + _scheduledRebalancer.scheduleRebalance(_manager, workflow, cleanupTime); + } + return buildEmptyAssignment(workflow, currStateOutput); + } + + if (!isWorkflowReadyForSchedule(workflowCfg)) { + LOG.info("Workflow " + workflow + " is not ready to schedule"); + // set the timer to trigger future schedule + _scheduledRebalancer + .scheduleRebalance(_manager, workflow, workflowCfg.getStartTime().getTime()); + return buildEmptyAssignment(workflow, currStateOutput); + } + + // Check for readiness, and stop processing if it's not ready + boolean isReady = + scheduleWorkflowIfReady(workflow, workflowCfg, workflowCtx); + if (isReady) { + // Schedule jobs from this workflow. + scheduleJobs(workflowCfg, workflowCtx); + } else { + LOG.debug("Workflow " + workflow + " is not ready to be scheduled."); + } + + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + return buildEmptyAssignment(workflow, currStateOutput); + } + + /** + * Figure out whether the jobs in the workflow should be run, + * and if it's ready, then just schedule it + */ + private void scheduleJobs(WorkflowConfig workflowCfg, WorkflowContext workflowCtx) { + ScheduleConfig scheduleConfig = workflowCfg.getScheduleConfig(); + if (scheduleConfig != null && scheduleConfig.isRecurring()) { + LOG.debug("Jobs from recurring workflow are not schedule-able"); + return; + } + + for (String job : workflowCfg.getJobDag().getAllNodes()) { + TaskState jobState = workflowCtx.getJobState(job); + if (jobState != null && !jobState.equals(TaskState.NOT_STARTED)) { + LOG.debug("Job " + job + " is already started or completed."); + continue; + } + // check ancestor job status + if (isJobReadyToSchedule(job, workflowCfg, workflowCtx)) { + JobConfig jobConfig = TaskUtil.getJobCfg(_manager, job); + scheduleSingleJob(job, jobConfig); + } + } + } + + /** + * Posts new job to cluster + */ + private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { + HelixAdmin admin = _manager.getClusterManagmentTool(); + + IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); + if (jobIS != null) { + LOG.info("Job " + jobResource + " idealstate already exists!"); + return; + } + + // Set up job resource based on partitions from target resource + int numIndependentTasks = jobConfig.getTaskConfigMap().size(); + int numPartitions = (numIndependentTasks > 0) ? + numIndependentTasks : + admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()) + .getPartitionSet().size(); + admin.addResource(_manager.getClusterName(), jobResource, numPartitions, + TaskConstants.STATE_MODEL_NAME); + + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + // Set the job configuration + PropertyKey.Builder keyBuilder = accessor.keyBuilder(); + HelixProperty resourceConfig = new HelixProperty(jobResource); + resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); + Map taskConfigMap = jobConfig.getTaskConfigMap(); + if (taskConfigMap != null) { + for (TaskConfig taskConfig : taskConfigMap.values()) { + resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); + } + } + accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); + + // Push out new ideal state based on number of target partitions + CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); + builder.setRebalancerMode(IdealState.RebalanceMode.TASK); + builder.setNumReplica(1); + builder.setNumPartitions(numPartitions); + builder.setStateModel(TaskConstants.STATE_MODEL_NAME); + + if (jobConfig.isDisableExternalView()) { + builder.setDisableExternalView(true); + } + + jobIS = builder.build(); + for (int i = 0; i < numPartitions; i++) { + jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList()); + jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap()); + } + jobIS.setRebalancerClassName(JobRebalancer.class.getName()); + admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); + } + + /** + * Check if a workflow is ready to schedule, and schedule a rebalance if it is not + * + * @param workflow the Helix resource associated with the workflow + * @param workflowCfg the workflow to check + * @param workflowCtx the current workflow context + * @return true if the workflow is ready for schedule, false if not ready + */ + private boolean scheduleWorkflowIfReady(String workflow, WorkflowConfig workflowCfg, + WorkflowContext workflowCtx) { + // non-scheduled workflow is ready to run immediately. + if (workflowCfg == null || workflowCfg.getScheduleConfig() == null) { + return true; + } + + // Figure out when this should be run, and if it's ready, then just run it + ScheduleConfig scheduleConfig = workflowCfg.getScheduleConfig(); + Date startTime = scheduleConfig.getStartTime(); + long currentTime = new Date().getTime(); + long delayFromStart = startTime.getTime() - currentTime; + + if (delayFromStart <= 0) { + // Recurring workflows are just templates that spawn new workflows + if (scheduleConfig.isRecurring()) { + // Skip scheduling this workflow if it's not in a start state + if (!workflowCfg.getTargetState().equals(TargetState.START)) { + LOG.debug("Skip scheduling since the workflow has not been started " + workflow); + return false; + } + + // Skip scheduling this workflow again if the previous run (if any) is still active + String lastScheduled = workflowCtx.getLastScheduledSingleWorkflow(); + if (lastScheduled != null) { + WorkflowContext lastWorkflowCtx = TaskUtil.getWorkflowContext(_manager, lastScheduled); + if (lastWorkflowCtx != null + && lastWorkflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + LOG.info("Skip scheduling since last schedule has not completed yet " + lastScheduled); + return false; + } + } + + // Figure out how many jumps are needed, thus the time to schedule the next workflow + // The negative of the delay is the amount of time past the start time + long period = + scheduleConfig.getRecurrenceUnit().toMillis(scheduleConfig.getRecurrenceInterval()); + long offsetMultiplier = (-delayFromStart) / period; + long timeToSchedule = period * offsetMultiplier + startTime.getTime(); + + // Now clone the workflow if this clone has not yet been created + DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String newWorkflowName = workflow + "_" + df.format(new Date(timeToSchedule)); + LOG.debug("Ready to start workflow " + newWorkflowName); + if (!newWorkflowName.equals(lastScheduled)) { + Workflow clonedWf = TaskUtil + .cloneWorkflow(_manager, workflow, newWorkflowName, new Date(timeToSchedule)); + TaskDriver driver = new TaskDriver(_manager); + try { + // Start the cloned workflow + driver.start(clonedWf); + } catch (Exception e) { + LOG.error("Failed to schedule cloned workflow " + newWorkflowName, e); + } + // Persist workflow start regardless of success to avoid retrying and failing + workflowCtx.setLastScheduledSingleWorkflow(newWorkflowName); + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + } + + // Change the time to trigger the pipeline to that of the next run + _scheduledRebalancer.scheduleRebalance(_manager, workflow, (timeToSchedule + period)); + } else { + // one time workflow. + // Remove any timers that are past-time for this workflowg + long scheduledTime = _scheduledRebalancer.getRebalanceTime(workflow); + if (scheduledTime > 0 && currentTime > scheduledTime) { + _scheduledRebalancer.removeScheduledRebalance(workflow); + } + return true; + } + } else { + // set the timer to trigger future schedule + _scheduledRebalancer.scheduleRebalance(_manager, workflow, startTime.getTime()); + } + + return false; + } + + /** + * Cleans up workflow configs and workflow contexts associated with this workflow, + * including all job-level configs and context, plus workflow-level information. + */ + private void cleanupWorkflow(String workflow, WorkflowConfig workflowcfg, + WorkflowContext workflowCtx) { + LOG.info("Cleaning up workflow: " + workflow); + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + /* + if (workflowCtx != null && workflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + LOG.error("Workflow " + workflow + " has not completed, abort the clean up task."); + return; + }*/ + + for (String job : workflowcfg.getJobDag().getAllNodes()) { + cleanupJob(job, workflow); + } + + // clean up workflow-level info if this was the last in workflow + if (workflowcfg.isTerminable() || workflowcfg.getTargetState() == TargetState.DELETE) { + // clean up IS & EV + TaskUtil.cleanupIdealStateExtView(_manager.getHelixDataAccessor(), workflow); + + // delete workflow config + PropertyKey workflowCfgKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); + if (accessor.getProperty(workflowCfgKey) != null) { + if (!accessor.removeProperty(workflowCfgKey)) { + LOG.error(String.format( + "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix.", + workflow, workflowCfgKey)); + } + } + // Delete workflow context + String workflowPropStoreKey = TaskUtil.getWorkflowContextKey(workflow); + LOG.info("Removing workflow context: " + workflowPropStoreKey); + if (!_manager.getHelixPropertyStore().remove(workflowPropStoreKey, AccessOption.PERSISTENT)) { + LOG.error(String.format( + "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix. Aborting further clean up steps.", + workflow, workflowPropStoreKey)); + } + + // Remove pending timer task for this workflow if exists + _scheduledRebalancer.removeScheduledRebalance(workflow); + } + } + + + /** + * Cleans up workflow configs and workflow contexts associated with this workflow, + * including all job-level configs and context, plus workflow-level information. + */ + private void cleanupJob(final String job, String workflow) { + LOG.info("Cleaning up job: " + job + " in workflow: " + workflow); + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + // Remove any idealstate and externalView. + TaskUtil.cleanupIdealStateExtView(accessor, job); + + // Remove DAG references in workflow + PropertyKey workflowKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); + DataUpdater dagRemover = new DataUpdater() { + @Override + public ZNRecord update(ZNRecord currentData) { + if (currentData != null) { + JobDag jobDag = JobDag.fromJson(currentData.getSimpleField(WorkflowConfig.DAG)); + for (String child : jobDag.getDirectChildren(job)) { + jobDag.getChildrenToParents().get(child).remove(job); + } + for (String parent : jobDag.getDirectParents(job)) { + jobDag.getParentsToChildren().get(parent).remove(job); + } + jobDag.getChildrenToParents().remove(job); + jobDag.getParentsToChildren().remove(job); + jobDag.getAllNodes().remove(job); + try { + currentData.setSimpleField(WorkflowConfig.DAG, jobDag.toJson()); + } catch (Exception e) { + LOG.error("Could not update DAG for job: " + job, e); + } + } else { + LOG.error("Could not update DAG for job: " + job + " ZNRecord is null."); + } + return currentData; + } + }; + accessor.getBaseDataAccessor().update(workflowKey.getPath(), dagRemover, + AccessOption.PERSISTENT); + + // Delete job configs. + PropertyKey cfgKey = TaskUtil.getWorkflowConfigKey(accessor, job); + if (accessor.getProperty(cfgKey) != null) { + if (!accessor.removeProperty(cfgKey)) { + LOG.error(String.format( + "Error occurred while trying to clean up job %s. Failed to remove node %s from Helix.", + job, cfgKey)); + } + } + + // Delete job context + // For recurring workflow, it's OK if the node doesn't exist. + String propStoreKey = TaskUtil.getWorkflowContextKey(job); + if (!_manager.getHelixPropertyStore().remove(propStoreKey, AccessOption.PERSISTENT)) { + LOG.warn(String.format( + "Error occurred while trying to clean up job %s. Failed to remove node %s from Helix.", + job, propStoreKey)); + } + + LOG.info(String.format("Successfully cleaned up job context %s.", job)); + + _scheduledRebalancer.removeScheduledRebalance(job); + } + + @Override + public IdealState computeNewIdealState(String resourceName, IdealState currentIdealState, + CurrentStateOutput currentStateOutput, ClusterDataCache clusterData) { + // Nothing to do here with workflow resource. + return currentIdealState; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `admin.getResourceIdealState(TaskRebalancer._manager.getClusterName(),jobConfig.getTargetResource())` could be null and is dereferenced at line 168. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WorkflowRebalancer.scheduleSingleJob(String,JobConfig) + +### Procedure Id: +org.apache.helix.task.WorkflowRebalancer.scheduleSingleJob(java.lang.String,org.apache.helix.task.Jo.a9c9d069f7c6046b827b01fb147e6d9e + +### File: +helix-core/src/main/java/org/apache/helix/task/WorkflowRebalancer.java + +### Key: +WorkflowRebalancer.java|scheduleSingleJob|NULL_DEREFERENCE + +### Node Key: +50cb5ef8465ad6b6a77b806e5d8dd53e + +### Hash: +6f1669f78223e1a8b897ab78c2995f5a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9616/instruction.md b/inferredbugs-9616/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7790af36ece61d495d14514c160be461952fd5d --- /dev/null +++ b/inferredbugs-9616/instruction.md @@ -0,0 +1,787 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 54 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; + +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.apache.helix.api.listeners.ConfigChangeListener; +import org.apache.helix.api.listeners.ControllerChangeListener; +import org.apache.helix.api.listeners.CurrentStateChangeListener; +import org.apache.helix.api.listeners.IdealStateChangeListener; +import org.apache.helix.api.listeners.InstanceConfigChangeListener; +import org.apache.helix.api.listeners.LiveInstanceChangeListener; +import org.apache.helix.api.listeners.MessageListener; +import org.apache.helix.api.listeners.PreFetch; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixManager; +import org.apache.helix.NotificationContext; +import org.apache.helix.NotificationContext.Type; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.ZNRecord; +import org.apache.helix.controller.pipeline.Pipeline; +import org.apache.helix.controller.pipeline.PipelineRegistry; +import org.apache.helix.controller.stages.AttributeName; +import org.apache.helix.controller.stages.BestPossibleStateCalcStage; +import org.apache.helix.controller.stages.ClusterDataCache; +import org.apache.helix.controller.stages.ClusterEvent; +import org.apache.helix.controller.stages.ClusterEventBlockingQueue; +import org.apache.helix.controller.stages.ClusterEventType; +import org.apache.helix.controller.stages.CompatibilityCheckStage; +import org.apache.helix.controller.stages.CurrentStateComputationStage; +import org.apache.helix.controller.stages.ExternalViewComputeStage; +import org.apache.helix.controller.stages.IntermediateStateCalcStage; +import org.apache.helix.controller.stages.MessageGenerationPhase; +import org.apache.helix.controller.stages.MessageSelectionStage; +import org.apache.helix.controller.stages.MessageThrottleStage; +import org.apache.helix.controller.stages.PersistAssignmentStage; +import org.apache.helix.controller.stages.ReadClusterDataStage; +import org.apache.helix.controller.stages.ResourceComputationStage; +import org.apache.helix.controller.stages.ResourceValidationStage; +import org.apache.helix.controller.stages.TaskAssignmentStage; +import org.apache.helix.model.ClusterConfig; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.InstanceConfig; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.model.Message; +import org.apache.helix.model.PauseSignal; +import org.apache.helix.monitoring.mbeans.ClusterEventMonitor; +import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; +import org.apache.helix.task.TaskDriver; +import org.apache.log4j.Logger; + +import static org.apache.helix.HelixConstants.ChangeType; + +/** + * Cluster Controllers main goal is to keep the cluster state as close as possible to Ideal State. + * It does this by listening to changes in cluster state and scheduling new tasks to get cluster + * state to best possible ideal state. Every instance of this class can control can control only one + * cluster Get all the partitions use IdealState, CurrentState and Messages
    + * foreach partition
    + * 1. get the (instance,state) from IdealState, CurrentState and PendingMessages
    + * 2. compute best possible state (instance,state) pair. This needs previous step data and state + * model constraints
    + * 3. compute the messages/tasks needed to move to 1 to 2
    + * 4. select the messages that can be sent, needs messages and state model constraints
    + * 5. send messages + */ +public class GenericHelixController implements ConfigChangeListener, IdealStateChangeListener, + LiveInstanceChangeListener, MessageListener, CurrentStateChangeListener, + ControllerChangeListener, InstanceConfigChangeListener { + private static final Logger logger = Logger.getLogger(GenericHelixController.class.getName()); + private static final long EVENT_THREAD_JOIN_TIMEOUT = 1000; + private static final int ASYNC_TASKS_THREADPOOL_SIZE = 40; + private final PipelineRegistry _registry; + + final AtomicReference> _lastSeenInstances; + final AtomicReference> _lastSeenSessions; + + ClusterStatusMonitor _clusterStatusMonitor; + + /** + * A queue for controller events and a thread that will consume it + */ + private final ClusterEventBlockingQueue _eventQueue; + private final ClusterEventProcessor _eventThread; + + /** + * The _paused flag is checked by function handleEvent(), while if the flag is set handleEvent() + * will be no-op. Other event handling logic keeps the same when the flag is set. + */ + private boolean _paused; + + /** + * The timer that can periodically run the rebalancing pipeline. The timer will start if there is + * one resource group has the config to use the timer. + */ + Timer _rebalanceTimer = null; + long _timerPeriod = Long.MAX_VALUE; + + /** + * A cache maintained across pipelines + */ + private ClusterDataCache _cache; + private ExecutorService _asyncTasksThreadPool; + + private String _clusterName; + + /** + * Default constructor that creates a default pipeline registry. This is sufficient in most cases, + * but if there is a some thing specific needed use another constructor where in you can pass a + * pipeline registry + */ + public GenericHelixController() { + this(createDefaultRegistry()); + } + + public GenericHelixController(String clusterName) { + this(createDefaultRegistry(), clusterName); + } + + class RebalanceTask extends TimerTask { + HelixManager _manager; + + public RebalanceTask(HelixManager manager) { + _manager = manager; + } + + @Override + public void run() { + //TODO: this is the temporary workaround + _cache.requireFullRefresh(); + _cache.refresh(_manager.getHelixDataAccessor()); + if (_cache.getLiveInstances() != null) { + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + synchronized (_manager) { + checkLiveInstancesObservation(new ArrayList<>(_cache.getLiveInstances().values()), + changeContext); + } + } + + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + ClusterEvent event = new ClusterEvent(_clusterName,ClusterEventType.PeriodicalRebalance); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + List dummy = new ArrayList(); + event.addAttribute(AttributeName.eventData.name(), dummy); + // Should be able to process + _eventQueue.put(event); + logger.info("Controller periodicalRebalance event triggered!"); + } + } + + // TODO who should stop this timer + /** + * Starts the rebalancing timer with the specified period. Start the timer if necessary; If the + * period is smaller than the current period, cancel the current timer and use the new period. + */ + void startRebalancingTimer(long period, HelixManager manager) { + if (period != _timerPeriod) { + logger.info("Controller starting timer at period " + period); + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + } + _rebalanceTimer = new Timer(true); + _timerPeriod = period; + _rebalanceTimer + .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); + } else { + logger.info("Controller already has timer at period " + _timerPeriod); + } + } + + /** + * Stops the rebalancing timer + */ + void stopRebalancingTimer() { + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + _rebalanceTimer = null; + } + _timerPeriod = Integer.MAX_VALUE; + } + + private static PipelineRegistry createDefaultRegistry() { + logger.info("createDefaultRegistry"); + synchronized (GenericHelixController.class) { + PipelineRegistry registry = new PipelineRegistry(); + + // cluster data cache refresh + Pipeline dataRefresh = new Pipeline(); + dataRefresh.addStage(new ReadClusterDataStage()); + + // rebalance pipeline + Pipeline rebalancePipeline = new Pipeline(); + rebalancePipeline.addStage(new ResourceComputationStage()); + rebalancePipeline.addStage(new ResourceValidationStage()); + rebalancePipeline.addStage(new CurrentStateComputationStage()); + rebalancePipeline.addStage(new BestPossibleStateCalcStage()); + rebalancePipeline.addStage(new IntermediateStateCalcStage()); + rebalancePipeline.addStage(new MessageGenerationPhase()); + rebalancePipeline.addStage(new MessageSelectionStage()); + rebalancePipeline.addStage(new MessageThrottleStage()); + rebalancePipeline.addStage(new TaskAssignmentStage()); + rebalancePipeline.addStage(new PersistAssignmentStage()); + + // external view generation + Pipeline externalViewPipeline = new Pipeline(); + externalViewPipeline.addStage(new ExternalViewComputeStage()); + + // backward compatibility check + Pipeline liveInstancePipeline = new Pipeline(); + liveInstancePipeline.addStage(new CompatibilityCheckStage()); + + registry.register(ClusterEventType.IdealStateChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.CurrentStateChange, dataRefresh, rebalancePipeline, externalViewPipeline); + registry.register(ClusterEventType.ConfigChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.LiveInstanceChange, dataRefresh, liveInstancePipeline, rebalancePipeline, + externalViewPipeline); + + registry.register(ClusterEventType.MessageChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.ExternalViewChange, dataRefresh); + registry.register(ClusterEventType.Resume, dataRefresh, rebalancePipeline, externalViewPipeline); + registry + .register(ClusterEventType.PeriodicalRebalance, dataRefresh, rebalancePipeline, externalViewPipeline); + return registry; + } + } + + public GenericHelixController(PipelineRegistry registry) { + this(registry, null); + } + + private GenericHelixController(PipelineRegistry registry, String clusterName) { + _paused = false; + _registry = registry; + _lastSeenInstances = new AtomicReference<>(); + _lastSeenSessions = new AtomicReference<>(); + _clusterName = clusterName; + _asyncTasksThreadPool = Executors.newFixedThreadPool(ASYNC_TASKS_THREADPOOL_SIZE); + _cache = new ClusterDataCache(clusterName); + _cache.setAsyncTasksThreadPool(_asyncTasksThreadPool); + _eventQueue = new ClusterEventBlockingQueue(); + _eventThread = new ClusterEventProcessor(); + _eventThread.setDaemon(true); + _eventThread.start(); + } + + /** + * lock-always: caller always needs to obtain an external lock before call, calls to handleEvent() + * should be serialized + * @param event + */ + protected synchronized void handleEvent(ClusterEvent event) { + HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); + if (manager == null) { + logger.error("No cluster manager in event:" + event.getEventType()); + return; + } + + if (!manager.isLeader()) { + logger.error("Cluster manager: " + manager.getInstanceName() + " is not leader for " + manager + .getClusterName() + ". Pipeline will not be invoked"); + return; + } + + if (_paused) { + logger.info("Cluster " + manager.getClusterName() + " is paused. Ignoring the event:" + event + .getEventType()); + return; + } + + NotificationContext context = null; + if (event.getAttribute(AttributeName.changeContext.name()) != null) { + context = event.getAttribute(AttributeName.changeContext.name()); + } + + // Initialize _clusterStatusMonitor + if (context != null) { + if (context.getType() == Type.FINALIZE) { + stopRebalancingTimer(); + logger.info("Get FINALIZE notification, skip the pipeline. Event :" + event.getEventType()); + return; + } else { + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(manager.getClusterName()); + } + // TODO: should be in the initization of controller. + if (_cache != null) { + checkRebalancingTimer(manager, Collections.EMPTY_LIST, _cache.getClusterConfig()); + } + TaskDriver driver = new TaskDriver(manager); + _clusterStatusMonitor.refreshWorkflowsStatus(driver); + _clusterStatusMonitor.refreshJobsStatus(driver); + event.addAttribute(AttributeName.clusterStatusMonitor.name(), _clusterStatusMonitor); + } + } + + // add the cache + event.addAttribute(AttributeName.ClusterDataCache.name(), _cache); + + List pipelines = _registry.getPipelinesForEvent(event.getEventType()); + if (pipelines == null || pipelines.size() == 0) { + logger.info("No pipeline to run for event:" + event.getEventType()); + return; + } + + logger.info("START: Invoking controller pipeline for event: " + event.getEventType()); + long startTime = System.currentTimeMillis(); + for (Pipeline pipeline : pipelines) { + try { + pipeline.handle(event); + pipeline.finish(); + } catch (Exception e) { + logger.error("Exception while executing pipeline: " + pipeline + + ". Will not continue to next pipeline", e); + break; + } + } + long endTime = System.currentTimeMillis(); + logger.info("END: Invoking controller pipeline for event: " + event.getEventType() + " for cluster " + + manager.getClusterName() + ", took " + (endTime - startTime) + " ms"); + + // report event process durations + if (_clusterStatusMonitor != null) { + NotificationContext notificationContext = event.getAttribute(AttributeName.changeContext.name()); + long enqueueTime = event.getCreationTime(); + long zkCallbackTime; + StringBuilder sb = new StringBuilder(); + if (notificationContext != null) { + zkCallbackTime = notificationContext.getCreationTime(); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.Callback.name(), + enqueueTime - zkCallbackTime); + sb.append(String.format( + "Callback time for event: " + event.getEventType() + " took: " + (enqueueTime + - zkCallbackTime) + " ms\n")); + + } + _clusterStatusMonitor.updateClusterEventDuration(ClusterEventMonitor.PhaseName.InQueue.name(), + startTime - enqueueTime); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.TotalProcessed.name(), + endTime - startTime); + sb.append(String.format( + "InQueue time for event: " + event.getEventType() + " took: " + (startTime - enqueueTime) + + " ms\n")); + sb.append(String.format( + "TotalProcessed time for event: " + event.getEventType() + " took: " + (endTime - startTime) + + " ms")); + logger.info(sb.toString()); + } + } + + + @Override + @PreFetch(enabled = false) + public void onStateChange(String instanceName, List statesInfo, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onStateChange()"); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.CURRENT_STATE); + } + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.CurrentStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + logger.info("END: GenericClusterController.onStateChange()"); + } + + @Override + @PreFetch(enabled = false) + public void onMessage(String instanceName, List messages, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onMessage() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.MESSAGE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.MessageChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (_clusterStatusMonitor != null && messages != null) { + _clusterStatusMonitor.addMessageQueueSize(instanceName, messages.size()); + } + + logger.info("END: GenericClusterController.onMessage() for cluster " + _clusterName); + } + + @Override + public void onLiveInstanceChange(List liveInstances, + NotificationContext changeContext) { + logger.info("START: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } + + if (liveInstances == null) { + liveInstances = Collections.emptyList(); + } + _cache.setLiveInstances(liveInstances); + + // Go though the live instance list and make sure that we are observing them + // accordingly. The action is done regardless of the paused flag. + if (changeContext.getType() == NotificationContext.Type.INIT + || changeContext.getType() == NotificationContext.Type.CALLBACK) { + checkLiveInstancesObservation(liveInstances, changeContext); + } else if (changeContext.getType() == NotificationContext.Type.FINALIZE) { + // on finalize, should remove all message/current-state listeners + logger.info("remove message/current-state listeners. lastSeenInstances: " + _lastSeenInstances + + ", lastSeenSessions: " + _lastSeenSessions); + liveInstances = Collections.emptyList(); + checkLiveInstancesObservation(liveInstances, changeContext); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.LiveInstanceChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.eventData.name(), liveInstances); + _eventQueue.put(event); + logger.info( + "END: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + } + + private void checkRebalancingTimer(HelixManager manager, List idealStates, + ClusterConfig clusterConfig) { + if (manager.getConfigAccessor() == null) { + logger.warn(manager.getInstanceName() + + " config accessor doesn't exist. should be in file-based mode."); + return; + } + + long minPeriod = Long.MAX_VALUE; + if (clusterConfig != null) { + long period = clusterConfig.getRebalanceTimePeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + // TODO: resource level rebalance does not make sense, to remove it! + for (IdealState idealState : idealStates) { + long period = idealState.getRebalanceTimerPeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + if (minPeriod != Long.MAX_VALUE) { + startRebalancingTimer(minPeriod, manager); + } + } + + @Override + @PreFetch(enabled = false) + public void onIdealStateChange(List idealStates, NotificationContext changeContext) { + logger.info( + "START: Generic GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.IDEAL_STATE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.IdealStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (changeContext.getType() != Type.FINALIZE) { + checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); + } + + logger.info("END: GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onConfigChange(List configs, NotificationContext changeContext) { + logger.info("START: GenericClusterController.onConfigChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.INSTANCE_CONFIG); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.ConfigChange); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + + _eventQueue.put(event); + + logger.info("END: GenericClusterController.onConfigChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onInstanceConfigChange(List instanceConfigs, + NotificationContext changeContext) { + logger.info( + "START: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + onConfigChange(instanceConfigs, changeContext); + logger.info("END: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + } + + @Override + public void onControllerChange(NotificationContext changeContext) { + logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); + _cache.requireFullRefresh(); + if (changeContext != null && changeContext.getType() == Type.FINALIZE) { + logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); + return; + } + HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); + + // double check if this controller is the leader + Builder keyBuilder = accessor.keyBuilder(); + LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); + if (leader == null) { + logger + .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); + return; + } else { + String leaderName = leader.getInstanceName(); + + String instanceName = changeContext.getManager().getInstanceName(); + if (leaderName == null || !leaderName.equals(instanceName)) { + logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); + return; + } + } + + PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); + if (pauseSignal != null) { + if (!_paused) { + _paused = true; + logger.info("controller is now paused"); + } + } else { + if (_paused) { + _paused = false; + logger.info("controller is now resumed"); + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.eventData.name(), pauseSignal); + _eventQueue.put(event); + } + } + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); + } + _clusterStatusMonitor.setEnabled(!_paused); + logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); + } + + /** + * Go through the list of liveinstances in the cluster, and add currentstateChange listener and + * Message listeners to them if they are newly added. For current state change, the observation is + * tied to the session id of each live instance. + */ + protected void checkLiveInstancesObservation(List liveInstances, + NotificationContext changeContext) { + + // construct maps for current live-instances + Map curInstances = new HashMap(); + Map curSessions = new HashMap<>(); + for (LiveInstance liveInstance : liveInstances) { + curInstances.put(liveInstance.getInstanceName(), liveInstance); + curSessions.put(liveInstance.getSessionId(), liveInstance); + } + + // TODO: remove the synchronization here once we move this update into dataCache. + synchronized (_lastSeenInstances) { + Map lastInstances = _lastSeenInstances.get(); + Map lastSessions = _lastSeenSessions.get(); + + HelixManager manager = changeContext.getManager(); + Builder keyBuilder = new Builder(manager.getClusterName()); + if (lastSessions != null) { + for (String session : lastSessions.keySet()) { + if (!curSessions.containsKey(session)) { + // remove current-state listener for expired session + String instanceName = lastSessions.get(session).getInstanceName(); + manager.removeListener(keyBuilder.currentStates(instanceName, session), this); + } + } + } + + if (lastInstances != null) { + for (String instance : lastInstances.keySet()) { + if (!curInstances.containsKey(instance)) { + // remove message listener for disconnected instances + manager.removeListener(keyBuilder.messages(instance), this); + } + } + } + + for (String session : curSessions.keySet()) { + if (lastSessions == null || !lastSessions.containsKey(session)) { + String instanceName = curSessions.get(session).getInstanceName(); + try { + // add current-state listeners for new sessions + manager.addCurrentStateChangeListener(this, instanceName, session); + logger.info(manager.getInstanceName() + " added current-state listener for instance: " + + instanceName + ", session: " + session + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add current state listener for instance: " + instanceName + + " with session: " + session, e); + } + } + } + + for (String instance : curInstances.keySet()) { + if (lastInstances == null || !lastInstances.containsKey(instance)) { + try { + // add message listeners for new instances + manager.addMessageListener(this, instance); + logger.info(manager.getInstanceName() + " added message listener for " + instance + + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add message listener for instance: " + instance, e); + } + } + } + + // update last-seen + _lastSeenInstances.set(curInstances); + _lastSeenSessions.set(curSessions); + } + } + + public void shutdownClusterStatusMonitor(String clusterName) { + if (_clusterStatusMonitor != null) { + logger.info("Shut down _clusterStatusMonitor for cluster " + clusterName); + _clusterStatusMonitor.reset(); + _clusterStatusMonitor = null; + } + } + + public void shutdown() throws InterruptedException { + stopRebalancingTimer(); + while (_eventThread.isAlive()) { + _eventThread.interrupt(); + _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); + } + _asyncTasksThreadPool.shutdown(); + } + + private class ClusterEventProcessor extends Thread { + @Override + public void run() { + logger.info("START ClusterEventProcessor thread for cluster " + _clusterName); + while (!isInterrupted()) { + try { + ClusterEvent event = _eventQueue.take(); + handleEvent(event); + } catch (InterruptedException e) { + logger.warn("ClusterEventProcessor interrupted", e); + interrupt(); + } catch (ZkInterruptedException e) { + logger.warn("ClusterEventProcessor caught a ZK connection interrupt", e); + interrupt(); + } catch (ThreadDeath death) { + throw death; + } catch (Throwable t) { + logger.error("ClusterEventProcessor failed while running the controller pipeline", t); + } + } + logger.info("END ClusterEventProcessor thread"); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.controller.GenericHelixController.onMessage` reads without synchronization from `this.org.apache.helix.controller.GenericHelixController._clusterStatusMonitor`. Potentially races with write in method `GenericHelixController.handleEvent(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericHelixController.onMessage(String,List,NotificationContext) + +### Procedure Id: +org.apache.helix.controller.GenericHelixController.onMessage(java.lang.String,java.util.List,org.apa.2622c71ff639542b21f94378ed82ef51 + +### File: +helix-core/src/main/java/org/apache/helix/controller/GenericHelixController.java + +### Key: +GenericHelixController.java|onMessage|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +f89bb53a08a46e438957c362ed31187f + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9617/instruction.md b/inferredbugs-9617/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c337fc6eaae12b260853dfe8b32395ed2d0f73f9 --- /dev/null +++ b/inferredbugs-9617/instruction.md @@ -0,0 +1,787 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 53 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; + +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.apache.helix.api.listeners.ConfigChangeListener; +import org.apache.helix.api.listeners.ControllerChangeListener; +import org.apache.helix.api.listeners.CurrentStateChangeListener; +import org.apache.helix.api.listeners.IdealStateChangeListener; +import org.apache.helix.api.listeners.InstanceConfigChangeListener; +import org.apache.helix.api.listeners.LiveInstanceChangeListener; +import org.apache.helix.api.listeners.MessageListener; +import org.apache.helix.api.listeners.PreFetch; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixManager; +import org.apache.helix.NotificationContext; +import org.apache.helix.NotificationContext.Type; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.ZNRecord; +import org.apache.helix.controller.pipeline.Pipeline; +import org.apache.helix.controller.pipeline.PipelineRegistry; +import org.apache.helix.controller.stages.AttributeName; +import org.apache.helix.controller.stages.BestPossibleStateCalcStage; +import org.apache.helix.controller.stages.ClusterDataCache; +import org.apache.helix.controller.stages.ClusterEvent; +import org.apache.helix.controller.stages.ClusterEventBlockingQueue; +import org.apache.helix.controller.stages.ClusterEventType; +import org.apache.helix.controller.stages.CompatibilityCheckStage; +import org.apache.helix.controller.stages.CurrentStateComputationStage; +import org.apache.helix.controller.stages.ExternalViewComputeStage; +import org.apache.helix.controller.stages.IntermediateStateCalcStage; +import org.apache.helix.controller.stages.MessageGenerationPhase; +import org.apache.helix.controller.stages.MessageSelectionStage; +import org.apache.helix.controller.stages.MessageThrottleStage; +import org.apache.helix.controller.stages.PersistAssignmentStage; +import org.apache.helix.controller.stages.ReadClusterDataStage; +import org.apache.helix.controller.stages.ResourceComputationStage; +import org.apache.helix.controller.stages.ResourceValidationStage; +import org.apache.helix.controller.stages.TaskAssignmentStage; +import org.apache.helix.model.ClusterConfig; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.InstanceConfig; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.model.Message; +import org.apache.helix.model.PauseSignal; +import org.apache.helix.monitoring.mbeans.ClusterEventMonitor; +import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; +import org.apache.helix.task.TaskDriver; +import org.apache.log4j.Logger; + +import static org.apache.helix.HelixConstants.ChangeType; + +/** + * Cluster Controllers main goal is to keep the cluster state as close as possible to Ideal State. + * It does this by listening to changes in cluster state and scheduling new tasks to get cluster + * state to best possible ideal state. Every instance of this class can control can control only one + * cluster Get all the partitions use IdealState, CurrentState and Messages
    + * foreach partition
    + * 1. get the (instance,state) from IdealState, CurrentState and PendingMessages
    + * 2. compute best possible state (instance,state) pair. This needs previous step data and state + * model constraints
    + * 3. compute the messages/tasks needed to move to 1 to 2
    + * 4. select the messages that can be sent, needs messages and state model constraints
    + * 5. send messages + */ +public class GenericHelixController implements ConfigChangeListener, IdealStateChangeListener, + LiveInstanceChangeListener, MessageListener, CurrentStateChangeListener, + ControllerChangeListener, InstanceConfigChangeListener { + private static final Logger logger = Logger.getLogger(GenericHelixController.class.getName()); + private static final long EVENT_THREAD_JOIN_TIMEOUT = 1000; + private static final int ASYNC_TASKS_THREADPOOL_SIZE = 40; + private final PipelineRegistry _registry; + + final AtomicReference> _lastSeenInstances; + final AtomicReference> _lastSeenSessions; + + ClusterStatusMonitor _clusterStatusMonitor; + + /** + * A queue for controller events and a thread that will consume it + */ + private final ClusterEventBlockingQueue _eventQueue; + private final ClusterEventProcessor _eventThread; + + /** + * The _paused flag is checked by function handleEvent(), while if the flag is set handleEvent() + * will be no-op. Other event handling logic keeps the same when the flag is set. + */ + private boolean _paused; + + /** + * The timer that can periodically run the rebalancing pipeline. The timer will start if there is + * one resource group has the config to use the timer. + */ + Timer _rebalanceTimer = null; + long _timerPeriod = Long.MAX_VALUE; + + /** + * A cache maintained across pipelines + */ + private ClusterDataCache _cache; + private ExecutorService _asyncTasksThreadPool; + + private String _clusterName; + + /** + * Default constructor that creates a default pipeline registry. This is sufficient in most cases, + * but if there is a some thing specific needed use another constructor where in you can pass a + * pipeline registry + */ + public GenericHelixController() { + this(createDefaultRegistry()); + } + + public GenericHelixController(String clusterName) { + this(createDefaultRegistry(), clusterName); + } + + class RebalanceTask extends TimerTask { + HelixManager _manager; + + public RebalanceTask(HelixManager manager) { + _manager = manager; + } + + @Override + public void run() { + //TODO: this is the temporary workaround + _cache.requireFullRefresh(); + _cache.refresh(_manager.getHelixDataAccessor()); + if (_cache.getLiveInstances() != null) { + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + synchronized (_manager) { + checkLiveInstancesObservation(new ArrayList<>(_cache.getLiveInstances().values()), + changeContext); + } + } + + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + ClusterEvent event = new ClusterEvent(_clusterName,ClusterEventType.PeriodicalRebalance); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + List dummy = new ArrayList(); + event.addAttribute(AttributeName.eventData.name(), dummy); + // Should be able to process + _eventQueue.put(event); + logger.info("Controller periodicalRebalance event triggered!"); + } + } + + // TODO who should stop this timer + /** + * Starts the rebalancing timer with the specified period. Start the timer if necessary; If the + * period is smaller than the current period, cancel the current timer and use the new period. + */ + void startRebalancingTimer(long period, HelixManager manager) { + if (period != _timerPeriod) { + logger.info("Controller starting timer at period " + period); + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + } + _rebalanceTimer = new Timer(true); + _timerPeriod = period; + _rebalanceTimer + .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); + } else { + logger.info("Controller already has timer at period " + _timerPeriod); + } + } + + /** + * Stops the rebalancing timer + */ + void stopRebalancingTimer() { + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + _rebalanceTimer = null; + } + _timerPeriod = Integer.MAX_VALUE; + } + + private static PipelineRegistry createDefaultRegistry() { + logger.info("createDefaultRegistry"); + synchronized (GenericHelixController.class) { + PipelineRegistry registry = new PipelineRegistry(); + + // cluster data cache refresh + Pipeline dataRefresh = new Pipeline(); + dataRefresh.addStage(new ReadClusterDataStage()); + + // rebalance pipeline + Pipeline rebalancePipeline = new Pipeline(); + rebalancePipeline.addStage(new ResourceComputationStage()); + rebalancePipeline.addStage(new ResourceValidationStage()); + rebalancePipeline.addStage(new CurrentStateComputationStage()); + rebalancePipeline.addStage(new BestPossibleStateCalcStage()); + rebalancePipeline.addStage(new IntermediateStateCalcStage()); + rebalancePipeline.addStage(new MessageGenerationPhase()); + rebalancePipeline.addStage(new MessageSelectionStage()); + rebalancePipeline.addStage(new MessageThrottleStage()); + rebalancePipeline.addStage(new TaskAssignmentStage()); + rebalancePipeline.addStage(new PersistAssignmentStage()); + + // external view generation + Pipeline externalViewPipeline = new Pipeline(); + externalViewPipeline.addStage(new ExternalViewComputeStage()); + + // backward compatibility check + Pipeline liveInstancePipeline = new Pipeline(); + liveInstancePipeline.addStage(new CompatibilityCheckStage()); + + registry.register(ClusterEventType.IdealStateChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.CurrentStateChange, dataRefresh, rebalancePipeline, externalViewPipeline); + registry.register(ClusterEventType.ConfigChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.LiveInstanceChange, dataRefresh, liveInstancePipeline, rebalancePipeline, + externalViewPipeline); + + registry.register(ClusterEventType.MessageChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.ExternalViewChange, dataRefresh); + registry.register(ClusterEventType.Resume, dataRefresh, rebalancePipeline, externalViewPipeline); + registry + .register(ClusterEventType.PeriodicalRebalance, dataRefresh, rebalancePipeline, externalViewPipeline); + return registry; + } + } + + public GenericHelixController(PipelineRegistry registry) { + this(registry, null); + } + + private GenericHelixController(PipelineRegistry registry, String clusterName) { + _paused = false; + _registry = registry; + _lastSeenInstances = new AtomicReference<>(); + _lastSeenSessions = new AtomicReference<>(); + _clusterName = clusterName; + _asyncTasksThreadPool = Executors.newFixedThreadPool(ASYNC_TASKS_THREADPOOL_SIZE); + _cache = new ClusterDataCache(clusterName); + _cache.setAsyncTasksThreadPool(_asyncTasksThreadPool); + _eventQueue = new ClusterEventBlockingQueue(); + _eventThread = new ClusterEventProcessor(); + _eventThread.setDaemon(true); + _eventThread.start(); + } + + /** + * lock-always: caller always needs to obtain an external lock before call, calls to handleEvent() + * should be serialized + * @param event + */ + protected synchronized void handleEvent(ClusterEvent event) { + HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); + if (manager == null) { + logger.error("No cluster manager in event:" + event.getEventType()); + return; + } + + if (!manager.isLeader()) { + logger.error("Cluster manager: " + manager.getInstanceName() + " is not leader for " + manager + .getClusterName() + ". Pipeline will not be invoked"); + return; + } + + if (_paused) { + logger.info("Cluster " + manager.getClusterName() + " is paused. Ignoring the event:" + event + .getEventType()); + return; + } + + NotificationContext context = null; + if (event.getAttribute(AttributeName.changeContext.name()) != null) { + context = event.getAttribute(AttributeName.changeContext.name()); + } + + // Initialize _clusterStatusMonitor + if (context != null) { + if (context.getType() == Type.FINALIZE) { + stopRebalancingTimer(); + logger.info("Get FINALIZE notification, skip the pipeline. Event :" + event.getEventType()); + return; + } else { + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(manager.getClusterName()); + } + // TODO: should be in the initization of controller. + if (_cache != null) { + checkRebalancingTimer(manager, Collections.EMPTY_LIST, _cache.getClusterConfig()); + } + TaskDriver driver = new TaskDriver(manager); + _clusterStatusMonitor.refreshWorkflowsStatus(driver); + _clusterStatusMonitor.refreshJobsStatus(driver); + event.addAttribute(AttributeName.clusterStatusMonitor.name(), _clusterStatusMonitor); + } + } + + // add the cache + event.addAttribute(AttributeName.ClusterDataCache.name(), _cache); + + List pipelines = _registry.getPipelinesForEvent(event.getEventType()); + if (pipelines == null || pipelines.size() == 0) { + logger.info("No pipeline to run for event:" + event.getEventType()); + return; + } + + logger.info("START: Invoking controller pipeline for event: " + event.getEventType()); + long startTime = System.currentTimeMillis(); + for (Pipeline pipeline : pipelines) { + try { + pipeline.handle(event); + pipeline.finish(); + } catch (Exception e) { + logger.error("Exception while executing pipeline: " + pipeline + + ". Will not continue to next pipeline", e); + break; + } + } + long endTime = System.currentTimeMillis(); + logger.info("END: Invoking controller pipeline for event: " + event.getEventType() + " for cluster " + + manager.getClusterName() + ", took " + (endTime - startTime) + " ms"); + + // report event process durations + if (_clusterStatusMonitor != null) { + NotificationContext notificationContext = event.getAttribute(AttributeName.changeContext.name()); + long enqueueTime = event.getCreationTime(); + long zkCallbackTime; + StringBuilder sb = new StringBuilder(); + if (notificationContext != null) { + zkCallbackTime = notificationContext.getCreationTime(); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.Callback.name(), + enqueueTime - zkCallbackTime); + sb.append(String.format( + "Callback time for event: " + event.getEventType() + " took: " + (enqueueTime + - zkCallbackTime) + " ms\n")); + + } + _clusterStatusMonitor.updateClusterEventDuration(ClusterEventMonitor.PhaseName.InQueue.name(), + startTime - enqueueTime); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.TotalProcessed.name(), + endTime - startTime); + sb.append(String.format( + "InQueue time for event: " + event.getEventType() + " took: " + (startTime - enqueueTime) + + " ms\n")); + sb.append(String.format( + "TotalProcessed time for event: " + event.getEventType() + " took: " + (endTime - startTime) + + " ms")); + logger.info(sb.toString()); + } + } + + + @Override + @PreFetch(enabled = false) + public void onStateChange(String instanceName, List statesInfo, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onStateChange()"); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.CURRENT_STATE); + } + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.CurrentStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + logger.info("END: GenericClusterController.onStateChange()"); + } + + @Override + @PreFetch(enabled = false) + public void onMessage(String instanceName, List messages, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onMessage() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.MESSAGE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.MessageChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (_clusterStatusMonitor != null && messages != null) { + _clusterStatusMonitor.addMessageQueueSize(instanceName, messages.size()); + } + + logger.info("END: GenericClusterController.onMessage() for cluster " + _clusterName); + } + + @Override + public void onLiveInstanceChange(List liveInstances, + NotificationContext changeContext) { + logger.info("START: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } + + if (liveInstances == null) { + liveInstances = Collections.emptyList(); + } + _cache.setLiveInstances(liveInstances); + + // Go though the live instance list and make sure that we are observing them + // accordingly. The action is done regardless of the paused flag. + if (changeContext.getType() == NotificationContext.Type.INIT + || changeContext.getType() == NotificationContext.Type.CALLBACK) { + checkLiveInstancesObservation(liveInstances, changeContext); + } else if (changeContext.getType() == NotificationContext.Type.FINALIZE) { + // on finalize, should remove all message/current-state listeners + logger.info("remove message/current-state listeners. lastSeenInstances: " + _lastSeenInstances + + ", lastSeenSessions: " + _lastSeenSessions); + liveInstances = Collections.emptyList(); + checkLiveInstancesObservation(liveInstances, changeContext); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.LiveInstanceChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.eventData.name(), liveInstances); + _eventQueue.put(event); + logger.info( + "END: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + } + + private void checkRebalancingTimer(HelixManager manager, List idealStates, + ClusterConfig clusterConfig) { + if (manager.getConfigAccessor() == null) { + logger.warn(manager.getInstanceName() + + " config accessor doesn't exist. should be in file-based mode."); + return; + } + + long minPeriod = Long.MAX_VALUE; + if (clusterConfig != null) { + long period = clusterConfig.getRebalanceTimePeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + // TODO: resource level rebalance does not make sense, to remove it! + for (IdealState idealState : idealStates) { + long period = idealState.getRebalanceTimerPeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + if (minPeriod != Long.MAX_VALUE) { + startRebalancingTimer(minPeriod, manager); + } + } + + @Override + @PreFetch(enabled = false) + public void onIdealStateChange(List idealStates, NotificationContext changeContext) { + logger.info( + "START: Generic GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.IDEAL_STATE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.IdealStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (changeContext.getType() != Type.FINALIZE) { + checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); + } + + logger.info("END: GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onConfigChange(List configs, NotificationContext changeContext) { + logger.info("START: GenericClusterController.onConfigChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.INSTANCE_CONFIG); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.ConfigChange); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + + _eventQueue.put(event); + + logger.info("END: GenericClusterController.onConfigChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onInstanceConfigChange(List instanceConfigs, + NotificationContext changeContext) { + logger.info( + "START: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + onConfigChange(instanceConfigs, changeContext); + logger.info("END: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + } + + @Override + public void onControllerChange(NotificationContext changeContext) { + logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); + _cache.requireFullRefresh(); + if (changeContext != null && changeContext.getType() == Type.FINALIZE) { + logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); + return; + } + HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); + + // double check if this controller is the leader + Builder keyBuilder = accessor.keyBuilder(); + LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); + if (leader == null) { + logger + .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); + return; + } else { + String leaderName = leader.getInstanceName(); + + String instanceName = changeContext.getManager().getInstanceName(); + if (leaderName == null || !leaderName.equals(instanceName)) { + logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); + return; + } + } + + PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); + if (pauseSignal != null) { + if (!_paused) { + _paused = true; + logger.info("controller is now paused"); + } + } else { + if (_paused) { + _paused = false; + logger.info("controller is now resumed"); + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.eventData.name(), pauseSignal); + _eventQueue.put(event); + } + } + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); + } + _clusterStatusMonitor.setEnabled(!_paused); + logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); + } + + /** + * Go through the list of liveinstances in the cluster, and add currentstateChange listener and + * Message listeners to them if they are newly added. For current state change, the observation is + * tied to the session id of each live instance. + */ + protected void checkLiveInstancesObservation(List liveInstances, + NotificationContext changeContext) { + + // construct maps for current live-instances + Map curInstances = new HashMap(); + Map curSessions = new HashMap<>(); + for (LiveInstance liveInstance : liveInstances) { + curInstances.put(liveInstance.getInstanceName(), liveInstance); + curSessions.put(liveInstance.getSessionId(), liveInstance); + } + + // TODO: remove the synchronization here once we move this update into dataCache. + synchronized (_lastSeenInstances) { + Map lastInstances = _lastSeenInstances.get(); + Map lastSessions = _lastSeenSessions.get(); + + HelixManager manager = changeContext.getManager(); + Builder keyBuilder = new Builder(manager.getClusterName()); + if (lastSessions != null) { + for (String session : lastSessions.keySet()) { + if (!curSessions.containsKey(session)) { + // remove current-state listener for expired session + String instanceName = lastSessions.get(session).getInstanceName(); + manager.removeListener(keyBuilder.currentStates(instanceName, session), this); + } + } + } + + if (lastInstances != null) { + for (String instance : lastInstances.keySet()) { + if (!curInstances.containsKey(instance)) { + // remove message listener for disconnected instances + manager.removeListener(keyBuilder.messages(instance), this); + } + } + } + + for (String session : curSessions.keySet()) { + if (lastSessions == null || !lastSessions.containsKey(session)) { + String instanceName = curSessions.get(session).getInstanceName(); + try { + // add current-state listeners for new sessions + manager.addCurrentStateChangeListener(this, instanceName, session); + logger.info(manager.getInstanceName() + " added current-state listener for instance: " + + instanceName + ", session: " + session + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add current state listener for instance: " + instanceName + + " with session: " + session, e); + } + } + } + + for (String instance : curInstances.keySet()) { + if (lastInstances == null || !lastInstances.containsKey(instance)) { + try { + // add message listeners for new instances + manager.addMessageListener(this, instance); + logger.info(manager.getInstanceName() + " added message listener for " + instance + + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add message listener for instance: " + instance, e); + } + } + } + + // update last-seen + _lastSeenInstances.set(curInstances); + _lastSeenSessions.set(curSessions); + } + } + + public void shutdownClusterStatusMonitor(String clusterName) { + if (_clusterStatusMonitor != null) { + logger.info("Shut down _clusterStatusMonitor for cluster " + clusterName); + _clusterStatusMonitor.reset(); + _clusterStatusMonitor = null; + } + } + + public void shutdown() throws InterruptedException { + stopRebalancingTimer(); + while (_eventThread.isAlive()) { + _eventThread.interrupt(); + _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); + } + _asyncTasksThreadPool.shutdown(); + } + + private class ClusterEventProcessor extends Thread { + @Override + public void run() { + logger.info("START ClusterEventProcessor thread for cluster " + _clusterName); + while (!isInterrupted()) { + try { + ClusterEvent event = _eventQueue.take(); + handleEvent(event); + } catch (InterruptedException e) { + logger.warn("ClusterEventProcessor interrupted", e); + interrupt(); + } catch (ZkInterruptedException e) { + logger.warn("ClusterEventProcessor caught a ZK connection interrupt", e); + interrupt(); + } catch (ThreadDeath death) { + throw death; + } catch (Throwable t) { + logger.error("ClusterEventProcessor failed while running the controller pipeline", t); + } + } + logger.info("END ClusterEventProcessor thread"); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.helix.controller.GenericHelixController.stopRebalancingTimer` writes to field `this.org.apache.helix.controller.GenericHelixController._timerPeriod` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericHelixController.stopRebalancingTimer() + +### Procedure Id: +org.apache.helix.controller.GenericHelixController.stopRebalancingTimer():void.300691c867b9ec153986206771373244 + +### File: +helix-core/src/main/java/org/apache/helix/controller/GenericHelixController.java + +### Key: +GenericHelixController.java|stopRebalancingTimer|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +21d79b8dd286ece39a578ee849194a74 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9618/instruction.md b/inferredbugs-9618/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..227a33db12bae9c60edbff5f83601dcf45a7f308 --- /dev/null +++ b/inferredbugs-9618/instruction.md @@ -0,0 +1,1160 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 30 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.lang.management.ManagementFactory; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedList; +import java.util.List; +import java.util.Timer; +import java.util.concurrent.TimeUnit; + +import org.I0Itec.zkclient.ZkConnection; +import org.apache.helix.BaseDataAccessor; +import org.apache.helix.ClusterMessagingService; +import org.apache.helix.ConfigAccessor; +import org.apache.helix.ConfigChangeListener; +import org.apache.helix.AccessOption; +import org.apache.helix.ControllerChangeListener; +import org.apache.helix.CurrentStateChangeListener; +import org.apache.helix.ExternalViewChangeListener; +import org.apache.helix.HealthStateChangeListener; +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixConstants.ChangeType; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixException; +import org.apache.helix.HelixManager; +import org.apache.helix.HelixTimerTask; +import org.apache.helix.IdealStateChangeListener; +import org.apache.helix.InstanceConfigChangeListener; +import org.apache.helix.InstanceType; +import org.apache.helix.LiveInstanceChangeListener; +import org.apache.helix.LiveInstanceInfoProvider; +import org.apache.helix.MessageListener; +import org.apache.helix.PreConnectCallback; +import org.apache.helix.HelixManagerProperties; +import org.apache.helix.PropertyKey; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.PropertyPathConfig; +import org.apache.helix.PropertyType; +import org.apache.helix.ScopedConfigChangeListener; +import org.apache.helix.ZNRecord; +import org.apache.helix.controller.restlet.ZKPropertyTransferServer; +import org.apache.helix.healthcheck.HealthStatsAggregationTask; +import org.apache.helix.healthcheck.ParticipantHealthReportCollector; +import org.apache.helix.healthcheck.ParticipantHealthReportCollectorImpl; +import org.apache.helix.messaging.DefaultMessagingService; +import org.apache.helix.messaging.handling.MessageHandlerFactory; +import org.apache.helix.model.ConfigScope; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.HelixConfigScope; +import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty; +import org.apache.helix.model.InstanceConfig; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.model.Message.MessageType; +import org.apache.helix.model.builder.ConfigScopeBuilder; +import org.apache.helix.model.StateModelDefinition; +import org.apache.helix.monitoring.ZKPathDataDumpTask; +import org.apache.helix.participant.DistClusterControllerElection; +import org.apache.helix.participant.HelixStateMachineEngine; +import org.apache.helix.participant.StateMachineEngine; +import org.apache.helix.participant.statemachine.ScheduledTaskStateModelFactory; +import org.apache.helix.store.zk.ZkHelixPropertyStore; +import org.apache.log4j.Logger; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; + + +public class ZKHelixManager implements HelixManager +{ + private static Logger logger = + Logger.getLogger(ZKHelixManager.class); + private static final int RETRY_LIMIT = 3; + private static final int CONNECTIONTIMEOUT = 60 * 1000; + private final String _clusterName; + private final String _instanceName; + private final String _zkConnectString; + private static final int DEFAULT_SESSION_TIMEOUT = 30 * 1000; + private ZKHelixDataAccessor _helixAccessor; + private ConfigAccessor _configAccessor; + protected ZkClient _zkClient; + protected List _handlers; + private final ZkStateChangeListener _zkStateChangeListener; + private final InstanceType _instanceType; + volatile String _sessionId; + private Timer _timer; + private CallbackHandler _leaderElectionHandler; + private ParticipantHealthReportCollectorImpl _participantHealthCheckInfoCollector; + private final DefaultMessagingService _messagingService; + private ZKHelixAdmin _managementTool; + private final String _version; + private final HelixManagerProperties _properties; + private final StateMachineEngine _stateMachEngine; + private int _sessionTimeout; + private ZkHelixPropertyStore _helixPropertyStore; + private final List _controllerTimerTasks; + private BaseDataAccessor _baseDataAccessor; + List _preConnectCallbacks = + new LinkedList(); + ZKPropertyTransferServer _transferServer = null; + int _flappingTimeWindowMs; + int _maxDisconnectThreshold; + public static final int FLAPPING_TIME_WINDIOW = 300000; // Default to 300 sec + public static final int MAX_DISCONNECT_THRESHOLD = 5; + LiveInstanceInfoProvider _liveInstanceInfoProvider = null; + public static final String ALLOW_PARTICIPANT_AUTO_JOIN = "allowParticipantAutoJoin"; + + public ZKHelixManager(String clusterName, + String instanceName, + InstanceType instanceType, + String zkConnectString) + { + logger.info("Create a zk-based cluster manager. clusterName:" + clusterName + + ", instanceName:" + instanceName + ", type:" + instanceType + ", zkSvr:" + + zkConnectString); + _flappingTimeWindowMs = FLAPPING_TIME_WINDIOW; + try + { + _flappingTimeWindowMs = + Integer.parseInt(System.getProperty("helixmanager.flappingTimeWindow", "" + + FLAPPING_TIME_WINDIOW)); + } + catch (NumberFormatException e) + { + logger.warn("Exception while parsing helixmanager.flappingTimeWindow: " + + System.getProperty("helixmanager.flappingTimeWindow", "" + FLAPPING_TIME_WINDIOW)); + } + _maxDisconnectThreshold = MAX_DISCONNECT_THRESHOLD; + try + { + _maxDisconnectThreshold = + Integer.parseInt(System.getProperty("helixmanager.maxDisconnectThreshold", "" + + MAX_DISCONNECT_THRESHOLD)); + } + catch (NumberFormatException e) + { + logger.warn("Exception while parsing helixmanager.maxDisconnectThreshold: " + + System.getProperty("helixmanager.maxDisconnectThreshold", "" + MAX_DISCONNECT_THRESHOLD)); + } + int sessionTimeoutInt = -1; + try + { + sessionTimeoutInt = + Integer.parseInt(System.getProperty("zk.session.timeout", "" + + DEFAULT_SESSION_TIMEOUT)); + } + catch (NumberFormatException e) + { + logger.warn("Exception while parsing session timeout: " + + System.getProperty("zk.session.timeout", "" + DEFAULT_SESSION_TIMEOUT)); + } + if (sessionTimeoutInt > 0) + { + _sessionTimeout = sessionTimeoutInt; + } + else + { + _sessionTimeout = DEFAULT_SESSION_TIMEOUT; + } + if (instanceName == null) + { + try + { + instanceName = + InetAddress.getLocalHost().getCanonicalHostName() + "-" + + instanceType.toString(); + } + catch (UnknownHostException e) + { + // can ignore it + logger.info("Unable to get host name. Will set it to UNKNOWN, mostly ignorable", + e); + instanceName = "UNKNOWN"; + } + } + + _clusterName = clusterName; + _instanceName = instanceName; + _instanceType = instanceType; + _zkConnectString = zkConnectString; + _zkStateChangeListener = new ZkStateChangeListener(this, _flappingTimeWindowMs, _maxDisconnectThreshold); + _timer = null; + + _messagingService = new DefaultMessagingService(this); + + _properties = + new HelixManagerProperties("cluster-manager-version.properties"); + _version = _properties.getVersion(); + + _stateMachEngine = new HelixStateMachineEngine(this); + + // add all timer tasks + _controllerTimerTasks = new ArrayList(); + if (_instanceType == InstanceType.CONTROLLER) + { + _controllerTimerTasks.add(new HealthStatsAggregationTask(this)); + } + } + + @Override + public boolean removeListener(PropertyKey key, Object listener) + { + logger.info("Removing listener: " + listener + " on path: " + key.getPath() + + " from cluster: " + _clusterName + " by instance: " + _instanceName); + + synchronized (this) + { + List toRemove = new ArrayList(); + for (CallbackHandler handler : _handlers) + { + // compare property-key path and listener reference + if (handler.getPath().equals(key.getPath()) && handler.getListener().equals(listener)) + { + toRemove.add(handler); + } + } + + _handlers.removeAll(toRemove); + + // handler.reset() may modify the handlers list, so do it outside the iteration + for (CallbackHandler handler : toRemove) { + handler.reset(); + } + } + + return true; + } + + private void addListener(Object listener, PropertyKey propertyKey, ChangeType changeType, EventType[] eventType) + { + checkConnected(); + + PropertyType type = propertyKey.getType(); + CallbackHandler handler = + createCallBackHandler(propertyKey, listener, eventType, changeType); + + synchronized (this) + { + _handlers.add(handler); + logger.info("Add listener: " + listener + " for type: " + type + " to path: " + handler.getPath()); + } + } + + @Override + public void addIdealStateChangeListener(final IdealStateChangeListener listener) throws Exception + { + addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE, + new EventType[] { EventType.NodeDataChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception + { + addListener(listener, new Builder(_clusterName).liveInstances(), ChangeType.LIVE_INSTANCE, + new EventType[] { EventType.NodeDataChanged, EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addConfigChangeListener(ConfigChangeListener listener) + { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addInstanceConfigChangeListener(InstanceConfigChangeListener listener) + { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addConfigChangeListener(ScopedConfigChangeListener listener, ConfigScopeProperty scope) + { + Builder keyBuilder = new Builder(_clusterName); + + PropertyKey propertyKey = null; + switch(scope) + { + case CLUSTER: + propertyKey = keyBuilder.clusterConfigs(); + break; + case PARTICIPANT: + propertyKey = keyBuilder.instanceConfigs(); + break; + case RESOURCE: + propertyKey = keyBuilder.resourceConfigs(); + break; + default: + break; + } + + if (propertyKey != null) + { + addListener(listener, propertyKey, ChangeType.CONFIG, + new EventType[] { EventType.NodeChildrenChanged }); + } else + { + logger.error("Can't add listener to config scope: " + scope); + } + } + + // TODO: Decide if do we still need this since we are exposing + // ClusterMessagingService + @Override + public void addMessageListener(MessageListener listener, String instanceName) + { + addListener(listener, new Builder(_clusterName).messages(instanceName), ChangeType.MESSAGE, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + void addControllerMessageListener(MessageListener listener) + { + addListener(listener, new Builder(_clusterName).controllerMessages(), ChangeType.MESSAGES_CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addCurrentStateChangeListener(CurrentStateChangeListener listener, + String instanceName, + String sessionId) + { + addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId), ChangeType.CURRENT_STATE, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addHealthStateChangeListener(HealthStateChangeListener listener, + String instanceName) + { + addListener(listener, new Builder(_clusterName).healthReports(instanceName), ChangeType.HEALTH, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addExternalViewChangeListener(ExternalViewChangeListener listener) + { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public void addControllerListener(ControllerChangeListener listener) + { + addListener(listener, new Builder(_clusterName).controller(), ChangeType.CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated }); + } + + @Override + public HelixDataAccessor getHelixDataAccessor() + { + checkConnected(); + return _helixAccessor; + } + + @Override + public ConfigAccessor getConfigAccessor() + { + checkConnected(); + return _configAccessor; + } + + @Override + public String getClusterName() + { + return _clusterName; + } + + @Override + public String getInstanceName() + { + return _instanceName; + } + + @Override + public void connect() throws Exception + { + logger.info("ClusterManager.connect()"); + if (_zkStateChangeListener.isConnected()) + { + logger.warn("Cluster manager " + _clusterName + " " + _instanceName + + " already connected"); + return; + } + + try + { + createClient(_zkConnectString); + _messagingService.onConnected(); + } + catch (Exception e) + { + logger.error(e); + disconnect(); + throw e; + } + } + + @Override + public void disconnect() + { + if (!isConnected()) + { + logger.error("ClusterManager " + _instanceName + " already disconnected"); + return; + } + disconnectInternal(); + } + + void disconnectInternal() + { + // This function can be called when the connection are in bad state(e.g. flapping), + // in which isConnected() could be false and we want to disconnect from cluster. + logger.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + + _clusterName); + + /** + * shutdown thread pool first to avoid reset() being invoked in the middle of state + * transition + */ + _messagingService.getExecutor().shutdown(); + resetHandlers(); + + _helixAccessor.shutdown(); + + if (_leaderElectionHandler != null) + { + _leaderElectionHandler.reset(); + } + + if (_participantHealthCheckInfoCollector != null) + { + _participantHealthCheckInfoCollector.stop(); + } + + if (_timer != null) + { + _timer.cancel(); + _timer = null; + } + + if (_instanceType == InstanceType.CONTROLLER) + { + stopTimerTasks(); + } + + // unsubscribe accessor from controllerChange + _zkClient.unsubscribeAll(); + + _zkClient.close(); + + // HACK seems that zkClient is not sending DISCONNECT event + _zkStateChangeListener.disconnect(); + logger.info("Cluster manager: " + _instanceName + " disconnected"); + + } + + @Override + public String getSessionId() + { + checkConnected(); + return _sessionId; + } + + @Override + public boolean isConnected() + { + return _zkStateChangeListener.isConnected(); + } + + @Override + public long getLastNotificationTime() + { + return -1; + } + + private void addLiveInstance() + { + LiveInstance liveInstance = new LiveInstance(_instanceName); + liveInstance.setSessionId(_sessionId); + liveInstance.setHelixVersion(_version); + liveInstance.setLiveInstance(ManagementFactory.getRuntimeMXBean().getName()); + + if(_liveInstanceInfoProvider != null) + { + logger.info("invoking _liveInstanceInfoProvider"); + ZNRecord additionalLiveInstanceInfo = _liveInstanceInfoProvider.getAdditionalLiveInstanceInfo(); + if(additionalLiveInstanceInfo != null) + { + additionalLiveInstanceInfo.merge(liveInstance.getRecord()); + ZNRecord mergedLiveInstance = new ZNRecord(additionalLiveInstanceInfo, _instanceName); + liveInstance = new LiveInstance(mergedLiveInstance); + logger.info("liveInstance content :" + _instanceName + " " + liveInstance.toString()); + } + } + + logger.info("Add live instance: InstanceName: " + _instanceName + " Session id:" + + _sessionId); + Builder keyBuilder = _helixAccessor.keyBuilder(); + if (!_helixAccessor.createProperty(keyBuilder.liveInstance(_instanceName), + liveInstance)) + { + String errorMsg = + "Fail to create live instance node after waiting, so quit. instance:" + + _instanceName; + logger.warn(errorMsg); + throw new HelixException(errorMsg); + + } + String currentStatePathParent = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, + _clusterName, + _instanceName, + getSessionId()); + + if (!_zkClient.exists(currentStatePathParent)) + { + _zkClient.createPersistent(currentStatePathParent); + logger.info("Creating current state path " + currentStatePathParent); + } + } + + private void startStatusUpdatedumpTask() + { + long initialDelay = 30 * 60 * 1000; + long period = 120 * 60 * 1000; + int timeThresholdNoChange = 180 * 60 * 1000; + + if (_timer == null) + { + _timer = new Timer(true); + _timer.scheduleAtFixedRate(new ZKPathDataDumpTask(this, + _zkClient, + timeThresholdNoChange), + initialDelay, + period); + } + } + + private void createClient(String zkServers) throws Exception + { + String propertyStorePath = + PropertyPathConfig.getPath(PropertyType.PROPERTYSTORE, _clusterName); + + // by default use ZNRecordStreamingSerializer except for paths within the property + // store which expects raw byte[] serialization/deserialization + PathBasedZkSerializer zkSerializer = + ChainedPathZkSerializer.builder(new ZNRecordStreamingSerializer()) + .serialize(propertyStorePath, new ByteArraySerializer()) + .build(); + + _zkClient = new ZkClient(zkServers, _sessionTimeout, CONNECTIONTIMEOUT, zkSerializer); + + ZkBaseDataAccessor baseDataAccessor = + new ZkBaseDataAccessor(_zkClient); + if (_instanceType == InstanceType.PARTICIPANT) + { + String curStatePath = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, + _clusterName, + _instanceName); + _baseDataAccessor = + new ZkCacheBaseDataAccessor(baseDataAccessor, + Arrays.asList(curStatePath)); + } + else if (_instanceType == InstanceType.CONTROLLER) + { + String extViewPath = PropertyPathConfig.getPath(PropertyType.EXTERNALVIEW, + + _clusterName); + _baseDataAccessor = + new ZkCacheBaseDataAccessor(baseDataAccessor, + Arrays.asList(extViewPath)); + + } + else + { + _baseDataAccessor = baseDataAccessor; + } + + _helixAccessor = + new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor); + _configAccessor = new ConfigAccessor(_zkClient); + int retryCount = 0; + + _zkClient.subscribeStateChanges(_zkStateChangeListener); + while (retryCount < RETRY_LIMIT) + { + try + { + _zkClient.waitUntilConnected(_sessionTimeout, TimeUnit.MILLISECONDS); + _zkStateChangeListener.handleStateChanged(KeeperState.SyncConnected); + _zkStateChangeListener.handleNewSession(); + break; + } + catch (HelixException e) + { + logger.error("fail to createClient.", e); + throw e; + } + catch (Exception e) + { + retryCount++; + + logger.error("fail to createClient. retry " + retryCount, e); + if (retryCount == RETRY_LIMIT) + { + throw e; + } + } + } + } + + private CallbackHandler createCallBackHandler(PropertyKey propertyKey, + Object listener, + EventType[] eventTypes, + ChangeType changeType) + { + if (listener == null) + { + throw new HelixException("Listener cannot be null"); + } + return new CallbackHandler(this, _zkClient, propertyKey, listener, eventTypes, changeType); + } + + /** + * This will be invoked when ever a new session is created
    + * + * case 1: the cluster manager was a participant carry over current state, add live + * instance, and invoke message listener; case 2: the cluster manager was controller and + * was a leader before do leader election, and if it becomes leader again, invoke ideal + * state listener, current state listener, etc. if it fails to become leader in the new + * session, then becomes standby; case 3: the cluster manager was controller and was NOT + * a leader before do leader election, and if it becomes leader, instantiate and invoke + * ideal state listener, current state listener, etc. if if fails to become leader in + * the new session, stay as standby + */ + + protected void handleNewSession() + { + boolean isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); + while (!isConnected) + { + logger.error("Could NOT connect to zk server in " + CONNECTIONTIMEOUT + "ms. zkServer: " + + _zkConnectString + ", expiredSessionId: " + _sessionId + ", clusterName: " + + _clusterName); + isConnected = _zkClient.waitUntilConnected(CONNECTIONTIMEOUT, TimeUnit.MILLISECONDS); + } + + ZkConnection zkConnection = ((ZkConnection) _zkClient.getConnection()); + + synchronized (this) + { + _sessionId = Long.toHexString(zkConnection.getZookeeper().getSessionId()); + } + _baseDataAccessor.reset(); + + // reset all handlers so they have a chance to unsubscribe zk changes from zkclient + // abandon all callback-handlers added in expired session + resetHandlers(); + _handlers = new ArrayList(); + + logger.info("Handling new session, session id:" + _sessionId + ", instance:" + + _instanceName + ", instanceTye: " + _instanceType + ", cluster: " + _clusterName); + + logger.info(zkConnection.getZookeeper()); + + if (!ZKUtil.isClusterSetup(_clusterName, _zkClient)) + { + throw new HelixException("Initial cluster structure is not set up for cluster:" + + _clusterName); + } + // Read cluster config and see if instance can auto join the cluster + boolean autoJoin = false; + try + { + ConfigScope scope = + new ConfigScopeBuilder().forCluster(getClusterName()) + .build(); + autoJoin = Boolean.parseBoolean(getConfigAccessor().get(scope, ALLOW_PARTICIPANT_AUTO_JOIN)); + logger.info("Auto joining " + _clusterName +" is true"); + } + catch(Exception e) + { + } + if (!ZKUtil.isInstanceSetup(_zkClient, _clusterName, _instanceName, _instanceType)) + { + if(!autoJoin) + { + throw new HelixException("Initial cluster structure is not set up for instance:" + + _instanceName + " instanceType:" + _instanceType); + } + else + { + logger.info("Auto joining instance " + _instanceName); + InstanceConfig instanceConfig = new InstanceConfig(_instanceName); + String hostName = _instanceName; + String port = ""; + int lastPos = _instanceName.lastIndexOf("_"); + if (lastPos > 0) + { + hostName = _instanceName.substring(0, lastPos); + port = _instanceName.substring(lastPos + 1); + } + instanceConfig.setHostName(hostName); + instanceConfig.setPort(port); + instanceConfig.setInstanceEnabled(true); + getClusterManagmentTool().addInstance(_clusterName, instanceConfig); + } + } + + if (_instanceType == InstanceType.PARTICIPANT + || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) + { + handleNewSessionAsParticipant(); + } + + if (_instanceType == InstanceType.CONTROLLER + || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) + { + addControllerMessageListener(_messagingService.getExecutor()); + MessageHandlerFactory defaultControllerMsgHandlerFactory = + new DefaultControllerMessageHandlerFactory(); + _messagingService.getExecutor() + .registerMessageHandlerFactory(defaultControllerMsgHandlerFactory.getMessageType(), + defaultControllerMsgHandlerFactory); + MessageHandlerFactory defaultSchedulerMsgHandlerFactory = + new DefaultSchedulerMessageHandlerFactory(this); + _messagingService.getExecutor() + .registerMessageHandlerFactory(defaultSchedulerMsgHandlerFactory.getMessageType(), + defaultSchedulerMsgHandlerFactory); + MessageHandlerFactory defaultParticipantErrorMessageHandlerFactory = + new DefaultParticipantErrorMessageHandlerFactory(this); + _messagingService.getExecutor() + .registerMessageHandlerFactory(defaultParticipantErrorMessageHandlerFactory.getMessageType(), + defaultParticipantErrorMessageHandlerFactory); + + // create a new leader-election handler for a new session + if (_leaderElectionHandler != null) { + _leaderElectionHandler.reset(); + } + _leaderElectionHandler = + createCallBackHandler(new Builder(_clusterName).controller(), + new DistClusterControllerElection(_zkConnectString), + new EventType[] { EventType.NodeChildrenChanged, + EventType.NodeDeleted, EventType.NodeCreated }, + ChangeType.CONTROLLER); + } + + if (_instanceType == InstanceType.PARTICIPANT + || _instanceType == InstanceType.CONTROLLER_PARTICIPANT + || (_instanceType == InstanceType.CONTROLLER && isLeader())) + { + initHandlers(); + } + } + + private void handleNewSessionAsParticipant() + { + // In case there is a live instance record on zookeeper + Builder keyBuilder = _helixAccessor.keyBuilder(); + + if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) + { + logger.warn("Found another instance with same instanceName: " + _instanceName + + " in cluster " + _clusterName); + // Wait for a while, in case previous storage node exits unexpectedly + // and its liveinstance + // still hangs around until session timeout happens + try + { + Thread.sleep(_sessionTimeout + 5000); + } + catch (InterruptedException e) + { + logger.warn("Sleep interrupted while waiting for previous liveinstance to go away.", + e); + } + + if (_helixAccessor.getProperty(keyBuilder.liveInstance(_instanceName)) != null) + { + String errorMessage = + "instance " + _instanceName + " already has a liveinstance in cluster " + + _clusterName; + logger.error(errorMessage); + throw new HelixException(errorMessage); + } + } + // Invoke the PreConnectCallbacks + for (PreConnectCallback callback : _preConnectCallbacks) + { + callback.onPreConnect(); + } + addLiveInstance(); + carryOverPreviousCurrentState(); + + // In case the cluster manager is running as a participant, setup message + // listener + _messagingService.registerMessageHandlerFactory(MessageType.STATE_TRANSITION.toString(), + _stateMachEngine); + addMessageListener(_messagingService.getExecutor(), _instanceName); + addControllerListener(_helixAccessor); + + ScheduledTaskStateModelFactory stStateModelFactory = new ScheduledTaskStateModelFactory(_messagingService.getExecutor()); + _stateMachEngine.registerStateModelFactory(DefaultSchedulerMessageHandlerFactory.SCHEDULER_TASK_QUEUE, stStateModelFactory); + + if (_participantHealthCheckInfoCollector == null) + { + _participantHealthCheckInfoCollector = + new ParticipantHealthReportCollectorImpl(this, _instanceName); + _participantHealthCheckInfoCollector.start(); + } + // start the participant health check timer, also create zk path for health + // check info + String healthCheckInfoPath = + _helixAccessor.keyBuilder().healthReports(_instanceName).getPath(); + if (!_zkClient.exists(healthCheckInfoPath)) + { + _zkClient.createPersistent(healthCheckInfoPath, true); + logger.info("Creating healthcheck info path " + healthCheckInfoPath); + } + } + + @Override + public void addPreConnectCallback(PreConnectCallback callback) + { + logger.info("Adding preconnect callback"); + _preConnectCallbacks.add(callback); + } + + private void resetHandlers() + { + synchronized (this) + { + if (_handlers != null) + { + // get a copy of the list and iterate over the copy list + // in case handler.reset() will modify the original handler list + List tmpHandlers = new ArrayList(); + tmpHandlers.addAll(_handlers); + + for (CallbackHandler handler : tmpHandlers) + { + handler.reset(); + logger.info("reset handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + private void initHandlers() + { + synchronized (this) + { + if (_handlers != null) + { + // may add new currentState and message listeners during init() + // so make a copy and iterate over the copy + List tmpHandlers = new ArrayList(); + tmpHandlers.addAll(_handlers); + for (CallbackHandler handler : tmpHandlers) + { + handler.init(); + logger.info("init handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + @Override + public boolean isLeader() + { + if (!isConnected()) + { + return false; + } + + if (_instanceType != InstanceType.CONTROLLER) + { + return false; + } + + Builder keyBuilder = _helixAccessor.keyBuilder(); + LiveInstance leader = _helixAccessor.getProperty(keyBuilder.controllerLeader()); + if (leader == null) + { + return false; + } + else + { + String leaderName = leader.getInstanceName(); + // TODO need check sessionId also, but in distributed mode, leader's + // sessionId is + // not equal to + // the leader znode's sessionId field which is the sessionId of the + // controller_participant that + // successfully creates the leader node + if (leaderName == null || !leaderName.equals(_instanceName)) + { + return false; + } + } + return true; + } + + /** + * carry over current-states from last sessions + * set to initial state for current session only when the state doesn't exist in current session + */ + private void carryOverPreviousCurrentState() + { + Builder keyBuilder = _helixAccessor.keyBuilder(); + List sessions = _helixAccessor.getChildNames(keyBuilder.sessions(_instanceName)); + + // carry-over + for (String session : sessions) { + if (session.equals(_sessionId)) { + continue; + } + + List lastCurStates = + _helixAccessor.getChildValues(keyBuilder.currentStates(_instanceName, session)); + + for (CurrentState lastCurState : lastCurStates) { + logger.info("Carrying over old session: " + session + ", resource: " + + lastCurState.getId() + " to current session: " + _sessionId); + String stateModelDefRef = lastCurState.getStateModelDefRef(); + if (stateModelDefRef == null) + { + logger.error("skip carry-over because previous current state doesn't have a state model definition. previous current-state: " + + lastCurState); + continue; + } + StateModelDefinition stateModel = + _helixAccessor.getProperty(keyBuilder.stateModelDef(stateModelDefRef)); + + String curStatePath = keyBuilder.currentState(_instanceName, _sessionId, lastCurState.getResourceName()).getPath(); + _helixAccessor.getBaseDataAccessor().update(curStatePath, + new CurStateCarryOverUpdater(_sessionId, stateModel.getInitialState(), lastCurState), AccessOption.PERSISTENT); + } + } + + // remove previous current states + for (String session : sessions) + { + if (session.equals(_sessionId)) { + continue; + } + + String path = + _helixAccessor.keyBuilder() + .currentStates(_instanceName, session) + .getPath(); + logger.info("Removing current states from previous sessions. path: " + path); + _zkClient.deleteRecursive(path); + } + } + + @Override + public synchronized ZkHelixPropertyStore getHelixPropertyStore() + { + checkConnected(); + + if (_helixPropertyStore == null) + { + String path = + PropertyPathConfig.getPath(PropertyType.HELIX_PROPERTYSTORE, _clusterName); + + _helixPropertyStore = + new ZkHelixPropertyStore(new ZkBaseDataAccessor(_zkClient), + path, + null); + } + + return _helixPropertyStore; + } + + @Override + public synchronized HelixAdmin getClusterManagmentTool() + { + checkConnected(); + if (_zkClient != null) + { + _managementTool = new ZKHelixAdmin(_zkClient); + } + else + { + logger.error("Couldn't get ZKClusterManagementTool because zkClient is null"); + } + + return _managementTool; + } + + @Override + public ClusterMessagingService getMessagingService() + { + // The caller can register message handler factories on messaging service before the + // helix manager is connected. Thus we do not do connected check here. + return _messagingService; + } + + @Override + public ParticipantHealthReportCollector getHealthReportCollector() + { + checkConnected(); + return _participantHealthCheckInfoCollector; + } + + @Override + public InstanceType getInstanceType() + { + return _instanceType; + } + + private void checkConnected() + { + if (!isConnected()) + { + throw new HelixException("ClusterManager not connected. Call clusterManager.connect()"); + } + } + + @Override + public String getVersion() + { + return _version; + } + + @Override + public HelixManagerProperties getProperties() { + return _properties; + } + + @Override + public StateMachineEngine getStateMachineEngine() + { + return _stateMachEngine; + } + + // TODO: rename this and not expose this function as part of interface + @Override + public void startTimerTasks() + { + for (HelixTimerTask task : _controllerTimerTasks) + { + task.start(); + } + startStatusUpdatedumpTask(); + } + + @Override + public void stopTimerTasks() + { + for (HelixTimerTask task : _controllerTimerTasks) + { + task.stop(); + } + } + + @Override + public void setLiveInstanceInfoProvider( + LiveInstanceInfoProvider liveInstanceInfoProvider) + { + _liveInstanceInfoProvider = liveInstanceInfoProvider; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.manager.zk.ZKHelixManager.handleNewSession` indirectly reads with synchronization from `this.org.apache.helix.manager.zk.ZKHelixManager._handlers`. Potentially races with unsynchronized write in method `ZKHelixManager.handleNewSession()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZKHelixManager.handleNewSession() + +### Procedure Id: +org.apache.helix.manager.zk.ZKHelixManager.handleNewSession():void.ada16e6739ae09352eab6ae3589b1a25 + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZKHelixManager.java + +### Key: +ZKHelixManager.java|handleNewSession|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +021d59e89b3aaa1d882e01554e94e6dd + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9619/instruction.md b/inferredbugs-9619/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a6524fef43b37e106abf0fc06d39174c762d0dd --- /dev/null +++ b/inferredbugs-9619/instruction.md @@ -0,0 +1,358 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 37 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.ByteArrayInputStream; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.I0Itec.zkclient.exception.ZkMarshallingError; +import org.I0Itec.zkclient.serialize.ZkSerializer; +import org.apache.helix.HelixException; +import org.apache.helix.ZNRecord; +import org.apache.log4j.Logger; +import org.codehaus.jackson.JsonFactory; +import org.codehaus.jackson.JsonGenerator; +import org.codehaus.jackson.JsonParser; +import org.codehaus.jackson.JsonToken; +import org.restlet.engine.util.Base64; + + +public class ZNRecordStreamingSerializer implements ZkSerializer { + private static Logger LOG = Logger.getLogger(ZNRecordStreamingSerializer.class); + + private static int getListFieldBound(ZNRecord record) { + int max = Integer.MAX_VALUE; + if (record.getSimpleFields().containsKey(ZNRecord.LIST_FIELD_BOUND)) { + String maxStr = record.getSimpleField(ZNRecord.LIST_FIELD_BOUND); + try { + max = Integer.parseInt(maxStr); + } catch (Exception e) { + LOG.error("IllegalNumberFormat for list field bound: " + maxStr); + } + } + return max; + } + + @Override + public byte[] serialize(Object data) throws ZkMarshallingError { + if (!(data instanceof ZNRecord)) { + // null is NOT an instance of any class + LOG.error("Input object must be of type ZNRecord but it is " + data + + ". Will not write to zk"); + throw new HelixException("Input object is not of type ZNRecord (was " + data + ")"); + } + + // apply retention policy on list field + ZNRecord record = (ZNRecord) data; + int max = getListFieldBound(record); + if (max < Integer.MAX_VALUE) { + Map> listMap = record.getListFields(); + for (String key : listMap.keySet()) { + List list = listMap.get(key); + if (list.size() > max) { + listMap.put(key, list.subList(0, max)); + } + } + } + + StringWriter sw = new StringWriter(); + try { + JsonFactory f = new JsonFactory(); + JsonGenerator g = f.createJsonGenerator(sw); + + g.writeStartObject(); + + // write id field + g.writeRaw("\n "); + g.writeStringField("id", record.getId()); + + // write simepleFields + g.writeRaw("\n "); + g.writeObjectFieldStart("simpleFields"); + for (String key : record.getSimpleFields().keySet()) { + g.writeRaw("\n "); + g.writeStringField(key, record.getSimpleField(key)); + } + g.writeRaw("\n "); + g.writeEndObject(); // for simpleFields + + // write listFields + g.writeRaw("\n "); + g.writeObjectFieldStart("listFields"); + for (String key : record.getListFields().keySet()) { + // g.writeStringField(key, record.getListField(key).toString()); + + // g.writeObjectFieldStart(key); + g.writeRaw("\n "); + g.writeArrayFieldStart(key); + List list = record.getListField(key); + for (String listValue : list) { + g.writeString(listValue); + } + // g.writeEndObject(); + g.writeEndArray(); + + } + g.writeRaw("\n "); + g.writeEndObject(); // for listFields + + // write mapFields + g.writeRaw("\n "); + g.writeObjectFieldStart("mapFields"); + for (String key : record.getMapFields().keySet()) { + // g.writeStringField(key, record.getMapField(key).toString()); + g.writeRaw("\n "); + g.writeObjectFieldStart(key); + Map map = record.getMapField(key); + for (String mapKey : map.keySet()) { + g.writeRaw("\n "); + g.writeStringField(mapKey, map.get(mapKey)); + } + g.writeRaw("\n "); + g.writeEndObject(); + + } + g.writeRaw("\n "); + g.writeEndObject(); // for mapFields + + byte[] rawPayload = record.getRawPayload(); + if (rawPayload != null && rawPayload.length > 0) { + // write rawPayload + g.writeRaw("\n "); + g.writeStringField("rawPayload", Base64.encode(rawPayload, false)); + } + + g.writeRaw("\n"); + g.writeEndObject(); // for whole znrecord + + // important: will force flushing of output, close underlying output + // stream + g.close(); + } catch (Exception e) { + LOG.error("Exception during data serialization. Will not write to zk. Data (first 1k): " + + sw.toString().substring(0, 1024), e); + throw new HelixException(e); + } + + // check size + if (sw.toString().getBytes().length > ZNRecord.SIZE_LIMIT) { + LOG.error("Data size larger than 1M, ZNRecord.id: " + record.getId() + + ". Will not write to zk. Data (first 1k): " + sw.toString().substring(0, 1024)); + throw new HelixException("Data size larger than 1M, ZNRecord.id: " + record.getId()); + } + + return sw.toString().getBytes(); + } + + @Override + public Object deserialize(byte[] bytes) throws ZkMarshallingError { + if (bytes == null || bytes.length == 0) { + LOG.error("ZNode is empty."); + return null; + } + + ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ZNRecord record = null; + + try { + JsonFactory f = new JsonFactory(); + JsonParser jp = f.createJsonParser(bais); + + jp.nextToken(); // will return JsonToken.START_OBJECT (verify?) + while (jp.nextToken() != JsonToken.END_OBJECT) { + String fieldname = jp.getCurrentName(); + jp.nextToken(); // move to value, or START_OBJECT/START_ARRAY + if ("id".equals(fieldname)) { + // contains an object + record = new ZNRecord(jp.getText()); + } else if ("simpleFields".equals(fieldname)) { + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + jp.nextToken(); // move to value + record.setSimpleField(key, jp.getText()); + } + } else if ("mapFields".equals(fieldname)) { + // user.setVerified(jp.getCurrentToken() == JsonToken.VALUE_TRUE); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + record.setMapField(key, new TreeMap()); + jp.nextToken(); // move to value + + while (jp.nextToken() != JsonToken.END_OBJECT) { + String mapKey = jp.getCurrentName(); + jp.nextToken(); // move to value + record.getMapField(key).put(mapKey, jp.getText()); + } + } + + } else if ("listFields".equals(fieldname)) { + // user.setUserImage(jp.getBinaryValue()); + while (jp.nextToken() != JsonToken.END_OBJECT) { + String key = jp.getCurrentName(); + record.setListField(key, new ArrayList()); + jp.nextToken(); // move to value + while (jp.nextToken() != JsonToken.END_ARRAY) { + record.getListField(key).add(jp.getText()); + } + + } + + } else if ("rawPayload".equals(fieldname)) { + record.setRawPayload(Base64.decode(jp.getText())); + } else { + throw new IllegalStateException("Unrecognized field '" + fieldname + "'!"); + } + } + jp.close(); // ensure resources get cleaned up timely and properly + } catch (Exception e) { + LOG.error("Exception during deserialization of bytes: " + new String(bytes), e); + } + + return record; + } + + public static void main(String[] args) { + ZNRecord record = new ZNRecord("record"); + final int recordSize = 10; + for (int i = 0; i < recordSize; i++) { + record.setSimpleField("" + i, "" + i); + record.setListField("" + i, new ArrayList()); + for (int j = 0; j < recordSize; j++) { + record.getListField("" + i).add("" + j); + } + + record.setMapField("" + i, new TreeMap()); + for (int j = 0; j < recordSize; j++) { + record.getMapField("" + i).put("" + j, "" + j); + } + } + + ZNRecordStreamingSerializer serializer = new ZNRecordStreamingSerializer(); + byte[] bytes = serializer.serialize(record); + System.out.println(new String(bytes)); + ZNRecord record2 = (ZNRecord) serializer.deserialize(bytes); + System.out.println(record2); + + long start = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + bytes = serializer.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer.deserialize(bytes); + // System.out.println(record2); + } + long end = System.currentTimeMillis(); + System.out.println("ZNRecordStreamingSerializer time used: " + (end - start)); + + ZNRecordSerializer serializer2 = new ZNRecordSerializer(); + bytes = serializer2.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer2.deserialize(bytes); + // System.out.println(record2); + + start = System.currentTimeMillis(); + for (int i = 0; i < 100; i++) { + bytes = serializer2.serialize(record); + // System.out.println(new String(bytes)); + record2 = (ZNRecord) serializer2.deserialize(bytes); + // System.out.println(record2); + } + end = System.currentTimeMillis(); + System.out.println("ZNRecordSerializer time used: " + (end - start)); + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `record` last assigned on line 176 could be null and is dereferenced at line 222. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Object ZNRecordStreamingSerializer.deserialize(byte[]) + +### Procedure Id: +org.apache.helix.manager.zk.ZNRecordStreamingSerializer.deserialize(byte[]):java.lang.Object.cdedc9809357a72edb66d8f57e43b2da + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZNRecordStreamingSerializer.java + +### Key: +ZNRecordStreamingSerializer.java|deserialize|NULL_DEREFERENCE + +### Node Key: +09634589313b8637b1fe1e1bb0135b05 + +### Hash: +56aacf463a17e67f4af9b283f3a4c931 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9620/instruction.md b/inferredbugs-9620/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63a4b536e4d9d99bdf65b1c59f7a5aeeb428a149 --- /dev/null +++ b/inferredbugs-9620/instruction.md @@ -0,0 +1,245 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 39 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +import org.apache.helix.AccessOption; +import org.apache.helix.PropertyPathConfig; +import org.apache.helix.PropertyType; +import org.apache.helix.TestHelper; +import org.apache.helix.ZNRecord; +import org.apache.helix.ZNRecordUpdater; +import org.apache.helix.ZkUnitTestBase; +import org.apache.helix.manager.zk.ZkBaseDataAccessor; +import org.apache.helix.manager.zk.ZkCacheBaseDataAccessor; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class TestWtCacheSyncOpSingleThread extends ZkUnitTestBase { + // TODO: add TestZkCacheSyncOpSingleThread + // TODO: add TestZkCacheAsyncOpMultiThread + @Test + public void testHappyPathZkCacheBaseDataAccessor() throws Exception { + String className = TestHelper.getTestClassName(); + String methodName = TestHelper.getTestMethodName(); + String clusterName = className + "_" + methodName; + System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); + + // init zkCacheDataAccessor + String curStatePath = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901"); + String extViewPath = PropertyPathConfig.getPath(PropertyType.EXTERNALVIEW, clusterName); + + ZkBaseDataAccessor baseAccessor = new ZkBaseDataAccessor(_gZkClient); + + baseAccessor.create(curStatePath, null, AccessOption.PERSISTENT); + + List cachePaths = Arrays.asList(curStatePath, extViewPath); + ZkCacheBaseDataAccessor accessor = + new ZkCacheBaseDataAccessor(baseAccessor, null, cachePaths, null); + + boolean ret = TestHelper.verifyZkCache(cachePaths, accessor._wtCache._cache, _gZkClient, true); + Assert.assertTrue(ret, "wtCache doesn't match data on Zk"); + + // create 10 current states + for (int i = 0; i < 10; i++) { + String path = curStatePath + "/session_0/TestDB" + i; + boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); + Assert.assertTrue(success, "Should succeed in create: " + path); + } + + // verify wtCache + // TestHelper.printCache(accessor._wtCache); + ret = TestHelper.verifyZkCache(cachePaths, accessor._wtCache._cache, _gZkClient, false); + Assert.assertTrue(ret, "wtCache doesn't match data on Zk"); + + // update each current state 10 times, single thread + for (int i = 0; i < 10; i++) { + String path = curStatePath + "/session_0/TestDB" + i; + for (int j = 0; j < 10; j++) { + ZNRecord newRecord = new ZNRecord("TestDB" + i); + newRecord.setSimpleField("" + j, "" + j); + boolean success = + accessor.update(path, new ZNRecordUpdater(newRecord), AccessOption.PERSISTENT); + Assert.assertTrue(success, "Should succeed in update: " + path); + + } + } + + // verify cache + // TestHelper.printCache(accessor._wtCache._cache); + ret = TestHelper.verifyZkCache(cachePaths, accessor._wtCache._cache, _gZkClient, false); + Assert.assertTrue(ret, "wtCache doesn't match data on Zk"); + + // set 10 external views + for (int i = 0; i < 10; i++) { + String path = + PropertyPathConfig.getPath(PropertyType.EXTERNALVIEW, clusterName, "TestDB" + i); + boolean success = accessor.set(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); + Assert.assertTrue(success, "Should succeed in set: " + path); + } + + // verify wtCache + // accessor.printWtCache(); + ret = TestHelper.verifyZkCache(cachePaths, accessor._wtCache._cache, _gZkClient, false); + Assert.assertTrue(ret, "wtCache doesn't match data on Zk"); + + // get 10 external views + for (int i = 0; i < 10; i++) { + String path = + PropertyPathConfig.getPath(PropertyType.EXTERNALVIEW, clusterName, "TestDB" + i); + ZNRecord record = accessor.get(path, null, 0); + Assert.assertEquals(record.getId(), "TestDB" + i); + } + + // getChildNames + List childNames = accessor.getChildNames(extViewPath, 0); + // System.out.println(childNames); + Assert.assertEquals(childNames.size(), 10, "Should contain only: TestDB0-9"); + for (int i = 0; i < 10; i++) { + Assert.assertTrue(childNames.contains("TestDB" + i)); + } + + // exists + for (int i = 0; i < 10; i++) { + String path = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", + "session_0", "TestDB" + i); + + Assert.assertTrue(accessor.exists(path, 0)); + } + + System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); + } + + @Test + public void testCreateFailZkCacheBaseDataAccessor() { + String className = TestHelper.getTestClassName(); + String methodName = TestHelper.getTestMethodName(); + String clusterName = className + "_" + methodName; + System.out.println("START " + clusterName + " at " + new Date(System.currentTimeMillis())); + + // init zkCacheDataAccessor + String curStatePath = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901"); + + ZkBaseDataAccessor baseAccessor = new ZkBaseDataAccessor(_gZkClient); + + ZkCacheBaseDataAccessor accessor = + new ZkCacheBaseDataAccessor(baseAccessor, null, Arrays.asList(curStatePath), null); + + // create 10 current states + for (int i = 0; i < 10; i++) { + String path = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", + "session_1", "TestDB" + i); + boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); + Assert.assertTrue(success, "Should succeed in create: " + path); + } + + // create same 10 current states again, should fail + for (int i = 0; i < 10; i++) { + String path = + PropertyPathConfig.getPath(PropertyType.CURRENTSTATES, clusterName, "localhost_8901", + "session_1", "TestDB" + i); + boolean success = accessor.create(path, new ZNRecord("TestDB" + i), AccessOption.PERSISTENT); + Assert.assertFalse(success, "Should fail in create due to NodeExists: " + path); + } + + System.out.println("END " + clusterName + " at " + new Date(System.currentTimeMillis())); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `accessor._chrootPath` last assigned on line 149 could be null and is dereferenced by call to `create(...)` at line 156. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestWtCacheSyncOpSingleThread.testCreateFailZkCacheBaseDataAccessor() + +### Procedure Id: +org.apache.helix.manager.zk.TestWtCacheSyncOpSingleThread.testCreateFailZkCacheBaseDataAccessor():vo.a86099bba3c9aeea474a2142d3bce985 + +### File: +helix-core/src/test/java/org/apache/helix/manager/zk/TestWtCacheSyncOpSingleThread.java + +### Key: +TestWtCacheSyncOpSingleThread.java|testCreateFailZkCacheBaseDataAccessor|NULL_DEREFERENCE + +### Node Key: +ab90eb1f14d7d343025d6336d1c68b84 + +### Hash: +abdd79b3c6dfd9369cf24689400e8345 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9621/instruction.md b/inferredbugs-9621/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a311f5362ac26492d6c1911ea56667f8957f8c86 --- /dev/null +++ b/inferredbugs-9621/instruction.md @@ -0,0 +1,787 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 52 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Timer; +import java.util.TimerTask; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; + +import org.I0Itec.zkclient.exception.ZkInterruptedException; +import org.apache.helix.api.listeners.ConfigChangeListener; +import org.apache.helix.api.listeners.ControllerChangeListener; +import org.apache.helix.api.listeners.CurrentStateChangeListener; +import org.apache.helix.api.listeners.IdealStateChangeListener; +import org.apache.helix.api.listeners.InstanceConfigChangeListener; +import org.apache.helix.api.listeners.LiveInstanceChangeListener; +import org.apache.helix.api.listeners.MessageListener; +import org.apache.helix.api.listeners.PreFetch; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixManager; +import org.apache.helix.NotificationContext; +import org.apache.helix.NotificationContext.Type; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.ZNRecord; +import org.apache.helix.controller.pipeline.Pipeline; +import org.apache.helix.controller.pipeline.PipelineRegistry; +import org.apache.helix.controller.stages.AttributeName; +import org.apache.helix.controller.stages.BestPossibleStateCalcStage; +import org.apache.helix.controller.stages.ClusterDataCache; +import org.apache.helix.controller.stages.ClusterEvent; +import org.apache.helix.controller.stages.ClusterEventBlockingQueue; +import org.apache.helix.controller.stages.ClusterEventType; +import org.apache.helix.controller.stages.CompatibilityCheckStage; +import org.apache.helix.controller.stages.CurrentStateComputationStage; +import org.apache.helix.controller.stages.ExternalViewComputeStage; +import org.apache.helix.controller.stages.IntermediateStateCalcStage; +import org.apache.helix.controller.stages.MessageGenerationPhase; +import org.apache.helix.controller.stages.MessageSelectionStage; +import org.apache.helix.controller.stages.MessageThrottleStage; +import org.apache.helix.controller.stages.PersistAssignmentStage; +import org.apache.helix.controller.stages.ReadClusterDataStage; +import org.apache.helix.controller.stages.ResourceComputationStage; +import org.apache.helix.controller.stages.ResourceValidationStage; +import org.apache.helix.controller.stages.TaskAssignmentStage; +import org.apache.helix.model.ClusterConfig; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.InstanceConfig; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.model.Message; +import org.apache.helix.model.PauseSignal; +import org.apache.helix.monitoring.mbeans.ClusterEventMonitor; +import org.apache.helix.monitoring.mbeans.ClusterStatusMonitor; +import org.apache.helix.task.TaskDriver; +import org.apache.log4j.Logger; + +import static org.apache.helix.HelixConstants.ChangeType; + +/** + * Cluster Controllers main goal is to keep the cluster state as close as possible to Ideal State. + * It does this by listening to changes in cluster state and scheduling new tasks to get cluster + * state to best possible ideal state. Every instance of this class can control can control only one + * cluster Get all the partitions use IdealState, CurrentState and Messages
    + * foreach partition
    + * 1. get the (instance,state) from IdealState, CurrentState and PendingMessages
    + * 2. compute best possible state (instance,state) pair. This needs previous step data and state + * model constraints
    + * 3. compute the messages/tasks needed to move to 1 to 2
    + * 4. select the messages that can be sent, needs messages and state model constraints
    + * 5. send messages + */ +public class GenericHelixController implements ConfigChangeListener, IdealStateChangeListener, + LiveInstanceChangeListener, MessageListener, CurrentStateChangeListener, + ControllerChangeListener, InstanceConfigChangeListener { + private static final Logger logger = Logger.getLogger(GenericHelixController.class.getName()); + private static final long EVENT_THREAD_JOIN_TIMEOUT = 1000; + private static final int ASYNC_TASKS_THREADPOOL_SIZE = 40; + private final PipelineRegistry _registry; + + final AtomicReference> _lastSeenInstances; + final AtomicReference> _lastSeenSessions; + + ClusterStatusMonitor _clusterStatusMonitor; + + /** + * A queue for controller events and a thread that will consume it + */ + private final ClusterEventBlockingQueue _eventQueue; + private final ClusterEventProcessor _eventThread; + + /** + * The _paused flag is checked by function handleEvent(), while if the flag is set handleEvent() + * will be no-op. Other event handling logic keeps the same when the flag is set. + */ + private boolean _paused; + + /** + * The timer that can periodically run the rebalancing pipeline. The timer will start if there is + * one resource group has the config to use the timer. + */ + Timer _rebalanceTimer = null; + long _timerPeriod = Long.MAX_VALUE; + + /** + * A cache maintained across pipelines + */ + private ClusterDataCache _cache; + private ExecutorService _asyncTasksThreadPool; + + private String _clusterName; + + /** + * Default constructor that creates a default pipeline registry. This is sufficient in most cases, + * but if there is a some thing specific needed use another constructor where in you can pass a + * pipeline registry + */ + public GenericHelixController() { + this(createDefaultRegistry()); + } + + public GenericHelixController(String clusterName) { + this(createDefaultRegistry(), clusterName); + } + + class RebalanceTask extends TimerTask { + HelixManager _manager; + + public RebalanceTask(HelixManager manager) { + _manager = manager; + } + + @Override + public void run() { + //TODO: this is the temporary workaround + _cache.requireFullRefresh(); + _cache.refresh(_manager.getHelixDataAccessor()); + if (_cache.getLiveInstances() != null) { + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + synchronized (_manager) { + checkLiveInstancesObservation(new ArrayList<>(_cache.getLiveInstances().values()), + changeContext); + } + } + + NotificationContext changeContext = new NotificationContext(_manager); + changeContext.setType(NotificationContext.Type.CALLBACK); + ClusterEvent event = new ClusterEvent(_clusterName,ClusterEventType.PeriodicalRebalance); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + List dummy = new ArrayList(); + event.addAttribute(AttributeName.eventData.name(), dummy); + // Should be able to process + _eventQueue.put(event); + logger.info("Controller periodicalRebalance event triggered!"); + } + } + + // TODO who should stop this timer + /** + * Starts the rebalancing timer with the specified period. Start the timer if necessary; If the + * period is smaller than the current period, cancel the current timer and use the new period. + */ + void startRebalancingTimer(long period, HelixManager manager) { + if (period != _timerPeriod) { + logger.info("Controller starting timer at period " + period); + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + } + _rebalanceTimer = new Timer(true); + _timerPeriod = period; + _rebalanceTimer + .scheduleAtFixedRate(new RebalanceTask(manager), _timerPeriod, _timerPeriod); + } else { + logger.info("Controller already has timer at period " + _timerPeriod); + } + } + + /** + * Stops the rebalancing timer + */ + void stopRebalancingTimer() { + if (_rebalanceTimer != null) { + _rebalanceTimer.cancel(); + _rebalanceTimer = null; + } + _timerPeriod = Integer.MAX_VALUE; + } + + private static PipelineRegistry createDefaultRegistry() { + logger.info("createDefaultRegistry"); + synchronized (GenericHelixController.class) { + PipelineRegistry registry = new PipelineRegistry(); + + // cluster data cache refresh + Pipeline dataRefresh = new Pipeline(); + dataRefresh.addStage(new ReadClusterDataStage()); + + // rebalance pipeline + Pipeline rebalancePipeline = new Pipeline(); + rebalancePipeline.addStage(new ResourceComputationStage()); + rebalancePipeline.addStage(new ResourceValidationStage()); + rebalancePipeline.addStage(new CurrentStateComputationStage()); + rebalancePipeline.addStage(new BestPossibleStateCalcStage()); + rebalancePipeline.addStage(new IntermediateStateCalcStage()); + rebalancePipeline.addStage(new MessageGenerationPhase()); + rebalancePipeline.addStage(new MessageSelectionStage()); + rebalancePipeline.addStage(new MessageThrottleStage()); + rebalancePipeline.addStage(new TaskAssignmentStage()); + rebalancePipeline.addStage(new PersistAssignmentStage()); + + // external view generation + Pipeline externalViewPipeline = new Pipeline(); + externalViewPipeline.addStage(new ExternalViewComputeStage()); + + // backward compatibility check + Pipeline liveInstancePipeline = new Pipeline(); + liveInstancePipeline.addStage(new CompatibilityCheckStage()); + + registry.register(ClusterEventType.IdealStateChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.CurrentStateChange, dataRefresh, rebalancePipeline, externalViewPipeline); + registry.register(ClusterEventType.ConfigChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.LiveInstanceChange, dataRefresh, liveInstancePipeline, rebalancePipeline, + externalViewPipeline); + + registry.register(ClusterEventType.MessageChange, dataRefresh, rebalancePipeline); + registry.register(ClusterEventType.ExternalViewChange, dataRefresh); + registry.register(ClusterEventType.Resume, dataRefresh, rebalancePipeline, externalViewPipeline); + registry + .register(ClusterEventType.PeriodicalRebalance, dataRefresh, rebalancePipeline, externalViewPipeline); + return registry; + } + } + + public GenericHelixController(PipelineRegistry registry) { + this(registry, null); + } + + private GenericHelixController(PipelineRegistry registry, String clusterName) { + _paused = false; + _registry = registry; + _lastSeenInstances = new AtomicReference<>(); + _lastSeenSessions = new AtomicReference<>(); + _clusterName = clusterName; + _asyncTasksThreadPool = Executors.newFixedThreadPool(ASYNC_TASKS_THREADPOOL_SIZE); + _cache = new ClusterDataCache(clusterName); + _cache.setAsyncTasksThreadPool(_asyncTasksThreadPool); + _eventQueue = new ClusterEventBlockingQueue(); + _eventThread = new ClusterEventProcessor(); + _eventThread.setDaemon(true); + _eventThread.start(); + } + + /** + * lock-always: caller always needs to obtain an external lock before call, calls to handleEvent() + * should be serialized + * @param event + */ + protected synchronized void handleEvent(ClusterEvent event) { + HelixManager manager = event.getAttribute(AttributeName.helixmanager.name()); + if (manager == null) { + logger.error("No cluster manager in event:" + event.getEventType()); + return; + } + + if (!manager.isLeader()) { + logger.error("Cluster manager: " + manager.getInstanceName() + " is not leader for " + manager + .getClusterName() + ". Pipeline will not be invoked"); + return; + } + + if (_paused) { + logger.info("Cluster " + manager.getClusterName() + " is paused. Ignoring the event:" + event + .getEventType()); + return; + } + + NotificationContext context = null; + if (event.getAttribute(AttributeName.changeContext.name()) != null) { + context = event.getAttribute(AttributeName.changeContext.name()); + } + + // Initialize _clusterStatusMonitor + if (context != null) { + if (context.getType() == Type.FINALIZE) { + stopRebalancingTimer(); + logger.info("Get FINALIZE notification, skip the pipeline. Event :" + event.getEventType()); + return; + } else { + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(manager.getClusterName()); + } + // TODO: should be in the initization of controller. + if (_cache != null) { + checkRebalancingTimer(manager, Collections.EMPTY_LIST, _cache.getClusterConfig()); + } + TaskDriver driver = new TaskDriver(manager); + _clusterStatusMonitor.refreshWorkflowsStatus(driver); + _clusterStatusMonitor.refreshJobsStatus(driver); + event.addAttribute(AttributeName.clusterStatusMonitor.name(), _clusterStatusMonitor); + } + } + + // add the cache + event.addAttribute(AttributeName.ClusterDataCache.name(), _cache); + + List pipelines = _registry.getPipelinesForEvent(event.getEventType()); + if (pipelines == null || pipelines.size() == 0) { + logger.info("No pipeline to run for event:" + event.getEventType()); + return; + } + + logger.info("START: Invoking controller pipeline for event: " + event.getEventType()); + long startTime = System.currentTimeMillis(); + for (Pipeline pipeline : pipelines) { + try { + pipeline.handle(event); + pipeline.finish(); + } catch (Exception e) { + logger.error("Exception while executing pipeline: " + pipeline + + ". Will not continue to next pipeline", e); + break; + } + } + long endTime = System.currentTimeMillis(); + logger.info("END: Invoking controller pipeline for event: " + event.getEventType() + " for cluster " + + manager.getClusterName() + ", took " + (endTime - startTime) + " ms"); + + // report event process durations + if (_clusterStatusMonitor != null) { + NotificationContext notificationContext = event.getAttribute(AttributeName.changeContext.name()); + long enqueueTime = event.getCreationTime(); + long zkCallbackTime; + StringBuilder sb = new StringBuilder(); + if (notificationContext != null) { + zkCallbackTime = notificationContext.getCreationTime(); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.Callback.name(), + enqueueTime - zkCallbackTime); + sb.append(String.format( + "Callback time for event: " + event.getEventType() + " took: " + (enqueueTime + - zkCallbackTime) + " ms\n")); + + } + _clusterStatusMonitor.updateClusterEventDuration(ClusterEventMonitor.PhaseName.InQueue.name(), + startTime - enqueueTime); + _clusterStatusMonitor + .updateClusterEventDuration(ClusterEventMonitor.PhaseName.TotalProcessed.name(), + endTime - startTime); + sb.append(String.format( + "InQueue time for event: " + event.getEventType() + " took: " + (startTime - enqueueTime) + + " ms\n")); + sb.append(String.format( + "TotalProcessed time for event: " + event.getEventType() + " took: " + (endTime - startTime) + + " ms")); + logger.info(sb.toString()); + } + } + + + @Override + @PreFetch(enabled = false) + public void onStateChange(String instanceName, List statesInfo, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onStateChange()"); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.CURRENT_STATE); + } + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.CurrentStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + logger.info("END: GenericClusterController.onStateChange()"); + } + + @Override + @PreFetch(enabled = false) + public void onMessage(String instanceName, List messages, + NotificationContext changeContext) { + logger.info("START: GenericClusterController.onMessage() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.MESSAGE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.MessageChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.instanceName.name(), instanceName); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (_clusterStatusMonitor != null && messages != null) { + _clusterStatusMonitor.addMessageQueueSize(instanceName, messages.size()); + } + + logger.info("END: GenericClusterController.onMessage() for cluster " + _clusterName); + } + + @Override + public void onLiveInstanceChange(List liveInstances, + NotificationContext changeContext) { + logger.info("START: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } + + if (liveInstances == null) { + liveInstances = Collections.emptyList(); + } + _cache.setLiveInstances(liveInstances); + + // Go though the live instance list and make sure that we are observing them + // accordingly. The action is done regardless of the paused flag. + if (changeContext.getType() == NotificationContext.Type.INIT + || changeContext.getType() == NotificationContext.Type.CALLBACK) { + checkLiveInstancesObservation(liveInstances, changeContext); + } else if (changeContext.getType() == NotificationContext.Type.FINALIZE) { + // on finalize, should remove all message/current-state listeners + logger.info("remove message/current-state listeners. lastSeenInstances: " + _lastSeenInstances + + ", lastSeenSessions: " + _lastSeenSessions); + liveInstances = Collections.emptyList(); + checkLiveInstancesObservation(liveInstances, changeContext); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.LiveInstanceChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.eventData.name(), liveInstances); + _eventQueue.put(event); + logger.info( + "END: Generic GenericClusterController.onLiveInstanceChange() for cluster " + _clusterName); + } + + private void checkRebalancingTimer(HelixManager manager, List idealStates, + ClusterConfig clusterConfig) { + if (manager.getConfigAccessor() == null) { + logger.warn(manager.getInstanceName() + + " config accessor doesn't exist. should be in file-based mode."); + return; + } + + long minPeriod = Long.MAX_VALUE; + if (clusterConfig != null) { + long period = clusterConfig.getRebalanceTimePeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + // TODO: resource level rebalance does not make sense, to remove it! + for (IdealState idealState : idealStates) { + long period = idealState.getRebalanceTimerPeriod(); + if (period > 0 && minPeriod > period) { + minPeriod = period; + } + } + + if (minPeriod != Long.MAX_VALUE) { + startRebalancingTimer(minPeriod, manager); + } + } + + @Override + @PreFetch(enabled = false) + public void onIdealStateChange(List idealStates, NotificationContext changeContext) { + logger.info( + "START: Generic GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.IDEAL_STATE); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.IdealStateChange); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + + _eventQueue.put(event); + + if (changeContext.getType() != Type.FINALIZE) { + checkRebalancingTimer(changeContext.getManager(), idealStates, _cache.getClusterConfig()); + } + + logger.info("END: GenericClusterController.onIdealStateChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onConfigChange(List configs, NotificationContext changeContext) { + logger.info("START: GenericClusterController.onConfigChange() for cluster " + _clusterName); + if (changeContext == null || changeContext.getType() != Type.CALLBACK) { + _cache.requireFullRefresh(); + } else { + _cache.updateDataChange(ChangeType.INSTANCE_CONFIG); + } + + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.ConfigChange); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + + _eventQueue.put(event); + + logger.info("END: GenericClusterController.onConfigChange() for cluster " + _clusterName); + } + + @Override + @PreFetch(enabled = false) + public void onInstanceConfigChange(List instanceConfigs, + NotificationContext changeContext) { + logger.info( + "START: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + onConfigChange(instanceConfigs, changeContext); + logger.info("END: GenericClusterController.onInstanceConfigChange() for cluster " + _clusterName); + } + + @Override + public void onControllerChange(NotificationContext changeContext) { + logger.info("START: GenericClusterController.onControllerChange() for cluster " + _clusterName); + _cache.requireFullRefresh(); + if (changeContext != null && changeContext.getType() == Type.FINALIZE) { + logger.info("GenericClusterController.onControllerChange() FINALIZE for cluster " + _clusterName); + return; + } + HelixDataAccessor accessor = changeContext.getManager().getHelixDataAccessor(); + + // double check if this controller is the leader + Builder keyBuilder = accessor.keyBuilder(); + LiveInstance leader = accessor.getProperty(keyBuilder.controllerLeader()); + if (leader == null) { + logger + .warn("No controller exists for cluster:" + changeContext.getManager().getClusterName()); + return; + } else { + String leaderName = leader.getInstanceName(); + + String instanceName = changeContext.getManager().getInstanceName(); + if (leaderName == null || !leaderName.equals(instanceName)) { + logger.warn("leader name does NOT match, my name: " + instanceName + ", leader: " + leader); + return; + } + } + + PauseSignal pauseSignal = accessor.getProperty(keyBuilder.pause()); + if (pauseSignal != null) { + if (!_paused) { + _paused = true; + logger.info("controller is now paused"); + } + } else { + if (_paused) { + _paused = false; + logger.info("controller is now resumed"); + ClusterEvent event = new ClusterEvent(_clusterName, ClusterEventType.Resume); + event.addAttribute(AttributeName.changeContext.name(), changeContext); + event.addAttribute(AttributeName.helixmanager.name(), changeContext.getManager()); + event.addAttribute(AttributeName.eventData.name(), pauseSignal); + _eventQueue.put(event); + } + } + if (_clusterStatusMonitor == null) { + _clusterStatusMonitor = new ClusterStatusMonitor(changeContext.getManager().getClusterName()); + } + _clusterStatusMonitor.setEnabled(!_paused); + logger.info("END: GenericClusterController.onControllerChange() for cluster " + _clusterName); + } + + /** + * Go through the list of liveinstances in the cluster, and add currentstateChange listener and + * Message listeners to them if they are newly added. For current state change, the observation is + * tied to the session id of each live instance. + */ + protected void checkLiveInstancesObservation(List liveInstances, + NotificationContext changeContext) { + + // construct maps for current live-instances + Map curInstances = new HashMap(); + Map curSessions = new HashMap<>(); + for (LiveInstance liveInstance : liveInstances) { + curInstances.put(liveInstance.getInstanceName(), liveInstance); + curSessions.put(liveInstance.getSessionId(), liveInstance); + } + + // TODO: remove the synchronization here once we move this update into dataCache. + synchronized (_lastSeenInstances) { + Map lastInstances = _lastSeenInstances.get(); + Map lastSessions = _lastSeenSessions.get(); + + HelixManager manager = changeContext.getManager(); + Builder keyBuilder = new Builder(manager.getClusterName()); + if (lastSessions != null) { + for (String session : lastSessions.keySet()) { + if (!curSessions.containsKey(session)) { + // remove current-state listener for expired session + String instanceName = lastSessions.get(session).getInstanceName(); + manager.removeListener(keyBuilder.currentStates(instanceName, session), this); + } + } + } + + if (lastInstances != null) { + for (String instance : lastInstances.keySet()) { + if (!curInstances.containsKey(instance)) { + // remove message listener for disconnected instances + manager.removeListener(keyBuilder.messages(instance), this); + } + } + } + + for (String session : curSessions.keySet()) { + if (lastSessions == null || !lastSessions.containsKey(session)) { + String instanceName = curSessions.get(session).getInstanceName(); + try { + // add current-state listeners for new sessions + manager.addCurrentStateChangeListener(this, instanceName, session); + logger.info(manager.getInstanceName() + " added current-state listener for instance: " + + instanceName + ", session: " + session + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add current state listener for instance: " + instanceName + + " with session: " + session, e); + } + } + } + + for (String instance : curInstances.keySet()) { + if (lastInstances == null || !lastInstances.containsKey(instance)) { + try { + // add message listeners for new instances + manager.addMessageListener(this, instance); + logger.info(manager.getInstanceName() + " added message listener for " + instance + + ", listener: " + this); + } catch (Exception e) { + logger.error("Fail to add message listener for instance: " + instance, e); + } + } + } + + // update last-seen + _lastSeenInstances.set(curInstances); + _lastSeenSessions.set(curSessions); + } + } + + public void shutdownClusterStatusMonitor(String clusterName) { + if (_clusterStatusMonitor != null) { + logger.info("Shut down _clusterStatusMonitor for cluster " + clusterName); + _clusterStatusMonitor.reset(); + _clusterStatusMonitor = null; + } + } + + public void shutdown() throws InterruptedException { + stopRebalancingTimer(); + while (_eventThread.isAlive()) { + _eventThread.interrupt(); + _eventThread.join(EVENT_THREAD_JOIN_TIMEOUT); + } + _asyncTasksThreadPool.shutdown(); + } + + private class ClusterEventProcessor extends Thread { + @Override + public void run() { + logger.info("START ClusterEventProcessor thread for cluster " + _clusterName); + while (!isInterrupted()) { + try { + ClusterEvent event = _eventQueue.take(); + handleEvent(event); + } catch (InterruptedException e) { + logger.warn("ClusterEventProcessor interrupted", e); + interrupt(); + } catch (ZkInterruptedException e) { + logger.warn("ClusterEventProcessor caught a ZK connection interrupt", e); + interrupt(); + } catch (ThreadDeath death) { + throw death; + } catch (Throwable t) { + logger.error("ClusterEventProcessor failed while running the controller pipeline", t); + } + } + logger.info("END ClusterEventProcessor thread"); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.apache.helix.controller.GenericHelixController.stopRebalancingTimer` writes to field `this.org.apache.helix.controller.GenericHelixController._rebalanceTimer` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void GenericHelixController.stopRebalancingTimer() + +### Procedure Id: +org.apache.helix.controller.GenericHelixController.stopRebalancingTimer():void.300691c867b9ec153986206771373244 + +### File: +helix-core/src/main/java/org/apache/helix/controller/GenericHelixController.java + +### Key: +GenericHelixController.java|stopRebalancingTimer|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +97024edbb590ae21918f376b0751a262 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9626/instruction.md b/inferredbugs-9626/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f68b3283c12c4facf51efd9c0b9d955013bea7f2 --- /dev/null +++ b/inferredbugs-9626/instruction.md @@ -0,0 +1,315 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 46 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.model; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.helix.HelixProperty; +import org.apache.helix.ZNRecord; +import org.apache.log4j.Logger; + +/** + * Current states of partitions in a resource for an instance. + */ +public class CurrentState extends HelixProperty { + private static Logger LOG = Logger.getLogger(CurrentState.class); + + /** + * Lookup keys for the current state + */ + public enum CurrentStateProperty { + SESSION_ID, + CURRENT_STATE, + REQUESTED_STATE, + INFO, + STATE_MODEL_DEF, + STATE_MODEL_FACTORY_NAME, + RESOURCE // , + // BUCKET_SIZE + } + + /** + * Instantiate a current state with a resource + * @param resourceName name identifying the resource + */ + public CurrentState(String resourceName) { + super(resourceName); + } + + /** + * Instantiate a current state with a pre-populated ZNRecord + * @param record a ZNRecord corresponding to the current state + */ + public CurrentState(ZNRecord record) { + super(record); + } + + /** + * Get the name of the resource + * @return String resource identifier + */ + public String getResourceName() { + return _record.getId(); + } + + /** + * Get the partitions on this instance and the state that each partition is currently in. + * @return (partition, state) pairs + */ + public Map getPartitionStateMap() { + Map map = new HashMap(); + Map> mapFields = _record.getMapFields(); + for (String partitionName : mapFields.keySet()) { + Map tempMap = mapFields.get(partitionName); + if (tempMap != null) { + map.put(partitionName, tempMap.get(CurrentStateProperty.CURRENT_STATE.toString())); + } + } + return map; + } + + /** + * Get the session that this current state corresponds to + * @return String session identifier + */ + public String getSessionId() { + return _record.getSimpleField(CurrentStateProperty.SESSION_ID.toString()); + } + + /** + * Set the session that this current state corresponds to + * @param sessionId String session identifier + */ + public void setSessionId(String sessionId) { + _record.setSimpleField(CurrentStateProperty.SESSION_ID.toString(), sessionId); + } + + /** + * Get the state of a partition on this instance + * @param partitionName the name of the partition + * @return the state, or null if the partition is not present + */ + public String getState(String partitionName) { + Map> mapFields = _record.getMapFields(); + Map mapField = mapFields.get(partitionName); + if (mapField != null) { + return mapField.get(CurrentStateProperty.CURRENT_STATE.toString()); + } + return null; + } + + public String getInfo(String partitionName) { + Map> mapFields = _record.getMapFields(); + Map mapField = mapFields.get(partitionName); + if (mapField != null) { + return mapField.get(CurrentStateProperty.INFO.name()); + } + return null; + } + + public String getRequestedState(String partitionName) { + Map> mapFields = _record.getMapFields(); + Map mapField = mapFields.get(partitionName); + if (mapField != null) { + return mapField.get(CurrentStateProperty.REQUESTED_STATE.name()); + } + return null; + } + + /** + * Set the state model that the resource follows + * @param stateModelName an identifier of the state model + */ + public void setStateModelDefRef(String stateModelName) { + _record.setSimpleField(CurrentStateProperty.STATE_MODEL_DEF.toString(), stateModelName); + } + + /** + * Get the state model that the resource follows + * @return an identifier of the state model + */ + public String getStateModelDefRef() { + return _record.getSimpleField(CurrentStateProperty.STATE_MODEL_DEF.toString()); + } + + /** + * Set the state that a partition is currently in on this instance + * @param partitionName the name of the partition + * @param state the state of the partition + */ + public void setState(String partitionName, String state) { + Map> mapFields = _record.getMapFields(); + if (mapFields.get(partitionName) == null) { + mapFields.put(partitionName, new TreeMap()); + } + mapFields.get(partitionName).put(CurrentStateProperty.CURRENT_STATE.toString(), state); + } + + public void setInfo(String partitionName, String info) { + Map> mapFields = _record.getMapFields(); + if (mapFields.get(partitionName) == null) { + mapFields.put(partitionName, new TreeMap()); + } + mapFields.get(partitionName).put(CurrentStateProperty.INFO.name(), info); + } + + public void setRequestedState(String partitionName, String state) { + Map> mapFields = _record.getMapFields(); + if (mapFields.get(partitionName) == null) { + mapFields.put(partitionName, new TreeMap()); + } + mapFields.get(partitionName).put(CurrentStateProperty.REQUESTED_STATE.name(), state); + } + + /** + * Set the state model factory + * @param factoryName the name of the factory + */ + public void setStateModelFactoryName(String factoryName) { + _record.setSimpleField(CurrentStateProperty.STATE_MODEL_FACTORY_NAME.toString(), factoryName); + } + + /** + * Get the state model factory + * @return a name that identifies the state model factory + */ + public String getStateModelFactoryName() { + return _record.getSimpleField(CurrentStateProperty.STATE_MODEL_FACTORY_NAME.toString()); + } + + // @Override + // public int getBucketSize() + // { + // String bucketSizeStr = + // _record.getSimpleField(CurrentStateProperty.BUCKET_SIZE.toString()); + // int bucketSize = 0; + // if (bucketSizeStr != null) + // { + // try + // { + // bucketSize = Integer.parseInt(bucketSizeStr); + // } + // catch (NumberFormatException e) + // { + // // OK + // } + // } + // return bucketSize; + // } + // + // @Override + // public void setBucketSize(int bucketSize) + // { + // if (bucketSize > 0) + // { + // _record.setSimpleField(CurrentStateProperty.BUCKET_SIZE.toString(), "" + bucketSize); + // } + // } + + @Override + public boolean isValid() { + if (getStateModelDefRef() == null) { + LOG.error("Current state does not contain state model ref. id:" + getResourceName()); + return false; + } + if (getSessionId() == null) { + LOG.error("CurrentState does not contain session id, id : " + getResourceName()); + return false; + } + return true; + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `mapFields.get(partitionName)` could be null and is dereferenced at line 180. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CurrentState.setRequestedState(String,String) + +### Procedure Id: +org.apache.helix.model.CurrentState.setRequestedState(java.lang.String,java.lang.String):void.692908a424b528af4437406dd22ba483 + +### File: +helix-core/src/main/java/org/apache/helix/model/CurrentState.java + +### Key: +CurrentState.java|setRequestedState|NULL_DEREFERENCE + +### Node Key: +7ce77dfc12bcde1470a9df893e63147d + +### Hash: +adfbd76ad836dd11244d10cdd4b5da7b + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9627/instruction.md b/inferredbugs-9627/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9535bbf5ebb0ff3ff6837182c6c5952c0062f7ac --- /dev/null +++ b/inferredbugs-9627/instruction.md @@ -0,0 +1,1473 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 79 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.io.IOException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Timer; +import java.util.concurrent.TimeUnit; +import javax.management.JMException; + +import com.google.common.collect.Sets; + +import org.apache.helix.BaseDataAccessor; +import org.apache.helix.ClusterMessagingService; +import org.apache.helix.ConfigAccessor; +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixConstants.ChangeType; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixException; +import org.apache.helix.HelixManager; +import org.apache.helix.HelixManagerProperties; +import org.apache.helix.HelixManagerProperty; +import org.apache.helix.HelixPropertyFactory; +import org.apache.helix.HelixTimerTask; +import org.apache.helix.InstanceType; +import org.apache.helix.LiveInstanceInfoProvider; +import org.apache.helix.PreConnectCallback; +import org.apache.helix.PropertyKey; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.PropertyPathBuilder; +import org.apache.helix.PropertyType; +import org.apache.helix.SystemPropertyKeys; +import org.apache.helix.api.listeners.ClusterConfigChangeListener; +import org.apache.helix.api.listeners.ConfigChangeListener; +import org.apache.helix.api.listeners.ControllerChangeListener; +import org.apache.helix.api.listeners.CurrentStateChangeListener; +import org.apache.helix.api.listeners.CustomizedStateChangeListener; +import org.apache.helix.api.listeners.CustomizedStateConfigChangeListener; +import org.apache.helix.api.listeners.CustomizedStateRootChangeListener; +import org.apache.helix.api.listeners.CustomizedViewChangeListener; +import org.apache.helix.api.listeners.CustomizedViewRootChangeListener; +import org.apache.helix.api.listeners.ExternalViewChangeListener; +import org.apache.helix.api.listeners.IdealStateChangeListener; +import org.apache.helix.api.listeners.InstanceConfigChangeListener; +import org.apache.helix.api.listeners.LiveInstanceChangeListener; +import org.apache.helix.api.listeners.MessageListener; +import org.apache.helix.api.listeners.ResourceConfigChangeListener; +import org.apache.helix.api.listeners.ScopedConfigChangeListener; +import org.apache.helix.controller.GenericHelixController; +import org.apache.helix.controller.pipeline.Pipeline; +import org.apache.helix.healthcheck.ParticipantHealthReportCollector; +import org.apache.helix.healthcheck.ParticipantHealthReportCollectorImpl; +import org.apache.helix.healthcheck.ParticipantHealthReportTask; +import org.apache.helix.messaging.DefaultMessagingService; +import org.apache.helix.model.BuiltInStateModelDefinitions; +import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty; +import org.apache.helix.model.LiveInstance; +import org.apache.helix.monitoring.ZKPathDataDumpTask; +import org.apache.helix.monitoring.mbeans.HelixCallbackMonitor; +import org.apache.helix.monitoring.mbeans.MonitorLevel; +import org.apache.helix.msdcommon.exception.InvalidRoutingDataException; +import org.apache.helix.participant.HelixStateMachineEngine; +import org.apache.helix.participant.StateMachineEngine; +import org.apache.helix.store.zk.AutoFallbackPropertyStore; +import org.apache.helix.store.zk.ZkHelixPropertyStore; +import org.apache.helix.util.HelixUtil; +import org.apache.helix.zookeeper.api.client.HelixZkClient; +import org.apache.helix.zookeeper.api.client.RealmAwareZkClient; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.helix.zookeeper.impl.factory.DedicatedZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.HelixZkClientFactory; +import org.apache.helix.zookeeper.impl.factory.SharedZkClientFactory; +import org.apache.helix.zookeeper.zkclient.IZkStateListener; +import org.apache.helix.zookeeper.zkclient.exception.ZkInterruptedException; +import org.apache.helix.zookeeper.zkclient.serialize.PathBasedZkSerializer; +import org.apache.zookeeper.Watcher.Event.EventType; +import org.apache.zookeeper.Watcher.Event.KeeperState; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.apache.helix.zookeeper.datamodel.serializer.ChainedPathZkSerializer; +import org.apache.helix.zookeeper.datamodel.serializer.ZNRecordSerializer; + +public class ZKHelixManager implements HelixManager, IZkStateListener { + private static Logger LOG = LoggerFactory.getLogger(ZKHelixManager.class); + + public static final String ALLOW_PARTICIPANT_AUTO_JOIN = "allowParticipantAutoJoin"; + private static final int FLAPPING_TIME_WINDOW = 300000; // Default to 300 sec + public static final int DEFAULT_MAX_DISCONNECT_THRESHOLD = 600; // Default to be a large number + private static final int DEFAULT_WAIT_CONNECTED_TIMEOUT = 10 * 1000; // wait until connected for up to 10 seconds. + + protected final String _zkAddress; + private final String _clusterName; + private final String _instanceName; + private final InstanceType _instanceType; + private final int _waitForConnectedTimeout; // wait time for testing connect + private final int _sessionTimeout; // client side session timeout, will be overridden by server timeout. Disconnect after timeout + private final int _connectionInitTimeout; // client timeout to init connect + private final List _preConnectCallbacks; + protected final List _handlers; + private final HelixManagerProperties _properties; + private final HelixManagerProperty _helixManagerProperty; + private final HelixManagerStateListener _stateListener; + + /** + * helix version# + */ + private final String _version; + private int _reportLatency; + + protected RealmAwareZkClient _zkclient; + private final DefaultMessagingService _messagingService; + private Map _callbackMonitors; + + private final MonitorLevel _monitorLevel; + + private BaseDataAccessor _baseDataAccessor; + private ZKHelixDataAccessor _dataAccessor; + private final Builder _keyBuilder; + private ConfigAccessor _configAccessor; + private ZkHelixPropertyStore _helixPropertyStore; + protected LiveInstanceInfoProvider _liveInstanceInfoProvider = null; + + private volatile String _sessionId; + + /** + * Keep track of timestamps that zk State has become Disconnected If in a _timeWindowLengthMs + * window zk State has become Disconnected for more than_maxDisconnectThreshold times disconnect + * the zkHelixManager + */ + private final List _disconnectTimeHistory = new ArrayList(); + private final int _flappingTimeWindowMs; + private final int _maxDisconnectThreshold; + + /** + * participant fields + */ + private final StateMachineEngine _stateMachineEngine; + private final List _timerTasks = new ArrayList<>(); + + private final ParticipantHealthReportCollectorImpl _participantHealthInfoCollector; + private Long _sessionStartTime; + private ParticipantManager _participantManager; + + /** + * controller fields + */ + private GenericHelixController _controller; + private Set _enabledPipelineTypes; + private CallbackHandler _leaderElectionHandler = null; + protected final List _controllerTimerTasks = new ArrayList<>(); + + /** + * status dump timer-task + */ + protected static class StatusDumpTask extends HelixTimerTask { + final HelixManager helixController; + + public StatusDumpTask(HelixManager helixController) { + this.helixController = helixController; + } + + @Override + public synchronized void start() { + long initialDelay = 0; + long period = 15 * 60 * 1000; + long timeThresholdNoChangeForStatusUpdates = 15 * 60 * 1000; // 15 minutes + long timeThresholdNoChangeForErrors = 24 * 60 * 60 * 1000; // 1 day + int maximumNumberOfLeafNodesAllowed = 100; + + if (_timer == null) { + LOG.info("Start StatusDumpTask"); + _timer = new Timer("StatusDumpTimerTask", true); + _timer.scheduleAtFixedRate( + new ZKPathDataDumpTask(helixController, timeThresholdNoChangeForStatusUpdates, + timeThresholdNoChangeForErrors, maximumNumberOfLeafNodesAllowed), initialDelay, + period); + } + } + + @Override + public synchronized void stop() { + if (_timer != null) { + LOG.info("Stop StatusDumpTask"); + _timer.cancel(); + _timer = null; + } + } + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress) { + this(clusterName, instanceName, instanceType, zkAddress, null); + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress, HelixManagerStateListener stateListener) { + this(clusterName, instanceName, instanceType, zkAddress, stateListener, + HelixPropertyFactory.getInstance().getHelixManagerProperty(zkAddress, clusterName)); + } + + public ZKHelixManager(String clusterName, String instanceName, InstanceType instanceType, + String zkAddress, HelixManagerStateListener stateListener, + HelixManagerProperty helixManagerProperty) { + + LOG.info("Create a zk-based cluster manager. zkSvr: " + zkAddress + ", clusterName: " + + clusterName + ", instanceName: " + instanceName + ", type: " + instanceType); + + _zkAddress = zkAddress; + _clusterName = clusterName; + _instanceType = instanceType; + + if (instanceName == null) { + try { + instanceName = + InetAddress.getLocalHost().getCanonicalHostName() + "-" + instanceType.toString(); + } catch (UnknownHostException e) { + // can ignore it + LOG.info("Unable to get host name. Will set it to UNKNOWN, mostly ignorable", e); + instanceName = "UNKNOWN"; + } + } + + _instanceName = instanceName; + _enabledPipelineTypes = + Sets.newHashSet(Pipeline.Type.DEFAULT, Pipeline.Type.TASK); + _preConnectCallbacks = new ArrayList<>(); + _handlers = new ArrayList<>(); + _properties = new HelixManagerProperties(SystemPropertyKeys.CLUSTER_MANAGER_VERSION); + _version = _properties.getVersion(); + + _keyBuilder = new Builder(clusterName); + _messagingService = new DefaultMessagingService(this); + try { + _callbackMonitors = new HashMap<>(); + for (ChangeType changeType : ChangeType.values()) { + HelixCallbackMonitor callbackMonitor = + new HelixCallbackMonitor(instanceType, clusterName, instanceName, changeType); + callbackMonitor.register(); + _callbackMonitors.put(changeType, callbackMonitor); + } + } catch (JMException e) { + LOG.error("Error in creating callback monitor.", e); + } + + _stateListener = stateListener; + _helixManagerProperty = helixManagerProperty; + + /** + * use system property if available + */ + _flappingTimeWindowMs = HelixUtil.getSystemPropertyAsInt(SystemPropertyKeys.FLAPPING_TIME_WINDOW, + ZKHelixManager.FLAPPING_TIME_WINDOW); + + _maxDisconnectThreshold = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.MAX_DISCONNECT_THRESHOLD, + ZKHelixManager.DEFAULT_MAX_DISCONNECT_THRESHOLD); + + _sessionTimeout = HelixUtil.getSystemPropertyAsInt(SystemPropertyKeys.ZK_SESSION_TIMEOUT, + HelixZkClient.DEFAULT_SESSION_TIMEOUT); + + _connectionInitTimeout = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.ZK_CONNECTION_TIMEOUT, + HelixZkClient.DEFAULT_CONNECTION_TIMEOUT); + + _waitForConnectedTimeout = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.ZK_WAIT_CONNECTED_TIMEOUT, + DEFAULT_WAIT_CONNECTED_TIMEOUT); + + _reportLatency = HelixUtil + .getSystemPropertyAsInt(SystemPropertyKeys.PARTICIPANT_HEALTH_REPORT_LATENCY, + ParticipantHealthReportTask.DEFAULT_REPORT_LATENCY); + + MonitorLevel configuredMonitorLevel; + try { + configuredMonitorLevel = MonitorLevel.valueOf( + System.getProperty(SystemPropertyKeys.MONITOR_LEVEL, MonitorLevel.DEFAULT.name())); + } catch (IllegalArgumentException ex) { + LOG.warn("Unrecognizable Monitor Level configuration. Use DEFAULT monitor level.", ex); + configuredMonitorLevel = MonitorLevel.DEFAULT; + } + _monitorLevel = configuredMonitorLevel; + + /** + * instance type specific init + */ + switch (instanceType) { + case PARTICIPANT: + _stateMachineEngine = new HelixStateMachineEngine(this); + _participantHealthInfoCollector = + new ParticipantHealthReportCollectorImpl(this, _instanceName); + _timerTasks + .add(new ParticipantHealthReportTask(_participantHealthInfoCollector, _reportLatency)); + break; + case CONTROLLER: + _stateMachineEngine = null; + _participantHealthInfoCollector = null; + _controllerTimerTasks.add(new StatusDumpTask(this)); + + break; + case CONTROLLER_PARTICIPANT: + _stateMachineEngine = new HelixStateMachineEngine(this); + _participantHealthInfoCollector = + new ParticipantHealthReportCollectorImpl(this, _instanceName); + + _timerTasks + .add(new ParticipantHealthReportTask(_participantHealthInfoCollector, _reportLatency)); + _controllerTimerTasks.add(new StatusDumpTask(this)); + break; + case ADMINISTRATOR: + case SPECTATOR: + _stateMachineEngine = null; + _participantHealthInfoCollector = null; + break; + default: + throw new IllegalArgumentException("unrecognized type: " + instanceType); + } + } + + public void setEnabledControlPipelineTypes(Set types) { + if (!InstanceType.CONTROLLER.equals(_instanceType) && !InstanceType.CONTROLLER_PARTICIPANT + .equals(_instanceType)) { + throw new IllegalStateException( + String.format("Cannot enable control pipeline for instance type %s", _instanceType)); + } + _enabledPipelineTypes = types; + } + + @Override public boolean removeListener(PropertyKey key, Object listener) { + LOG.info("Removing listener: " + listener + " on path: " + key.getPath() + " from cluster: " + + _clusterName + " by instance: " + _instanceName); + + synchronized (this) { + List toRemove = new ArrayList<>(); + for (CallbackHandler handler : _handlers) { + // compare property-key path and listener reference + if (handler.getPath().equals(key.getPath()) && handler.getListener().equals(listener)) { + toRemove.add(handler); + } + } + + _handlers.removeAll(toRemove); + + // handler.reset() may modify the handlers list, so do it outside the iteration + for (CallbackHandler handler : toRemove) { + handler.reset(true); + } + } + + return true; + } + + void checkConnected() { + checkConnected(-1); + } + + /** + * Check if HelixManager is connected, if it is not connected, + * wait for the specified timeout and check again before return. + * + * @param timeout + */ + void checkConnected(long timeout) { + if (_zkclient == null || _zkclient.isClosed()) { + throw new HelixException( + "HelixManager (ZkClient) is not connected. Call HelixManager#connect()"); + } + + boolean isConnected = isConnected(); + if (!isConnected && timeout > 0) { + LOG.warn( + "zkClient to " + _zkAddress + " is not connected, wait for " + _waitForConnectedTimeout + + "ms."); + isConnected = _zkclient.waitUntilConnected(_waitForConnectedTimeout, TimeUnit.MILLISECONDS); + } + + if (!isConnected) { + LOG.error("zkClient is not connected after waiting " + timeout + "ms." + + ", clusterName: " + _clusterName + ", zkAddress: " + _zkAddress); + throw new HelixException( + "HelixManager is not connected within retry timeout for cluster " + _clusterName); + } + } + + void addListener(Object listener, PropertyKey propertyKey, ChangeType changeType, + EventType[] eventType) { + checkConnected(_waitForConnectedTimeout); + + PropertyType type = propertyKey.getType(); + + synchronized (this) { + for (CallbackHandler handler : _handlers) { + // compare property-key path and listener reference + if (handler.getPath().equals(propertyKey.getPath()) + && handler.getListener().equals(listener)) { + LOG.info("Listener: " + listener + " on path: " + propertyKey.getPath() + + " already exists. skip add"); + + return; + } + } + + CallbackHandler newHandler = + new CallbackHandler(this, _zkclient, propertyKey, listener, eventType, changeType, + _callbackMonitors.get(changeType)); + + _handlers.add(newHandler); + LOG.info("Added listener: " + listener + " for type: " + type + " to path: " + + newHandler.getPath()); + } + } + + @Override + public void addIdealStateChangeListener(final IdealStateChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addIdealStateChangeListener(final org.apache.helix.IdealStateChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).idealStates(), ChangeType.IDEAL_STATE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addLiveInstanceChangeListener(LiveInstanceChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).liveInstances(), ChangeType.LIVE_INSTANCE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addLiveInstanceChangeListener(org.apache.helix.LiveInstanceChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).liveInstances(), ChangeType.LIVE_INSTANCE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addConfigChangeListener(ConfigChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addInstanceConfigChangeListener(InstanceConfigChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Deprecated + @Override + public void addInstanceConfigChangeListener(org.apache.helix.InstanceConfigChangeListener listener) + throws Exception { + addListener(listener, new Builder(_clusterName).instanceConfigs(), ChangeType.INSTANCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addResourceConfigChangeListener(ResourceConfigChangeListener listener) throws Exception{ + addListener(listener, new Builder(_clusterName).resourceConfigs(), ChangeType.RESOURCE_CONFIG, + new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedStateConfigChangeListener( + CustomizedStateConfigChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).customizedStateConfig(), + ChangeType.CUSTOMIZED_STATE_CONFIG, new EventType[] { + EventType.NodeDataChanged + }); + } + + @Override + public void addClusterfigChangeListener(ClusterConfigChangeListener listener) throws Exception{ + addListener(listener, new Builder(_clusterName).clusterConfig(), ChangeType.CLUSTER_CONFIG, + new EventType[] { EventType.NodeDataChanged + }); + } + + @Override + public void addConfigChangeListener(ScopedConfigChangeListener listener, ConfigScopeProperty scope) + throws Exception { + Builder keyBuilder = new Builder(_clusterName); + + PropertyKey propertyKey = null; + switch (scope) { + case CLUSTER: + propertyKey = keyBuilder.clusterConfigs(); + break; + case PARTICIPANT: + propertyKey = keyBuilder.instanceConfigs(); + break; + case RESOURCE: + propertyKey = keyBuilder.resourceConfigs(); + break; + default: + break; + } + + if (propertyKey != null) { + addListener(listener, propertyKey, ChangeType.CONFIG, new EventType[] { + EventType.NodeChildrenChanged + }); + } else { + LOG.error("Can't add listener to config scope: " + scope); + } + } + + + @Deprecated + @Override + public void addConfigChangeListener(org.apache.helix.ScopedConfigChangeListener listener, ConfigScopeProperty scope) + throws Exception { + addConfigChangeListener((ScopedConfigChangeListener) listener, scope); + } + + // TODO: Decide if do we still need this since we are exposing + // ClusterMessagingService + @Override + public void addMessageListener(MessageListener listener, String instanceName) { + addListener(listener, new Builder(_clusterName).messages(instanceName), ChangeType.MESSAGE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addMessageListener(org.apache.helix.MessageListener listener, String instanceName) { + addListener(listener, new Builder(_clusterName).messages(instanceName), ChangeType.MESSAGE, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addControllerMessageListener(MessageListener listener) { + addListener(listener, new Builder(_clusterName).controllerMessages(), + ChangeType.MESSAGES_CONTROLLER, new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addControllerMessageListener(org.apache.helix.MessageListener listener) { + addListener(listener, new Builder(_clusterName).controllerMessages(), + ChangeType.MESSAGES_CONTROLLER, new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addCurrentStateChangeListener(CurrentStateChangeListener listener, + String instanceName, String sessionId) throws Exception { + addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId), + ChangeType.CURRENT_STATE, new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Deprecated + @Override + public void addCurrentStateChangeListener(org.apache.helix.CurrentStateChangeListener listener, + String instanceName, String sessionId) throws Exception { + addListener(listener, new Builder(_clusterName).currentStates(instanceName, sessionId), + ChangeType.CURRENT_STATE, new EventType[] { EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedStateRootChangeListener(CustomizedStateRootChangeListener listener, + String instanceName) throws Exception { + addListener(listener, new Builder(_clusterName).customizedStatesRoot(instanceName), + ChangeType.CUSTOMIZED_STATE_ROOT, new EventType[]{EventType.NodeChildrenChanged}); + } + + @Override + public void addCustomizedStateChangeListener(CustomizedStateChangeListener listener, + String instanceName, String customizedStateType) throws Exception { + addListener(listener, + new Builder(_clusterName).customizedStates(instanceName, customizedStateType), + ChangeType.CUSTOMIZED_STATE, new EventType[]{EventType.NodeChildrenChanged}); + } + + @Override + public void addExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addCustomizedViewChangeListener(CustomizedViewChangeListener listener, String customizedStateType) + throws Exception { + addListener(listener, new Builder(_clusterName).customizedView(customizedStateType), + ChangeType.CUSTOMIZED_VIEW, new EventType[] { + EventType.NodeChildrenChanged + }); + } + + @Override + public void addCustomizedViewRootChangeListener(CustomizedViewRootChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).customizedViews(), + ChangeType.CUSTOMIZED_VIEW_ROOT, new EventType[] { + EventType.NodeChildrenChanged + }); + } + + @Override + public void addTargetExternalViewChangeListener(ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.TARGET_EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addExternalViewChangeListener(org.apache.helix.ExternalViewChangeListener listener) throws Exception { + addListener(listener, new Builder(_clusterName).externalViews(), ChangeType.EXTERNAL_VIEW, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public void addControllerListener(ControllerChangeListener listener) { + addListener(listener, new Builder(_clusterName).controller(), ChangeType.CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Deprecated + @Override + public void addControllerListener(org.apache.helix.ControllerChangeListener listener) { + addListener(listener, new Builder(_clusterName).controller(), ChangeType.CONTROLLER, + new EventType[] { EventType.NodeChildrenChanged }); + } + + @Override + public HelixDataAccessor getHelixDataAccessor() { + checkConnected(_waitForConnectedTimeout); + return _dataAccessor; + } + + @Override + public ConfigAccessor getConfigAccessor() { + checkConnected(_waitForConnectedTimeout); + return _configAccessor; + } + + @Override + public String getClusterName() { + return _clusterName; + } + + /** + * Returns a string that can be used to connect to metadata store for this HelixManager instance + * i.e. for ZkHelixManager, this will have format "{zookeeper-address}:{port}" + * @return a string used to connect to metadata store + */ + @Override + public String getMetadataStoreConnectionString() { + return _zkAddress; + } + + @Override + public String getInstanceName() { + return _instanceName; + } + + BaseDataAccessor createBaseDataAccessor() { + ZkBaseDataAccessor baseDataAccessor = new ZkBaseDataAccessor<>(_zkclient); + return baseDataAccessor; + } + + /** + * Add Helix built-in state model definitions if not exist + */ + private void addBuiltInStateModelDefinitions() { + for (BuiltInStateModelDefinitions def : BuiltInStateModelDefinitions.values()) { + // creation succeeds only if not exist + _dataAccessor.createStateModelDef(def.getStateModelDefinition()); + } + } + + private boolean isMonitorRootPathOnly() { + switch (_monitorLevel) { + case ALL: + return false; + case AGGREGATED_ONLY: + return true; + default: + // Otherwise, apply the default policy. Emitting full metrics for controllers only. + return !_instanceType.equals(InstanceType.CONTROLLER) && !_instanceType + .equals(InstanceType.CONTROLLER_PARTICIPANT); + } + } + + void createClient() throws Exception { + final RealmAwareZkClient newClient = createSingleRealmZkClient(); + + synchronized (this) { + if (_zkclient != null) { + _zkclient.close(); + } + _zkclient = newClient; + + _baseDataAccessor = createBaseDataAccessor(); + + _dataAccessor = new ZKHelixDataAccessor(_clusterName, _instanceType, _baseDataAccessor); + _configAccessor = new ConfigAccessor(_zkclient); + + if (_instanceType == InstanceType.CONTROLLER + || _instanceType == InstanceType.CONTROLLER_PARTICIPANT) { + addBuiltInStateModelDefinitions(); + } + } + + // subscribe to state change + _zkclient.subscribeStateChanges(this); + int retryCount = 0; + while (retryCount < 3) { + try { + final long sessionId = + _zkclient.waitForEstablishedSession(_connectionInitTimeout, TimeUnit.MILLISECONDS); + handleStateChanged(KeeperState.SyncConnected); + /* + * This listener is subscribed after SyncConnected and firing new session events, + * which means this listener has not yet handled new session, so we have to handle new + * session here just for this listener. + */ + handleNewSession(ZKUtil.toHexSessionId(sessionId)); + break; + } catch (HelixException e) { + LOG.error("fail to createClient.", e); + throw e; + } catch (Exception e) { + retryCount++; + LOG.error("fail to createClient. retry " + retryCount, e); + if (retryCount == 3) { + throw e; + } + } + } + } + + @Override + public void connect() throws Exception { + LOG.info("ClusterManager.connect()"); + if (isConnected()) { + LOG.warn("Cluster manager: " + _instanceName + " for cluster: " + _clusterName + + " already connected. skip connect"); + return; + } + + switch (_instanceType) { + case CONTROLLER: + case CONTROLLER_PARTICIPANT: + if (_controller == null) { + _controller = new GenericHelixController(_clusterName, _enabledPipelineTypes); + _messagingService.getExecutor().setController(_controller); + } + break; + default: + break; + } + + try { + createClient(); + _messagingService.onConnected(); + } catch (Exception e) { + LOG.error("fail to connect " + _instanceName, e); + try { + disconnect(); + } catch (Exception ex) { + // if zk connection fails to be created, disconnect may throw exception about reporting disconnect to ZK. + } + throw e; + } + } + + @Override + public void disconnect() { + if (_zkclient == null || _zkclient.isClosed()) { + LOG.info("instanceName: " + _instanceName + " already disconnected"); + return; + } + + LOG.info("disconnect " + _instanceName + "(" + _instanceType + ") from " + _clusterName); + + try { + /** + * stop all timer tasks + */ + stopTimerTasks(); + + /** + * shutdown thread pool first to avoid reset() being invoked in the middle of state + * transition + */ + _messagingService.getExecutor().shutdown(); + + // TODO reset user defined handlers only + // TODO Fix the issue that when connection disconnected, reset handlers will be blocked. -- JJ + // This is because reset logic contains ZK operations. + resetHandlers(true); + + if (_leaderElectionHandler != null) { + _leaderElectionHandler.reset(true); + } + + } finally { + GenericHelixController controller = _controller; + if (controller != null) { + try { + controller.shutdown(); + } catch (InterruptedException e) { + LOG.info("Interrupted shutting down GenericHelixController", e); + } + } + + ParticipantManager participantManager = _participantManager; + if (participantManager != null) { + participantManager.disconnect(); + } + + for (HelixCallbackMonitor callbackMonitor : _callbackMonitors.values()) { + callbackMonitor.unregister(); + } + + _helixPropertyStore = null; + + synchronized (this) { + if (_controller != null) { + _controller = null; + _leaderElectionHandler = null; + } + + if (_participantManager != null) { + _participantManager = null; + } + + if (_zkclient != null) { + _zkclient.close(); + } + } + _sessionStartTime = null; + LOG.info("Cluster manager: " + _instanceName + " disconnected"); + } + } + + @Override + public String getSessionId() { + checkConnected(_waitForConnectedTimeout); + // TODO: session id should be updated after zk client is connected. + // Otherwise, this session id might be an expired one. + return _sessionId; + } + + @Override + public boolean isConnected() { + if (_zkclient == null || _zkclient.isClosed()) { + return false; + } + // Don't check ZkConnection state, which is different from ZkClient's watcher state. + // ZkConnection state is the internal state of the connection, which can be different from the + // ZkClient state due to internal thread/retry logic. + try { + return _zkclient.waitUntilConnected(0, TimeUnit.MILLISECONDS); + } catch (ZkInterruptedException ex) { + return false; + } + } + + @Override + public long getLastNotificationTime() { + return 0; + } + + @Override + public void addPreConnectCallback(PreConnectCallback callback) { + LOG.info("Adding preconnect callback: " + callback); + _preConnectCallbacks.add(callback); + } + + @Override + public boolean isLeader() { + String warnLogPrefix = String + .format("Instance %s is not leader of cluster %s due to", _instanceName, _clusterName); + if (_instanceType != InstanceType.CONTROLLER + && _instanceType != InstanceType.CONTROLLER_PARTICIPANT) { + LOG.warn(String + .format("%s instance type %s does not match to CONTROLLER/CONTROLLER_PARTICIPANT", + warnLogPrefix, _instanceType.name())); + return false; + } + + if (!isConnected()) { + LOG.warn(String.format("%s HelixManager is not connected", warnLogPrefix)); + return false; + } + + try { + LiveInstance leader = _dataAccessor.getProperty(_keyBuilder.controllerLeader()); + if (leader != null) { + String leaderName = leader.getInstanceName(); + String sessionId = leader.getEphemeralOwner(); + if (leaderName != null && leaderName.equals(_instanceName) && sessionId + .equals(_sessionId)) { + return true; + } + LOG.warn(String + .format("%s current session %s does not match leader session %s", warnLogPrefix, + _sessionId, sessionId)); + } else { + LOG.warn(String.format("%s leader ZNode is null", warnLogPrefix)); + } + } catch (Exception e) { + LOG.warn(String.format("%s exception happen when session check", warnLogPrefix), e); + } + return false; + } + + @Override + public synchronized ZkHelixPropertyStore getHelixPropertyStore() { + checkConnected(_waitForConnectedTimeout); + + if (_helixPropertyStore == null) { + String path = PropertyPathBuilder.propertyStore(_clusterName); + String fallbackPath = String.format("/%s/%s", _clusterName, "HELIX_PROPERTYSTORE"); + _helixPropertyStore = + new AutoFallbackPropertyStore<>(new ZkBaseDataAccessor<>(_zkclient), + path, fallbackPath); + } + + return _helixPropertyStore; + } + + @Override + public synchronized HelixAdmin getClusterManagmentTool() { + checkConnected(_waitForConnectedTimeout); + if (_zkclient != null && !_zkclient.isClosed()) { + return new ZKHelixAdmin(_zkclient); + } + + LOG.error("Couldn't get ZKClusterManagementTool because zkclient is null"); + return null; + } + + @Override + public ClusterMessagingService getMessagingService() { + // The caller can register message handler factories on messaging service before the + // helix manager is connected. Thus we do not do connected check here. + return _messagingService; + } + + @Override + public InstanceType getInstanceType() { + return _instanceType; + } + + @Override + public String getVersion() { + return _version; + } + + @Override + public HelixManagerProperties getProperties() { + return _properties; + } + + @Override + public StateMachineEngine getStateMachineEngine() { + return _stateMachineEngine; + } + + // TODO: rename this and not expose this function as part of interface + @Override + public void startTimerTasks() { + for (HelixTimerTask task : _timerTasks) { + task.start(); + } + } + + @Override + public void stopTimerTasks() { + for (HelixTimerTask task : _timerTasks) { + task.stop(); + } + } + + @Override + public void setLiveInstanceInfoProvider(LiveInstanceInfoProvider liveInstanceInfoProvider) { + _liveInstanceInfoProvider = liveInstanceInfoProvider; + } + + /** + * wait until we get a non-zero session-id. note that we might lose zkconnection + * right after we read session-id. but it's ok to get stale session-id and we will have + * another handle-new-session callback to correct this. + */ + void waitUntilConnected() { + boolean isConnected; + do { + isConnected = + _zkclient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); + if (!isConnected) { + LOG.error("fail to connect zkserver: " + _zkAddress + " in " + + HelixZkClient.DEFAULT_CONNECTION_TIMEOUT + "ms. expiredSessionId: " + _sessionId + + ", clusterName: " + _clusterName); + continue; + } + + _sessionId = ZKUtil.toHexSessionId(_zkclient.getSessionId()); + + /** + * at the time we read session-id, zkconnection might be lost again + * wait until we get a non-zero session-id + */ + } while (!isConnected || "0".equals(_sessionId)); + + LOG.info("Handling new session, session id: " + _sessionId + ", instance: " + _instanceName + + ", instanceTye: " + _instanceType + ", cluster: " + _clusterName); + } + + void initHandlers(List handlers) { + synchronized (this) { + if (handlers != null) { + // get a copy of the list and iterate over the copy list + // in case handler.init() modifies the original handler list + List tmpHandlers = new ArrayList<>(handlers); + for (CallbackHandler handler : tmpHandlers) { + handler.init(); + LOG.info("init handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + void resetHandlers(boolean isShutdown) { + synchronized (this) { + if (_handlers != null) { + // get a copy of the list and iterate over the copy list + // in case handler.reset() modifies the original handler list + List tmpHandlers = new ArrayList<>(_handlers); + for (CallbackHandler handler : tmpHandlers) { + handler.reset(isShutdown); + LOG.info("reset handler: " + handler.getPath() + ", " + handler.getListener()); + } + } + } + } + + /** + * If zk state has changed into Disconnected for maxDisconnectThreshold times during previous + * timeWindowLengthMs Ms + * time window, we think that there are something wrong going on and disconnect the zkHelixManager + * from zk. + */ + boolean isFlapping() { + if (_disconnectTimeHistory.size() == 0) { + return false; + } + long mostRecentTimestamp = _disconnectTimeHistory.get(_disconnectTimeHistory.size() - 1); + + // Remove disconnect history timestamp that are older than flappingTimeWindowMs ago + while ((_disconnectTimeHistory.get(0) + _flappingTimeWindowMs) < mostRecentTimestamp) { + _disconnectTimeHistory.remove(0); + } + return _disconnectTimeHistory.size() > _maxDisconnectThreshold; + } + + @Override + public void handleStateChanged(KeeperState state) { + switch (state) { + case SyncConnected: + LOG.info("KeeperState: " + state + ", instance: " + _instanceName + ", type: " + _instanceType); + break; + case Disconnected: + /** + * Track the time stamp that the disconnected happens, then check history and see if + * we should disconnect the helix-manager + */ + _disconnectTimeHistory.add(System.currentTimeMillis()); + if (isFlapping()) { + String errorMsg = "instanceName: " + _instanceName + " is flapping. disconnect it. " + + " maxDisconnectThreshold: " + _maxDisconnectThreshold + " disconnects in " + + _flappingTimeWindowMs + "ms."; + LOG.error(errorMsg); + + // Only disable the instance when it's instance type is PARTICIPANT + if (_instanceType.equals(InstanceType.PARTICIPANT)) { + LOG.warn("instanceName: " + _instanceName + + " is flapping. Since it is a participant, disable it."); + try { + getClusterManagmentTool().enableInstance(_clusterName, _instanceName, false); + } catch (Exception e) { + LOG.error("Failed to disable participant before disconnecting participant.", e); + } + } + + try { + // TODO Call disconnect in another thread. + // handleStateChanged is triggered in ZkClient eventThread. The disconnect logic will + // interrupt this thread. This issue prevents the ZkClient.close() from complete. So the + // client is left in a strange state. + disconnect(); + } catch (Exception ex) { + LOG.error("Disconnect HelixManager is not completely done.", ex); + } + + if (_stateListener != null) { + try { + _stateListener.onDisconnected(this, new HelixException(errorMsg)); + } catch (Exception e) { + LOG.warn("stateListener.onDisconnected callback fails", e); + } + } + break; + } + // if not flapping, share the continuous logic with Expired case + case Expired: + LOG.warn("KeeperState:" + state + ", SessionId: " + _sessionId + ", instance: " + + _instanceName + ", type: " + _instanceType); + break; + default: + LOG.info("KeeperState:" + state + ", currentSessionId: " + _sessionId + ", instance: " + + _instanceName + ", type: " + _instanceType); + break; + } + } + + /** + * Called after zookeeper session has expired and a new session has been established. This method + * may cause session race condition when creating ephemeral nodes. Internally, this method calls + * {@link #handleNewSession(String)} with a null value as the sessionId parameter, which results + * in later creating the ephemeral node in the session of the latest zk connection. + * But please note that the session of the latest zk connection might not be the expected session. + * This is the session race condition issue. + * + * To avoid the race condition issue, please use {@link #handleNewSession(String)}. + * + * @deprecated + * This method is deprecated, because it may cause session race condition when creating ephemeral + * nodes. It is kept for backward compatibility in case a user class extends this class. + * + * Please use {@link #handleNewSession(String)} instead, which takes care of race condition. + * + * @throws Exception If any error occurs. + */ + @Deprecated + public void handleNewSession() throws Exception { + handleNewSession(null); + } + + /** + * Called after the zookeeper session has expired and a new session has been established. This + * methods handles a new session with its session id passed in. Before handling, this method + * waits until zk client is connected to zk service and gets a non-zero session id(current actual + * session id). If the passed-in(expected) session id does not match current actual session id, + * the expected session id is expired and will NOT be handled. + * + * @param sessionId the new session's id. The ephemeral nodes are expected to be created in this + * session. If this session id is expired, ephemeral nodes should not be created. + * @throws Exception if any error occurs during handling new session + */ + @Override + public void handleNewSession(String sessionId) throws Exception { + /* + * TODO: after removing I0ItecIZkStateListenerImpl, null session should be checked and + * discarded. + * Null session is still a special case here, which is treated as non-session aware operation. + * This special case could still potentially cause race condition, so null session should NOT + * be acceptable, once I0ItecIZkStateListenerImpl is removed. Currently this special case + * is kept for backward compatibility. + */ + + // Wait until we get a non-zero session id. Otherwise, getSessionId() might be null. + waitUntilConnected(); + + /* + * Filter out stale sessions. If a session id is not null and not the same as current session + * id, this session is expired. With this filtering, expired sessions are NOT handled, + * so performance is expected to improve. + */ + if (sessionId != null && !getSessionId().equals(sessionId)) { + LOG.warn("Session is expired and not handled. Expected: {}. Actual: {}.", sessionId, + getSessionId()); + return; + } + + /* + * When a null session id is passed in, we will take current session's id for following + * operations. Please note that current session might not be the one we expect to handle, + * because the one we expect might be already expired when the zk event is waiting in the + * event queue. Why we use current session here is for backward compatibility with the old + * method handleNewSession(). + */ + if (sessionId == null) { + sessionId = getSessionId(); + LOG.debug("Session id: is passed in. Current session id: {} will be used.", sessionId); + } + + LOG.info("Handle new session, instance: {}, type: {}, session id: {}.", _instanceName, + _instanceType, sessionId); + + /** + * stop all timer tasks, reset all handlers, make sure cleanup completed for previous session + * disconnect if fail to cleanup + */ + stopTimerTasks(); + if (_leaderElectionHandler != null) { + _leaderElectionHandler.reset(false); + } + resetHandlers(false); + + /** + * clean up write-through cache + */ + _baseDataAccessor.reset(); + + /** + * from here on, we are dealing with new session + */ + if (!ZKUtil.isClusterSetup(_clusterName, _zkclient)) { + throw new HelixException("Cluster structure is not set up for cluster: " + _clusterName); + } + + _sessionStartTime = System.currentTimeMillis(); + + switch (_instanceType) { + case PARTICIPANT: + handleNewSessionAsParticipant(sessionId); + break; + case CONTROLLER: + handleNewSessionAsController(); + break; + case CONTROLLER_PARTICIPANT: + handleNewSessionAsParticipant(sessionId); + handleNewSessionAsController(); + break; + case ADMINISTRATOR: + case SPECTATOR: + default: + break; + } + + startTimerTasks(); + + /** + * init handlers + * ok to init message handler and data-accessor twice + * the second init will be skipped (see CallbackHandler) + */ + initHandlers(_handlers); + + if (_stateListener != null) { + try { + _stateListener.onConnected(this); + } catch (Exception e) { + LOG.warn("stateListener.onConnected callback fails", e); + } + } + } + + void handleNewSessionAsParticipant(final String sessionId) throws Exception { + if (_participantManager != null) { + _participantManager.reset(); + } + _participantManager = + new ParticipantManager(this, _zkclient, _sessionTimeout, _liveInstanceInfoProvider, + _preConnectCallbacks, sessionId, _helixManagerProperty); + _participantManager.handleNewSession(); + } + + // TODO: pass in session id and make this method session aware to avoid potential session race + // condition. + void handleNewSessionAsController() { + if (_leaderElectionHandler != null) { + _leaderElectionHandler.init(); + } else { + _leaderElectionHandler = + new CallbackHandler(this, _zkclient, _keyBuilder.controller(), + new DistributedLeaderElection(this, _controller, _controllerTimerTasks), + new EventType[] { + EventType.NodeChildrenChanged, EventType.NodeDeleted, EventType.NodeCreated + }, ChangeType.CONTROLLER, _callbackMonitors.get(ChangeType.CONTROLLER)); + } + } + + @Override + public ParticipantHealthReportCollector getHealthReportCollector() { + return _participantHealthInfoCollector; + } + + @Override + public void handleSessionEstablishmentError(Throwable error) throws Exception { + LOG.warn("Handling Session Establishment Error. Disconnect Helix Manager.", error); + disconnect(); + + if (_stateListener != null) { + _stateListener.onDisconnected(this, error); + } + } + + @Override + public Long getSessionStartTime() { + return _sessionStartTime; + } + + /* + * Prepares connection config and client config based on the internal parameters given to + * HelixManager in order to create a ZkClient instance to use. Note that a shared ZkClient + * instance will be created if connecting as an ADMINISTRATOR to minimize the cost of creating + * ZkConnections. + */ + private RealmAwareZkClient createSingleRealmZkClient() { + final String shardingKey = buildShardingKey(); + PathBasedZkSerializer zkSerializer = + ChainedPathZkSerializer.builder(new ZNRecordSerializer()).build(); + + RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig = + new RealmAwareZkClient.RealmAwareZkConnectionConfig.Builder() + .setRealmMode(RealmAwareZkClient.RealmMode.SINGLE_REALM) + .setZkRealmShardingKey(shardingKey) + .setSessionTimeout(_sessionTimeout).build(); + + RealmAwareZkClient.RealmAwareZkClientConfig clientConfig = + new RealmAwareZkClient.RealmAwareZkClientConfig(); + + clientConfig.setZkSerializer(zkSerializer) + .setConnectInitTimeout(_connectionInitTimeout) + .setMonitorType(_instanceType.name()) + .setMonitorKey(_clusterName) + .setMonitorInstanceName(_instanceName) + .setMonitorRootPathOnly(isMonitorRootPathOnly()); + + if (_instanceType == InstanceType.ADMINISTRATOR) { + return resolveZkClient(SharedZkClientFactory.getInstance(), connectionConfig, + clientConfig); + } + + return resolveZkClient(DedicatedZkClientFactory.getInstance(), connectionConfig, + clientConfig); + } + + /* + * Resolves what type of ZkClient this HelixManager should use based on whether MULTI_ZK_ENABLED + * System config is set or not. Two types of ZkClients are available: + * 1) If MULTI_ZK_ENABLED is set to true, we create a dedicated RealmAwareZkClient + * that provides full ZkClient functionalities and connects to the correct ZK by querying + * MetadataStoreDirectoryService. + * 2) Otherwise, we create a dedicated HelixZkClient which plainly connects to + * the ZK address given. + */ + private RealmAwareZkClient resolveZkClient(HelixZkClientFactory zkClientFactory, + RealmAwareZkClient.RealmAwareZkConnectionConfig connectionConfig, + RealmAwareZkClient.RealmAwareZkClientConfig clientConfig) { + if (Boolean.getBoolean(SystemPropertyKeys.MULTI_ZK_ENABLED)) { + try { + // Create realm-aware ZkClient. + return zkClientFactory.buildZkClient(connectionConfig, clientConfig); + } catch (IllegalArgumentException | IOException | InvalidRoutingDataException e) { + throw new HelixException("Not able to connect on realm-aware mode for sharding key: " + + connectionConfig.getZkRealmShardingKey(), e); + } + } + + // If multi-zk mode is not enabled, create HelixZkClient with the provided zk address. + HelixZkClient.ZkClientConfig helixZkClientConfig = clientConfig.createHelixZkClientConfig(); + HelixZkClient.ZkConnectionConfig helixZkConnectionConfig = + new HelixZkClient.ZkConnectionConfig(_zkAddress) + .setSessionTimeout(connectionConfig.getSessionTimeout()); + + return zkClientFactory.buildZkClient(helixZkConnectionConfig, helixZkClientConfig); + } + + private String buildShardingKey() { + return _clusterName.charAt(0) == '/' ? _clusterName : "/" + _clusterName; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.manager.zk.ZKHelixManager.createClient` indirectly reads with synchronization from `record.org.apache.helix.zookeeper.datamodel.ZNRecord._creationTime`. Potentially races with unsynchronized write in method `ZKHelixManager.disconnect()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZKHelixManager.createClient() + +### Procedure Id: +org.apache.helix.manager.zk.ZKHelixManager.createClient():void.121b2e04dedc8530eb906785a84cdf38 + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZKHelixManager.java + +### Key: +ZKHelixManager.java|createClient|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +65d224aa8fe49e3f6706a9c5a93f38c1 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9628/instruction.md b/inferredbugs-9628/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b84e974e0fc4295468c642e8424b140002e90d9 --- /dev/null +++ b/inferredbugs-9628/instruction.md @@ -0,0 +1,486 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 41 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.task; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import org.I0Itec.zkclient.DataUpdater; +import org.apache.helix.*; +import org.apache.helix.controller.stages.ClusterDataCache; +import org.apache.helix.controller.stages.CurrentStateOutput; +import org.apache.helix.model.*; +import org.apache.helix.model.builder.CustomModeISBuilder; +import org.apache.log4j.Logger; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * Custom rebalancer implementation for the {@code Workflow} in task state model. + */ +public class WorkflowRebalancer extends TaskRebalancer { + private static final Logger LOG = Logger.getLogger(WorkflowRebalancer.class); + + @Override + public ResourceAssignment computeBestPossiblePartitionState(ClusterDataCache clusterData, + IdealState taskIs, Resource resource, CurrentStateOutput currStateOutput) { + final String workflow = resource.getResourceName(); + LOG.debug("Computer Best Partition for workflow: " + workflow); + + // Fetch workflow configuration and context + WorkflowConfig workflowCfg = TaskUtil.getWorkflowCfg(_manager, workflow); + if (workflowCfg == null) { + LOG.warn("Workflow configuration is NULL for " + workflow); + return buildEmptyAssignment(workflow, currStateOutput); + } + + WorkflowContext workflowCtx = TaskUtil.getWorkflowContext(_manager, workflow); + // Initialize workflow context if needed + if (workflowCtx == null) { + workflowCtx = new WorkflowContext(new ZNRecord("WorkflowContext")); + workflowCtx.setStartTime(System.currentTimeMillis()); + LOG.debug("Workflow context is created for " + workflow); + } + + // Clean up if workflow marked for deletion + TargetState targetState = workflowCfg.getTargetState(); + if (targetState == TargetState.DELETE) { + LOG.info("Workflow is marked as deleted " + workflow + " cleaning up the workflow context."); + cleanupWorkflow(workflow, workflowCfg, workflowCtx); + return buildEmptyAssignment(workflow, currStateOutput); + } + + if (targetState == TargetState.STOP) { + LOG.info("Workflow " + workflow + "is marked as stopped."); + // Workflow has been stopped if all jobs are stopped + // TODO: what should we do if workflowCtx is not set yet? + if (workflowCtx != null && isWorkflowStopped(workflowCtx, workflowCfg)) { + workflowCtx.setWorkflowState(TaskState.STOPPED); + } + return buildEmptyAssignment(workflow, currStateOutput); + } + + long currentTime = System.currentTimeMillis(); + // Check if workflow is completed and mark it if it is completed. + if (workflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + if (isWorkflowComplete(workflowCtx, workflowCfg)) { + workflowCtx.setWorkflowState(TaskState.COMPLETED); + workflowCtx.setFinishTime(currentTime); + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + } + } + + if (workflowCtx.getFinishTime() != WorkflowContext.UNFINISHED) { + LOG.info("Workflow " + workflow + " is completed."); + long expiryTime = workflowCfg.getExpiry(); + // Check if this workflow has been finished past its expiry. + if (workflowCtx.getFinishTime() + expiryTime <= currentTime) { + LOG.info("Workflow " + workflow + " passed expiry time, cleaning up the workflow context."); + cleanupWorkflow(workflow, workflowCfg, workflowCtx); + } else { + // schedule future cleanup work + long cleanupTime = workflowCtx.getFinishTime() + expiryTime; + _scheduledRebalancer.scheduleRebalance(_manager, workflow, cleanupTime); + } + return buildEmptyAssignment(workflow, currStateOutput); + } + + if (!isWorkflowReadyForSchedule(workflowCfg)) { + LOG.info("Workflow " + workflow + " is not ready to schedule"); + // set the timer to trigger future schedule + _scheduledRebalancer + .scheduleRebalance(_manager, workflow, workflowCfg.getStartTime().getTime()); + return buildEmptyAssignment(workflow, currStateOutput); + } + + // Check for readiness, and stop processing if it's not ready + boolean isReady = + scheduleWorkflowIfReady(workflow, workflowCfg, workflowCtx); + if (isReady) { + // Schedule jobs from this workflow. + scheduleJobs(workflowCfg, workflowCtx); + } else { + LOG.debug("Workflow " + workflow + " is not ready to be scheduled."); + } + + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + return buildEmptyAssignment(workflow, currStateOutput); + } + + /** + * Figure out whether the jobs in the workflow should be run, + * and if it's ready, then just schedule it + */ + private void scheduleJobs(WorkflowConfig workflowCfg, WorkflowContext workflowCtx) { + ScheduleConfig scheduleConfig = workflowCfg.getScheduleConfig(); + if (scheduleConfig != null && scheduleConfig.isRecurring()) { + LOG.debug("Jobs from recurring workflow are not schedule-able"); + return; + } + + for (String job : workflowCfg.getJobDag().getAllNodes()) { + TaskState jobState = workflowCtx.getJobState(job); + if (jobState != null && !jobState.equals(TaskState.NOT_STARTED)) { + LOG.debug("Job " + job + " is already started or completed."); + continue; + } + // check ancestor job status + if (isJobReadyToSchedule(job, workflowCfg, workflowCtx)) { + JobConfig jobConfig = TaskUtil.getJobCfg(_manager, job); + scheduleSingleJob(job, jobConfig); + } + } + } + + /** + * Posts new job to cluster + */ + private void scheduleSingleJob(String jobResource, JobConfig jobConfig) { + HelixAdmin admin = _manager.getClusterManagmentTool(); + + IdealState jobIS = admin.getResourceIdealState(_manager.getClusterName(), jobResource); + if (jobIS != null) { + LOG.info("Job " + jobResource + " idealstate already exists!"); + return; + } + + // Set up job resource based on partitions from target resource + int numIndependentTasks = jobConfig.getTaskConfigMap().size(); + int numPartitions = (numIndependentTasks > 0) ? + numIndependentTasks : + admin.getResourceIdealState(_manager.getClusterName(), jobConfig.getTargetResource()) + .getPartitionSet().size(); + admin.addResource(_manager.getClusterName(), jobResource, numPartitions, + TaskConstants.STATE_MODEL_NAME); + + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + // Set the job configuration + PropertyKey.Builder keyBuilder = accessor.keyBuilder(); + HelixProperty resourceConfig = new HelixProperty(jobResource); + resourceConfig.getRecord().getSimpleFields().putAll(jobConfig.getResourceConfigMap()); + Map taskConfigMap = jobConfig.getTaskConfigMap(); + if (taskConfigMap != null) { + for (TaskConfig taskConfig : taskConfigMap.values()) { + resourceConfig.getRecord().setMapField(taskConfig.getId(), taskConfig.getConfigMap()); + } + } + accessor.setProperty(keyBuilder.resourceConfig(jobResource), resourceConfig); + + // Push out new ideal state based on number of target partitions + CustomModeISBuilder builder = new CustomModeISBuilder(jobResource); + builder.setRebalancerMode(IdealState.RebalanceMode.TASK); + builder.setNumReplica(1); + builder.setNumPartitions(numPartitions); + builder.setStateModel(TaskConstants.STATE_MODEL_NAME); + + if (jobConfig.isDisableExternalView()) { + builder.disableExternalView(); + } + + jobIS = builder.build(); + for (int i = 0; i < numPartitions; i++) { + jobIS.getRecord().setListField(jobResource + "_" + i, new ArrayList()); + jobIS.getRecord().setMapField(jobResource + "_" + i, new HashMap()); + } + jobIS.setRebalancerClassName(JobRebalancer.class.getName()); + admin.setResourceIdealState(_manager.getClusterName(), jobResource, jobIS); + } + + /** + * Check if a workflow is ready to schedule, and schedule a rebalance if it is not + * + * @param workflow the Helix resource associated with the workflow + * @param workflowCfg the workflow to check + * @param workflowCtx the current workflow context + * @return true if the workflow is ready for schedule, false if not ready + */ + private boolean scheduleWorkflowIfReady(String workflow, WorkflowConfig workflowCfg, + WorkflowContext workflowCtx) { + // non-scheduled workflow is ready to run immediately. + if (workflowCfg == null || workflowCfg.getScheduleConfig() == null) { + return true; + } + + // Figure out when this should be run, and if it's ready, then just run it + ScheduleConfig scheduleConfig = workflowCfg.getScheduleConfig(); + Date startTime = scheduleConfig.getStartTime(); + long currentTime = new Date().getTime(); + long delayFromStart = startTime.getTime() - currentTime; + + if (delayFromStart <= 0) { + // Recurring workflows are just templates that spawn new workflows + if (scheduleConfig.isRecurring()) { + // Skip scheduling this workflow if it's not in a start state + if (!workflowCfg.getTargetState().equals(TargetState.START)) { + LOG.debug("Skip scheduling since the workflow has not been started " + workflow); + return false; + } + + // Skip scheduling this workflow again if the previous run (if any) is still active + String lastScheduled = workflowCtx.getLastScheduledSingleWorkflow(); + if (lastScheduled != null) { + WorkflowContext lastWorkflowCtx = TaskUtil.getWorkflowContext(_manager, lastScheduled); + if (lastWorkflowCtx != null + && lastWorkflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + LOG.info("Skip scheduling since last schedule has not completed yet " + lastScheduled); + return false; + } + } + + // Figure out how many jumps are needed, thus the time to schedule the next workflow + // The negative of the delay is the amount of time past the start time + long period = + scheduleConfig.getRecurrenceUnit().toMillis(scheduleConfig.getRecurrenceInterval()); + long offsetMultiplier = (-delayFromStart) / period; + long timeToSchedule = period * offsetMultiplier + startTime.getTime(); + + // Now clone the workflow if this clone has not yet been created + DateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss"); + df.setTimeZone(TimeZone.getTimeZone("UTC")); + String newWorkflowName = workflow + "_" + df.format(new Date(timeToSchedule)); + LOG.debug("Ready to start workflow " + newWorkflowName); + if (!newWorkflowName.equals(lastScheduled)) { + Workflow clonedWf = TaskUtil + .cloneWorkflow(_manager, workflow, newWorkflowName, new Date(timeToSchedule)); + TaskDriver driver = new TaskDriver(_manager); + try { + // Start the cloned workflow + driver.start(clonedWf); + } catch (Exception e) { + LOG.error("Failed to schedule cloned workflow " + newWorkflowName, e); + } + // Persist workflow start regardless of success to avoid retrying and failing + workflowCtx.setLastScheduledSingleWorkflow(newWorkflowName); + TaskUtil.setWorkflowContext(_manager, workflow, workflowCtx); + } + + // Change the time to trigger the pipeline to that of the next run + _scheduledRebalancer.scheduleRebalance(_manager, workflow, (timeToSchedule + period)); + } else { + // one time workflow. + // Remove any timers that are past-time for this workflowg + long scheduledTime = _scheduledRebalancer.getRebalanceTime(workflow); + if (scheduledTime > 0 && currentTime > scheduledTime) { + _scheduledRebalancer.removeScheduledRebalance(workflow); + } + return true; + } + } else { + // set the timer to trigger future schedule + _scheduledRebalancer.scheduleRebalance(_manager, workflow, startTime.getTime()); + } + + return false; + } + + /** + * Cleans up workflow configs and workflow contexts associated with this workflow, + * including all job-level configs and context, plus workflow-level information. + */ + private void cleanupWorkflow(String workflow, WorkflowConfig workflowcfg, + WorkflowContext workflowCtx) { + LOG.info("Cleaning up workflow: " + workflow); + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + /* + if (workflowCtx != null && workflowCtx.getFinishTime() == WorkflowContext.UNFINISHED) { + LOG.error("Workflow " + workflow + " has not completed, abort the clean up task."); + return; + }*/ + + for (String job : workflowcfg.getJobDag().getAllNodes()) { + cleanupJob(job, workflow); + } + + // clean up workflow-level info if this was the last in workflow + if (workflowcfg.isTerminable() || workflowcfg.getTargetState() == TargetState.DELETE) { + // clean up IS & EV + TaskUtil.cleanupIdealStateExtView(_manager.getHelixDataAccessor(), workflow); + + // delete workflow config + PropertyKey workflowCfgKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); + if (accessor.getProperty(workflowCfgKey) != null) { + if (!accessor.removeProperty(workflowCfgKey)) { + LOG.error(String.format( + "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix.", + workflow, workflowCfgKey)); + } + } + // Delete workflow context + String workflowPropStoreKey = TaskUtil.getWorkflowContextKey(workflow); + LOG.info("Removing workflow context: " + workflowPropStoreKey); + if (!_manager.getHelixPropertyStore().remove(workflowPropStoreKey, AccessOption.PERSISTENT)) { + LOG.error(String.format( + "Error occurred while trying to clean up workflow %s. Failed to remove node %s from Helix. Aborting further clean up steps.", + workflow, workflowPropStoreKey)); + } + + // Remove pending timer task for this workflow if exists + _scheduledRebalancer.removeScheduledRebalance(workflow); + } + } + + + /** + * Cleans up workflow configs and workflow contexts associated with this workflow, + * including all job-level configs and context, plus workflow-level information. + */ + private void cleanupJob(final String job, String workflow) { + LOG.info("Cleaning up job: " + job + " in workflow: " + workflow); + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + // Remove any idealstate and externalView. + TaskUtil.cleanupIdealStateExtView(accessor, job); + + // Remove DAG references in workflow + PropertyKey workflowKey = TaskUtil.getWorkflowConfigKey(accessor, workflow); + DataUpdater dagRemover = new DataUpdater() { + @Override + public ZNRecord update(ZNRecord currentData) { + if (currentData != null) { + JobDag jobDag = JobDag.fromJson(currentData.getSimpleField(WorkflowConfig.DAG)); + for (String child : jobDag.getDirectChildren(job)) { + jobDag.getChildrenToParents().get(child).remove(job); + } + for (String parent : jobDag.getDirectParents(job)) { + jobDag.getParentsToChildren().get(parent).remove(job); + } + jobDag.getChildrenToParents().remove(job); + jobDag.getParentsToChildren().remove(job); + jobDag.getAllNodes().remove(job); + try { + currentData.setSimpleField(WorkflowConfig.DAG, jobDag.toJson()); + } catch (Exception e) { + LOG.error("Could not update DAG for job: " + job, e); + } + } else { + LOG.error("Could not update DAG for job: " + job + " ZNRecord is null."); + } + return currentData; + } + }; + accessor.getBaseDataAccessor().update(workflowKey.getPath(), dagRemover, + AccessOption.PERSISTENT); + + // Delete job configs. + PropertyKey cfgKey = TaskUtil.getWorkflowConfigKey(accessor, job); + if (accessor.getProperty(cfgKey) != null) { + if (!accessor.removeProperty(cfgKey)) { + LOG.error(String.format( + "Error occurred while trying to clean up job %s. Failed to remove node %s from Helix.", + job, cfgKey)); + } + } + + // Delete job context + // For recurring workflow, it's OK if the node doesn't exist. + String propStoreKey = TaskUtil.getWorkflowContextKey(job); + if (!_manager.getHelixPropertyStore().remove(propStoreKey, AccessOption.PERSISTENT)) { + LOG.warn(String.format( + "Error occurred while trying to clean up job %s. Failed to remove node %s from Helix.", + job, propStoreKey)); + } + + LOG.info(String.format("Successfully cleaned up job context %s.", job)); + + _scheduledRebalancer.removeScheduledRebalance(job); + } + + @Override + public IdealState computeNewIdealState(String resourceName, IdealState currentIdealState, + CurrentStateOutput currentStateOutput, ClusterDataCache clusterData) { + // Nothing to do here with workflow resource. + return currentIdealState; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `admin.getResourceIdealState(TaskRebalancer._manager.getClusterName(),jobConfig.getTargetResource())` could be null and is dereferenced at line 168. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WorkflowRebalancer.scheduleSingleJob(String,JobConfig) + +### Procedure Id: +org.apache.helix.task.WorkflowRebalancer.scheduleSingleJob(java.lang.String,org.apache.helix.task.Jo.a9c9d069f7c6046b827b01fb147e6d9e + +### File: +helix-core/src/main/java/org/apache/helix/task/WorkflowRebalancer.java + +### Key: +WorkflowRebalancer.java|scheduleSingleJob|NULL_DEREFERENCE + +### Node Key: +50cb5ef8465ad6b6a77b806e5d8dd53e + +### Hash: +6f1669f78223e1a8b897ab78c2995f5a + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9629/instruction.md b/inferredbugs-9629/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7e248ba9f2068111abbaa7596af296df0a27fe0 --- /dev/null +++ b/inferredbugs-9629/instruction.md @@ -0,0 +1,545 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 83 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.messaging.handling; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.helix.HelixAdmin; +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixDefinedState; +import org.apache.helix.HelixException; +import org.apache.helix.HelixManager; +import org.apache.helix.HelixRollbackException; +import org.apache.helix.NotificationContext; +import org.apache.helix.NotificationContext.MapKey; +import org.apache.helix.PropertyKey; +import org.apache.helix.PropertyKey.Builder; +import org.apache.helix.zookeeper.datamodel.ZNRecord; +import org.apache.helix.zookeeper.datamodel.ZNRecordBucketizer; +import org.apache.helix.zookeeper.datamodel.ZNRecordDelta; +import org.apache.helix.zookeeper.datamodel.ZNRecordDelta.MergeOperation; +import org.apache.helix.model.CurrentState; +import org.apache.helix.model.Message; +import org.apache.helix.model.Message.Attributes; +import org.apache.helix.participant.statemachine.StateModel; +import org.apache.helix.participant.statemachine.StateModelFactory; +import org.apache.helix.participant.statemachine.StateModelParser; +import org.apache.helix.participant.statemachine.StateTransitionError; +import org.apache.helix.util.StatusUpdateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HelixStateTransitionHandler extends MessageHandler { + public static class HelixStateMismatchException extends Exception { + public HelixStateMismatchException(String info) { + super(info); + } + } + + /** + * If current state == toState in message, this is considered as Duplicated state transition + */ + public static class HelixDuplicatedStateTransitionException extends Exception { + public HelixDuplicatedStateTransitionException(String info) { + super(info); + } + } + + private static final Logger logger = LoggerFactory.getLogger(HelixStateTransitionHandler.class); + private final StateModel _stateModel; + StatusUpdateUtil _statusUpdateUtil; + private final StateModelParser _transitionMethodFinder; + private final CurrentState _currentStateDelta; + private final HelixManager _manager; + private final StateModelFactory _stateModelFactory; + volatile boolean _isTimeout = false; + + public HelixStateTransitionHandler(StateModelFactory stateModelFactory, + StateModel stateModel, Message message, NotificationContext context, + CurrentState currentStateDelta) { + super(message, context); + _stateModel = stateModel; + _statusUpdateUtil = new StatusUpdateUtil(); + _transitionMethodFinder = new StateModelParser(); + _currentStateDelta = currentStateDelta; + _manager = _notificationContext.getManager(); + _stateModelFactory = stateModelFactory; + } + + void preHandleMessage() throws Exception { + if (!_message.isValid()) { + String errorMessage = "Invalid Message, ensure that message: " + _message + + " has all the required fields: " + Arrays.toString(Message.Attributes.values()); + + _statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, errorMessage, + _manager); + logger.error(errorMessage); + throw new HelixException(errorMessage); + } + + logger.info("handling message: " + _message.getMsgId() + " transit " + + _message.getResourceName() + "." + _message.getPartitionName() + "|" + + _message.getPartitionNames() + " from:" + _message.getFromState() + " to:" + + _message.getToState() + ", relayedFrom: " + _message.getRelaySrcHost()); + + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + + String partitionName = _message.getPartitionName(); + String fromState = _message.getFromState(); + String toState = _message.getToState(); + + // Verify the fromState and current state of the stateModel + // getting current state from state model will provide most up-to-date + // current state. In case current state is null, partition is in initial + // state and we are setting it in current state + String state = _stateModel.getCurrentState() != null ? _stateModel.getCurrentState() + : _currentStateDelta.getState(partitionName); + + // Set start time right before invoke client logic + _currentStateDelta.setStartTime(_message.getPartitionName(), System.currentTimeMillis()); + + Exception err = null; + if (toState.equalsIgnoreCase(state)) { + // To state equals current state, we can just ignore the message + err = new HelixDuplicatedStateTransitionException( + String.format("Partition %s current state is same as toState (%s->%s) from message.", + partitionName, fromState, toState)); + } else if (fromState != null && !fromState.equals("*") && !fromState.equalsIgnoreCase(state)) { + // If current state is neither toState nor fromState in message, there is a problem + err = new HelixStateMismatchException(String.format( + "Current state of stateModel does not match the fromState in Message, CurrentState: %s, Message: %s->%s, Partition: %s, from: %s, to: %s", + state, fromState, toState, partitionName, _message.getMsgSrc(), _message.getTgtName())); + } + + if (err != null) { + _statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, err.getMessage(), + _manager); + logger.error(err.getMessage()); + throw err; + } + + // Reset the REQUESTED_STATE property if it exists. + try { + String instance = _manager.getInstanceName(); + String sessionId = _message.getTgtSessionId(); + String resource = _message.getResourceName(); + ZNRecordBucketizer bucketizer = new ZNRecordBucketizer(_message.getBucketSize()); + PropertyKey key = accessor.keyBuilder().currentState(instance, sessionId, resource, + bucketizer.getBucketName(partitionName)); + ZNRecord rec = new ZNRecord(resource); + Map map = new TreeMap(); + map.put(CurrentState.CurrentStateProperty.REQUESTED_STATE.name(), null); + rec.getMapFields().put(partitionName, map); + ZNRecordDelta delta = new ZNRecordDelta(rec, ZNRecordDelta.MergeOperation.SUBTRACT); + List deltaList = new ArrayList(); + deltaList.add(delta); + CurrentState currStateUpdate = new CurrentState(resource); + currStateUpdate.setDeltaList(deltaList); + + // Update the ZK current state of the node + if (!accessor.updateProperty(key, currStateUpdate)) { + logger.error("Fails to persist current state back to ZK for resource " + resource + + " partition: " + partitionName); + } + } catch (Exception e) { + logger.error("Error when removing " + CurrentState.CurrentStateProperty.REQUESTED_STATE.name() + + " from current state.", e); + StateTransitionError error = + new StateTransitionError(ErrorType.FRAMEWORK, ErrorCode.ERROR, e); + _stateModel.rollbackOnError(_message, _notificationContext, error); + _statusUpdateUtil.logError( + _message, HelixStateTransitionHandler.class, e, "Error when removing " + + CurrentState.CurrentStateProperty.REQUESTED_STATE.name() + " from current state.", + _manager); + } + } + + void postHandleMessage() { + HelixTaskResult taskResult = + (HelixTaskResult) _notificationContext.get(MapKey.HELIX_TASK_RESULT.toString()); + Exception exception = taskResult.getException(); + + String partitionKey = _message.getPartitionName(); + String resource = _message.getResourceName(); + String sessionId = _message.getTgtSessionId(); + String instanceName = _manager.getInstanceName(); + + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + Builder keyBuilder = accessor.keyBuilder(); + + int bucketSize = _message.getBucketSize(); + ZNRecordBucketizer bucketizer = new ZNRecordBucketizer(bucketSize); + + // No need to sync on manager, we are cancel executor in expiry session before start executor in + // new session + // sessionId might change when we update the state model state. + // for zk current state it is OK as we have the per-session current state node + if (!_message.getTgtSessionId().equals(_manager.getSessionId())) { + logger.warn("Session id has changed. Skip postExecutionMessage. Old session " + + _message.getExecutionSessionId() + " , new session : " + _manager.getSessionId()); + return; + } + + // Set the INFO property and mark the end time, previous state of the state transition + _currentStateDelta.setInfo(partitionKey, taskResult.getInfo()); + _currentStateDelta.setEndTime(partitionKey, taskResult.getCompleteTime()); + _currentStateDelta.setPreviousState(partitionKey, _message.getFromState()); + + // add host name this state transition is triggered by. + if (Message.MessageType.RELAYED_MESSAGE.name().equals(_message.getMsgSubType())) { + _currentStateDelta.setTriggerHost(partitionKey, _message.getRelaySrcHost()); + } else { + _currentStateDelta.setTriggerHost(partitionKey, _message.getMsgSrc()); + } + + if (taskResult.isSuccess()) { + // String fromState = message.getFromState(); + String toState = _message.getToState(); + _currentStateDelta.setState(partitionKey, toState); + + if (toState.equalsIgnoreCase(HelixDefinedState.DROPPED.toString())) { + // for "OnOfflineToDROPPED" message, we need to remove the resource key record + // from the current state of the instance because the resource key is dropped. + // In the state model it will be stayed as "OFFLINE", which is OK. + ZNRecord rec = new ZNRecord(_currentStateDelta.getId()); + rec.getMapFields().put(partitionKey, null); + ZNRecordDelta delta = new ZNRecordDelta(rec, MergeOperation.SUBTRACT); + + List deltaList = new ArrayList(); + deltaList.add(delta); + _currentStateDelta.setDeltaList(deltaList); + _stateModelFactory.removeStateModel(resource, partitionKey); + } else { + // if the partition is not to be dropped, update _stateModel to the TO_STATE + _stateModel.updateState(toState); + } + } else if (taskResult.isCancelled()) { + // Cancelled message does not need current state update + return; + } else { + if (exception instanceof HelixStateMismatchException) { + // if fromState mismatch, set current state on zk to stateModel's current state + logger.warn("Force CurrentState on Zk to be stateModel's CurrentState. partitionKey: " + + partitionKey + ", currentState: " + _stateModel.getCurrentState() + ", message: " + + _message); + _currentStateDelta.setState(partitionKey, _stateModel.getCurrentState()); + } else { + StateTransitionError error = + new StateTransitionError(ErrorType.INTERNAL, ErrorCode.ERROR, exception); + if (exception instanceof InterruptedException) { + if (_isTimeout) { + error = new StateTransitionError(ErrorType.INTERNAL, ErrorCode.TIMEOUT, exception); + } else { + // State transition interrupted but not caused by timeout. Keep the current + // state in this case + logger.error( + "State transition interrupted but not timeout. Not updating state. Partition : " + + _message.getPartitionName() + " MsgId : " + _message.getMsgId()); + return; + } + } + _stateModel.rollbackOnError(_message, _notificationContext, error); + _currentStateDelta.setState(partitionKey, HelixDefinedState.ERROR.toString()); + _stateModel.updateState(HelixDefinedState.ERROR.toString()); + + // if we have errors transit from ERROR state, disable the partition + if (_message.getFromState().equalsIgnoreCase(HelixDefinedState.ERROR.toString())) { + disablePartition(); + } + } + } + + try { + // Update the ZK current state of the node + PropertyKey key = keyBuilder.currentState(instanceName, sessionId, resource, + bucketizer.getBucketName(partitionKey)); + if (_message.getAttribute(Attributes.PARENT_MSG_ID) == null) { + // normal message + if (!accessor.updateProperty(key, _currentStateDelta)) { + throw new HelixException("Fails to persist current state back to ZK for resource " + + resource + " partition: " + _message.getPartitionName()); + } + } else { + // sub-message of a batch message + ConcurrentHashMap csUpdateMap = + (ConcurrentHashMap) _notificationContext + .get(MapKey.CURRENT_STATE_UPDATE.toString()); + csUpdateMap.put(partitionKey, new CurrentStateUpdate(key, _currentStateDelta)); + } + } catch (Exception e) { + logger.error("Error when updating current-state ", e); + StateTransitionError error = + new StateTransitionError(ErrorType.FRAMEWORK, ErrorCode.ERROR, e); + _stateModel.rollbackOnError(_message, _notificationContext, error); + _statusUpdateUtil.logError(_message, HelixStateTransitionHandler.class, e, + "Error when update current-state ", _manager); + } + } + + void disablePartition() { + String instanceName = _manager.getInstanceName(); + String resourceName = _message.getResourceName(); + String partitionName = _message.getPartitionName(); + String clusterName = _manager.getClusterName(); + HelixAdmin admin = _manager.getClusterManagmentTool(); + admin.enablePartition(false, clusterName, instanceName, resourceName, + Arrays.asList(partitionName)); + logger.info("error in transit from ERROR to " + _message.getToState() + " for partition: " + + partitionName + ". disable it on " + instanceName); + + } + + @Override + public HelixTaskResult handleMessage() { + NotificationContext context = _notificationContext; + Message message = _message; + + synchronized (_stateModel) { + HelixTaskResult taskResult = new HelixTaskResult(); + HelixManager manager = context.getManager(); + + _statusUpdateUtil.logInfo(message, HelixStateTransitionHandler.class, + "Message handling task begin execute", manager); + message.setExecuteStartTimeStamp(System.currentTimeMillis()); + + try { + preHandleMessage(); + invoke(manager, context, taskResult, message); + } catch (HelixDuplicatedStateTransitionException e) { + // Duplicated state transition problem is fine + taskResult.setSuccess(true); + taskResult.setMessage(e.toString()); + taskResult.setInfo(e.getMessage()); + } catch (HelixStateMismatchException e) { + // Simply log error and return from here if State mismatch. + // The current state of the state model is intact. + taskResult.setSuccess(false); + taskResult.setMessage(e.toString()); + taskResult.setException(e); + } catch (Exception e) { + String errorMessage = + "Exception while executing a state transition task " + message.getPartitionName(); + logger.error(errorMessage, e); + if (e.getCause() != null && e.getCause() instanceof InterruptedException) { + e = (InterruptedException) e.getCause(); + } + + if (e instanceof HelixRollbackException + || (e.getCause() != null && e.getCause() instanceof HelixRollbackException)) { + // TODO : Support cancel to any state + logger.info("Rollback happened of state transition on resource \"" + + _message.getResourceName() + "\" partition \"" + _message.getPartitionName() + + "\" from \"" + _message.getFromState() + "\" to \"" + _message.getToState() + "\""); + taskResult.setCancelled(true); + } else { + _statusUpdateUtil.logError(message, HelixStateTransitionHandler.class, e, errorMessage, + manager); + taskResult.setSuccess(false); + taskResult.setMessage(e.toString()); + taskResult.setException(e); + taskResult.setInterrupted(e instanceof InterruptedException); + } + } + + taskResult.setCompleteTime(System.currentTimeMillis()); + // add task result to context for postHandling + context.add(MapKey.HELIX_TASK_RESULT.toString(), taskResult); + postHandleMessage(); + + return taskResult; + } + } + + private void invoke(HelixManager manager, NotificationContext context, HelixTaskResult taskResult, + Message message) throws IllegalAccessException, InvocationTargetException, + InterruptedException, HelixRollbackException { + _statusUpdateUtil.logInfo(message, HelixStateTransitionHandler.class, + "Message handling invoking", manager); + + // by default, we invoke state transition function in state model + Method methodToInvoke = null; + String fromState = message.getFromState(); + String toState = message.getToState(); + methodToInvoke = _transitionMethodFinder.getMethodForTransition(_stateModel.getClass(), + fromState, toState, new Class[] { + Message.class, NotificationContext.class + }); + if (methodToInvoke != null) { + logger.info(String.format( + "Instance %s, partition %s received state transition from %s to %s on session %s, message id: %s", + message.getTgtName(), message.getPartitionName(), message.getFromState(), + message.getToState(), message.getTgtSessionId(), message.getMsgId())); + + if (_cancelled) { + throw new HelixRollbackException(String.format( + "Instance %s, partition %s state transition from %s to %s on session %s has been cancelled, message id: %s", + message.getTgtName(), message.getPartitionName(), message.getFromState(), + message.getToState(), message.getTgtSessionId(), message.getMsgId())); + } + + Object result = methodToInvoke.invoke(_stateModel, new Object[] { + message, context + }); + taskResult.setSuccess(true); + String resultStr; + if (result == null || result instanceof Void) { + resultStr = ""; + } else { + resultStr = result.toString(); + } + taskResult.setInfo(resultStr); + } else { + String errorMessage = "Unable to find method for transition from " + fromState + " to " + + toState + " in " + _stateModel.getClass(); + logger.error(errorMessage); + taskResult.setSuccess(false); + taskResult.setInfo(errorMessage); + _statusUpdateUtil.logError(message, HelixStateTransitionHandler.class, errorMessage, manager); + } + } + + @Override + public void onError(Exception e, ErrorCode code, ErrorType type) { + HelixDataAccessor accessor = _manager.getHelixDataAccessor(); + Builder keyBuilder = accessor.keyBuilder(); + String instanceName = _manager.getInstanceName(); + String resourceName = _message.getResourceName(); + String partition = _message.getPartitionName(); + + // All internal error has been processed already, so we can skip them + if (type == ErrorType.INTERNAL) { + logger.error("Skip internal error. errCode: " + code + ", errMsg: " + e.getMessage()); + return; + } + + try { + // set current state to ERROR for the partition + // if the transition is not canceled, it should go into error state + if (code == ErrorCode.ERROR) { + CurrentState currentStateDelta = new CurrentState(resourceName); + currentStateDelta.setState(partition, HelixDefinedState.ERROR.toString()); + _stateModel.updateState(HelixDefinedState.ERROR.toString()); + + // if transit from ERROR state, disable the partition + if (_message.getFromState().equalsIgnoreCase(HelixDefinedState.ERROR.toString())) { + disablePartition(); + } + + if (!accessor.updateProperty( + keyBuilder.currentState(instanceName, _message.getTgtSessionId(), resourceName), + currentStateDelta)) { + logger.error("Fails to persist ERROR current state to ZK for resource " + resourceName + + " partition: " + partition); + } + } + } finally { + StateTransitionError error = new StateTransitionError(type, code, e); + _stateModel.rollbackOnError(_message, _notificationContext, error); + } + + } + + @Override + public void onTimeout() { + _isTimeout = true; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.messaging.handling.HelixStateTransitionHandler.preHandleMessage` indirectly reads without synchronization from `this.org.apache.helix.messaging.handling.HelixStateTransitionHandler._stateModel.org.apache.helix.participant.statemachine.StateModel._currentState`. Potentially races with write in method `HelixStateTransitionHandler.handleMessage()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void HelixStateTransitionHandler.preHandleMessage() + +### Procedure Id: +org.apache.helix.messaging.handling.HelixStateTransitionHandler.preHandleMessage():void.422a93b1c324481e3c94a0ca0a98f58f + +### File: +helix-core/src/main/java/org/apache/helix/messaging/handling/HelixStateTransitionHandler.java + +### Key: +HelixStateTransitionHandler.java|preHandleMessage|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +0f268efbb67a44434ebe35d7a24fd0be + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9642/instruction.md b/inferredbugs-9642/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68f652fbce12a5cf036f001e81b51004732411c7 --- /dev/null +++ b/inferredbugs-9642/instruction.md @@ -0,0 +1,905 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 76 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.manager.zk; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantLock; + +import org.I0Itec.zkclient.DataUpdater; +import org.I0Itec.zkclient.IZkChildListener; +import org.I0Itec.zkclient.IZkDataListener; +import org.I0Itec.zkclient.exception.ZkNoNodeException; +import org.I0Itec.zkclient.serialize.ZkSerializer; +import org.apache.helix.AccessOption; +import org.apache.helix.HelixException; +import org.apache.helix.manager.zk.ZkAsyncCallbacks.CreateCallbackHandler; +import org.apache.helix.manager.zk.ZkBaseDataAccessor.RetCode; +import org.apache.helix.manager.zk.client.HelixZkClient; +import org.apache.helix.manager.zk.client.SharedZkClientFactory; +import org.apache.helix.store.HelixPropertyListener; +import org.apache.helix.store.HelixPropertyStore; +import org.apache.helix.store.zk.ZNode; +import org.apache.helix.util.PathUtils; +import org.apache.zookeeper.KeeperException.Code; +import org.apache.zookeeper.data.Stat; +import org.apache.zookeeper.server.DataTree; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class ZkCacheBaseDataAccessor implements HelixPropertyStore { + private static final Logger LOG = LoggerFactory.getLogger(ZkCacheBaseDataAccessor.class); + + protected WriteThroughCache _wtCache; + protected ZkCallbackCache _zkCache; + + final ZkBaseDataAccessor _baseAccessor; + final Map> _cacheMap; + + final String _chrootPath; + final List _wtCachePaths; + final List _zkCachePaths; + + final HelixGroupCommit _groupCommit = new HelixGroupCommit(); + + // fire listeners + private final ReentrantLock _eventLock = new ReentrantLock(); + private ZkCacheEventThread _eventThread; + + private HelixZkClient _zkclient = null; + + public ZkCacheBaseDataAccessor(ZkBaseDataAccessor baseAccessor, List wtCachePaths) { + this(baseAccessor, null, wtCachePaths, null); + } + + public ZkCacheBaseDataAccessor(ZkBaseDataAccessor baseAccessor, String chrootPath, + List wtCachePaths, List zkCachePaths) { + _baseAccessor = baseAccessor; + + if (chrootPath == null || chrootPath.equals("/")) { + _chrootPath = null; + } else { + PathUtils.validatePath(chrootPath); + _chrootPath = chrootPath; + } + + _wtCachePaths = wtCachePaths; + _zkCachePaths = zkCachePaths; + + // TODO: need to make sure no overlap between wtCachePaths and zkCachePaths + // TreeMap key is ordered by key string length, so more general (i.e. short) prefix + // comes first + _cacheMap = new TreeMap<>(new Comparator() { + @Override + public int compare(String o1, String o2) { + int len1 = o1.split("/").length; + int len2 = o2.split("/").length; + return len1 - len2; + } + }); + + start(); + } + + public ZkCacheBaseDataAccessor(String zkAddress, ZkSerializer serializer, String chrootPath, + List wtCachePaths, List zkCachePaths) { + this(zkAddress, serializer, chrootPath, wtCachePaths, zkCachePaths, null, null); + } + + public ZkCacheBaseDataAccessor(String zkAddress, ZkSerializer serializer, String chrootPath, + List wtCachePaths, List zkCachePaths, String monitorType, String monitorkey) { + HelixZkClient.ZkClientConfig clientConfig = new HelixZkClient.ZkClientConfig(); + clientConfig.setZkSerializer(serializer) + .setMonitorType(monitorType) + .setMonitorKey(monitorkey); + _zkclient = SharedZkClientFactory.getInstance() + .buildZkClient(new HelixZkClient.ZkConnectionConfig(zkAddress), clientConfig); + + _zkclient.waitUntilConnected(HelixZkClient.DEFAULT_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS); + _baseAccessor = new ZkBaseDataAccessor<>(_zkclient); + + if (chrootPath == null || chrootPath.equals("/")) { + _chrootPath = null; + } else { + PathUtils.validatePath(chrootPath); + _chrootPath = chrootPath; + } + + _wtCachePaths = wtCachePaths; + _zkCachePaths = zkCachePaths; + + // TODO: need to make sure no overlap between wtCachePaths and zkCachePaths + // TreeMap key is ordered by key string length, so more general (i.e. short) prefix + // comes first + _cacheMap = new TreeMap<>(new Comparator() { + @Override + public int compare(String o1, String o2) { + int len1 = o1.split("/").length; + int len2 = o2.split("/").length; + return len1 - len2; + } + }); + + start(); + } + + private String prependChroot(String clientPath) { + PathUtils.validatePath(clientPath); + + if (_chrootPath != null) { + // handle clientPath = "/" + if (clientPath.length() == 1) { + return _chrootPath; + } + return _chrootPath + clientPath; + } else { + return clientPath; + } + } + + private List prependChroot(List clientPaths) { + List serverPaths = new ArrayList(); + for (String clientPath : clientPaths) { + serverPaths.add(prependChroot(clientPath)); + } + return serverPaths; + } + + /** + * find the first path in paths that is a descendant + */ + private String firstCachePath(List paths) { + for (String cachePath : _cacheMap.keySet()) { + for (String path : paths) { + if (path.startsWith(cachePath)) { + return path; + } + } + } + return null; + } + + private Cache getCache(String path) { + for (String cachePath : _cacheMap.keySet()) { + if (path.startsWith(cachePath)) { + return _cacheMap.get(cachePath); + } + } + + return null; + } + + private Cache getCache(List paths) { + Cache cache = null; + for (String path : paths) { + for (String cachePath : _cacheMap.keySet()) { + if (cache == null && path.startsWith(cachePath)) { + cache = _cacheMap.get(cachePath); + } else if (cache != null && cache != _cacheMap.get(cachePath)) { + throw new IllegalArgumentException( + "Couldn't do cross-cache async operations. paths: " + paths); + } + } + } + + return cache; + } + + private void updateCache(Cache cache, List createPaths, boolean success, + String updatePath, T data, Stat stat) { + if (createPaths == null || createPaths.isEmpty()) { + if (success) { + cache.update(updatePath, data, stat); + } + } else { + String firstPath = firstCachePath(createPaths); + if (firstPath != null) { + cache.updateRecursive(firstPath); + } + } + } + + @Override + public boolean create(String path, T data, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + if (cache != null) { + try { + cache.lockWrite(); + ZkBaseDataAccessor.AccessResult result = + _baseAccessor.doCreate(serverPath, data, options); + boolean success = (result._retCode == RetCode.OK); + + updateCache(cache, result._pathCreated, success, serverPath, data, ZNode.ZERO_STAT); + + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _baseAccessor.create(serverPath, data, options); + } + + @Override + public boolean set(String path, T data, int options) { + return set(path, data, -1, options); + } + + @Override + public boolean set(String path, T data, int expectVersion, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + boolean success = false; + try { + if (cache != null) { + cache.lockWrite(); + ZkBaseDataAccessor.AccessResult result = + _baseAccessor.doSet(serverPath, data, expectVersion, options); + success = result._retCode == RetCode.OK; + + updateCache(cache, result._pathCreated, success, serverPath, data, result._stat); + } else { + // no cache + success = _baseAccessor.set(serverPath, data, expectVersion, options); + } + } catch (Exception e) { + } finally { + if (cache != null) { + cache.unlockWrite(); + } + } + return success; + } + + @Override + public boolean update(String path, DataUpdater updater, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + + if (cache != null) { + try { + cache.lockWrite(); + ZkBaseDataAccessor.AccessResult result = + _baseAccessor.doUpdate(serverPath, updater, options); + boolean success = (result._retCode == RetCode.OK); + updateCache(cache, result._pathCreated, success, serverPath, result._updatedValue, + result._stat); + + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _groupCommit.commit(_baseAccessor, options, serverPath, updater); + // return _baseAccessor.update(serverPath, updater, options); + } + + @Override + public boolean exists(String path, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + if (cache != null) { + boolean exists = cache.exists(serverPath); + if (exists) { + return true; + } + } + + // if not exists in cache, always fall back to zk + return _baseAccessor.exists(serverPath, options); + } + + @Override + public boolean remove(String path, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + if (cache != null) { + try { + cache.lockWrite(); + + boolean success = _baseAccessor.remove(serverPath, options); + if (success) { + cache.purgeRecursive(serverPath); + } + + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _baseAccessor.remove(serverPath, options); + } + + @Override + public T get(String path, Stat stat, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + if (cache != null) { + T record = null; + ZNode znode = cache.get(serverPath); + + if (znode != null) { + // TODO: shall return a deep copy instead of reference + record = ((T) znode.getData()); + if (stat != null) { + DataTree.copyStat(znode.getStat(), stat); + } + return record; + + } else { + // if cache miss, fall back to zk and update cache + try { + cache.lockWrite(); + record = _baseAccessor + .get(serverPath, stat, options | AccessOption.THROW_EXCEPTION_IFNOTEXIST); + cache.update(serverPath, record, stat); + } catch (ZkNoNodeException e) { + if (AccessOption.isThrowExceptionIfNotExist(options)) { + throw e; + } + } finally { + cache.unlockWrite(); + } + + return record; + } + } + + // no cache + return _baseAccessor.get(serverPath, stat, options); + } + + @Override + public Stat getStat(String path, int options) { + String clientPath = path; + String serverPath = prependChroot(clientPath); + + Cache cache = getCache(serverPath); + if (cache != null) { + Stat stat = new Stat(); + ZNode znode = cache.get(serverPath); + + if (znode != null) { + return znode.getStat(); + + } else { + // if cache miss, fall back to zk and update cache + try { + cache.lockWrite(); + T data = _baseAccessor.get(serverPath, stat, options); + cache.update(serverPath, data, stat); + } catch (ZkNoNodeException e) { + return null; + } finally { + cache.unlockWrite(); + } + + return stat; + } + } + + // no cache + return _baseAccessor.getStat(serverPath, options); + } + + @Override + public boolean[] createChildren(List paths, List records, int options) { + final int size = paths.size(); + List serverPaths = prependChroot(paths); + + Cache cache = getCache(serverPaths); + if (cache != null) { + try { + cache.lockWrite(); + boolean[] needCreate = new boolean[size]; + Arrays.fill(needCreate, true); + List> pathsCreatedList = + new ArrayList>(Collections.>nCopies(size, null)); + CreateCallbackHandler[] createCbList = + _baseAccessor.create(serverPaths, records, needCreate, pathsCreatedList, options); + + boolean[] success = new boolean[size]; + for (int i = 0; i < size; i++) { + CreateCallbackHandler cb = createCbList[i]; + success[i] = (Code.get(cb.getRc()) == Code.OK); + + updateCache(cache, pathsCreatedList.get(i), success[i], serverPaths.get(i), + records.get(i), ZNode.ZERO_STAT); + } + + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _baseAccessor.createChildren(serverPaths, records, options); + } + + @Override + public boolean[] setChildren(List paths, List records, int options) { + final int size = paths.size(); + List serverPaths = prependChroot(paths); + + Cache cache = getCache(serverPaths); + if (cache != null) { + try { + cache.lockWrite(); + List setStats = new ArrayList(); + List> pathsCreatedList = + new ArrayList>(Collections.>nCopies(size, null)); + boolean[] success = + _baseAccessor.set(serverPaths, records, pathsCreatedList, setStats, options); + + for (int i = 0; i < size; i++) { + updateCache(cache, pathsCreatedList.get(i), success[i], serverPaths.get(i), + records.get(i), setStats.get(i)); + } + + return success; + } finally { + cache.unlockWrite(); + } + } + + return _baseAccessor.setChildren(serverPaths, records, options); + } + + @Override + public boolean[] updateChildren(List paths, List> updaters, int options) { + final int size = paths.size(); + List serverPaths = prependChroot(paths); + + Cache cache = getCache(serverPaths); + if (cache != null) { + try { + cache.lockWrite(); + + List setStats = new ArrayList(); + boolean[] success = new boolean[size]; + List> pathsCreatedList = + new ArrayList>(Collections.>nCopies(size, null)); + List updateData = + _baseAccessor.update(serverPaths, updaters, pathsCreatedList, setStats, options); + + // System.out.println("updateChild: "); + // for (T data : updateData) + // { + // System.out.println(data); + // } + + for (int i = 0; i < size; i++) { + success[i] = (updateData.get(i) != null); + updateCache(cache, pathsCreatedList.get(i), success[i], serverPaths.get(i), + updateData.get(i), setStats.get(i)); + } + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _baseAccessor.updateChildren(serverPaths, updaters, options); + } + + // TODO: change to use async_exists + @Override + public boolean[] exists(List paths, int options) { + final int size = paths.size(); + + boolean exists[] = new boolean[size]; + for (int i = 0; i < size; i++) { + exists[i] = exists(paths.get(i), options); + } + return exists; + } + + @Override + public boolean[] remove(List paths, int options) { + final int size = paths.size(); + List serverPaths = prependChroot(paths); + + Cache cache = getCache(serverPaths); + if (cache != null) { + try { + cache.lockWrite(); + + boolean[] success = _baseAccessor.remove(serverPaths, options); + + for (int i = 0; i < size; i++) { + if (success[i]) { + cache.purgeRecursive(serverPaths.get(i)); + } + } + return success; + } finally { + cache.unlockWrite(); + } + } + + // no cache + return _baseAccessor.remove(serverPaths, options); + } + + @Override + public List get(List paths, List stats, int options) { + return get(paths, stats, options, false); + } + + @Override + public List get(List paths, List stats, int options, boolean throwException) + throws HelixException { + if (paths == null || paths.isEmpty()) { + return Collections.emptyList(); + } + + final int size = paths.size(); + List serverPaths = prependChroot(paths); + + List records = new ArrayList(Collections.nCopies(size, null)); + List readStats = new ArrayList(Collections.nCopies(size, null)); + + boolean needRead = false; + boolean needReads[] = new boolean[size]; // init to false + + Cache cache = getCache(serverPaths); + if (cache != null) { + try { + cache.lockRead(); + for (int i = 0; i < size; i++) { + ZNode zNode = cache.get(serverPaths.get(i)); + if (zNode != null) { + // TODO: shall return a deep copy instead of reference + records.set(i, (T) zNode.getData()); + readStats.set(i, zNode.getStat()); + } else { + needRead = true; + needReads[i] = true; + } + } + } finally { + cache.unlockRead(); + } + + // cache miss, fall back to zk and update cache + if (needRead) { + cache.lockWrite(); + try { + List readRecords = + _baseAccessor.get(serverPaths, readStats, needReads, throwException); + for (int i = 0; i < size; i++) { + if (needReads[i]) { + records.set(i, readRecords.get(i)); + cache.update(serverPaths.get(i), readRecords.get(i), readStats.get(i)); + } + } + } finally { + cache.unlockWrite(); + } + } + + if (stats != null) { + stats.clear(); + stats.addAll(readStats); + } + + return records; + } + + // no cache + return _baseAccessor.get(serverPaths, stats, options, throwException); + } + + // TODO: add cache + @Override + public Stat[] getStats(List paths, int options) { + List serverPaths = prependChroot(paths); + return _baseAccessor.getStats(serverPaths, options); + } + + @Override + public List getChildNames(String parentPath, int options) { + String serverParentPath = prependChroot(parentPath); + + Cache cache = getCache(serverParentPath); + if (cache != null) { + // System.out.println("zk-cache"); + ZNode znode = cache.get(serverParentPath); + + if (znode != null && znode.getChildSet() != Collections.emptySet()) { + // System.out.println("zk-cache-hit: " + parentPath); + List childNames = new ArrayList(znode.getChildSet()); + Collections.sort(childNames); + return childNames; + } else { + // System.out.println("zk-cache-miss"); + try { + cache.lockWrite(); + + List childNames = _baseAccessor.getChildNames(serverParentPath, options); + // System.out.println("\t--" + childNames); + cache.addToParentChildSet(serverParentPath, childNames); + + return childNames; + } finally { + cache.unlockWrite(); + } + } + } + + // no cache + return _baseAccessor.getChildNames(serverParentPath, options); + } + + @Override + public List getChildren(String parentPath, List stats, int options) { + List childNames = getChildNames(parentPath, options); + if (childNames == null) { + return null; + } + + List paths = new ArrayList<>(); + for (String childName : childNames) { + String path = parentPath.equals("/") ? "/" + childName : parentPath + "/" + childName; + paths.add(path); + } + + return get(paths, stats, options); + } + + @Override + public List getChildren(String parentPath, List stats, int options, int retryCount, + int retryInterval) throws HelixException { + return getChildren(parentPath, stats, options); + } + + @Override + public void subscribeDataChanges(String path, IZkDataListener listener) { + String serverPath = prependChroot(path); + + _baseAccessor.subscribeDataChanges(serverPath, listener); + } + + @Override + public void unsubscribeDataChanges(String path, IZkDataListener listener) { + String serverPath = prependChroot(path); + + _baseAccessor.unsubscribeDataChanges(serverPath, listener); + } + + @Override + public List subscribeChildChanges(String path, IZkChildListener listener) { + String serverPath = prependChroot(path); + + return _baseAccessor.subscribeChildChanges(serverPath, listener); + } + + @Override + public void unsubscribeChildChanges(String path, IZkChildListener listener) { + String serverPath = prependChroot(path); + + _baseAccessor.unsubscribeChildChanges(serverPath, listener); + } + + @Override + public void subscribe(String parentPath, HelixPropertyListener listener) { + String serverPath = prependChroot(parentPath); + _zkCache.subscribe(serverPath, listener); + } + + @Override + public void unsubscribe(String parentPath, HelixPropertyListener listener) { + String serverPath = prependChroot(parentPath); + _zkCache.unsubscribe(serverPath, listener); + } + + @Override + public void start() { + + LOG.info("START: Init ZkCacheBaseDataAccessor: " + _chrootPath + ", " + _wtCachePaths + ", " + + _zkCachePaths); + + // start event thread + try { + _eventLock.lockInterruptibly(); + if (_eventThread != null) { + LOG.warn(_eventThread + " has already started"); + } else { + + if (_zkCachePaths == null || _zkCachePaths.isEmpty()) { + LOG.warn("ZkCachePaths is null or empty. Will not start ZkCacheEventThread"); + } else { + LOG.debug("Starting ZkCacheEventThread..."); + + _eventThread = new ZkCacheEventThread(""); + _eventThread.start(); + } + } + } catch (InterruptedException e) { + LOG.error("Current thread is interrupted when starting ZkCacheEventThread. ", e); + } finally { + _eventLock.unlock(); + } + LOG.debug("Start ZkCacheEventThread...done"); + + _wtCache = new WriteThroughCache(_baseAccessor, _wtCachePaths); + _zkCache = new ZkCallbackCache(_baseAccessor, _chrootPath, _zkCachePaths, _eventThread); + + if (_wtCachePaths != null && !_wtCachePaths.isEmpty()) { + for (String path : _wtCachePaths) { + _cacheMap.put(path, _wtCache); + } + } + + if (_zkCachePaths != null && !_zkCachePaths.isEmpty()) { + for (String path : _zkCachePaths) { + _cacheMap.put(path, _zkCache); + } + } + } + + @Override + public void stop() { + try { + _eventLock.lockInterruptibly(); + + if (_zkclient != null) { + _zkclient.close(); + _zkclient = null; + } + + if (_eventThread == null) { + LOG.warn(_eventThread + " has already stopped"); + return; + } + + LOG.debug("Stopping ZkCacheEventThread..."); + _eventThread.interrupt(); + _eventThread.join(2000); + _eventThread = null; + } catch (InterruptedException e) { + LOG.error("Current thread is interrupted when stopping ZkCacheEventThread."); + } finally { + _eventLock.unlock(); + } + + LOG.debug("Stop ZkCacheEventThread...done"); + + } + + @Override + public void reset() { + if (_wtCache != null) { + _wtCache.reset(); + } + + if (_zkCache != null) { + _zkCache.reset(); + } + } + + @Override + public void close() { + if (_zkclient != null) { + _zkclient.close(); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `org.apache.helix.manager.zk.ZkCacheBaseDataAccessor.close` reads without synchronization from `this.org.apache.helix.manager.zk.ZkCacheBaseDataAccessor._zkclient`. Potentially races with write in method `ZkCacheBaseDataAccessor.stop()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ZkCacheBaseDataAccessor.close() + +### Procedure Id: +org.apache.helix.manager.zk.ZkCacheBaseDataAccessor.close():void.b941aa08d339319650d7c0f33b6fc843 + +### File: +helix-core/src/main/java/org/apache/helix/manager/zk/ZkCacheBaseDataAccessor.java + +### Key: +ZkCacheBaseDataAccessor.java|close|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +541f7897007569a8763a8544e8bb2a31 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9645/instruction.md b/inferredbugs-9645/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2758f3f25f2087162cd233302274aca5355dc08 --- /dev/null +++ b/inferredbugs-9645/instruction.md @@ -0,0 +1,228 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** helix +**Bug ID:** 40 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.apache.helix.controller.stages; + +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.helix.HelixDataAccessor; +import org.apache.helix.HelixManager; +import org.apache.helix.PropertyKey; +import org.apache.helix.controller.pipeline.AbstractBaseStage; +import org.apache.helix.model.BuiltInStateModelDefinitions; +import org.apache.helix.model.ClusterConfig; +import org.apache.helix.model.IdealState; +import org.apache.helix.model.MasterSlaveSMD; +import org.apache.helix.model.Partition; +import org.apache.helix.model.Resource; +import org.apache.log4j.Logger; + +/** + * Persist the ResourceAssignment of each resource that went through rebalancing + */ +public class PersistAssignmentStage extends AbstractBaseStage { + private static final Logger LOG = Logger.getLogger(PersistAssignmentStage.class); + + @Override public void process(ClusterEvent event) throws Exception { + LOG.info("START PersistAssignmentStage.process()"); + long startTime = System.currentTimeMillis(); + + ClusterDataCache cache = event.getAttribute("ClusterDataCache"); + ClusterConfig clusterConfig = cache.getClusterConfig(); + + if (clusterConfig.isPersistBestPossibleAssignment()) { + HelixManager helixManager = event.getAttribute("helixmanager"); + HelixDataAccessor accessor = helixManager.getHelixDataAccessor(); + PropertyKey.Builder keyBuilder = accessor.keyBuilder(); + BestPossibleStateOutput bestPossibleAssignments = + event.getAttribute(AttributeName.BEST_POSSIBLE_STATE.toString()); + Map resourceMap = event.getAttribute(AttributeName.RESOURCES.toString()); + + for (String resourceId : bestPossibleAssignments.resourceSet()) { + Resource resource = resourceMap.get(resourceId); + if (resource != null) { + boolean changed = false; + Map> bestPossibleAssignment = + bestPossibleAssignments.getResourceMap(resourceId); + IdealState idealState = cache.getIdealState(resourceId); + if (idealState == null) { + LOG.warn("IdealState not found for resource " + resourceId); + continue; + } + IdealState.RebalanceMode mode = idealState.getRebalanceMode(); + if (!mode.equals(IdealState.RebalanceMode.SEMI_AUTO) && !mode + .equals(IdealState.RebalanceMode.FULL_AUTO)) { + // do not persist assignment for resource in neither semi or full auto. + continue; + } + + //TODO: temporary solution for Espresso/Dbus backcompatible, should remove this. + Map> assignmentToPersist = + convertAssignmentPersisted(resource, idealState, bestPossibleAssignment); + + for (Partition partition : resource.getPartitions()) { + Map instanceMap = assignmentToPersist.get(partition); + Map existInstanceMap = + idealState.getInstanceStateMap(partition.getPartitionName()); + if (instanceMap == null && existInstanceMap == null) { + continue; + } + if (instanceMap == null || existInstanceMap == null || !instanceMap + .equals(existInstanceMap)) { + changed = true; + break; + } + } + if (changed) { + for (Partition partition : assignmentToPersist.keySet()) { + Map instanceMap = assignmentToPersist.get(partition); + idealState.setInstanceStateMap(partition.getPartitionName(), instanceMap); + } + accessor.setProperty(keyBuilder.idealStates(resourceId), idealState); + } + } + } + } + + long endTime = System.currentTimeMillis(); + LOG.info("END PersistAssignmentStage.process(), took " + (endTime - startTime) + " ms"); + } + + /** + * TODO: This is a temporary hacky for back-compatible support of Espresso and Databus, + * we should get rid of this conversion as soon as possible. + * --- Lei, 2016/9/9. + */ + private Map> convertAssignmentPersisted(Resource resource, + IdealState idealState, Map> bestPossibleAssignment) { + String stateModelDef = idealState.getStateModelDefRef(); + /** Only convert for MasterSlave resources */ + if (!stateModelDef.equals(BuiltInStateModelDefinitions.MasterSlave.name())) { + return bestPossibleAssignment; + } + + Map> assignmentToPersist = + new HashMap>(); + + for (Partition partition : resource.getPartitions()) { + Map instanceMap = new HashMap(); + instanceMap.putAll(bestPossibleAssignment.get(partition)); + + List preferenceList = idealState.getPreferenceList(partition.getPartitionName()); + boolean hasMaster = false; + for (String ins : preferenceList) { + String state = instanceMap.get(ins); + if (state == null || (!state.equals(MasterSlaveSMD.States.SLAVE.name()) && !state + .equals(MasterSlaveSMD.States.MASTER.name()))) { + instanceMap.put(ins, MasterSlaveSMD.States.SLAVE.name()); + } + + if (state != null && state.equals(MasterSlaveSMD.States.MASTER.name())) { + hasMaster = true; + } + } + + // if no master, just pick the first node in the preference list as the master. + if (!hasMaster && preferenceList.size() > 0) { + instanceMap.put(preferenceList.get(0), MasterSlaveSMD.States.MASTER.name()); + } + + assignmentToPersist.put(partition, instanceMap); + } + + return assignmentToPersist; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `bestPossibleAssignments` last assigned on line 57 could be null and is dereferenced at line 60. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void PersistAssignmentStage.process(ClusterEvent) + +### Procedure Id: +org.apache.helix.controller.stages.PersistAssignmentStage.process(org.apache.helix.controller.stages.5fe6a1979dfbfd1b713577472f77df88 + +### File: +helix-core/src/main/java/org/apache/helix/controller/stages/PersistAssignmentStage.java + +### Key: +PersistAssignmentStage.java|process|NULL_DEREFERENCE + +### Node Key: +75a3105ef036e14d28c2a0df35d92164 + +### Hash: +3452e6b23d26bab46ead54e2ad92ad85 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9673/instruction.md b/inferredbugs-9673/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f7c86e694ebf03eac88e24e43cc4526a87f3b74 --- /dev/null +++ b/inferredbugs-9673/instruction.md @@ -0,0 +1,276 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * dblock[at]dblock[dot]org + * alessandro[at]perucchi[dot]org + * widdis[at]gmail[dot]com + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonBuilderFactory; +import javax.json.JsonObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import oshi.hardware.Sensors; +import oshi.json.NullAwareJsonObjectBuilder; +import oshi.util.ExecutingCommand; + +public class WindowsSensors implements Sensors { + private static final Logger LOG = LoggerFactory.getLogger(WindowsSensors.class); + + private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); + + @Override + public double getCpuTemperature() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic Temperature get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currenttemperature")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public int[] getFanSpeeds() { + int[] fanSpeeds = new int[1]; + ArrayList hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Fan get DesiredSpeed"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("desiredspeed")) { + continue; + } else { + // If successful + try { + int rpm = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if (rpm > 0) { + fanSpeeds[0] = rpm; + return fanSpeeds; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return fanSpeeds; + } + + @Override + public double getCpuVoltage() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic cpu get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentvoltage")) { + continue; + } else { + // If successful this line is in tenths of volts + try { + int decivolts = Integer.parseInt(checkLine.trim()); + if (decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // If the eighth bit is set, bits 0-6 contain the voltage + // multiplied by 10. If the eighth bit is not set, then the bit + // setting in VoltageCaps represents the voltage value. + try { + int decivolts = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if ((decivolts & 0x80) > 0 && decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get VoltageCaps"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // Bits 0-3 of the field represent specific voltages that the + // processor socket can accept. + try { + int voltagebits = Integer.parseInt(checkLine.trim()); + // Return appropriate voltage + if ((voltagebits & 0x1) > 0) { + return 5.0; + } else if ((voltagebits & 0x2) > 0) { + return 3.3; + } else if ((voltagebits & 0x4) > 0) { + return 2.9; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public JsonObject toJSON() { + JsonArrayBuilder fanSpeedsArrayBuilder = jsonFactory.createArrayBuilder(); + for (int speed : getFanSpeeds()) { + fanSpeedsArrayBuilder.add(speed); + } + return NullAwareJsonObjectBuilder.wrap(jsonFactory.createObjectBuilder()).add("cpuTemperature", getCpuTemperature()) + .add("fanSpeeds", fanSpeedsArrayBuilder.build()).add("cpuVoltage", getCpuVoltage()).build(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `hwInfo` last assigned on line 40 could be null and is dereferenced at line 41. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +double WindowsSensors.getCpuTemperature() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsSensors.getCpuTemperature():double.e4340d82455d749f23b5cd0dc972186e + +### File: +src/main/java/oshi/hardware/platform/windows/WindowsSensors.java + +### Key: +WindowsSensors.java|getCpuTemperature|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +d4558c1ba88ab3a260dfb4309f1220e7 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9674/instruction.md b/inferredbugs-9674/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90a3e8471496150cb6ec081a09020c7a29fedcd5 --- /dev/null +++ b/inferredbugs-9674/instruction.md @@ -0,0 +1,276 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * dblock[at]dblock[dot]org + * alessandro[at]perucchi[dot]org + * widdis[at]gmail[dot]com + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; + +import javax.json.Json; +import javax.json.JsonArrayBuilder; +import javax.json.JsonBuilderFactory; +import javax.json.JsonObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import oshi.hardware.Sensors; +import oshi.json.NullAwareJsonObjectBuilder; +import oshi.util.ExecutingCommand; + +public class WindowsSensors implements Sensors { + private static final Logger LOG = LoggerFactory.getLogger(WindowsSensors.class); + + private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); + + @Override + public double getCpuTemperature() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic Temperature get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\wmi PATH MSAcpi_ThermalZoneTemperature get CurrentTemperature"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currenttemperature")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_TemperatureProbe get CurrentReading"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful this line is in tenths of degrees Kelvin + try { + int tempK = Integer.parseInt(checkLine.trim()); + if (tempK > 0) { + return (tempK - 2715) / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public int[] getFanSpeeds() { + int[] fanSpeeds = new int[1]; + ArrayList hwInfo = ExecutingCommand + .runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Fan get DesiredSpeed"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("desiredspeed")) { + continue; + } else { + // If successful + try { + int rpm = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if (rpm > 0) { + fanSpeeds[0] = rpm; + return fanSpeeds; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return fanSpeeds; + } + + @Override + public double getCpuVoltage() { + ArrayList hwInfo = ExecutingCommand.runNative("wmic cpu get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentvoltage")) { + continue; + } else { + // If successful this line is in tenths of volts + try { + int decivolts = Integer.parseInt(checkLine.trim()); + if (decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get CurrentVoltage"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // If the eighth bit is set, bits 0-6 contain the voltage + // multiplied by 10. If the eighth bit is not set, then the bit + // setting in VoltageCaps represents the voltage value. + try { + int decivolts = Integer.parseInt(checkLine.trim()); + // Check if 8th bit (of 16 bit number) is set + if ((decivolts & 0x80) > 0 && decivolts > 0) { + return decivolts / 10d; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + // Above query failed, try something else + hwInfo = ExecutingCommand.runNative("wmic /namespace:\\\\root\\cimv2 PATH Win32_Processor get VoltageCaps"); + for (String checkLine : hwInfo) { + if (checkLine.length() == 0 || checkLine.toLowerCase().contains("currentreading")) { + continue; + } else { + // If successful: + // Bits 0-3 of the field represent specific voltages that the + // processor socket can accept. + try { + int voltagebits = Integer.parseInt(checkLine.trim()); + // Return appropriate voltage + if ((voltagebits & 0x1) > 0) { + return 5.0; + } else if ((voltagebits & 0x2) > 0) { + return 3.3; + } else if ((voltagebits & 0x4) > 0) { + return 2.9; + } + } catch (NumberFormatException e) { + // If we failed to parse, give up + } + break; + } + } + return 0d; + } + + @Override + public JsonObject toJSON() { + JsonArrayBuilder fanSpeedsArrayBuilder = jsonFactory.createArrayBuilder(); + for (int speed : getFanSpeeds()) { + fanSpeedsArrayBuilder.add(speed); + } + return NullAwareJsonObjectBuilder.wrap(jsonFactory.createObjectBuilder()).add("cpuTemperature", getCpuTemperature()) + .add("fanSpeeds", fanSpeedsArrayBuilder.build()).add("cpuVoltage", getCpuVoltage()).build(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `hwInfo` last assigned on line 126 could be null and is dereferenced at line 127. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +double WindowsSensors.getCpuVoltage() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsSensors.getCpuVoltage():double.c3b455c9ed03d22da1bfbc8cfae9c7fa + +### File: +src/main/java/oshi/hardware/platform/windows/WindowsSensors.java + +### Key: +WindowsSensors.java|getCpuVoltage|NULL_DEREFERENCE + +### Node Key: +3136f63d7119a7aa69484bac205f617e + +### Hash: +b53c4bef33069d2a968b9afd130230c2 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9680/instruction.md b/inferredbugs-9680/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8048e221bc1be2c36d8aeca7a91667eb8434980 --- /dev/null +++ b/inferredbugs-9680/instruction.md @@ -0,0 +1,159 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) Alessandro Perucchi, 2014 + * alessandro[at]perucchi[dot]org + * All Rights Reserved + * Eclipse Public License (EPLv1) + * http://oshi.codeplex.com/license + */ +package oshi.software.os.linux.proc; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.Scanner; + +import oshi.hardware.Memory; + +/** + * Memory obtained by /proc/meminfo. + * + * @author alessandro[at]perucchi[dot]org + */ +public class GlobalMemory implements Memory { + + private long totalMemory = 0; + + public long getAvailable() { + long returnCurrentUsageMemory = 0; + Scanner in = null; + try { + in = new Scanner(new FileReader("/proc/meminfo")); + } catch (FileNotFoundException e) { + return returnCurrentUsageMemory; + } + in.useDelimiter("\n"); + while (in.hasNext()) { + String checkLine = in.next(); + if (checkLine.startsWith("MemAvailable:")) { + String[] memorySplit = checkLine.split("\\s+"); + returnCurrentUsageMemory = parseMeminfo(memorySplit); + break; + } else if (checkLine.startsWith("MemFree:")) { + String[] memorySplit = checkLine.split("\\s+"); + returnCurrentUsageMemory += parseMeminfo(memorySplit); + } else if (checkLine.startsWith("Inactive:")) { + String[] memorySplit = checkLine.split("\\s+"); + returnCurrentUsageMemory += parseMeminfo(memorySplit); + } + } + in.close(); + return returnCurrentUsageMemory; + } + + public long getTotal() { + if (totalMemory == 0) { + Scanner in = null; + try { + in = new Scanner(new FileReader("/proc/meminfo")); + } catch (FileNotFoundException e) { + totalMemory = 0; + return totalMemory; + } + in.useDelimiter("\n"); + while (in.hasNext()) { + String checkLine = in.next(); + if (checkLine.startsWith("MemTotal:")) { + String[] memorySplit = checkLine.split("\\s+"); + totalMemory = parseMeminfo(memorySplit); + break; + } + } + in.close(); + } + return totalMemory; + } + + private long parseMeminfo(String[] memorySplit) { + if (memorySplit.length < 2) { + return 0l; + } + long memory = new Long(memorySplit[1]); + if (memorySplit.length > 2 && memorySplit[2].equals("kB")) { + memory *= 1024; + } + return memory; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.Scanner` acquired to `in` by call to `new()` at line 56 is not released after line 70. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +long GlobalMemory.getTotal() + +### Procedure Id: +oshi.software.os.linux.proc.GlobalMemory.getTotal():long.06707bc15d00621e2ba4341f480e6da8 + +### File: +src/main/java/oshi/software/os/linux/proc/GlobalMemory.java + +### Key: +GlobalMemory.java|getTotal|RESOURCE_LEAK + +### Node Key: +96d0b7ce25d90477964b9aaec0fb9137 + +### Hash: +c0e5cd78b74975f27b35616d834e9949 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9681/instruction.md b/inferredbugs-9681/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1979a598ac64cdaef6e7a67e5ac2869003547c72 --- /dev/null +++ b/inferredbugs-9681/instruction.md @@ -0,0 +1,577 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 28 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.util.platform.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jna.NativeLong; +import com.sun.jna.Pointer; +import com.sun.jna.platform.win32.OleAuto; +import com.sun.jna.platform.win32.Variant.VARIANT; +import com.sun.jna.platform.win32.WTypes.BSTR; +import com.sun.jna.platform.win32.WinNT.HRESULT; +import com.sun.jna.platform.win32.COM.COMUtils; +import com.sun.jna.ptr.LongByReference; +import com.sun.jna.ptr.PointerByReference; + +import oshi.jna.platform.windows.Ole32; +import oshi.jna.platform.windows.COM.EnumWbemClassObject; +import oshi.jna.platform.windows.COM.WbemClassObject; +import oshi.jna.platform.windows.COM.WbemLocator; +import oshi.jna.platform.windows.COM.WbemServices; +import oshi.util.ParseUtil; + +/** + * Provides access to WMI queries + * + * @author widdis[at]gmail[dot]com + */ +public class WmiUtil { + private static final Logger LOG = LoggerFactory.getLogger(WmiUtil.class); + + public static final String DEFAULT_NAMESPACE = "ROOT\\CIMV2"; + + private static boolean securityInitialized = false; + + /** + * Enum for WMI queries for proper parsing from the returned VARIANT + */ + public enum ValueType { + STRING, UINT32, FLOAT, DATETIME + } + + /** + * For WMI queries requiring array input + */ + private static ValueType[] STRING_TYPE = { ValueType.STRING }; + private static ValueType[] UINT32_TYPE = { ValueType.UINT32 }; + private static ValueType[] FLOAT_TYPE = { ValueType.FLOAT }; + + /** + * Get a single Unsigned Integer value from WMI (as Long) + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A Long containing the value of the requested property + */ + public static Long selectUint32From(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, UINT32_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (Long) result.get(property).get(0); + } + return 0L; + } + + /** + * Get multiple Unsigned Integer values from WMI (as Longs) + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing Longs with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectUint32sFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, UINT32_TYPE); + HashMap> longMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList longList = new ArrayList<>(); + for (Object obj : result.get(key)) { + longList.add((Long) obj); + } + longMap.put(key, longList); + } + return longMap; + } + + /** + * Get a single Float value from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A Float containing the value of the requested property + */ + public static Float selectFloatFrom(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, FLOAT_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (Float) result.get(property).get(0); + } + return 0f; + } + + /** + * Get multiple Float values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing Floats with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectFloatsFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, FLOAT_TYPE); + HashMap> floatMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList floatList = new ArrayList<>(); + for (Object obj : result.get(key)) { + floatList.add((Float) obj); + } + floatMap.put(key, floatList); + } + return floatMap; + } + + /** + * Get a single String value from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param property + * The property whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A string containing the value of the requested property + */ + public static String selectStringFrom(String namespace, String wmiClass, String property, String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, property, + wmiClass, whereClause, STRING_TYPE); + if (result.containsKey(property) && !result.get(property).isEmpty()) { + return (String) result.get(property).get(0); + } + return ""; + } + + /** + * Get multiple String values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @return A map, with each property as the key, containing strings with the + * value of the requested properties. Each list's order corresponds + * to other lists. + */ + public static Map> selectStringsFrom(String namespace, String wmiClass, String properties, + String whereClause) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, STRING_TYPE); + HashMap> strMap = new HashMap<>(); + for (String key : result.keySet()) { + ArrayList strList = new ArrayList<>(); + for (Object obj : result.get(key)) { + strList.add((String) obj); + } + strMap.put(key, strList); + } + return strMap; + } + + /** + * Get multiple individually typed values from WMI + * + * @param namespace + * The namespace or null to use the default + * @param wmiClass + * The class to query + * @param properties + * A comma delimited list of properties whose value to return + * @param whereClause + * A WQL where clause matching properties and keywords + * @param propertyTypes + * An array of types corresponding to the properties, or a single + * element array + * @return A map, with each property as the key, containing Objects with the + * value of the requested properties. Each list's order corresponds + * to other lists. The type of the objects is identified by the + * propertyTypes array. If only one propertyType is given, all + * Objects will have that type. It is the responsibility of the + * caller to cast the returned objects. + */ + public static Map> selectObjectsFrom(String namespace, String wmiClass, String properties, + String whereClause, ValueType[] propertyTypes) { + Map> result = queryWMI(namespace == null ? DEFAULT_NAMESPACE : namespace, properties, + wmiClass, whereClause, propertyTypes); + return result; + } + + /** + * Query WMI for values + * + * @param namespace + * The namespace to query + * @param properties + * A single property or comma-delimited list of properties to + * enumerate + * @param wmiClass + * The WMI class to query + * @param propertyTypes + * An array corresponding to the properties, containing the type + * of data being queried, to control how VARIANT is parsed + * @return A map, with the string value of each property as the key, + * containing a list of Objects which can be cast appropriately per + * valType. The order of objects in each list corresponds to the + * other lists. + */ + private static Map> queryWMI(String namespace, String properties, String wmiClass, + String whereClause, ValueType[] propertyTypes) { + // Set up empty map + Map> values = new HashMap<>(); + String[] props = properties.split(","); + for (int i = 0; i < props.length; i++) { + values.put(props[i], new ArrayList()); + } + + // Initialize COM + if (!initCOM()) { + Ole32.INSTANCE.CoUninitialize(); + return values; + } + + PointerByReference pSvc = new PointerByReference(); + if (!connectServer(namespace, pSvc)) { + Ole32.INSTANCE.CoUninitialize(); + return values; + } + WbemServices svc = new WbemServices(pSvc.getValue()); + + PointerByReference pEnumerator = new PointerByReference(); + if (!selectProperties(svc, pEnumerator, properties, wmiClass, whereClause)) { + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return values; + } + EnumWbemClassObject enumerator = new EnumWbemClassObject(pEnumerator.getValue()); + + enumerateProperties(values, enumerator, props, propertyTypes); + + // Cleanup + enumerator.Release(); + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return values; + } + + /* + * Below methods ported from: Getting WMI Data from Local Computer + * https://msdn.microsoft.com/en-us/library/aa390423(v=VS.85).aspx + * + * Steps 1 - 7 correspond to the above link. + */ + /** + * Initializes COM library and sets security to impersonate the local user + * + * @return true if COM successfull initialized + */ + private static boolean initCOM() { + // Step 1: -------------------------------------------------- + // Initialize COM. ------------------------------------------ + HRESULT hres = Ole32.INSTANCE.CoInitializeEx(null, Ole32.COINIT_MULTITHREADED); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Failed to initialize COM library. Error code = 0x%08x", hres.intValue())); + return false; + } + if (securityInitialized) { + // Only run CoInitializeSecuirty once + return true; + } + // Step 2: -------------------------------------------------- + // Set general COM security levels -------------------------- + hres = Ole32.INSTANCE.CoInitializeSecurity(null, new NativeLong(-1), null, null, + Ole32.RPC_C_AUTHN_LEVEL_DEFAULT, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE, null); + if (COMUtils.FAILED(hres) && hres.intValue() != Ole32.RPC_E_TOO_LATE) { + LOG.error(String.format("Failed to initialize security. Error code = 0x%08x", hres.intValue())); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + securityInitialized = true; + return true; + } + + /** + * Obtains a locator to the WMI server and connects to the specified + * namespace + * + * @param namespace + * The namespace to connect to + * @param pSvc + * A pointer to receive an indirect to the WMI service + * @return true if successful; pSvc will contain an indirect pointer to the + * WMI service for future IWbemServices calls + */ + private static boolean connectServer(String namespace, PointerByReference pSvc) { + // Step 3: --------------------------------------------------- + // Obtain the initial locator to WMI ------------------------- + WbemLocator loc = WbemLocator.create(); + if (loc == null) { + return false; + } + // Step 4: ----------------------------------------------------- + // Connect to WMI through the IWbemLocator::ConnectServer method + // Connect to the namespace with the current user and obtain pointer + // pSvc to make IWbemServices calls. + HRESULT hres = loc.ConnectServer(new BSTR(namespace), null, null, null, null, null, null, pSvc); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Could not connect to namespace %s. Error code = 0x%08x", namespace, + hres.intValue())); + loc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + LOG.debug("Connected to {} WMI namespace", namespace); + loc.Release(); + + // Step 5: -------------------------------------------------- + // Set security levels on the proxy ------------------------- + hres = Ole32.INSTANCE.CoSetProxyBlanket(pSvc.getValue(), Ole32.RPC_C_AUTHN_WINNT, Ole32.RPC_C_AUTHZ_NONE, null, + Ole32.RPC_C_AUTHN_LEVEL_CALL, Ole32.RPC_C_IMP_LEVEL_IMPERSONATE, null, Ole32.EOAC_NONE); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Could not set proxy blanket. Error code = 0x%08x", hres.intValue())); + new WbemServices(pSvc.getValue()).Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + return true; + } + + /** + * Selects properties from WMI. Returns immediately, even while results are + * being retrieved; results may begun to be enumerated in the forward + * direction only. + * + * @param svc + * A WbemServices object to make the calls + * @param pEnumerator + * An enumerator to receive the results of the query + * @param properties + * A comma separated list of properties to query + * @param wmiClass + * The WMI class to query + * @param whereClause + * A WHERE clause to narrow the query + * @return True if successful. The enumerator will allow enumeration of + * results of the query + */ + private static boolean selectProperties(WbemServices svc, PointerByReference pEnumerator, String properties, + String wmiClass, String whereClause) { + // Step 6: -------------------------------------------------- + // Use the IWbemServices pointer to make requests of WMI ---- + String query = String.format("SELECT %s FROM %s %s", properties, wmiClass, + whereClause != null ? whereClause : ""); + LOG.debug("Query: {}", query); + HRESULT hres = svc.ExecQuery(new BSTR("WQL"), new BSTR(query), + new NativeLong( + EnumWbemClassObject.WBEM_FLAG_FORWARD_ONLY | EnumWbemClassObject.WBEM_FLAG_RETURN_IMMEDIATELY), + null, pEnumerator); + if (COMUtils.FAILED(hres)) { + LOG.error(String.format("Query '%s' failed. Error code = 0x%08x", query, hres.intValue())); + svc.Release(); + Ole32.INSTANCE.CoUninitialize(); + return false; + } + return true; + } + + /** + * Enumerate the results of a WMI query. This method is called while results + * are still being retrieved and may iterate in the forward direction only. + * + * @param values + * A map to hold the results of the query using the property as + * the key, and placing each enumerated result in a + * (common-index) list for each property + * @param enumerator + * The enumerator with the results + * @param properties + * Comma-delimited list of properties to retrieve + * @param propertyTypes + * An array of property types matching the properties or a single + * property type which will be used for all properties + */ + private static void enumerateProperties(Map> values, EnumWbemClassObject enumerator, + String[] properties, ValueType[] propertyTypes) { + if (propertyTypes.length > 1 && properties.length != propertyTypes.length) { + throw new IllegalArgumentException("Property type array size must be 1 or equal to properties array size."); + } + // Step 7: ------------------------------------------------- + // Get the data from the query in step 6 ------------------- + PointerByReference pclsObj = new PointerByReference(); + LongByReference uReturn = new LongByReference(0L); + while (enumerator.getPointer() != Pointer.NULL) { + HRESULT hres = enumerator.Next(new NativeLong(EnumWbemClassObject.WBEM_INFINITE), new NativeLong(1), + pclsObj, uReturn); + // Requested 1; if 0 objects returned, we're done + if (0L == uReturn.getValue() || COMUtils.FAILED(hres)) { + // Enumerator will be released by calling method so no need to + // release it here. + return; + } + VARIANT.ByReference vtProp = new VARIANT.ByReference(); + + // Get the value of the properties + WbemClassObject clsObj = new WbemClassObject(pclsObj.getValue()); + for (int p = 0; p < properties.length; p++) { + String property = properties[p]; + hres = clsObj.Get(new BSTR(property), new NativeLong(0L), vtProp, null, null); + + ValueType propertyType = propertyTypes.length > 1 ? propertyTypes[p] : propertyTypes[0]; + switch (propertyType) { + // WMI Longs will return as strings + case STRING: + values.get(property).add(vtProp.getValue() == null ? "unknown" : vtProp.stringValue()); + break; + // WMI Uint32s will return as longs + case UINT32: // WinDef.LONG TODO improve in JNA 4.3 + values.get(property) + .add(vtProp.getValue() == null ? 0L : vtProp._variant.__variant.lVal.longValue()); + break; + case FLOAT: + values.get(property).add(vtProp.getValue() == null ? 0f : vtProp.floatValue()); + break; + case DATETIME: + // Read a string in format 20160513072950.782000-420 and + // parse to a long representing ms since eopch + values.get(property).add(ParseUtil.cimDateTimeToMillis(vtProp.stringValue())); + break; + default: + // Should never get here! If you get this exception you've + // added something to the enum without adding it here. Tsk. + throw new IllegalArgumentException("Unimplemented enum type: " + propertyType.toString()); + } + OleAuto.INSTANCE.VariantClear(vtProp.getPointer()); + } + clsObj.Release(); + } + } +} +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `$T1_299` last assigned on line 484 could be null and is dereferenced at line 484. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WmiUtil.enumerateProperties(HashMap,EnumWbemClassObject,java.lang.String[],oshi.util.platform.windows.WmiUtil$ValueType[]) + +### Procedure Id: +oshi.util.platform.windows.WmiUtil.enumerateProperties(java.util.HashMap,oshi.jna.platform.windows.C.5f6d66bc2e64d1f4d951514562ae9e5b + +### File: +oshi-core/src/main/java/oshi/util/platform/windows/WmiUtil.java + +### Key: +WmiUtil.java|enumerateProperties|NULL_DEREFERENCE + +### Node Key: +df64850a52332193bad448f8258efd03 + +### Hash: +532bb3b24cbc5f049541d2d806e01472 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9687/instruction.md b/inferredbugs-9687/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d27f28386ffb706d180c51800ad11d6f2783e4a3 --- /dev/null +++ b/inferredbugs-9687/instruction.md @@ -0,0 +1,174 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/dblock/oshi) + * + * Copyright (c) 2010 - 2016 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * dblock[at]dblock[dot]org + * alessandro[at]perucchi[dot]org + * widdis[at]gmail[dot]com + * https://github.com/dblock/oshi/graphs/contributors + */ +package oshi.software.os.linux; + +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.Scanner; + +import javax.json.Json; +import javax.json.JsonBuilderFactory; +import javax.json.JsonObject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import oshi.software.os.OperatingSystem; +import oshi.software.os.OperatingSystemVersion; + +/** + * Linux is a family of free operating systems most commonly used on personal + * computers. + * + * @author alessandro[at]perucchi[dot]org + */ +public class LinuxOperatingSystem implements OperatingSystem { + + private static final Logger LOG = LoggerFactory.getLogger(LinuxOperatingSystem.class); + + private OperatingSystemVersion _version; + + private String _family; + + private JsonBuilderFactory jsonFactory = Json.createBuilderFactory(null); + + @Override + public String getFamily() { + if (this._family == null) { + try (final Scanner in = new Scanner(new FileReader("/etc/os-release"))) { + in.useDelimiter("\n"); + while (in.hasNext()) { + String[] splittedLine = in.next().split("="); + if (splittedLine[0].equals("NAME")) { + // remove beginning and ending '"' characters, etc from + // NAME="Ubuntu" + this._family = splittedLine[1].replaceAll("^\"|\"$", ""); + break; + } + } + } catch (FileNotFoundException e) { + LOG.trace("", e); + return ""; + } + } + return this._family; + } + + @Override + public String getManufacturer() { + return "GNU/Linux"; + } + + @Override + public OperatingSystemVersion getVersion() { + if (this._version == null) { + this._version = new LinuxOSVersionInfoEx(); + } + return this._version; + } + + @Override + public JsonObject toJSON() { + return jsonFactory.createObjectBuilder().add("manufacturer", getManufacturer()).add("family", getFamily()) + .add("version", getVersion().toJSON()).build(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append(getManufacturer()); + sb.append(" "); + sb.append(getFamily()); + sb.append(" "); + sb.append(getVersion().toString()); + return sb.toString(); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.util.Scanner` acquired to `in` by call to `new()` at line 52 is not released after line 63. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +String LinuxOperatingSystem.getFamily() + +### Procedure Id: +oshi.software.os.linux.LinuxOperatingSystem.getFamily():java.lang.String.fc47a5620fcec4e8772f8514799979ad + +### File: +src/main/java/oshi/software/os/linux/LinuxOperatingSystem.java + +### Key: +LinuxOperatingSystem.java|getFamily|RESOURCE_LEAK + +### Node Key: +e6c29f5c0982f2bca86f16af114980b5 + +### Hash: +68e564096d428dcc97a1df73791b234c + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9689/instruction.md b/inferredbugs-9689/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03104639739befa529f501095b63a806fbb971b8 --- /dev/null +++ b/inferredbugs-9689/instruction.md @@ -0,0 +1,382 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** oshi +**Bug ID:** 44 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Oshi (https://github.com/oshi/oshi) + * + * Copyright (c) 2010 - 2018 The Oshi Project Team + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Maintainers: + * dblock[at]dblock[dot]org + * widdis[at]gmail[dot]com + * enrico.bianchi[at]gmail[dot]com + * + * Contributors: + * https://github.com/oshi/oshi/graphs/contributors + */ +package oshi.hardware.platform.windows; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jna.Native; // NOSONAR +import com.sun.jna.platform.win32.Kernel32; +import com.sun.jna.platform.win32.WinDef.DWORD; +import com.sun.jna.platform.win32.WinDef.DWORDByReference; + +import oshi.hardware.Disks; +import oshi.hardware.HWDiskStore; +import oshi.hardware.HWPartition; +import oshi.jna.platform.windows.Pdh; +import oshi.util.MapUtil; +import oshi.util.ParseUtil; +import oshi.util.StringUtil; +import oshi.util.platform.windows.PdhUtil; +import oshi.util.platform.windows.WmiUtil; +import oshi.util.platform.windows.WmiUtil.ValueType; + +/** + * Windows hard disk implementation. + * + * @author enrico[dot]bianchi[at]gmail[dot]com + */ +public class WindowsDisks implements Disks { + + private static final long serialVersionUID = 1L; + + private static final Logger LOG = LoggerFactory.getLogger(WindowsDisks.class); + + /** + * Maps to store read/write bytes per drive index + */ + private static Map readMap = new HashMap<>(); + private static Map readByteMap = new HashMap<>(); + private static Map writeMap = new HashMap<>(); + private static Map writeByteMap = new HashMap<>(); + private static Map xferTimeMap = new HashMap<>(); + private static Map timeStampMap = new HashMap<>(); + private static Map> driveToPartitionMap = new HashMap<>(); + private static Map partitionToLogicalDriveMap = new HashMap<>(); + private static Map partitionMap = new HashMap<>(); + + private static final Pattern DEVICE_ID = Pattern.compile(".*\\.DeviceID=\"(.*)\""); + + private static final int BUFSIZE = 255; + + private static final String DISK_DRIVE_CLASS = "Win32_DiskDrive"; + + private static final String ANTECEDENT_PROPERTY = "Antecedent"; + private static final String DEPENDENT_PROPERTY = "Dependent"; + private static final String DESCRIPTION_PROPERTY = "Description"; + private static final String DEVICE_ID_PROPERTY = "DeviceID"; + private static final String DISK_INDEX_PROPERTY = "DiskIndex"; + private static final String INDEX_PROPERTY = "Index"; + private static final String MANUFACTURER_PROPERTY = "Manufacturer"; + private static final String MODEL_PROPERTY = "Model"; + private static final String NAME_PROPERTY = "Name"; + private static final String SERIALNUMBER_PROPERTY = "SerialNumber"; + private static final String SIZE_PROPERTY = "Size"; + private static final String TYPE_PROPERTY = "Type"; + + private static final String[] DRIVE_PROPERTIES = new String[] { NAME_PROPERTY, MANUFACTURER_PROPERTY, + MODEL_PROPERTY, SERIALNUMBER_PROPERTY, SIZE_PROPERTY, INDEX_PROPERTY }; + private static final ValueType[] DRIVE_TYPES = { ValueType.STRING, ValueType.STRING, ValueType.STRING, + ValueType.STRING, ValueType.STRING, ValueType.UINT32 }; + + private static final String DRIVE_TO_PARTITION_PROPERTIES = StringUtil.join(",", + new String[] { ANTECEDENT_PROPERTY, DEPENDENT_PROPERTY }); + private static final String LOGICAL_DISK_TO_PARTITION_PROPERTIES = StringUtil.join(",", + new String[] { ANTECEDENT_PROPERTY, DEPENDENT_PROPERTY }); + + private static final String[] PARTITION_PROPERTIES = new String[] { NAME_PROPERTY, TYPE_PROPERTY, + DESCRIPTION_PROPERTY, DEVICE_ID_PROPERTY, SIZE_PROPERTY, DISK_INDEX_PROPERTY, INDEX_PROPERTY }; + private static final ValueType[] PARTITION_TYPES = { ValueType.STRING, ValueType.STRING, ValueType.STRING, + ValueType.STRING, ValueType.STRING, ValueType.UINT32, ValueType.UINT32 }; + + private static final String PDH_DISK_READS_FORMAT = "\\PhysicalDisk(%s)\\Disk Reads/sec"; + private static final String PDH_DISK_READ_BYTES_FORMAT = "\\PhysicalDisk(%s)\\Disk Read Bytes/sec"; + private static final String PDH_DISK_WRITES_FORMAT = "\\PhysicalDisk(%s)\\Disk Writes/sec"; + private static final String PDH_DISK_WRITE_BYTES_FORMAT = "\\PhysicalDisk(%s)\\Disk Write Bytes/sec"; + private static final String PDH_DISK_TIME_FORMAT = "\\PhysicalDisk(%s)\\%% Disk Time"; + + private static final String PHYSICALDRIVE_PREFIX = "\\\\.\\PHYSICALDRIVE"; + + public static boolean updateDiskStats(HWDiskStore diskStore) { + String index = null; + HWPartition[] partitions = diskStore.getPartitions(); + if (partitions.length > 0) { + // If a partition exists on this drive, the major property + // corresponds to the disk index, so use it. + index = Integer.toString(partitions[0].getMajor()); + } else if (diskStore.getName().startsWith(PHYSICALDRIVE_PREFIX)) { + // If no partition exists, Windows reliably uses a name to match the + // disk index. That said, the skeptical person might wonder why a + // disk has read/write statistics without a partition, and wonder + // why this branch is even relevant as an option. The author of this + // comment does not have an answer for this valid question. + index = diskStore.getName().substring(PHYSICALDRIVE_PREFIX.length(), diskStore.getName().length()); + } else { + // The author of this comment cannot fathom a circumstance in which + // the code reaches this point, but just in case it does, here's the + // correct response. If you get this log warning, the circumstances + // would be of great interest to the project's maintainers. + LOG.warn("Couldn't match index for {}", diskStore.getName()); + return false; + } + populateReadWriteMaps(index); + if (readMap.containsKey(index)) { + diskStore.setReads(MapUtil.getOrDefault(readMap, index, 0L)); + diskStore.setReadBytes(MapUtil.getOrDefault(readByteMap, index, 0L)); + diskStore.setWrites(MapUtil.getOrDefault(writeMap, index, 0L)); + diskStore.setWriteBytes(MapUtil.getOrDefault(writeByteMap, index, 0L)); + diskStore.setTransferTime(MapUtil.getOrDefault(xferTimeMap, index, 0L)); + diskStore.setTimeStamp(MapUtil.getOrDefault(timeStampMap, index, 0L)); + return true; + } else { + return false; + } + + } + + @Override + public HWDiskStore[] getDisks() { + List result; + result = new ArrayList<>(); + populateReadWriteMaps(null); + populatePartitionMaps(); + + Map> vals = WmiUtil.selectObjectsFrom(null, DISK_DRIVE_CLASS, DRIVE_PROPERTIES, null, + DRIVE_TYPES); + for (int i = 0; i < vals.get(NAME_PROPERTY).size(); i++) { + HWDiskStore ds = new HWDiskStore(); + ds.setName((String) vals.get(NAME_PROPERTY).get(i)); + ds.setModel(String.format("%s %s", vals.get(MODEL_PROPERTY).get(i), vals.get(MANUFACTURER_PROPERTY).get(i)) + .trim()); + // Most vendors store serial # as a hex string; convert + ds.setSerial(ParseUtil.hexStringToString((String) vals.get(SERIALNUMBER_PROPERTY).get(i))); + String index = vals.get(INDEX_PROPERTY).get(i).toString(); + ds.setReads(MapUtil.getOrDefault(readMap, index, 0L)); + ds.setReadBytes(MapUtil.getOrDefault(readByteMap, index, 0L)); + ds.setWrites(MapUtil.getOrDefault(writeMap, index, 0L)); + ds.setWriteBytes(MapUtil.getOrDefault(writeByteMap, index, 0L)); + ds.setTransferTime(MapUtil.getOrDefault(xferTimeMap, index, 0L)); + ds.setTimeStamp(MapUtil.getOrDefault(timeStampMap, index, 0L)); + // If successful this line is the desired value + ds.setSize(ParseUtil.parseLongOrDefault((String) vals.get(SIZE_PROPERTY).get(i), 0L)); + // Get partitions + List partitions = new ArrayList<>(); + List partList = driveToPartitionMap.get(ds.getName()); + if (partList != null && !partList.isEmpty()) { + for (String part : partList) { + partitions.add(partitionMap.get(part)); + } + } + ds.setPartitions(partitions.toArray(new HWPartition[partitions.size()])); + // Add to list + result.add(ds); + } + return result.toArray(new HWDiskStore[result.size()]); + } + + /** + * Populates the maps for the specified index. If the index is null, + * populates all the maps + * + * @param index + * The index to populate/update maps for + */ + private static void populateReadWriteMaps(String index) { + // If index is null, start from scratch. + if (index == null) { + readMap.clear(); + readByteMap.clear(); + writeMap.clear(); + writeByteMap.clear(); + xferTimeMap.clear(); + timeStampMap.clear(); + } + // Fetch the instance names + // Call once to get string lengths + DWORDByReference pcchCounterListLength = new DWORDByReference(new DWORD(0)); + DWORDByReference pcchInstanceListLength = new DWORDByReference(new DWORD(0)); + Pdh.INSTANCE.PdhEnumObjectItems(null, null, "PhysicalDisk", null, pcchCounterListLength, null, + pcchInstanceListLength, 100, 0); + // Allocate memory and call again to populate strings + char[] mszCounterList = new char[pcchCounterListLength.getValue().intValue()]; + char[] mszInstanceList = new char[pcchInstanceListLength.getValue().intValue()]; + Pdh.INSTANCE.PdhEnumObjectItems(null, null, "PhysicalDisk", mszCounterList, pcchCounterListLength, + mszInstanceList, pcchInstanceListLength, 100, 0); + List instances = Native.toStringList(mszInstanceList); + instances.remove("_Total"); + // At this point we have a list of strings that PDH understands. Fetch + // the counters. + // Although the field names say "PerSec" this is the Raw Data/counters + // from which the associated fields are populated in the Formatted Data + for (String i : instances) { + String name = ParseUtil.whitespaces.split(i)[0]; + String readString = String.format(PDH_DISK_READS_FORMAT, i); + if (!PdhUtil.isCounter(readString)) { + PdhUtil.addCounter(readString); + } + String readBytesString = String.format(PDH_DISK_READ_BYTES_FORMAT, i); + if (!PdhUtil.isCounter(readBytesString)) { + PdhUtil.addCounter(readBytesString); + } + String writeString = String.format(PDH_DISK_WRITES_FORMAT, i); + if (!PdhUtil.isCounter(writeString)) { + PdhUtil.addCounter(writeString); + } + String writeBytesString = String.format(PDH_DISK_WRITE_BYTES_FORMAT, i); + if (!PdhUtil.isCounter(writeBytesString)) { + PdhUtil.addCounter(writeBytesString); + } + String xferTimeString = String.format(PDH_DISK_TIME_FORMAT, i); + if (!PdhUtil.isCounter(xferTimeString)) { + PdhUtil.addCounter(xferTimeString); + } + readMap.put(name, PdhUtil.queryCounter(readString)); + readByteMap.put(name, PdhUtil.queryCounter(readBytesString)); + writeMap.put(name, PdhUtil.queryCounter(writeString)); + writeByteMap.put(name, PdhUtil.queryCounter(writeBytesString)); + xferTimeMap.put(name, PdhUtil.queryCounter(xferTimeString) / 10000L); + timeStampMap.put(name, PdhUtil.queryCounterTimestamp(xferTimeString)); + } + } + + private void populatePartitionMaps() { + driveToPartitionMap.clear(); + partitionToLogicalDriveMap.clear(); + partitionMap.clear(); + // For Regexp matching DeviceIDs + Matcher mAnt; + Matcher mDep; + + // Map drives to partitions + Map> partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_DiskDriveToDiskPartition", + DRIVE_TO_PARTITION_PROPERTIES, null); + for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { + mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); + mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); + if (mAnt.matches() && mDep.matches()) { + MapUtil.createNewListIfAbsent(driveToPartitionMap, mAnt.group(1).replaceAll("\\\\\\\\", "\\\\")) + .add(mDep.group(1)); + } + } + + // Map partitions to logical disks + partitionQueryMap = WmiUtil.selectStringsFrom(null, "Win32_LogicalDiskToPartition", + LOGICAL_DISK_TO_PARTITION_PROPERTIES, null); + for (int i = 0; i < partitionQueryMap.get(ANTECEDENT_PROPERTY).size(); i++) { + mAnt = DEVICE_ID.matcher(partitionQueryMap.get(ANTECEDENT_PROPERTY).get(i)); + mDep = DEVICE_ID.matcher(partitionQueryMap.get(DEPENDENT_PROPERTY).get(i)); + if (mAnt.matches() && mDep.matches()) { + partitionToLogicalDriveMap.put(mAnt.group(1), mDep.group(1) + "\\"); + } + } + + // Next, get all partitions and create objects + final Map> hwPartitionQueryMap = WmiUtil.selectObjectsFrom(null, "Win32_DiskPartition", + PARTITION_PROPERTIES, null, PARTITION_TYPES); + for (int i = 0; i < hwPartitionQueryMap.get(NAME_PROPERTY).size(); i++) { + String deviceID = (String) hwPartitionQueryMap.get(DEVICE_ID_PROPERTY).get(i); + String logicalDrive = MapUtil.getOrDefault(partitionToLogicalDriveMap, deviceID, ""); + String uuid = ""; + if (!logicalDrive.isEmpty()) { + // Get matching volume for UUID + char[] volumeChr = new char[BUFSIZE]; + Kernel32.INSTANCE.GetVolumeNameForVolumeMountPoint(logicalDrive, volumeChr, BUFSIZE); + uuid = ParseUtil.parseUuidOrDefault(new String(volumeChr).trim(), ""); + } + partitionMap.put(deviceID, + new HWPartition((String) hwPartitionQueryMap.get(NAME_PROPERTY).get(i), + (String) hwPartitionQueryMap.get(TYPE_PROPERTY).get(i), + (String) hwPartitionQueryMap.get(DESCRIPTION_PROPERTY).get(i), uuid, + ParseUtil.parseLongOrDefault((String) hwPartitionQueryMap.get(SIZE_PROPERTY).get(i), 0L), + ((Long) hwPartitionQueryMap.get(DISK_INDEX_PROPERTY).get(i)).intValue(), + ((Long) hwPartitionQueryMap.get(INDEX_PROPERTY).get(i)).intValue(), logicalDrive)); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `partitionQueryMap.get("Antecedent")` could be null and is dereferenced at line 266. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void WindowsDisks.populatePartitionMaps() + +### Procedure Id: +oshi.hardware.platform.windows.WindowsDisks.populatePartitionMaps():void.f7f99bb7e95fa160894f1f3c2d1bcaf5 + +### File: +oshi-core/src/main/java/oshi/hardware/platform/windows/WindowsDisks.java + +### Key: +WindowsDisks.java|populatePartitionMaps|NULL_DEREFERENCE + +### Node Key: +ccf846dbf4c448ce9ebdc4cb034fb6c6 + +### Hash: +da0b596b0803278fe778332e328fe2f3 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9755/instruction.md b/inferredbugs-9755/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9eb376e0abf83c62aeca6582450bdadc81b1bf12 --- /dev/null +++ b/inferredbugs-9755/instruction.md @@ -0,0 +1,1179 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jboss-modules +**Bug ID:** 13 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * JBoss, Home of Professional Open Source. + * Copyright 2010, Red Hat, Inc., and individual contributors + * as indicated by the @author tags. See the copyright.txt file in the + * distribution for a full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ + +package org.jboss.modules; + +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.net.URLConnection; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.ServiceLoader; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; + +import org.jboss.modules.filter.PathFilter; +import org.jboss.modules.filter.PathFilters; +import org.jboss.modules.log.ModuleLogger; +import org.jboss.modules.log.NoopModuleLogger; + +import __redirected.__JAXPRedirected; + +import static org.jboss.modules.Linkage.State.*; + +/** + * A module is a unit of classes and other resources, along with the specification of what is imported and exported + * by this module from and to other modules. Modules are created by {@link ModuleLoader}s which build modules from + * various configuration information and resource roots. + * + * @author David M. Lloyd + * @author John Bailey + * @author Flavia Rainone + * @author Jason T. Greene + * @author thomas.diesler@jboss.com + * + * @apiviz.landmark +*/ +public final class Module { + + private static final AtomicReference BOOT_MODULE_LOADER = new AtomicReference(); + + static { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + try { + URL.setURLStreamHandlerFactory(new ModularURLStreamHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + try { + URLConnection.setContentHandlerFactory(new ModularContentHandlerFactory()); + } catch (Throwable t) { + // todo log a warning or something + } + + __JAXPRedirected.initAll(); + + return null; + } + }); + + final String pkgsString = AccessController.doPrivileged(new PropertyReadAction("jboss.modules.system.pkgs")); + final List list = new ArrayList(); + list.add("java."); + list.add("sun.reflect."); + list.add("__redirected."); + if (pkgsString != null) { + int i; + int nc = -1; + do { + i = nc + 1; + nc = pkgsString.indexOf(',', i); + String part; + if (nc == -1) { + part = pkgsString.substring(i).trim(); + } else { + part = pkgsString.substring(i, nc).trim(); + } + if (part.length() > 0) { + list.add((part + ".").intern()); + } + } while (nc != -1); + } + systemPackages = list.toArray(list.toArray(new String[list.size()])); + final ListIterator iterator = list.listIterator(); + // http://youtrack.jetbrains.net/issue/IDEA-72097 + //noinspection WhileLoopReplaceableByForEach + while (iterator.hasNext()) { + iterator.set(iterator.next().replace('.', '/')); + } + systemPaths = list.toArray(list.toArray(new String[list.size()])); + } + + // static properties + + static final String[] systemPackages; + static final String[] systemPaths; + + /** + * The system-wide module logger, which may be changed via {@link #setModuleLogger(org.jboss.modules.log.ModuleLogger)}. + */ + static volatile ModuleLogger log = NoopModuleLogger.getInstance(); + + // immutable properties + + /** + * The identifier of this module. + */ + private final ModuleIdentifier identifier; + /** + * The name of the main class, if any (may be {@code null}). + */ + private final String mainClassName; + /** + * The module class loader for this module. + */ + private final ModuleClassLoader moduleClassLoader; + /** + * The module loader which created this module. + */ + private final ModuleLoader moduleLoader; + /** + * This reference exists solely to prevent the {@code FutureModule} from getting GC'd prematurely. + */ + @SuppressWarnings({ "unused" }) + private final Object myKey; + /** + * The fallback local loader, if any is defined. + */ + private final LocalLoader fallbackLoader; + + // mutable properties + + /** + * The linkage state. + */ + private volatile Linkage linkage = Linkage.NONE; + + // private constants + + private static final RuntimePermission GET_CLASS_LOADER = new RuntimePermission("getClassLoader"); + private static final RuntimePermission GET_BOOT_MODULE_LOADER = new RuntimePermission("getBootModuleLoader"); + private static final RuntimePermission ACCESS_MODULE_LOGGER = new RuntimePermission("accessModuleLogger"); + private static final RuntimePermission ADD_CONTENT_HANDLER_FACTORY = new RuntimePermission("addContentHandlerFactory"); + private static final RuntimePermission ADD_URL_STREAM_HANDLER_FACTORY = new RuntimePermission("addURLStreamHandlerFactory"); + + /** + * Construct a new instance from a module specification. + * + * @param spec the module specification + * @param moduleLoader the module loader + * @param myKey the key to keep a strong reference to + */ + Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { + this.moduleLoader = moduleLoader; + this.myKey = myKey; + + // Initialize state from the spec. + identifier = spec.getModuleIdentifier(); + mainClassName = spec.getMainClass(); + fallbackLoader = spec.getFallbackLoader(); + //noinspection ThisEscapedInObjectConstruction + final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); + final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); + ModuleClassLoader moduleClassLoader = null; + if (factory != null) moduleClassLoader = factory.create(configuration); + if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); + this.moduleClassLoader = moduleClassLoader; + } + + LocalLoader getFallbackLoader() { + return fallbackLoader; + } + + Dependency[] getDependencies() { + return linkage.getSourceList(); + } + + ModuleClassLoader getClassLoaderPrivate() { + return moduleClassLoader; + } + + /** + * Get an exported resource from a specific root in this module. + * + * @param rootPath the module root to search + * @param resourcePath the path of the resource + * @return the resource + */ + public Resource getExportedResource(final String rootPath, final String resourcePath) { + return moduleClassLoader.loadResourceLocal(rootPath, resourcePath); + } + + /** + * Run a module's main class, if any. + * + * @param args the arguments to pass + * @throws NoSuchMethodException if there is no main method + * @throws InvocationTargetException if the main method failed + * @throws ClassNotFoundException if the main class is not found + */ + public void run(final String[] args) throws NoSuchMethodException, InvocationTargetException, ClassNotFoundException { + try { + if (mainClassName == null) { + throw new NoSuchMethodException("No main class defined for " + this); + } + final Class mainClass = moduleClassLoader.loadClass(mainClassName); + final Method mainMethod = mainClass.getMethod("main", String[].class); + final int modifiers = mainMethod.getModifiers(); + if (! Modifier.isStatic(modifiers)) { + throw new NoSuchMethodException("Main method is not static for " + this); + } + final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(moduleClassLoader); + // ignore the return value + mainMethod.invoke(null, new Object[] {args}); + } finally { + Thread.currentThread().setContextClassLoader(previousClassLoader); + } + } catch (IllegalAccessException e) { + // unexpected; should be public + throw new IllegalAccessError(e.getMessage()); + } + } + + /** + * Get this module's identifier. + * + * @return the identifier + */ + public ModuleIdentifier getIdentifier() { + return identifier; + } + + /** + * Get the module loader which created this module. + * + * @return the module loader of this module + */ + public ModuleLoader getModuleLoader() { + return moduleLoader; + } + + /** + * Load a service loader from this module. + * + * @param serviceType the service type class + * @param the service type + * @return the service loader + */ + public ServiceLoader loadService(Class serviceType) { + return ServiceLoader.load(serviceType, moduleClassLoader); + } + + /** + * Load a service loader from a module in the caller's module loader. The caller's + * module loader refers to the loader of the module of the class that calls this method. + * Note that {@link #loadService(Class)} is more efficient since it does not need to crawl + * the stack. + * + * @param the the service type + * @param identifier the module identifier containing the service loader + * @param serviceType the service type class + * @return the loaded service from the caller's module + * @throws ModuleLoadException if the named module failed to load + */ + public static ServiceLoader loadServiceFromCallerModuleLoader(ModuleIdentifier identifier, Class serviceType) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier).loadService(serviceType); + } + + /** + * Get the class loader for a module. The class loader can be used to access non-exported classes and + * resources of the module. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("getClassLoader") permission to verify access to the class loader. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module class loader + */ + public ModuleClassLoader getClassLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_CLASS_LOADER); + } + return moduleClassLoader; + } + + /** + * Get all the paths exported by this module. + * + * @return the paths that are exported by this module + */ + public Set getExportedPaths() { + return Collections.unmodifiableSet(getPathsUnchecked(true).keySet()); + } + + /** + * Get the module for a loaded class, or {@code null} if the class did not come from any module. + * + * @param clazz the class + * @return the module it came from + */ + public static Module forClass(Class clazz) { + final ClassLoader cl = clazz.getClassLoader(); + return forClassLoader(cl, false); + } + + /** + * Get the module for a class loader, or {@code null} if the class loader is not associated with any module. If + * the class loader is unknown, it is possible to check the parent class loader up the chain, and so on until a module is found. + * + * @param cl the class loader + * @param search {@code true} to search up the delegation chain + * @return the associated module + */ + public static Module forClassLoader(ClassLoader cl, boolean search) { + if (cl instanceof ModuleClassLoader) { + return ((ModuleClassLoader) cl).getModule(); + } else if (search) { + return forClassLoader(cl.getParent(), true); + } else { + return null; + } + } + + /** + * Gets the boot module loader. The boot module loader is the + * initial loader that is established by the module framework. It typically + * is based off of the environmental module path unless it is overridden by + * specifying a different class name for the {@code boot.module.loader} system + * property. + * + * @return the boot module loader + */ + public static ModuleLoader getBootModuleLoader() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(GET_BOOT_MODULE_LOADER); + } + ModuleLoader loader; + while ((loader = BOOT_MODULE_LOADER.get()) == null) { + loader = DefaultBootModuleLoaderHolder.INSTANCE; + if (BOOT_MODULE_LOADER.compareAndSet(null, loader)) { + break; + } + // get it again + } + return loader; + } + + static void initBootModuleLoader(ModuleLoader loader) { + BOOT_MODULE_LOADER.set(loader); + } + + /** + * Gets the current module loader. The current module loader is the + * loader of the module from the calling class. Note that this method + * must crawl the stack to determine this, so other mechanisms are more + * efficient. + * + * @return the current module loader, or {@code null} if this method is called outside of a module + */ + public static ModuleLoader getCallerModuleLoader() { + Module callerModule = getCallerModule(); + return callerModule == null ? null : callerModule.getModuleLoader(); + } + + /** + * Get the current thread's context module loader. This loader is the one which defined the module + * whose class loader is, or is a parent of, the thread's current context class loader. If there is none, + * then {@code null} is returned. + * + * @return the module loader, or {@code null} if none is set + */ + public static ModuleLoader getContextModuleLoader() { + return Module.forClassLoader(Thread.currentThread().getContextClassLoader(), true).getModuleLoader(); + } + + /** + * Get a module from the current module loader. Note that this must crawl the + * stack to determine this, so other mechanisms are more efficient. + * @see #getCallerModuleLoader() + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if the module could not be loaded + */ + public static Module getModuleFromCallerModuleLoader(final ModuleIdentifier identifier) throws ModuleLoadException { + return getCallerModuleLoader().loadModule(identifier); + } + + /** + * Get the caller's module. The caller's module is the module containing the method that calls this + * method. Note that this method crawls the stack so other ways of obtaining the + * module are more efficient. + * + * @return the current module + */ + public static Module getCallerModule() { + return forClass(CallerContext.getCallingClass()); + } + + /** + * Get the module with the given identifier from the module loader used by this module. + * + * @param identifier the module identifier + * @return the module + * @throws ModuleLoadException if an error occurs + */ + public Module getModule(final ModuleIdentifier identifier) throws ModuleLoadException { + return moduleLoader.loadModule(identifier); + } + + /** + * Load a class from a module in the system module loader. + * + * @see #getBootModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromBootModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getBootModuleLoader().loadModule(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a module in the caller's module loader. + * + * @see #getCallerModuleLoader() + * + * @param moduleIdentifier the identifier of the module from which the class + * should be loaded + * @param className the class name to load + * @return the class + * @throws ModuleLoadException if the module could not be loaded + * @throws ClassNotFoundException if the class could not be loaded + */ + public static Class loadClassFromCallerModuleLoader(final ModuleIdentifier moduleIdentifier, final String className) + throws ModuleLoadException, ClassNotFoundException { + return Class.forName(className, true, getModuleFromCallerModuleLoader(moduleIdentifier).getClassLoader()); + } + + /** + * Load a class from a local loader. + * + * @param className the class name + * @param exportsOnly {@code true} to only load if the class is exported, {@code false} to load any class + * @param resolve {@code true} to resolve the class after definition + * @return the class + */ + Class loadModuleClass(final String className, final boolean exportsOnly, final boolean resolve) { + for (String s : systemPackages) { + if (className.startsWith(s)) { + try { + return moduleClassLoader.loadClass(className, resolve); + } catch (ClassNotFoundException e) { + return null; + } + } + } + final String path = pathOfClass(className); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + Class clazz; + for (LocalLoader loader : loaders) { + clazz = loader.loadClassLocal(className, resolve); + if (clazz != null) { + return clazz; + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + return fallbackLoader.loadClassLocal(className, resolve); + } + return null; + } + + /** + * Load a resource from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the resource URL, or {@code null} if not found + */ + URL getResource(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + return moduleClassLoader.getResource(canonPath); + } + } + log.trace("Attempting to find resource %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + return resource.getURL(); + } + } + return null; + } + + /** + * Load all resources of a given name from a local loader. + * + * @param name the resource name + * @param exportsOnly {@code true} to only consider exported resources + * @return the enumeration of all the matching resource URLs (may be empty) + */ + Enumeration getResources(final String name, final boolean exportsOnly) { + final String canonPath = PathUtils.canonicalize(name); + for (String s : Module.systemPaths) { + if (canonPath.startsWith(s)) { + try { + return moduleClassLoader.getResources(canonPath); + } catch (IOException e) { + return ConcurrentClassLoader.EMPTY_ENUMERATION; + } + } + } + log.trace("Attempting to find all resources %s in %s", canonPath, this); + final String path = pathOf(canonPath); + final Map> paths = getPathsUnchecked(exportsOnly); + final List loaders = paths.get(path); + + final List list = new ArrayList(); + if (loaders != null) { + for (LocalLoader loader : loaders) { + final List resourceList = loader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + } + final LocalLoader fallbackLoader = this.fallbackLoader; + if (fallbackLoader != null) { + final List resourceList = fallbackLoader.loadResourceLocal(canonPath); + for (Resource resource : resourceList) { + list.add(resource.getURL()); + } + } + + return list.size() == 0 ? ConcurrentClassLoader.EMPTY_ENUMERATION : Collections.enumeration(list); + } + + /** + * Get an exported resource URL. + * + * @param name the resource name + * @return the resource, or {@code null} if it was not found + */ + public URL getExportedResource(final String name) { + return getResource(name, true); + } + + /** + * Get all exported resource URLs for a resource name. + * + * @param name the resource name + * @return the resource URLs + */ + public Enumeration getExportedResources(final String name) { + return getResources(name, true); + } + + /** + * Get the path name of a class. + * + * @param className the binary name of the class + * @return the parent path + */ + static String pathOfClass(final String className) { + final String resourceName = className.replace('.', '/'); + final String path; + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the path name of a resource. + * + * @param resourceName the resource name + * @return the parent path + */ + static String pathOf(final String resourceName) { + final String path; + if (resourceName.indexOf('/') == 0) { + return pathOf(resourceName.substring(1)); + } + final int idx = resourceName.lastIndexOf('/'); + if (idx > -1) { + path = resourceName.substring(0, idx); + } else { + path = ""; + } + return path; + } + + /** + * Get the file name of a class. + * + * @param className the class name + * @return the name of the corresponding class file + */ + static String fileNameOfClass(final String className) { + return className.replace('.', '/') + ".class"; + } + + /** + * Get the string representation of this module. + * + * @return the string representation + */ + @Override + public String toString() { + return "Module \"" + identifier + "\"" + " from " + moduleLoader.toString(); + } + + /** + * Get the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @return the module logger + */ + public static ModuleLogger getModuleLogger() { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + return log; + } + + /** + * Change the logger used by the module system. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("accessModuleLogger") permission to verify access to the module logger. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param logger the new logger, must not be {@code null} + */ + public static void setModuleLogger(final ModuleLogger logger) { + if (logger == null) { + throw new IllegalArgumentException("logger is null"); + } + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ACCESS_MODULE_LOGGER); + } + logger.greeting(); + log = logger; + } + + /** + * Return the start time in millis when Module.class was loaded. + * + * @return start time of Module.class load + */ + public static long getStartTime() { + return StartTimeHolder.START_TIME; + } + + /** + * Register an additional module which contains content handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addContentHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerContentHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_CONTENT_HANDLER_FACTORY); + } + ModularContentHandlerFactory.addHandlerModule(module); + } + + /** + * Register an additional module which contains URL handlers. + *

    + * If a security manager is present, then this method invokes the security manager's {@code checkPermission} method + * with a RuntimePermission("addURLStreamHandlerFactory") permission to verify access. If + * access is not granted, a {@code SecurityException} will be thrown. + * + * @param module the module to add + */ + public static void registerURLStreamHandlerFactoryModule(Module module) { + final SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + sm.checkPermission(ADD_URL_STREAM_HANDLER_FACTORY); + } + ModularURLStreamHandlerFactory.addHandlerModule(module); + } + + // Linking and resolution + + static final class Visited { + private final Module module; + private final FastCopyHashSet filters; + private final int hashCode; + + Visited(final Module module, final FastCopyHashSet filters) { + this.module = module; + this.filters = filters; + hashCode = filters.hashCode() * 13 + module.hashCode(); + } + + public int hashCode() { + return hashCode; + } + + public boolean equals(Object other) { + return other instanceof Visited && equals((Visited)other); + } + + public boolean equals(Visited other) { + return this == other || other != null && module == other.module && filters.equals(other.filters); + } + } + + long addPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + filterStack.add(importFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + filterStack.remove(importFilter); + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final PathFilter importFilter = classLoaderDependency.getImportFilter(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final PathFilter importFilter = localDependency.getImportFilter(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + if (importFilter.accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList()); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + return subtract; + } + + long addExportedPaths(Dependency[] dependencies, Map> map, FastCopyHashSet filterStack, Set visited) throws ModuleLoadException { + if (!visited.add(new Visited(this, filterStack))) { + return 0L; + } + long subtract = 0L; + moduleLoader.incScanCount(); + for (Dependency dependency : dependencies) { + final PathFilter exportFilter = dependency.getExportFilter(); + // skip non-exported dependencies altogether + if (exportFilter != PathFilters.rejectAll()) { + if (dependency instanceof ModuleDependency) { + final ModuleDependency moduleDependency = (ModuleDependency) dependency; + final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); + final ModuleIdentifier id = moduleDependency.getIdentifier(); + final Module module; + + try { + long pauseStart = Metrics.getCurrentCPUTime(); + try { + module = moduleLoader.preloadModule(id); + } finally { + subtract += Metrics.getCurrentCPUTime() - pauseStart; + } + } catch (ModuleLoadException ex) { + if (moduleDependency.isOptional()) { + continue; + } else { + throw ex; + } + } + if (module == null) { + if (!moduleDependency.isOptional()) { + throw new ModuleNotFoundException(id.toString()); + } + continue; + } + + final PathFilter importFilter = dependency.getImportFilter(); + if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { + subtract += module.addExportedPaths(module.getDependencies(), map, filterStack, visited); + } else { + final FastCopyHashSet clone = filterStack.clone(); + clone.add(importFilter); + clone.add(exportFilter); + subtract += module.addExportedPaths(module.getDependencies(), map, clone, visited); + } + } else if (dependency instanceof ModuleClassLoaderDependency) { + final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; + final LocalLoader localLoader = classLoaderDependency.getLocalLoader(); + final Set paths = classLoaderDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && classLoaderDependency.getImportFilter().accept(path) && classLoaderDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } else if (dependency instanceof LocalDependency) { + final LocalDependency localDependency = (LocalDependency) dependency; + final LocalLoader localLoader = localDependency.getLocalLoader(); + final Set paths = localDependency.getPaths(); + for (String path : paths) { + boolean accept = true; + for (Object filter : filterStack.getRawArray()) { + if (filter != null && ! ((PathFilter)filter).accept(path)) { + accept = false; break; + } + } + if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { + List list = map.get(path); + if (list == null) { + map.put(path, list = new ArrayList(1)); + list.add(localLoader); + } else if (! list.contains(localLoader)) { + list.add(localLoader); + } + } + } + } + // else unknown dep type so just skip + } + } + return subtract; + } + + Map> getPaths(final boolean exports) throws ModuleLoadException { + Linkage linkage = this.linkage; + Linkage.State state = linkage.getState(); + if (state.compareTo(exports ? LINKED_EXPORTS : LINKED) >= 0) { + return linkage.getPaths(exports); + } + // slow path loop + boolean intr = false; + try { + for (;;) { + synchronized (this) { + linkage = this.linkage; + state = linkage.getState(); + while (state == (exports ? LINKING_EXPORTS : LINKING) || state == NEW) try { + wait(); + linkage = this.linkage; + state = linkage.getState(); + } catch (InterruptedException e) { + intr = true; + } + if (state == (exports ? LINKED_EXPORTS : LINKED)) { + return linkage.getPaths(exports); + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), exports ? LINKING_EXPORTS : LINKING); + // fall out and link + } + if (exports) { + linkExports(linkage); + } else { + link(linkage); + } + } + } finally { + if (intr) { + Thread.currentThread().interrupt(); + } + } + } + + Map> getPathsUnchecked(final boolean export) { + try { + return getPaths(export); + } catch (ModuleLoadException e) { + throw e.toError(); + } + } + + boolean link(final Linkage linkage) throws ModuleLoadException { + final HashMap> importsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addPaths(dependencies, importsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED, importsMap, null); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + boolean linkExports(final Linkage linkage) throws ModuleLoadException { + final HashMap> exportsMap = new HashMap>(); + final Dependency[] dependencies = linkage.getSourceList(); + final long start = Metrics.getCurrentCPUTime(); + long subtractTime = 0L; + try { + final Set visited = new FastCopyHashSet(16); + final FastCopyHashSet filterStack = new FastCopyHashSet(8); + subtractTime += addExportedPaths(dependencies, exportsMap, filterStack, visited); + synchronized (this) { + if (this.linkage == linkage) { + this.linkage = new Linkage(linkage.getSourceList(), LINKED_EXPORTS, linkage.getAllPaths(), exportsMap); + notifyAll(); + return true; + } + // else all our efforts were just wasted since someone changed the deps in the meantime + return false; + } + } finally { + moduleLoader.addLinkTime(Metrics.getCurrentCPUTime() - start - subtractTime); + } + } + + void linkIfNecessary() throws ModuleLoadException { + Linkage linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + synchronized (this) { + linkage = this.linkage; + if (linkage.getState().compareTo(LINKING) >= 0) { + return; + } + this.linkage = linkage = new Linkage(linkage.getSourceList(), LINKING); + } + link(linkage); + } + + void relink() throws ModuleLoadException { + link(linkage); + } + + void setDependencies(final List dependencySpecs) throws ModuleLoadException { + synchronized (this) { + linkage = new Linkage(calculateDependencies(dependencySpecs), Linkage.State.UNLINKED, null, null); + notifyAll(); + } + } + + private Dependency[] calculateDependencies(final List dependencySpecs) { + final Dependency[] dependencies = new Dependency[dependencySpecs.size()]; + int i = 0; + for (DependencySpec spec : dependencySpecs) { + final Dependency dependency = spec.getDependency(this); + dependencies[i++] = dependency; + } + return dependencies; + } + + String getMainClass() { + return mainClassName; + } + + Package getPackage(final String name) { + List loaders = getPathsUnchecked(false).get(name.replace('.', '/')); + if (loaders != null) for (LocalLoader localLoader : loaders) { + Package pkg = localLoader.loadPackageLocal(name); + if (pkg != null) return pkg; + } + return null; + } + + Package[] getPackages() { + final ArrayList packages = new ArrayList(); + final Map> allPaths = getPathsUnchecked(false); + next: for (String path : allPaths.keySet()) { + String packageName = path.replace('/', '.'); + for (LocalLoader loader : allPaths.get(path)) { + Package pkg = loader.loadPackageLocal(packageName); + if (pkg != null) { + packages.add(pkg); + } + continue next; + } + } + return packages.toArray(new Package[packages.size()]); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `org.jboss.modules.Module.linkIfNecessary` indirectly writes to field `table.[_]` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Module.linkIfNecessary() + +### Procedure Id: +org.jboss.modules.Module.linkIfNecessary():void.7b13ae6ecd7c0744a8d922aafe73910e + +### File: +src/main/java/org/jboss/modules/Module.java + +### Key: +Module.java|linkIfNecessary|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +30e8b5c24ac362a9804b5b1fd4c7660b + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9810/instruction.md b/inferredbugs-9810/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..174f8ceb6da0916fd49963273258263cb9f3ddea --- /dev/null +++ b/inferredbugs-9810/instruction.md @@ -0,0 +1,407 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** leshan +**Bug ID:** 25 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/******************************************************************************* + * Copyright (c) 2015 Sierra Wireless and others. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.html. + * + * Contributors: + * Sierra Wireless - initial API and implementation + * Achim Kraus (Bosch Software Innovations GmbH) - use ServerIdentity + * Achim Kraus (Bosch Software Innovations GmbH) - implement REPLACE/UPDATE + *******************************************************************************/ +package org.eclipse.leshan.client.resource; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.eclipse.leshan.LwM2mId; +import org.eclipse.leshan.client.request.ServerIdentity; +import org.eclipse.leshan.client.servers.ServersInfoExtractor; +import org.eclipse.leshan.core.model.ObjectModel; +import org.eclipse.leshan.core.node.LwM2mObject; +import org.eclipse.leshan.core.node.LwM2mObjectInstance; +import org.eclipse.leshan.core.node.LwM2mPath; +import org.eclipse.leshan.core.node.LwM2mResource; +import org.eclipse.leshan.core.request.BootstrapDeleteRequest; +import org.eclipse.leshan.core.request.BootstrapWriteRequest; +import org.eclipse.leshan.core.request.ContentFormat; +import org.eclipse.leshan.core.request.CreateRequest; +import org.eclipse.leshan.core.request.DeleteRequest; +import org.eclipse.leshan.core.request.DownlinkRequest; +import org.eclipse.leshan.core.request.ExecuteRequest; +import org.eclipse.leshan.core.request.ObserveRequest; +import org.eclipse.leshan.core.request.ReadRequest; +import org.eclipse.leshan.core.request.WriteRequest; +import org.eclipse.leshan.core.request.WriteRequest.Mode; +import org.eclipse.leshan.core.response.BootstrapDeleteResponse; +import org.eclipse.leshan.core.response.BootstrapWriteResponse; +import org.eclipse.leshan.core.response.CreateResponse; +import org.eclipse.leshan.core.response.DeleteResponse; +import org.eclipse.leshan.core.response.ExecuteResponse; +import org.eclipse.leshan.core.response.ObserveResponse; +import org.eclipse.leshan.core.response.ReadResponse; +import org.eclipse.leshan.core.response.WriteResponse; + +public class ObjectEnabler extends BaseObjectEnabler { + + private Map instances; + private LwM2mInstanceEnablerFactory instanceFactory; + private ContentFormat defaultContentFormat; + + public ObjectEnabler(int id, ObjectModel objectModel, Map instances, + LwM2mInstanceEnablerFactory instanceFactory, ContentFormat defaultContentFormat) { + super(id, objectModel); + this.instances = new HashMap<>(instances); + this.instanceFactory = instanceFactory; + this.defaultContentFormat = defaultContentFormat; + for (Entry entry : this.instances.entrySet()) { + addInstance(entry.getKey(), entry.getValue()); + } + } + + @Override + public synchronized List getAvailableInstanceIds() { + List ids = new ArrayList<>(instances.keySet()); + Collections.sort(ids); + return ids; + } + + @Override + public synchronized List getAvailableResourceIds(int instanceId) { + LwM2mInstanceEnabler instanceEnabler = instances.get(instanceId); + if (instanceEnabler != null) { + return instanceEnabler.getAvailableResourceIds(getObjectModel()); + } else { + return Collections.emptyList(); + } + } + + public synchronized void addInstance(int instanceId, LwM2mInstanceEnabler newInstance) { + instances.put(instanceId, newInstance); + listenInstance(newInstance, instanceId); + } + + public synchronized LwM2mInstanceEnabler getInstance(int instanceId) { + return instances.get(instanceId); + } + + public synchronized LwM2mInstanceEnabler removeInstance(int instanceId) { + return instances.remove(instanceId); + } + + @Override + protected CreateResponse doCreate(ServerIdentity identity, CreateRequest request) { + Integer instanceId = request.getInstanceId(); // instanceId CAN be NULL + + // check instance id is valid + if (instanceId != null) { + if (instances.containsKey(instanceId)) { + return CreateResponse.badRequest("Target already exists"); + } + if (!getObjectModel().multiple && instanceId != 0) { + return CreateResponse.badRequest("id must be 0 for single instance"); + } + } else { + // default 0 instance id for single instance object + if (!getObjectModel().multiple) { + instanceId = 0; + } + } + + // create the new instance + LwM2mInstanceEnabler newInstance = instanceFactory.create(getObjectModel(), instanceId, instances.keySet()); + + // add/write resource + for (LwM2mResource resource : request.getResources()) { + newInstance.write(identity, resource.getId(), resource); + } + + // add new instance to this object + instances.put(newInstance.getId(), newInstance); + listenInstance(newInstance, newInstance.getId()); + + return CreateResponse.success(new LwM2mPath(request.getPath().getObjectId(), newInstance.getId()).toString()); + } + + @Override + protected ReadResponse doRead(ServerIdentity identity, ReadRequest request) { + LwM2mPath path = request.getPath(); + + // Manage Object case + if (path.isObject()) { + List lwM2mObjectInstances = new ArrayList<>(); + for (LwM2mInstanceEnabler instance : instances.values()) { + ReadResponse response = instance.read(identity); + if (response.isSuccess()) { + lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent()); + } + } + return ReadResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances)); + } + + // Manage Instance case + LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); + if (instance == null) + return ReadResponse.notFound(); + + if (path.getResourceId() == null) { + return instance.read(identity); + } + + // Manage Resource case + return instance.read(identity, path.getResourceId()); + } + + @Override + protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) { + final LwM2mPath path = request.getPath(); + + // Manage Object case + if (path.isObject()) { + List lwM2mObjectInstances = new ArrayList<>(); + for (LwM2mInstanceEnabler instance : instances.values()) { + ReadResponse response = instance.observe(identity); + if (response.isSuccess()) { + lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent()); + } + } + return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances)); + } + + // Manage Instance case + final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); + if (instance == null) + return ObserveResponse.notFound(); + + if (path.getResourceId() == null) { + return instance.observe(identity); + } + + // Manage Resource case + return instance.observe(identity, path.getResourceId()); + } + + @Override + protected WriteResponse doWrite(ServerIdentity identity, WriteRequest request) { + LwM2mPath path = request.getPath(); + + // Manage Instance case + LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); + if (instance == null) + return WriteResponse.notFound(); + + if (path.isObjectInstance()) { + return instance.write(identity, request.isReplaceRequest(), (LwM2mObjectInstance) request.getNode()); + } + + // Manage Resource case + return instance.write(identity, path.getResourceId(), (LwM2mResource) request.getNode()); + } + + @Override + protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) { + LwM2mPath path = request.getPath(); + + // Manage Object case + if (path.isObject()) { + for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) { + LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId()); + if (instanceEnabler == null) { + doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); + } else { + doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), path.getObjectInstanceId(), + instanceNode.getResources().values())); + } + } + return BootstrapWriteResponse.success(); + } + + // Manage Instance case + if (path.isObjectInstance()) { + LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode(); + LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); + if (instanceEnabler == null) { + doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode)); + } else { + doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(), + path.getObjectInstanceId(), instanceNode.getResources().values())); + } + return BootstrapWriteResponse.success(); + } + + // Manage resource case + LwM2mResource resource = (LwM2mResource) request.getNode(); + LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId()); + if (instanceEnabler == null) { + doCreate(identity, new CreateRequest(path.getObjectId(), + new LwM2mObjectInstance(path.getObjectInstanceId(), resource))); + } else { + instanceEnabler.write(identity, path.getResourceId(), resource); + } + return BootstrapWriteResponse.success(); + } + + @Override + protected ExecuteResponse doExecute(ServerIdentity identity, ExecuteRequest request) { + LwM2mPath path = request.getPath(); + LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId()); + if (instance == null) { + return ExecuteResponse.notFound(); + } + return instance.execute(identity, path.getResourceId(), request.getParameters()); + } + + @Override + protected DeleteResponse doDelete(ServerIdentity identity, DeleteRequest request) { + LwM2mInstanceEnabler deletedInstance = instances.remove(request.getPath().getObjectInstanceId()); + if (deletedInstance != null) { + deletedInstance.onDelete(identity); + return DeleteResponse.success(); + } + return DeleteResponse.notFound(); + } + + @Override + public BootstrapDeleteResponse doDelete(ServerIdentity identity, BootstrapDeleteRequest request) { + if (request.getPath().isRoot() || request.getPath().isObject()) { + if (id == LwM2mId.SECURITY) { + // For security object, we clean everything except bootstrap Server account. + Entry bootstrapServerAccount = null; + for (Entry instance : instances.entrySet()) { + if (ServersInfoExtractor.isBootstrapServer(instance.getValue())) { + bootstrapServerAccount = instance; + } + } + instances.clear(); + if (bootstrapServerAccount != null) { + instances.put(bootstrapServerAccount.getKey(), bootstrapServerAccount.getValue()); + } + return BootstrapDeleteResponse.success(); + } else { + instances.clear(); + return BootstrapDeleteResponse.success(); + } + } else if (request.getPath().isObjectInstance()) { + if (id == LwM2mId.SECURITY) { + // For security object, deleting bootstrap Server account is not allowed + LwM2mInstanceEnabler instance = instances.get(request.getPath().getObjectInstanceId()); + if (ServersInfoExtractor.isBootstrapServer(instance)) { + return BootstrapDeleteResponse.badRequest("bootstrap server can not be deleted"); + } + } + if (null != instances.remove(request.getPath().getObjectInstanceId())) { + return BootstrapDeleteResponse.success(); + } else { + return BootstrapDeleteResponse.badRequest(String.format("Instance %s not found", request.getPath())); + } + } + return BootstrapDeleteResponse.badRequest(String.format("unexcepted path %s", request.getPath())); + } + + private void listenInstance(LwM2mInstanceEnabler instance, final int instanceId) { + instance.addResourceChangedListener(new ResourceChangedListener() { + + @Override + public void resourcesChanged(int... resourceIds) { + NotifySender sender = getNotifySender(); + if (null != sender) { + // check, if sender is available + sender.sendNotify(getId() + ""); + sender.sendNotify(getId() + "/" + instanceId); + for (int resourceId : resourceIds) { + sender.sendNotify(getId() + "/" + instanceId + "/" + resourceId); + } + } + } + }); + } + + @Override + public ContentFormat getDefaultEncodingFormat(DownlinkRequest request) { + return defaultContentFormat; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `path.getObjectInstanceId()` could be null and is dereferenced at line 222. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +BootstrapWriteResponse ObjectEnabler.doWrite(ServerIdentity,BootstrapWriteRequest) + +### Procedure Id: +org.eclipse.leshan.client.resource.ObjectEnabler.doWrite(org.eclipse.leshan.client.request.ServerIde.0f78ce50283d201e03089de82b4b6e02 + +### File: +leshan-client-core/src/main/java/org/eclipse/leshan/client/resource/ObjectEnabler.java + +### Key: +ObjectEnabler.java|doWrite|NULL_DEREFERENCE + +### Node Key: +42f56fda1ad408e362508b93a175bb0c + +### Hash: +5b038b7525cc8ac039923e81109d254e + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9819/instruction.md b/inferredbugs-9819/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90da9f94cbd57945bf591d96d48e4a39a9dafc4f --- /dev/null +++ b/inferredbugs-9819/instruction.md @@ -0,0 +1,207 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** pippo +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package ro.pippo.session.xmemcached; + +import java.io.IOException; +import net.rubyeye.xmemcached.MemcachedClient; +import org.junit.AfterClass; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import ro.pippo.core.Application; +import ro.pippo.session.SessionData; + +/** + * @author Herman Barrantes + */ +@Ignore("You need run MemCached localy") +public class XmemcachedSessionDataStorageTest { + + private static final String KEY = "KEY"; + private static final String VALUE = "VALUE"; + private static final int IDLE_TIME = 1; + private static Application application; + private static MemcachedClient client; + + @BeforeClass + public static void setUpClass() { + application = new Application(); + client = XmemcachedFactory.create(application.getPippoSettings()); + } + + @AfterClass + public static void tearDownClass() throws IOException { + client.shutdown(); + } + + /** + * Test of create method, of class XmemcachedSessionDataStorage. + */ + @Test + public void testCreate() { + System.out.println("create"); + XmemcachedSessionDataStorage instance = new XmemcachedSessionDataStorage(client, IDLE_TIME); + SessionData sessionData = instance.create(); + sessionData.setAttribute(KEY, VALUE); + assertNotNull(sessionData); + assertNotNull(sessionData.getId()); + assertNotNull(sessionData.getCreationTime()); + assertEquals(sessionData.getAttribute(KEY), VALUE); + } + + /** + * Test of save method, of class XmemcachedSessionDataStorage. + */ + @Test + public void testSave() { + System.out.println("save"); + XmemcachedSessionDataStorage instance = new XmemcachedSessionDataStorage(client, IDLE_TIME); + SessionData sessionData = instance.create(); + String sessionId = sessionData.getId(); + sessionData.setAttribute(KEY, VALUE); + instance.save(sessionData); + SessionData saved = instance.get(sessionId); + assertEquals(sessionData, saved); + assertEquals(sessionData.getAttribute(KEY), saved.getAttribute(KEY)); + } + + /** + * Test of get method, of class XmemcachedSessionDataStorage. + */ + @Test + public void testGet() { + System.out.println("get"); + XmemcachedSessionDataStorage instance = new XmemcachedSessionDataStorage(client, IDLE_TIME); + SessionData sessionData = instance.create(); + String sessionId = sessionData.getId(); + sessionData.setAttribute(KEY, VALUE); + instance.save(sessionData); + SessionData saved = instance.get(sessionId); + assertEquals(sessionData, saved); + assertEquals(sessionData.getAttribute(KEY), saved.getAttribute(KEY)); + } + + /** + * Test of get method, of class XmemcachedSessionDataStorage. + * @throws java.lang.InterruptedException + */ + @Test + public void testGetExpired() throws InterruptedException { + System.out.println("get expired"); + XmemcachedSessionDataStorage instance = new XmemcachedSessionDataStorage(client, IDLE_TIME); + SessionData sessionData = instance.create(); + String sessionId = sessionData.getId(); + sessionData.setAttribute(KEY, VALUE); + instance.save(sessionData); + Thread.sleep(2000L); // 2seconds + SessionData deleted = instance.get(sessionId); + assertNull(deleted); + } + + /** + * Test of delete method, of class XmemcachedSessionDataStorage. + */ + @Test + public void testDelete() { + System.out.println("delete"); + XmemcachedSessionDataStorage instance = new XmemcachedSessionDataStorage(client, IDLE_TIME); + SessionData sessionData = instance.create(); + String sessionId = sessionData.getId(); + sessionData.setAttribute(KEY, VALUE); + instance.save(sessionData); + instance.delete(sessionId); + SessionData deleted = instance.get(sessionId); + assertNull(deleted); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `ro.pippo.session.xmemcached.XmemcachedSessionDataStorageTest.application.getPippoSettings()` could be null and is dereferenced by call to `create(...)` at line 45. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void XmemcachedSessionDataStorageTest.setUpClass() + +### Procedure Id: +ro.pippo.session.xmemcached.XmemcachedSessionDataStorageTest.setUpClass():void.ab454ec1134d97890581a69bb1e0a570 + +### File: +pippo-session-parent/pippo-session-xmemcached/src/test/java/ro/pippo/session/xmemcached/XmemcachedSessionDataStorageTest.java + +### Key: +XmemcachedSessionDataStorageTest.java|setUpClass|NULL_DEREFERENCE + +### Node Key: +265ba86214678cae77b0c9ab2eedcb6d + +### Hash: +d8e92666f781dde37881d23d0572e289 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9821/instruction.md b/inferredbugs-9821/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3b8295a30065bb6d912489a63d95194e89902db --- /dev/null +++ b/inferredbugs-9821/instruction.md @@ -0,0 +1,597 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 18 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is provided to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.basho.riak.client.bucket; + +import java.util.Collection; +import java.util.concurrent.Callable; + +import com.basho.riak.client.RiakRetryFailedException; +import com.basho.riak.client.builders.BucketPropertiesBuilder; +import com.basho.riak.client.cap.Quora; +import com.basho.riak.client.cap.Retrier; +import com.basho.riak.client.http.util.Constants; +import com.basho.riak.client.operations.RiakOperation; +import com.basho.riak.client.query.functions.NamedErlangFunction; +import com.basho.riak.client.query.functions.NamedFunction; +import com.basho.riak.client.raw.RawClient; +import com.basho.riak.client.raw.Transport; + +/** + * A {@link RiakOperation} for creating/updating a {@link Bucket}. + * + *

    + * This class is a fluid builder for creating a {@link RiakOperation} that sets + * bucket properties on a bucket in Riak. It delegates to a + * {@link BucketPropertiesBuilder} then uses its {@link RawClient} and + * {@link Retrier} to set the bucket properties in Riak. + *

    + *

    + * NOTE: all the parameters on the builder are optional. If omitted then the + * Riak defaults will be used. Also, very few of these properties are supported + * by both underlying APIs at present. They are here for completeness sake. + * Changes are underway to support all the properties. Check the docs for the + * individual parameters to see what is supported. + *

    + * + * @author russell + * + */ +public class WriteBucket implements RiakOperation { + + private final RawClient client; + private Retrier retrier; + private String name; + private final Collection existingPrecommitHooks; + + private BucketPropertiesBuilder builder = new BucketPropertiesBuilder(); + + /** + * Create WriteBucket operation that delegates to the given {@link RawClient} via the give {@link Retrier}. + * @param client the {@link RawClient} to delegate to + * @param name the name of the bucket to create/update + * @param retrier the {@link Retrier} to use + */ + public WriteBucket(final RawClient client, String name, final Retrier retrier) { + this.name = name; + this.client = client; + this.retrier = retrier; + this.existingPrecommitHooks = null; + } + + /** + * Create WriteBucket operation that delegates to the given + * {@link RawClient} via the give {@link Retrier}. + * + * @param client + * the {@link RawClient} to delegate to + * @param bucket + * the bucket to update + * @param retrier + * the {@link Retrier} to use + */ + public WriteBucket(final RawClient client, Bucket bucket, final Retrier retrier) { + this.name = bucket.getName(); + this.client = client; + this.retrier = retrier; + this.existingPrecommitHooks = bucket.getPrecommitHooks(); + } + + /** + * Creates/updates a Bucket in Riak with the set of properties configured. + * @return the {@link Bucket} + */ + public Bucket execute() throws RiakRetryFailedException { + final BucketProperties propsToStore = builder.build(); + + retrier.attempt(new Callable() { + public Void call() throws Exception { + client.updateBucket(name, propsToStore); + return null; + } + }); + + BucketProperties properties = retrier.attempt(new Callable() { + public BucketProperties call() throws Exception { + return client.fetchBucket(name); + } + }); + + return new DefaultBucket(name, properties, client, retrier); + } + + /** + * Should the bucket have allow_mult set to true? + * @param allowSiblings + * @return this + */ + public WriteBucket allowSiblings(boolean allowSiblings) { + builder.allowSiblings(allowSiblings); + return this; + } + + /** + * Is this bucket last_write_wins? + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport. + * @param lastWriteWins + * @return this + */ + public WriteBucket lastWriteWins(boolean lastWriteWins) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_LAST_WRITE_WINS); + builder.lastWriteWins(lastWriteWins); + return this; + } + + /** + * The n_val for this bucket + * @param nVal + * @return this + */ + public WriteBucket nVal(int nVal) { + builder.nVal(nVal); + return this; + } + + /** + * Which backend this bucket uses. + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param backend + * @return this + */ + public WriteBucket backend(String backend) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_BACKEND); + builder.backend(backend); + return this; + } + + /** + * A Collection of precommit hooks for this bucket + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param precommitHooks + * @return + */ + public WriteBucket precommitHooks(Collection precommitHooks) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); + builder.precommitHooks(precommitHooks); + return this; + } + + /** + * Add a precommit hook to the Collection of hooks to be written. + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param preCommitHook + * @return this + */ + public WriteBucket addPrecommitHook(NamedFunction preCommitHook) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); + builder.addPrecommitHook(preCommitHook); + return this; + } + + /** + * Add a collection of postcommit hooks to the bucket to be written. + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param postCommitHooks + * @return + */ + public WriteBucket postcommitHooks(Collection postCommitHooks) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_POSTCOMMIT); + builder.postcommitHooks(postCommitHooks); + return this; + } + + /** + * Add a postcommit hook to the Collection of post commit hooks for the bucket to written. + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param postcommitHook + * @return + */ + public WriteBucket addPostcommitHook(NamedErlangFunction postcommitHook) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_POSTCOMMIT); + builder.addPostcommitHook(postcommitHook); + return this; + } + + /** + * Set the chash_key_fun on the bucket to be written + * NOTE: at present this is not supported by the PB API and has no effect for that client. + * @param chashKeyFunction + * @return + */ + public WriteBucket chashKeyFunction(NamedErlangFunction chashKeyFunction) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_CHASHFUN); + builder.chashKeyFunction(chashKeyFunction); + return this; + } + + /** + * Set the link_walk_fun used by Riak on the bucket to be written. + * NOTE: at present this is not supported by the PB API and has no effect for that client. + * @param linkWalkFunction + * @return + */ + public WriteBucket linkWalkFunction(NamedErlangFunction linkWalkFunction) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_LINKFUN); + builder.linkWalkFunction(linkWalkFunction); + return this; + } + + /** + * set the small vclock prune size + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param smallVClock + * @return + */ + public WriteBucket smallVClock(int smallVClock) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_SMALL_VCLOCK); + builder.smallVClock(smallVClock); + return this; + } + + /** + * set the big_vclock prune size + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param bigVClock + * @return + */ + public WriteBucket bigVClock(int bigVClock) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_BIG_VCLOCK); + builder.bigVClock(bigVClock); + return this; + } + + /** + * set the young_vclock prune age + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param youngVClock + * @return + */ + public WriteBucket youngVClock(long youngVClock) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_YOUNG_VCLOCK); + builder.youngVClock(youngVClock); + return this; + } + + /** + * set the old_vclock prune age + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param oldVClock + * @return + */ + public WriteBucket oldVClock(long oldVClock) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_OLD_VCLOCK); + builder.oldVClock(oldVClock); + return this; + } + + /** + * The default r Quorom for the bucket + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param r + * @return + */ + public WriteBucket r(Quora r) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_R); + builder.r(r); + return this; + } + + /** + * The default r quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param r + * @return + */ + public WriteBucket r(int r) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_R); + builder.r(r); + return this; + } + + /** + * The default w quorom + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param w + * @return + */ + public WriteBucket w(Quora w) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_W); + builder.w(w); + return this; + } + + /** + * The default w quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param w + * @return + */ + public WriteBucket w(int w) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_W); + builder.w(w); + return this; + } + + /** + * The default rw quorom + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param rw + * @return + */ + public WriteBucket rw(Quora rw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_RW); + builder.rw(rw); + return this; + } + + /** + * The default rw quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param rw + * @return + */ + public WriteBucket rw(int rw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_RW); + builder.rw(rw); + return this; + } + + /** + * The default dw quorom + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param dw + * @return + */ + public WriteBucket dw(Quora dw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_DW); + builder.dw(dw); + return this; + } + + /** + * The default dw quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param dw + * @return + */ + public WriteBucket dw(int dw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_DW); + builder.dw(dw); + return this; + } + + /** + * The default pr quorom + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param pr + * @return + */ + public WriteBucket pr(Quora pr) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PR); + builder.pr(pr); + return this; + } + + /** + * The default pr quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param pr + * @return + */ + public WriteBucket pr(int pr) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PR); + builder.pr(pr); + return this; + } + + /** + * The default pw quorom + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param pw + * @return + */ + public WriteBucket pw(Quora pw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PW); + builder.pw(pw); + return this; + } + + /** + * The default dw quorom as an int + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param dw + * @return + */ + public WriteBucket pw(int pw) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_PW); + builder.pw(pw); + return this; + } + + /** + * The default basic_quorum value + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param basicQuorum + * @return + */ + public WriteBucket basicQuorum(boolean basicQuorum) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_BASIC_QUORUM); + builder.basicQuorum(basicQuorum); + return this; + } + + /** + * The default notfound_ok value + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @param notFoundOK + * @return + */ + public WriteBucket notFoundOK(boolean notFoundOK) { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_NOT_FOUND_OK); + builder.notFoundOK(notFoundOK); + return this; + } + + /** + * Specify the retrier to use for this operation. + * If non-provided will use the client configured default. + * + * @param retrier a Retrier to use for the execute operation + * @return this + */ + public WriteBucket withRetrier(final Retrier retrier) { + this.retrier = retrier; + return this; + } + + /** + * convenience for setting search=true **and** adding the search precommit + * hook (support for both pre-1.0 and 1.0 search) + * NOTE: at present this is not supported by PB API and + * an {@link UnsupportedPropertyException} will be thrown if called for that transport + * @return this + */ + public WriteBucket enableForSearch() { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); + builder.addPrecommitHook(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK).search(true); + return this; + } + + /** + * convenience for setting search=false **and** removing the search + * precommit hook (support for both pre-1.0 and 1.0 search) NOTE: at present + * this is not supported by PB API and an + * {@link UnsupportedPropertyException} will be thrown if called for that + * transport + * + * @return this + */ + public WriteBucket disableSearch() { + httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); + if (existingPrecommitHooks != null) { + synchronized (existingPrecommitHooks) { + existingPrecommitHooks.remove(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK); + for (NamedFunction f : existingPrecommitHooks) { + builder.addPrecommitHook(f); + } + } + } + builder.search(false); + return this; + } + + private void httpOnly(Transport transport, String propertyName) { + if(!Transport.HTTP.equals(transport)) { + throw new UnsupportedPropertyException(transport, propertyName); + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.basho.riak.client.bucket.WriteBucket.enableForSearch` indirectly writes to field `this.com.basho.riak.client.bucket.WriteBucket.builder.com.basho.riak.client.builders.BucketPropertiesBuilder.precommitHooks` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +WriteBucket WriteBucket.enableForSearch() + +### Procedure Id: +com.basho.riak.client.bucket.WriteBucket.enableForSearch():com.basho.riak.client.bucket.WriteBucket.faa628b58dcf33511d77f0731fed8568 + +### File: +src/main/java/com/basho/riak/client/bucket/WriteBucket.java + +### Key: +WriteBucket.java|enableForSearch|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +bc562b4d62d9fbc779a247db7ebbc45a + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9826/instruction.md b/inferredbugs-9826/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1245e7b3eba00e636ae106ca0c3fe306bda601b9 --- /dev/null +++ b/inferredbugs-9826/instruction.md @@ -0,0 +1,659 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 6 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.prefs.BackingStoreException; +import java.util.prefs.Preferences; +import org.apache.commons.codec.binary.Base64; + +import org.json.JSONObject; + +import com.basho.riak.client.http.util.Constants; +import com.basho.riak.client.util.CharsetUtils; +import com.basho.riak.pbc.RPB.RpbDelReq; +import com.basho.riak.pbc.RPB.RpbGetClientIdResp; +import com.basho.riak.pbc.RPB.RpbGetReq; +import com.basho.riak.pbc.RPB.RpbGetResp; +import com.basho.riak.pbc.RPB.RpbGetServerInfoResp; +import com.basho.riak.pbc.RPB.RpbListBucketsResp; +import com.basho.riak.pbc.RPB.RpbMapRedReq; +import com.basho.riak.pbc.RPB.RpbPutReq; +import com.basho.riak.pbc.RPB.RpbPutResp; +import com.basho.riak.pbc.RPB.RpbSetClientIdReq; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +//import com.trifork.riak.RPB.RpbListKeysResp; +//import com.trifork.riak.RPB.RpbMapRedResp; + +/** + * Low level protocol buffers client. + */ +public class RiakClient implements RiakMessageCodes { + + private static final int BUFFER_SIZE_KB; + + static { + BUFFER_SIZE_KB = Integer.parseInt(System.getProperty("com.basho.riak.client.pbc,buffer", "16")); + } + + private static final RiakObject[] NO_RIAK_OBJECTS = new RiakObject[0]; + private static final ByteString[] NO_BYTE_STRINGS = new ByteString[0]; + //private static final String[] NO_STRINGS = new String[0]; + //private static final MapReduceResponse[] NO_MAP_REDUCE_RESPONSES = new MapReduceResponse[0]; + + private String node; + private String serverVersion; + private InetAddress addr; + private int port; + private int bufferSizeKb; + + /** + * if this has been set (or gotten) then it will be applied to new + * connections + */ + private volatile ByteString clientID; + + public RiakClient(String host) throws IOException { + this(host, RiakConnection.DEFAULT_RIAK_PB_PORT); + } + + public RiakClient(String host, int port) throws IOException { + this(InetAddress.getByName(host), port); + } + + public RiakClient(InetAddress addr, int port) throws IOException { + this.addr = addr; + this.port = port; + this.bufferSizeKb = BUFFER_SIZE_KB; + } + + public RiakClient(String host, int port, int bufferSizeKb) throws IOException { + this.addr = InetAddress.getByName(host); + this.port = port; + this.bufferSizeKb = bufferSizeKb; + } + + private ThreadLocal connections = new ThreadLocal(); + + RiakConnection getConnection() throws IOException { + return getConnection(true); + } + + RiakConnection getConnection(boolean setClientId) throws IOException { + RiakConnection c = connections.get(); + if (c == null || !c.endIdleAndCheckValid()) { + c = new RiakConnection(addr, port, bufferSizeKb); + + if (this.clientID != null && setClientId) { + connections.set(c); + setClientID(clientID); + } + } + connections.set(null); + return c; + } + + void release(RiakConnection c) { + RiakConnection cc = connections.get(); + if (cc == null) { + c.beginIdle(); + connections.set(c); + } else { + c.close(); + } + } + + /** + * helper method to use a reasonable default client id + * beware, it caches the client id. If you call it multiple times on the same client + * you get the *same* id (not good for reusing a client with different ids) + * + * @throws IOException + */ + public void prepareClientID() throws IOException { + Preferences prefs = Preferences.userNodeForPackage(RiakClient.class); + + String clid = prefs.get("client_id", null); + if (clid == null) { + SecureRandom sr; + try { + sr = SecureRandom.getInstance("SHA1PRNG"); + // Not totally secure, but doesn't need to be + // and 100% less prone to 30 second hangs on linux jdk5 + sr.setSeed(UUID.randomUUID().getLeastSignificantBits() + new Date().getTime()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + byte[] data = new byte[6]; + sr.nextBytes(data); + clid = CharsetUtils.asString(Base64.encodeBase64Chunked(data), CharsetUtils.ISO_8859_1); + prefs.put("client_id", clid); + try { + prefs.flush(); + } catch (BackingStoreException e) { + throw new IOException(e.toString()); + } + } + + setClientID(clid); + } + + public void ping() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_PingReq); + c.receive_code(MSG_PingResp); + } finally { + release(c); + } + } + + /** + * Warning: the riak client id is 4 bytes. This method silently truncates anymore bytes than that. + * Be aware that if you have two client Ids, "boris1" and "boris2" this method will leave you with 1 client id, "bori". + * Use {@link RiakClient#prepareClientID()} to generate a reasonably unique Id. + * @see RiakClient#prepareClientID() + * @param id + * @throws IOException + */ + public void setClientID(String id) throws IOException { + if(id == null || id.length() < Constants.RIAK_CLIENT_ID_LENGTH) { + throw new IllegalArgumentException("Client ID must be at least " + Constants.RIAK_CLIENT_ID_LENGTH + " bytes long"); + } + setClientID(ByteString.copyFrom(CharsetUtils.utf8StringToBytes(id), 0, Constants.RIAK_CLIENT_ID_LENGTH)); + } + + // ///////////////////// + + public void setClientID(ByteString id) throws IOException { + if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { + id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); + } + RpbSetClientIdReq req = RPB.RpbSetClientIdReq.newBuilder().setClientId( + id).build(); + RiakConnection c = getConnection(false); + try { + c.send(MSG_SetClientIdReq, req); + c.receive_code(MSG_SetClientIdResp); + } finally { + release(c); + } + + this.clientID = id; + } + + public String getClientID() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_GetClientIdReq); + byte[] data = c.receive(MSG_GetClientIdResp); + if (data == null) + return null; + RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); + clientID = res.getClientId(); + return clientID.toStringUtf8(); + } finally { + release(c); + } + } + + public Map getServerInfo() throws IOException { + RiakConnection c = getConnection(); + try { + c.send(MSG_GetServerInfoReq); + byte[] data = c.receive(MSG_GetServerInfoResp); + if (data == null) + return Collections.emptyMap(); + + RpbGetServerInfoResp res = RPB.RpbGetServerInfoResp.parseFrom(data); + if (res.hasNode()) { + this.node = res.getNode().toStringUtf8(); + } + if (res.hasServerVersion()) { + this.serverVersion = res.getServerVersion().toStringUtf8(); + } + Map result = new HashMap(); + result.put("node", node); + result.put("server_version", serverVersion); + return result; + } finally { + release(c); + } + } + + // ///////////////////// + + public RiakObject[] fetch(String bucket, String key, int readQuorum) + throws IOException { + return fetch(ByteString.copyFromUtf8(bucket), ByteString + .copyFromUtf8(key), readQuorum); + } + + public RiakObject[] fetch(ByteString bucket, ByteString key, int readQuorum) + throws IOException { + RpbGetReq req = RPB.RpbGetReq.newBuilder().setBucket(bucket) + .setKey(key).setR(readQuorum).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetReq, req); + return process_fetch_reply(c, bucket, key); + } finally { + release(c); + } + + } + + public RiakObject[] fetch(String bucket, String key) throws IOException { + return fetch(ByteString.copyFromUtf8(bucket), ByteString + .copyFromUtf8(key)); + } + + public RiakObject[] fetch(ByteString bucket, ByteString key) + throws IOException { + RpbGetReq req = RPB.RpbGetReq.newBuilder().setBucket(bucket) + .setKey(key).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetReq, req); + return process_fetch_reply(c, bucket, key); + } finally { + release(c); + } + } + + private RiakObject[] process_fetch_reply(RiakConnection c, + ByteString bucket, ByteString key) throws IOException, + InvalidProtocolBufferException { + byte[] rep = c.receive(MSG_GetResp); + + if (rep == null) { + return NO_RIAK_OBJECTS; + } + + RpbGetResp resp = RPB.RpbGetResp.parseFrom(rep); + int count = resp.getContentCount(); + RiakObject[] out = new RiakObject[count]; + ByteString vclock = resp.getVclock(); + for (int i = 0; i < count; i++) { + out[i] = new RiakObject(vclock, bucket, key, resp.getContent(i)); + } + return out; + } + + // ///////////////////// + + public ByteString[] store(RiakObject[] values, RequestMeta meta) + throws IOException { + + RiakConnection c = getConnection(); + try { + BulkReader reader = new BulkReader(c, values.length); + Thread worker = new Thread(reader); + worker.start(); + + DataOutputStream dout = c.getOutputStream(); + + for (int i = 0; i < values.length; i++) { + RiakObject value = values[i]; + + RPB.RpbPutReq.Builder builder = RPB.RpbPutReq.newBuilder() + .setBucket(value.getBucketBS()) + .setKey(value.getKeyBS()).setContent( + value.buildContent()); + + if (value.getVclock() != null) { + builder.setVclock(value.getVclock()); + } + + builder.setReturnBody(true); + + if (meta != null) { + + if (meta.writeQuorum != null) { + builder.setW(meta.writeQuorum.intValue()); + } + + if (meta.durableWriteQuorum != null) { + builder.setDw(meta.durableWriteQuorum.intValue()); + } + } + + RpbPutReq req = builder.build(); + + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(MSG_PutReq); + req.writeTo(dout); + } + + dout.flush(); + + try { + worker.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + return reader.vclocks; + } finally { + release(c); + } + } + + class BulkReader implements Runnable { + + private ByteString[] vclocks; + private final RiakConnection c; + + public BulkReader(RiakConnection c, int count) { + this.c = c; + this.vclocks = new ByteString[count]; + } + + public void run() { + + try { + for (int i = 0; i < vclocks.length; i++) { + byte[] data = c.receive(MSG_PutResp); + if (data != null) { + RpbPutResp resp = RPB.RpbPutResp.parseFrom(data); + if (resp.hasVclock()) { + vclocks[i] = resp.getVclock(); + } + } + } + } catch (IOException e) { + // TODO + e.printStackTrace(); + } + + } + + } + + public void store(RiakObject value) throws IOException { + store(value, null); + } + + public RiakObject[] store(RiakObject value, IRequestMeta meta) + throws IOException { + + RPB.RpbPutReq.Builder builder = RPB.RpbPutReq.newBuilder().setBucket( + value.getBucketBS()).setKey(value.getKeyBS()).setContent( + value.buildContent()); + + if (value.getVclock() != null) { + builder.setVclock(value.getVclock()); + } + + if (meta != null) { + meta.preparePut(builder); + } + + RiakConnection c = getConnection(); + try { + c.send(MSG_PutReq, builder.build()); + byte[] r = c.receive(MSG_PutResp); + + if (r == null) { + return NO_RIAK_OBJECTS; + } + + RpbPutResp resp = RPB.RpbPutResp.parseFrom(r); + + RiakObject[] res = new RiakObject[resp.getContentsCount()]; + ByteString vclock = resp.getVclock(); + + for (int i = 0; i < res.length; i++) { + res[i] = new RiakObject(vclock, value.getBucketBS(), value + .getKeyBS(), resp.getContents(i)); + } + + return res; + } finally { + release(c); + } + } + + // ///////////////////// + + public void delete(String bucket, String key, int rw) throws IOException { + delete(ByteString.copyFromUtf8(bucket), ByteString.copyFromUtf8(key), + rw); + } + + public void delete(ByteString bucket, ByteString key, int rw) + throws IOException { + RpbDelReq req = RPB.RpbDelReq.newBuilder().setBucket(bucket) + .setKey(key).setRw(rw).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_DelReq, req); + c.receive_code(MSG_DelResp); + } finally { + release(c); + } + + } + + public void delete(String bucket, String key) throws IOException { + delete(ByteString.copyFromUtf8(bucket), ByteString.copyFromUtf8(key)); + } + + public void delete(ByteString bucket, ByteString key) throws IOException { + RpbDelReq req = RPB.RpbDelReq.newBuilder().setBucket(bucket) + .setKey(key).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_DelReq, req); + c.receive_code(MSG_DelResp); + } finally { + release(c); + } + } + + public ByteString[] listBuckets() throws IOException { + + byte[] data; + RiakConnection c = getConnection(); + try { + c.send(MSG_ListBucketsReq); + + data = c.receive(MSG_ListBucketsResp); + if (data == null) { + return NO_BYTE_STRINGS; + } + } finally { + release(c); + } + + RpbListBucketsResp resp = RPB.RpbListBucketsResp.parseFrom(data); + ByteString[] out = new ByteString[resp.getBucketsCount()]; + for (int i = 0; i < out.length; i++) { + out[i] = resp.getBuckets(i); + } + return out; + } + + public BucketProperties getBucketProperties(ByteString bucket) + throws IOException { + + RiakConnection c = getConnection(); + try { + c.send(MSG_GetBucketReq, RPB.RpbGetBucketReq.newBuilder() + .setBucket(bucket).build()); + + byte[] data = c.receive(MSG_GetBucketResp); + BucketProperties bp = new BucketProperties(); + if (data == null) { + return bp; + } + + bp.init(RPB.RpbGetBucketResp.parseFrom(data)); + return bp; + } finally { + release(c); + } + + } + + public void setBucketProperties(ByteString bucket, BucketProperties props) + throws IOException { + + RPB.RpbSetBucketReq req = RPB.RpbSetBucketReq.newBuilder().setBucket( + bucket).setProps(props.build()).build(); + + RiakConnection c = getConnection(); + try { + c.send(MSG_SetBucketReq, req); + c.receive_code(MSG_SetBucketResp); + } finally { + release(c); + } + } + + // ///////////////////// + + public KeySource listKeys(ByteString bucket) throws IOException { + + RiakConnection c = getConnection(); + c.send(MSG_ListKeysReq, RPB.RpbListKeysReq.newBuilder().setBucket( + bucket).build()); + + return new KeySource(this, c); + } + + // ///////////////////// + + public MapReduceResponseSource mapReduce(JSONObject obj) throws IOException { + return mapReduce(ByteString.copyFromUtf8(obj.toString()), + new RequestMeta().contentType("application/json")); + } + + public MapReduceResponseSource mapReduce(String request, + IRequestMeta meta) throws IOException { + return mapReduce(ByteString.copyFromUtf8(request), meta); + } + + public MapReduceResponseSource mapReduce(ByteString request, + IRequestMeta meta) throws IOException { + RiakConnection c = getConnection(); + + ByteString contentType = meta.getContentType(); + if (contentType == null) { + throw new IllegalArgumentException("no content type"); + } + RpbMapRedReq req = RPB.RpbMapRedReq.newBuilder().setRequest(request) + .setContentType(meta.getContentType()).build(); + + c.send(MSG_MapRedReq, req); + + return new MapReduceResponseSource(this, c, contentType); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.io.DataInputStream` acquired by call to `RiakConnection(...)` at line 111 is not released after line 119. +**Note**: potential exception at line 115 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +RiakConnection RiakClient.getConnection(boolean) + +### Procedure Id: +com.basho.riak.pbc.RiakClient.getConnection(boolean):com.basho.riak.pbc.RiakConnection.8bd314c9764aabfd41f07d3fc08a69ad + +### File: +src/main/java/com/basho/riak/pbc/RiakClient.java + +### Key: +RiakClient.java|getConnection|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +12002d71c32512e71a2f643c15ec5849 + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9828/instruction.md b/inferredbugs-9828/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..647f153d4b1f8220ea03c3cb0d64b9be44e42e58 --- /dev/null +++ b/inferredbugs-9828/instruction.md @@ -0,0 +1,300 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 1 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * This file is provided to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ +package com.basho.riak.client.raw; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; + +import com.basho.riak.client.RiakBucketInfo; +import com.basho.riak.client.RiakClient; +import com.basho.riak.client.RiakConfig; +import com.basho.riak.client.RiakLink; +import com.basho.riak.client.RiakObject; +import com.basho.riak.client.request.RequestMeta; +import com.basho.riak.client.request.RiakWalkSpec; +import com.basho.riak.client.response.HttpResponse; +import com.basho.riak.client.response.RiakExceptionHandler; +import com.basho.riak.client.response.RiakResponseException; +import com.basho.riak.client.response.StreamHandler; +import com.basho.riak.client.util.ClientHelper; +import com.basho.riak.client.util.ClientUtils; +import com.basho.riak.client.util.Constants; + +/** + * Implementation of the {@link RiakClient} that connects to the Riak Raw + * interface. + */ +public class RawClient implements RiakClient { + + private ClientHelper helper; + private String riakBasePath; + + public RawClient(RiakConfig config) { + helper = new ClientHelper(config); + riakBasePath = ClientUtils.getPathFromUrl(config.getUrl()); + } + + public RawClient(String url) { + helper = new ClientHelper(new RiakConfig(url)); + riakBasePath = ClientUtils.getPathFromUrl(url); + } + + public HttpResponse setBucketSchema(String bucket, RiakBucketInfo bucketInfo, RequestMeta meta) { + JSONObject schema = null; + try { + schema = new JSONObject().put(Constants.RAW_FL_SCHEMA, bucketInfo.getSchema()); + } catch (JSONException unreached) { + throw new IllegalStateException("wrapping valid json should be valid", unreached); + } + + return helper.setBucketSchema(bucket, schema, meta); + } + + public HttpResponse setBucketSchema(String bucket, RiakBucketInfo bucketInfo) { + return setBucketSchema(bucket, bucketInfo, null); + } + + public RawBucketResponse listBucket(String bucket, RequestMeta meta) { + HttpResponse r = helper.listBucket(bucket, meta); + if (r == null) + return null; + try { + return new RawBucketResponse(r); + } catch (JSONException e) { + helper.toss(new RiakResponseException(r, e)); + return null; + } + } + + public RawBucketResponse listBucket(String bucket) { + return listBucket(bucket, null); + } + + // Sends the object's link, user-defined metadata and vclock as HTTP headers + // and the value as the body + public RawStoreResponse store(RiakObject object, RequestMeta meta) { + if (meta == null) { + meta = new RequestMeta(); + } + Collection links = object.getLinks(); + Map usermeta = object.getUsermeta(); + StringBuilder linkHeader = new StringBuilder(); + String vclock = object.getVclock(); + + if (links != null) { + for (RiakLink link : links) { + if (linkHeader.length() > 0) { + linkHeader.append(", "); + } + linkHeader.append("<"); + linkHeader.append(riakBasePath); + linkHeader.append("/"); + linkHeader.append(link.getBucket()); + linkHeader.append("/"); + linkHeader.append(link.getKey()); + linkHeader.append(">; "); + linkHeader.append(Constants.RAW_LINK_TAG); + linkHeader.append("=\""); + linkHeader.append(link.getTag()); + linkHeader.append("\""); + } + } + if (linkHeader.length() > 0) { + meta.setHeader(Constants.HDR_LINK, linkHeader.toString()); + } + if (usermeta != null) { + for (String name : usermeta.keySet()) { + meta.setHeader(Constants.HDR_USERMETA_PREFIX + name, usermeta.get(name)); + } + } + if (vclock != null) { + meta.setHeader(Constants.HDR_VCLOCK, vclock); + } + + HttpResponse r = helper.store(object, meta); + if (r == null) + return null; + + return new RawStoreResponse(r); + } + + public RawStoreResponse store(RiakObject object) { + return store(object, null); + } + + public RawFetchResponse fetchMeta(String bucket, String key, RequestMeta meta) { + try { + return new RawFetchResponse(helper.fetchMeta(bucket, key, meta)); + } catch (RiakResponseException e) { + return new RawFetchResponse(helper.toss(e)); + } + } + + public RawFetchResponse fetchMeta(String bucket, String key) { + return fetchMeta(bucket, key, null); + } + + // Fetches the object or all sibling objects if there are multiple + public RawFetchResponse fetch(String bucket, String key, RequestMeta meta) { + if (meta == null) { + meta = new RequestMeta(); + } + + String accept = meta.getQueryParam(Constants.HDR_ACCEPT); + if (accept == null) { + meta.setHeader(Constants.HDR_ACCEPT, Constants.CTYPE_ANY + ", " + Constants.CTYPE_MULTIPART_MIXED); + } else { + meta.setHeader(Constants.HDR_ACCEPT, accept + ", " + Constants.CTYPE_MULTIPART_MIXED); + } + + HttpResponse r = helper.fetch(bucket, key, meta); + if (r == null) + return null; + + try { + return new RawFetchResponse(r); + } catch (RiakResponseException e) { + return new RawFetchResponse(helper.toss(e)); + } + + } + + public RawFetchResponse fetch(String bucket, String key) { + return fetch(bucket, key, null); + } + + public boolean stream(String bucket, String key, StreamHandler handler, RequestMeta meta) throws IOException { + return helper.stream(bucket, key, handler, meta); + } + + public HttpResponse delete(String bucket, String key, RequestMeta meta) { + return helper.delete(bucket, key, meta); + } + + public HttpResponse delete(String bucket, String key) { + return delete(bucket, key, null); + } + + public RawWalkResponse walk(String bucket, String key, String walkSpec, RequestMeta meta) { + HttpResponse r = helper.walk(bucket, key, walkSpec, meta); + if (r == null) + return null; + + try { + return new RawWalkResponse(r); + } catch (RiakResponseException e) { + return new RawWalkResponse(helper.toss(e)); + } + } + + public RawWalkResponse walk(String bucket, String key, String walkSpec) { + return walk(bucket, key, walkSpec, null); + } + + public RawWalkResponse walk(String bucket, String key, RiakWalkSpec walkSpec) { + return walk(bucket, key, walkSpec.toString(), null); + } + + /** @return the installed exception handler or null if not installed */ + public RiakExceptionHandler getExceptionHandler() { + return helper.getExceptionHandler(); + } + + /** + * Install an exception handler. If an exception handler is provided, then + * the Riak client will hand exceptions to the handler rather than throwing + * them. + */ + public void setExceptionHandler(RiakExceptionHandler exceptionHandler) { + helper.setExceptionHandler(exceptionHandler); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `null` could be null and is dereferenced by call to `fetch(...)` at line 178. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +RawFetchResponse RawClient.fetch(String,String) + +### Procedure Id: +com.basho.riak.client.raw.RawClient.fetch(java.lang.String,java.lang.String):com.basho.riak.client.r.68851800a206e19705d673d85ae08c78 + +### File: +src/main/java/com/basho/riak/client/raw/RawClient.java + +### Key: +RawClient.java|fetch|NULL_DEREFERENCE + +### Node Key: +8b99a1c23932de4aaee9b552926bd25a + +### Hash: +587a3b50b07fe04ca7f65c28253f8ca5 + +### Bug Type Hum: +Null Dereference + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9842/instruction.md b/inferredbugs-9842/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c14dc29440718401991bdd3784077a03ec59a0c --- /dev/null +++ b/inferredbugs-9842/instruction.md @@ -0,0 +1,243 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 14 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * This file is part of riak-java-pb-client + * + * Copyright (c) 2010 by Trifork + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + **/ + +package com.basho.riak.pbc; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Timer; +import java.util.TimerTask; + +import com.basho.riak.pbc.RPB.RpbErrorResp; +import com.google.protobuf.MessageLite; + +/** + * Wraps the {@link Socket} used to send/receive data to Riak's protocol buffers interface. + * + * See Basho Wiki for more details. + */ +class RiakConnection { + + static final int DEFAULT_RIAK_PB_PORT = 8087; + + private Socket sock; + private DataOutputStream dout; + private DataInputStream din; + + public RiakConnection(InetAddress addr, int port, int bufferSizeKb) throws IOException { + sock = new Socket(addr, port); + + sock.setSendBufferSize(1024 * bufferSizeKb); + + dout = new DataOutputStream(new BufferedOutputStream(sock + .getOutputStream(), 1024 * bufferSizeKb)); + din = new DataInputStream( + new BufferedInputStream(sock.getInputStream(), 1024 * bufferSizeKb)); + } + + /////////////////////// + + void send(int code, MessageLite req) throws IOException { + int len = req.getSerializedSize(); + dout.writeInt(len + 1); + dout.write(code); + req.writeTo(dout); + dout.flush(); + } + + void send(int code) throws IOException { + dout.writeInt(1); + dout.write(code); + dout.flush(); + } + + byte[] receive(int code) throws IOException { + int len = din.readInt(); + int get_code = din.read(); + + byte[] data = null; + if (len > 1) { + data = new byte[len - 1]; + din.readFully(data); + } + + if (get_code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); + throw new RiakError(err); + } + + if (code != get_code) { + throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); + } + + return data; + } + + void receive_code(int code) throws IOException, RiakError { + int len = din.readInt(); + int get_code = din.read(); + if (code == RiakClient.MSG_ErrorResp) { + RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); + throw new RiakError(err); + } + if (len != 1 || code != get_code) { + throw new IOException("bad message code"); + } + } + + static Timer TIMER = new Timer("riak-client-timeout-thread", true); + TimerTask idle_timeout; + + public void beginIdle() { + idle_timeout = new TimerTask() { + + @Override + public void run() { + RiakConnection.this.timer_fired(this); + } + }; + + TIMER.schedule(idle_timeout, 1000); + } + + synchronized void timer_fired(TimerTask fired_timer) { + if (idle_timeout != fired_timer) { + // if it is not our current timer, then ignore + return; + } + + close(); + } + + void close() { + if (isClosed()) + return; + + try { + sock.close(); + din = null; + dout = null; + sock = null; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + synchronized boolean endIdleAndCheckValid() { + TimerTask tt = idle_timeout; + if (tt != null) { tt.cancel(); } + idle_timeout = null; + + if (isClosed()) { + return false; + } else { + return true; + } + } + + public DataOutputStream getOutputStream() { + return dout; + } + + public boolean isClosed() { + return sock == null || sock.isClosed(); + } + + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `com.basho.riak.pbc.RiakConnection.close` writes to field `this.com.basho.riak.pbc.RiakConnection.dout` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void RiakConnection.close() + +### Procedure Id: +com.basho.riak.pbc.RiakConnection.close():void.a946b834a56d1390933ecb12ed4186fc + +### File: +src/main/java/com/basho/riak/pbc/RiakConnection.java + +### Key: +RiakConnection.java|close|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +2b0e6980fc97e4e8168bfb149e73e230 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9843/instruction.md b/inferredbugs-9843/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0723edfc268bcf266feee5726476958971ebe0f --- /dev/null +++ b/inferredbugs-9843/instruction.md @@ -0,0 +1,205 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** riak-java-client +**Bug ID:** 22 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.basho.riak.client.api.commands; + +import com.basho.riak.client.core.StreamingRiakFuture; +import com.basho.riak.client.core.util.BinaryValue; + +import java.util.Iterator; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TransferQueue; +import java.util.function.Function; + +public class ChunkedResponseIterator, CoreT> implements Iterator +{ + private final int timeout; + private volatile BinaryValue continuation = null; + private final StreamingRiakFuture coreFuture; + private final TransferQueue chunkQueue; + private final Function createNext; + private final Function> getNextIterator; + private final Function getContinuationFn; + + private Iterator currentIterator = null; + + public ChunkedResponseIterator(StreamingRiakFuture coreFuture, + int pollTimeout, + Function createNextFn, + Function> getNextIteratorFn) + { + this(coreFuture, pollTimeout, createNextFn, getNextIteratorFn, (x) -> null); + } + + public ChunkedResponseIterator(StreamingRiakFuture coreFuture, + int pollTimeout, + Function createNextFn, + Function> getNextIteratorFn, + Function getContinuationFn) + { + this.timeout = pollTimeout; + this.coreFuture = coreFuture; + this.chunkQueue = coreFuture.getResultsQueue(); + this.createNext = createNextFn; + this.getNextIterator = getNextIteratorFn; + this.getContinuationFn = getContinuationFn; + loadNextChunkIterator(); + } + + @Override + public boolean hasNext() + { + return currentIteratorHasNext() || possibleChunksRemaining(); + } + + private boolean currentIteratorHasNext() + { + return currentIterator != null && currentIterator.hasNext(); + } + + private boolean possibleChunksRemaining() + { + // Chunks may remain if : + // Core Operation Not Done OR items still in chunk Queue + return !coreFuture.isDone() || !chunkQueue.isEmpty(); + } + + public boolean hasContinuation() + { + return continuation != null || possibleChunksRemaining(); + } + + public BinaryValue getContinuation() + { + return continuation; + } + + @Override + public synchronized FinalT next() + { + if(!hasNext()) + { + return null; + } + + if(!currentIteratorHasNext()) + { + loadNextChunkIterator(); + + if(!hasNext()) + { + return null; + } + } + + return createNext.apply(currentIterator.next()); + } + + private void loadNextChunkIterator() + { + this.currentIterator = null; + boolean populatedChunkLoaded = false; + + try + { + while (!populatedChunkLoaded && possibleChunksRemaining()) + { + final ChunkT nextChunk = chunkQueue.poll(timeout, TimeUnit.MILLISECONDS); + + if (nextChunk != null) + { + this.currentIterator = getNextIterator.apply(nextChunk); + populatedChunkLoaded = currentIteratorHasNext(); + + loadContinuation(nextChunk); + } + } + } + catch (InterruptedException e) + { + Thread.currentThread().interrupt(); + throw new RuntimeException(e); + } + } + + private void loadContinuation(ChunkT nextChunk) + { + final BinaryValue fetchedContinuation = getContinuationFn.apply(nextChunk); + if(this.continuation == null && fetchedContinuation != null) + { + this.continuation = fetchedContinuation; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `com.basho.riak.client.api.commands.ChunkedResponseIterator.hasNext` indirectly reads without synchronization from `this.com.basho.riak.client.api.commands.ChunkedResponseIterator.currentIterator`. Potentially races with write in method `ChunkedResponseIterator.next()`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +boolean ChunkedResponseIterator.hasNext() + +### Procedure Id: +com.basho.riak.client.api.commands.ChunkedResponseIterator.hasNext():boolean.fd4da90e30705ccc42defa4f2c2ae29d + +### File: +src/main/java/com/basho/riak/client/api/commands/ChunkedResponseIterator.java + +### Key: +ChunkedResponseIterator.java|hasNext|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +87a45c546aceb3f65539a9ee4e163e32 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9872/instruction.md b/inferredbugs-9872/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fefc7c8e306004f4183898e180917beb8cce45c7 --- /dev/null +++ b/inferredbugs-9872/instruction.md @@ -0,0 +1,135 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-apns +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.notnoop.apns.internal; + +import static com.notnoop.apns.internal.MockingUtils.*; + +import java.io.ByteArrayOutputStream; + +import javax.net.SocketFactory; + +import org.junit.Assert; +import org.junit.Test; + +import com.notnoop.apns.ApnsNotification; + +public class ApnsConnectionTest { + ApnsNotification msg = new ApnsNotification ("a87d8878d878a79", "{\"aps\":{}}"); + + @Test + public void simpleSocket() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockSocketFactory(baos, null); + packetSentRegardless(factory, baos); + } + + @Test + public void closedSocket() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, true, 1); + packetSentRegardless(factory, baos); + } + + @Test + public void errorOnce() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 1); + packetSentRegardless(factory, baos); + } + + @Test + public void errorTwice() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 2); + packetSentRegardless(factory, baos); + } + + /** + * Connection fails after three retries + */ + @Test(expected = Exception.class) + public void errorThrice() { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + SocketFactory factory = mockClosedThenOpenSocket(baos, null, false, 3); + packetSentRegardless(factory, baos); + } + + private void packetSentRegardless(SocketFactory sf, ByteArrayOutputStream baos) { + ApnsConnection connection = new ApnsConnection(sf, "localhost", 80); + connection.DELAY_IN_MS = 0; + connection.sendMessage(msg); + Assert.assertArrayEquals(msg.marshall(), baos.toByteArray()); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `com.notnoop.apns.internal.ApnsConnection` acquired to `connection` by call to `ApnsConnection(...)` at line 56 is not released after line 58. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void ApnsConnectionTest.packetSentRegardless(SocketFactory,ByteArrayOutputStream) + +### Procedure Id: +com.notnoop.apns.internal.ApnsConnectionTest.packetSentRegardless(javax.net.SocketFactory,java.io.By.0c0a357a6d832fe3eaa9bd32a218aa84 + +### File: +src/test/java/com/notnoop/apns/internal/ApnsConnectionTest.java + +### Key: +ApnsConnectionTest.java|packetSentRegardless|RESOURCE_LEAK + +### Node Key: +141d12c688da63d404fcff6ee9c41043 + +### Hash: +9cbbff318372466aba416fa6b57931da + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9873/instruction.md b/inferredbugs-9873/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f3fa3469f64c59648a5495e047f63d984b72bfb --- /dev/null +++ b/inferredbugs-9873/instruction.md @@ -0,0 +1,391 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** java-apns +**Bug ID:** 5 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/* + * Copyright 2009, Mahmood Ali. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Mahmood Ali. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.notnoop.apns.internal; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.Socket; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLSocketFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.notnoop.apns.ApnsDelegate; +import com.notnoop.apns.ApnsNotification; +import com.notnoop.apns.DeliveryError; +import com.notnoop.apns.ReconnectPolicy; +import com.notnoop.apns.SimpleApnsNotification; +import com.notnoop.exceptions.ApnsDeliveryErrorException; +import com.notnoop.exceptions.NetworkIOException; +import java.util.LinkedList; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +public class ApnsConnectionImpl implements ApnsConnection { + + private static final Logger logger = LoggerFactory.getLogger(ApnsConnectionImpl.class); + + private final SocketFactory factory; + private final String host; + private final int port; + private final Proxy proxy; + private final ReconnectPolicy reconnectPolicy; + private final ApnsDelegate delegate; + private int cacheLength; + private final boolean errorDetection; + private final boolean autoAdjustCacheLength; + private final ConcurrentLinkedQueue cachedNotifications, notificationsBuffer; + + public ApnsConnectionImpl(SocketFactory factory, String host, int port) { + this(factory, host, port, new ReconnectPolicies.Never(), ApnsDelegate.EMPTY); + } + + public ApnsConnectionImpl(SocketFactory factory, String host, + int port, ReconnectPolicy reconnectPolicy, + ApnsDelegate delegate) { + this(factory, host, port, null, reconnectPolicy, + delegate); + } + + public ApnsConnectionImpl(SocketFactory factory, String host, + int port, Proxy proxy, ReconnectPolicy reconnectPolicy, + ApnsDelegate delegate) { + this(factory, host, port, proxy, reconnectPolicy, + delegate, false, ApnsConnection.DEFAULT_CACHE_LENGTH, true); + } + + public ApnsConnectionImpl(SocketFactory factory, String host, + int port, Proxy proxy, + ReconnectPolicy reconnectPolicy, ApnsDelegate delegate, + boolean errorDetection, int cacheLength, boolean autoAdjustCacheLength) { + this.factory = factory; + this.host = host; + this.port = port; + this.reconnectPolicy = reconnectPolicy; + this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate; + this.proxy = proxy; + this.errorDetection = errorDetection; + this.cacheLength = cacheLength; + this.autoAdjustCacheLength = autoAdjustCacheLength; + cachedNotifications = new ConcurrentLinkedQueue(); + notificationsBuffer = new ConcurrentLinkedQueue(); + } + + public synchronized void close() { + Utilities.close(socket); + } + + private void monitorSocket(final Socket socket) { + class MonitoringThread extends Thread { + + @Override + public void run() { + + try { + InputStream in = socket.getInputStream(); + + // TODO(jwilson): this should readFully() + final int expectedSize = 6; + byte[] bytes = new byte[expectedSize]; + while (in.read(bytes) == expectedSize) { + + int command = bytes[0] & 0xFF; + if (command != 8) { + throw new IOException("Unexpected command byte " + command); + } + int statusCode = bytes[1] & 0xFF; + DeliveryError e = DeliveryError.ofCode(statusCode); + + int id = Utilities.parseBytes(bytes[2], bytes[3], bytes[4], bytes[5]); + + Queue tempCache = new LinkedList(); + ApnsNotification notification = null; + boolean foundNotification = false; + + while (!cachedNotifications.isEmpty()) { + notification = cachedNotifications.poll(); + + if (notification.getIdentifier() == id) { + foundNotification = true; + break; + } + tempCache.add(notification); + } + + if (foundNotification) { + delegate.messageSendFailed(notification, new ApnsDeliveryErrorException(e)); + } else { + cachedNotifications.addAll(tempCache); + int resendSize = tempCache.size(); + logger.warn("Received error for message " + + "that wasn't in the cache..."); + if (autoAdjustCacheLength) { + cacheLength = cacheLength + (resendSize / 2); + delegate.cacheLengthExceeded(cacheLength); + } + delegate.messageSendFailed(null, new ApnsDeliveryErrorException(e)); + } + + int resendSize = 0; + + while (!cachedNotifications.isEmpty()) { + resendSize++; + notificationsBuffer.add(cachedNotifications.poll()); + } + delegate.notificationsResent(resendSize); + + delegate.connectionClosed(e, id); + + drainBuffer(); + } + + } catch (Exception e) { + // An exception when reading the error code is non-critical, it will cause another retry + // sending the message. Other than providing a more stable network connection to the APNS + // server we can't do much about it - so let's not spam the application's error log. + logger.info("Exception while waiting for error code", e); + delegate.connectionClosed(DeliveryError.UNKNOWN, -1); + } finally { + close(); + } + } + } + Thread t = new MonitoringThread(); + t.setDaemon(true); + t.start(); + } + // This method is only called from sendMessage. sendMessage + // has the required logic for retrying + private Socket socket; + + private synchronized Socket socket() throws NetworkIOException { + if (reconnectPolicy.shouldReconnect()) { + Utilities.close(socket); + socket = null; + } + + if (socket == null || socket.isClosed()) { + try { + if (proxy == null) { + socket = factory.createSocket(host, port); + } else if (proxy.type() == Proxy.Type.HTTP) { + TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder(); + socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, host, port); + } else { + boolean success = false; + Socket proxySocket = null; + try { + proxySocket = new Socket(proxy); + proxySocket.connect(new InetSocketAddress(host, port)); + socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false); + success = true; + } finally { + if (!success) { + Utilities.close(proxySocket); + } + } + } + + if (errorDetection) { + monitorSocket(socket); + } + + reconnectPolicy.reconnected(); + logger.debug("Made a new connection to APNS"); + } catch (IOException e) { + logger.error("Couldn't connect to APNS server", e); + throw new NetworkIOException(e); + } + } + return socket; + } + int DELAY_IN_MS = 1000; + private static final int RETRIES = 3; + + public synchronized void sendMessage(ApnsNotification m) throws NetworkIOException { + sendMessage(m, false); + } + + public synchronized void sendMessage(ApnsNotification m, boolean fromBuffer) throws NetworkIOException { + + int attempts = 0; + while (true) { + try { + attempts++; + Socket socket = socket(); + socket.getOutputStream().write(m.marshall()); + socket.getOutputStream().flush(); + cacheNotification(m); + + delegate.messageSent(m, fromBuffer); + + logger.debug("Message \"{}\" sent", m); + + attempts = 0; + drainBuffer(); + break; + } catch (Exception e) { + Utilities.close(socket); + socket = null; + if (attempts >= RETRIES) { + logger.error("Couldn't send message after " + RETRIES + " retries." + m, e); + delegate.messageSendFailed(m, e); + Utilities.wrapAndThrowAsRuntimeException(e); + } + // The first failure might be due to closed connection + // don't delay quite yet + if (attempts != 1) { + // Do not spam the log files when the APNS server closed the socket (due to a + // bad token, for example), only log when on the second retry. + logger.info("Failed to send message " + m + "... trying again after delay", e); + Utilities.sleep(DELAY_IN_MS); + } + } + } + } + + private void drainBuffer() { + if (!notificationsBuffer.isEmpty()) { + sendMessage(notificationsBuffer.poll(), true); + } + } + + private void cacheNotification(ApnsNotification notification) { + cachedNotifications.add(notification); + while (cachedNotifications.size() > cacheLength) { + cachedNotifications.poll(); + logger.debug("Removing notification from cache " + notification); + } + } + + public ApnsConnectionImpl copy() { + return new ApnsConnectionImpl(factory, host, port, proxy, reconnectPolicy.copy(), + delegate, errorDetection, cacheLength, autoAdjustCacheLength); + } + + public void testConnection() throws NetworkIOException { + ApnsConnectionImpl testConnection = null; + try { + testConnection = new ApnsConnectionImpl(factory, host, port, proxy, reconnectPolicy.copy(), delegate); + testConnection.sendMessage(new SimpleApnsNotification(new byte[]{0}, new byte[]{0})); + } finally { + if (testConnection != null) { + testConnection.close(); + } + } + } + + public void setCacheLength(int cacheLength) { + this.cacheLength = cacheLength; + } + + public int getCacheLength() { + return cacheLength; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `java.net.Socket` acquired by call to `new()` at line 210 is not released after line 222. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +Socket ApnsConnectionImpl.socket() + +### Procedure Id: +com.notnoop.apns.internal.ApnsConnectionImpl.socket():java.net.Socket.a138b65e6aa79efe703468c951cc43cc + +### File: +src/main/java/com/notnoop/apns/internal/ApnsConnectionImpl.java + +### Key: +ApnsConnectionImpl.java|socket|RESOURCE_LEAK + +### Node Key: +53a5b11fd6ccc7e244ddc8e893bdc553 + +### Hash: +534efb82ff63844d8410c77f043f375b + +### Bug Type Hum: +Resource Leak + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9880/instruction.md b/inferredbugs-9880/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..384ba07001cc50bacaf8227b6dac4401c9617022 --- /dev/null +++ b/inferredbugs-9880/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 32 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + // descending. + return Float.compare(o.first, first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + private float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * ((label ? 1f : 0f) - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + private float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + private float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + private void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + private void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + private float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + private void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + private static final Comparator PAIR_COMPARATOR = + (l, r) -> l.first > r.first ? 1 : 0; + + List predict(int[] input, + int k, + Vector hidden, + Vector output) { + assert (k > 0); + computeHidden(input, hidden); + PriorityQueue heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + List result = new ArrayList<>(heap); + Collections.sort(result); + return result; + } + + List predict(int[] input, int k) { + return predict(input, k, hidden_, output_); + } + + private void findKBest(int k, + PriorityQueue heap, + Vector hidden, + Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + private void dfs(int k, + int node, + float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + private void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + private int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + private void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + private static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + private static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + private float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + private float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.update` reads without synchronization from `this.zemberek.embedding.fasttext.Model.loss_`. Potentially races with write in method `Model.update(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Model.update(int[],int,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.update(int[],int,float):void.49e2c20141a9f555936abeccf294c2e6 + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|update|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +8bab92d9cd8ab9494c6ef43d58e7b09e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9881/instruction.md b/inferredbugs-9881/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..543d9c542340109b1ea1b6103263b7b2ff5ced67 --- /dev/null +++ b/inferredbugs-9881/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 35 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + // descending. + return Float.compare(o.first, first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + private float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * ((label ? 1f : 0f) - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + private float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + private float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + private void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + private void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + private float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + private void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + private static final Comparator PAIR_COMPARATOR = + (l, r) -> l.first > r.first ? 1 : 0; + + List predict(int[] input, + int k, + Vector hidden, + Vector output) { + assert (k > 0); + computeHidden(input, hidden); + PriorityQueue heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + List result = new ArrayList<>(heap); + Collections.sort(result); + return result; + } + + List predict(int[] input, int k) { + return predict(input, k, hidden_, output_); + } + + private void findKBest(int k, + PriorityQueue heap, + Vector hidden, + Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + private void dfs(int k, + int node, + float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + private void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + private int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + private void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + private static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + private static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + private float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + private float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `zemberek.embedding.fasttext.Model.update` writes to field `this.zemberek.embedding.fasttext.Model.loss_` outside of synchronization. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void Model.update(int[],int,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.update(int[],int,float):void.49e2c20141a9f555936abeccf294c2e6 + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|update|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e31424531b3de3ef8c99f701dd90eb42 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9886/instruction.md b/inferredbugs-9886/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26593f6c0ce7352a2f2c0667b2671aff0cf626a2 --- /dev/null +++ b/inferredbugs-9886/instruction.md @@ -0,0 +1,449 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 27 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + // descending. + return Float.compare(o.first, first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + private float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * ((label ? 1f : 0f) - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + private float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + private float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + private void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + private void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + private float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + private void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + private static final Comparator PAIR_COMPARATOR = + (l, r) -> l.first > r.first ? 1 : 0; + + List predict(int[] input, + int k, + Vector hidden, + Vector output) { + assert (k > 0); + computeHidden(input, hidden); + PriorityQueue heap = new PriorityQueue<>(k+1, PAIR_COMPARATOR); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + List result = new ArrayList<>(heap); + Collections.sort(result); + return result; + } + + List predict(int[] input, int k) { + return predict(input, k, hidden_, output_); + } + + private void findKBest(int k, + PriorityQueue heap, + Vector hidden, + Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + private void dfs(int k, + int node, + float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + private void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + private int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + private void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + private static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + private static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + private float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + private float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.predict` indirectly reads without synchronization from `this.zemberek.embedding.fasttext.Model.wi_.zemberek.embedding.fasttext.Matrix.data_.[_]`. Potentially races with write in method `Model.update(...)`. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List Model.predict(int[],int,Vector,Vector) + +### Procedure Id: +zemberek.embedding.fasttext.Model.predict(int[],int,zemberek.embedding.fasttext.Vector,zemberek.embe.daed85040bd1a222589ecb2cdae37283 + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|predict|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +6ab8c5d920d50d933f420101a9a935dd + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9887/instruction.md b/inferredbugs-9887/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5dec8fb447e6aa26d81af1bae5a0b60ca6842b0c --- /dev/null +++ b/inferredbugs-9887/instruction.md @@ -0,0 +1,442 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 9 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + //TODO: check below + return Float.compare(this.first, o.first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * (label ? 1f : 0f - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + void predict(int[] input, int k, + PriorityQueue heap, + Vector hidden, Vector output) { + assert (k > 0); + //heap.reserve(k + 1); + computeHidden(input, hidden); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + // TODO: write below if necessary. + //std::sort_heap(heap.begin(), heap.end(), comparePairs); + } + + void predict(int[] input, int k, + PriorityQueue heap) { + predict(input, k, heap, hidden_, output_); + } + + void findKBest(int k, PriorityQueue heap, + Vector hidden, Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + void dfs(int k, int node, float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + + void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.binaryLogistic` indirectly reads without synchronization from `fasttext.Model.zemberek.embedding.fasttext.Model.t_log`. Potentially races with write in method `Model.initLog()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +float Model.binaryLogistic(int,boolean,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.binaryLogistic(int,boolean,float):float.692e211b4649cfe78f82841bc3e3c33c + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|binaryLogistic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +e388f1a8a75874ae025364e84b30cb45 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9888/instruction.md b/inferredbugs-9888/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f725e77024b091b9027e2770fe3f387c64c164c6 --- /dev/null +++ b/inferredbugs-9888/instruction.md @@ -0,0 +1,442 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 11 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + //TODO: check below + return Float.compare(this.first, o.first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * (label ? 1f : 0f - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + void predict(int[] input, int k, + PriorityQueue heap, + Vector hidden, Vector output) { + assert (k > 0); + //heap.reserve(k + 1); + computeHidden(input, hidden); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + // TODO: write below if necessary. + //std::sort_heap(heap.begin(), heap.end(), comparePairs); + } + + void predict(int[] input, int k, + PriorityQueue heap) { + predict(input, k, heap, hidden_, output_); + } + + void findKBest(int k, PriorityQueue heap, + Vector hidden, Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + void dfs(int k, int node, float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + + void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `zemberek.embedding.fasttext.Model.negativeSampling` indirectly writes to field `this.zemberek.embedding.fasttext.Model.grad_.zemberek.embedding.fasttext.Vector.data_.[_]` outside of synchronization. + Reporting because another access to the same memory occurs on a background thread, although this access may not. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +float Model.negativeSampling(int,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.negativeSampling(int,float):float.04864267f49892ecff95455a09d41be9 + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|negativeSampling|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +5163eec6c38e5aefa41f0cb09030b5b8 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9889/instruction.md b/inferredbugs-9889/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bf634ca3ebf2d329c9b12dca089790bbcf82476 --- /dev/null +++ b/inferredbugs-9889/instruction.md @@ -0,0 +1,442 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 7 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + //TODO: check below + return Float.compare(this.first, o.first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * (label ? 1f : 0f - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + void predict(int[] input, int k, + PriorityQueue heap, + Vector hidden, Vector output) { + assert (k > 0); + //heap.reserve(k + 1); + computeHidden(input, hidden); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + // TODO: write below if necessary. + //std::sort_heap(heap.begin(), heap.end(), comparePairs); + } + + void predict(int[] input, int k, + PriorityQueue heap) { + predict(input, k, heap, hidden_, output_); + } + + void findKBest(int k, PriorityQueue heap, + Vector hidden, Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + void dfs(int k, int node, float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + + void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.binaryLogistic` indirectly reads with synchronization from `this.zemberek.embedding.fasttext.Model.hidden_.zemberek.embedding.fasttext.Vector.data_.[_]`. Potentially races with unsynchronized write in method `Model.update(...)`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +float Model.binaryLogistic(int,boolean,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.binaryLogistic(int,boolean,float):float.692e211b4649cfe78f82841bc3e3c33c + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|binaryLogistic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +bed2c7c87503b377eaa142ece2b303a4 + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed. diff --git a/inferredbugs-9900/instruction.md b/inferredbugs-9900/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6bace34b889640e8e1ddfafe3014e8e48894954 --- /dev/null +++ b/inferredbugs-9900/instruction.md @@ -0,0 +1,442 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** zemberek-nlp +**Bug ID:** 8 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package zemberek.embedding.fasttext; + +import zemberek.core.collections.IntVector; + +import java.util.*; + +public class Model { + + static class Node { + int parent; + int left; + int right; + long count; // TODO: this can be an int. + boolean binary; + } + + static class Pair implements Comparable { + + final float first; + final int second; + + Pair(float first, int second) { + this.first = first; + this.second = second; + } + + @Override + public int compareTo(Pair o) { + //TODO: check below + return Float.compare(this.first, o.first); + } + } + + private Matrix wi_; + private Matrix wo_; + private Args args_; + private Vector hidden_; + private Vector output_; + private Vector grad_; + private int hsz_; + private int isz_; + private int osz_; + private float loss_; + private long nexamples_; + private static float[] t_sigmoid; + private static float[] t_log; + // used for negative sampling: + private int[] negatives; + private int negpos; + // used for hierarchical softmax: + private List paths = new ArrayList<>(); + private List codes = new ArrayList<>(); + private Node[] tree; + + private static final int NEGATIVE_TABLE_SIZE = 10000000; + + private static final int SIGMOID_TABLE_SIZE = 512; + private static final int MAX_SIGMOID = 8; + private static final int LOG_TABLE_SIZE = 512; + + Random random; + + static { + initLog(); + initSigmoid(); + } + + Model(Matrix wi, + Matrix wo, + Args args, + int seed) { + hidden_ = new Vector(args.dim); + output_ = new Vector(wo.m_); + grad_ = new Vector(args.dim); + random = new Random(seed); + wi_ = wi; + wo_ = wo; + args_ = args; + isz_ = wi.m_; + osz_ = wo.m_; + hsz_ = args.dim; + negpos = 0; + loss_ = 0.0f; + nexamples_ = 1; + } + + float binaryLogistic(int target, boolean label, float lr) { + float score = sigmoid(wo_.dotRow(hidden_, target)); + float alpha = lr * (label ? 1f : 0f - score); + grad_.addRow(wo_, target, alpha); + synchronized (this) { + wo_.addRow(hidden_, target, alpha); + } + if (label) { + return -log(score); + } else { + return -log(1.0f - score); + } + } + + float negativeSampling(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + for (int n = 0; n <= args_.neg; n++) { + if (n == 0) { + loss += binaryLogistic(target, true, lr); + } else { + loss += binaryLogistic(getNegative(target), false, lr); + } + } + return loss; + } + + + float hierarchicalSoftmax(int target, float lr) { + float loss = 0.0f; + grad_.zero(); + IntVector binaryCode = codes.get(target); + IntVector pathToRoot = paths.get(target); + for (int i = 0; i < pathToRoot.size(); i++) { + loss += binaryLogistic(pathToRoot.get(i), binaryCode.get(i) == 1, lr); + } + return loss; + } + + void computeOutputSoftmax(Vector hidden, Vector output) { + output.mul(wo_, hidden); + float max = output.data_[0], z = 0.0f; + for (int i = 0; i < osz_; i++) { + max = Math.max(output.data_[i], max); + } + for (int i = 0; i < osz_; i++) { + output.data_[i] = (float) Math.exp(output.data_[i] - max); + z += output.data_[i]; + } + for (int i = 0; i < osz_; i++) { + output.data_[i] /= z; + } + } + + void computeOutputSoftmax() { + computeOutputSoftmax(hidden_, output_); + } + + float softmax(int target, float lr) { + grad_.zero(); + computeOutputSoftmax(); + for (int i = 0; i < osz_; i++) { + float label = (i == target) ? 1.0f : 0.0f; + float alpha = lr * (label - output_.data_[i]); + grad_.addRow(wo_, i, alpha); + synchronized (this) { + wo_.addRow(hidden_, i, alpha); + } + } + return -log(output_.data_[target]); + } + + void computeHidden(int[] input, Vector hidden) { + assert (hidden.size() == hsz_); + hidden.zero(); + for (int i : input) { + hidden.addRow(wi_, i); + } + hidden.mul(1.0f / input.length); + } + + + void predict(int[] input, int k, + PriorityQueue heap, + Vector hidden, Vector output) { + assert (k > 0); + //heap.reserve(k + 1); + computeHidden(input, hidden); + if (args_.loss == Args.loss_name.hs) { + dfs(k, 2 * osz_ - 2, 0.0f, heap, hidden); + } else { + findKBest(k, heap, hidden, output); + } + // TODO: write below if necessary. + //std::sort_heap(heap.begin(), heap.end(), comparePairs); + } + + void predict(int[] input, int k, + PriorityQueue heap) { + predict(input, k, heap, hidden_, output_); + } + + void findKBest(int k, PriorityQueue heap, + Vector hidden, Vector output) { + computeOutputSoftmax(hidden, output); + for (int i = 0; i < osz_; i++) { + if (heap.size() == k && log(output.data_[i]) < heap.peek().first) { + continue; + } + heap.add(new Pair(output.data_[i], i)); + if (heap.size() > k) { + heap.remove(); + } + } + } + + //todo: check here. + void dfs(int k, int node, float score, + PriorityQueue heap, + Vector hidden) { + if (heap.size() == k && score < heap.peek().first) { + return; + } + + if (tree[node].left == -1 && tree[node].right == -1) { + heap.add(new Pair(score, node)); + if (heap.size() > k) { + heap.remove(); + } + return; + } + + float f = sigmoid(wo_.dotRow(hidden, node - osz_)); + dfs(k, tree[node].left, score + log(1.0f - f), heap, hidden); + dfs(k, tree[node].right, score + log(f), heap, hidden); + } + + + void update(int[] input, int target, float lr) { + assert (target >= 0); + assert (target < osz_); + if (input.length == 0) return; + computeHidden(input, hidden_); + if (args_.loss == Args.loss_name.ns) { + loss_ += negativeSampling(target, lr); + } else if (args_.loss == Args.loss_name.hs) { + loss_ += hierarchicalSoftmax(target, lr); + } else { + loss_ += softmax(target, lr); + } + nexamples_ += 1; + + if (args_.model == Args.model_name.sup) { + grad_.mul(1.0f / input.length); + } + synchronized (this) { + for (int i : input) { + wi_.addRow(grad_, i, 1.0f); + } + } + } + + void setTargetCounts(long[] counts) { + assert (counts.length == osz_); + if (args_.loss == Args.loss_name.ns) { + initTableNegatives(counts); + } + if (args_.loss == Args.loss_name.hs) { + buildTree(counts); + } + } + + + void initTableNegatives(long[] counts) { + IntVector vec = new IntVector(counts.length*10); + float z = 0.0f; + for (long count : counts) { + z += (float) Math.pow(count, 0.5); + } + for (int i = 0; i < counts.length; i++) { + float c = (float) Math.pow(counts[i], 0.5); + for (int j = 0; j < c * NEGATIVE_TABLE_SIZE / z; j++) { + vec.add(i); + } + } + vec.shuffle(random); + negatives = vec.copyOf(); + } + + int getNegative(int target) { + int negative; + do { + negative = negatives[negpos]; + negpos = (negpos + 1) % negatives.length; + } while (target == negative); + return negative; + } + + void buildTree(long[] counts) { + tree = new Node[2 * osz_ - 1]; + for (int i = 0; i < 2 * osz_ - 1; i++) { + tree[i].parent = -1; + tree[i].left = -1; + tree[i].right = -1; + tree[i].count = (long) 1e15; + tree[i].binary = false; + } + for (int i = 0; i < osz_; i++) { + tree[i].count = counts[i]; + } + int leaf = osz_ - 1; + int node = osz_; + for (int i = osz_; i < 2 * osz_ - 1; i++) { + int[] mini = new int[2]; + for (int j = 0; j < 2; j++) { + if (leaf >= 0 && tree[leaf].count < tree[node].count) { + mini[j] = leaf--; + } else { + mini[j] = node++; + } + } + tree[i].left = mini[0]; + tree[i].right = mini[1]; + tree[i].count = tree[mini[0]].count + tree[mini[1]].count; + tree[mini[0]].parent = i; + tree[mini[1]].parent = i; + tree[mini[1]].binary = true; + } + for (int i = 0; i < osz_; i++) { + IntVector path = new IntVector(); + IntVector code = new IntVector(); + int j = i; + while (tree[j].parent != -1) { + path.add(tree[j].parent - osz_); + code.add(tree[j].binary ? 1 : 0); + j = tree[j].parent; + } + paths.add(path); + codes.add(code); + } + } + + float getLoss() { + return loss_ / nexamples_; + } + + static void initSigmoid() { + t_sigmoid = new float[SIGMOID_TABLE_SIZE + 1]; + for (int i = 0; i < SIGMOID_TABLE_SIZE + 1; i++) { + float x = i * 2f * MAX_SIGMOID / SIGMOID_TABLE_SIZE - MAX_SIGMOID; + t_sigmoid[i] = 1.0f / (1.0f + (float) Math.exp(-x)); + } + } + + static void initLog() { + t_log = new float[LOG_TABLE_SIZE + 1]; + for (int i = 0; i < LOG_TABLE_SIZE + 1; i++) { + float x = (i + 1e-5f) / LOG_TABLE_SIZE; + t_log[i] = (float) Math.log(x); + } + } + + float log(float x) { + if (x > 1.0f) { + return 0.0f; + } + int i = (int) (x * LOG_TABLE_SIZE); + return t_log[i]; + } + + float sigmoid(float x) { + if (x < -MAX_SIGMOID) { + return 0.0f; + } else if (x > MAX_SIGMOID) { + return 1.0f; + } else { + int i = (int) ((x + MAX_SIGMOID) * SIGMOID_TABLE_SIZE / MAX_SIGMOID / 2); + return t_sigmoid[i]; + } + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Read/Write race. Non-private method `zemberek.embedding.fasttext.Model.binaryLogistic` indirectly reads without synchronization from `fasttext.Model.zemberek.embedding.fasttext.Model.t_log.[_]`. Potentially races with write in method `Model.initLog()`. + Reporting because this access may occur on a background thread. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +float Model.binaryLogistic(int,boolean,float) + +### Procedure Id: +zemberek.embedding.fasttext.Model.binaryLogistic(int,boolean,float):float.692e211b4649cfe78f82841bc3e3c33c + +### File: +experiment/src/main/java/zemberek/embedding/fasttext/Model.java + +### Key: +Model.java|binaryLogistic|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +924326efbfd19c7c4a2ffbb378808f5e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Analyze the bug information provided above. Your task is to: + +1. **Understand the Bug**: Examine the buggy code and identify what the issue was +2. **Analyze the Root Cause**: Determine why this bug occurred (logic error, edge case, etc.) +3. **Evaluate the Fix**: Understand how the after code addresses the issue +4. **Code Review**: Provide insights on code quality, potential improvements, and best practices + +### Analysis Questions: +- What was the specific bug or issue in the original code? +- What scenarios would trigger this bug? +- How does the fix address the root cause? +- Are there any potential edge cases the fix might miss? +- What coding practices could have prevented this bug? +- Are there alternative ways to implement the fix? + +Use the provided environment to explore, test, or reproduce the bug if needed.