diff --git a/inferredbugs-0033/instruction.md b/inferredbugs-0033/instruction.md index b6faa89062bc9640ee01f7dc98d94344caf1d1f0..1d4e38dbf5cec5ee58f669be773e9914d035c6d0 100644 --- a/inferredbugs-0033/instruction.md +++ b/inferredbugs-0033/instruction.md @@ -255,19 +255,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0200/instruction.md b/inferredbugs-0200/instruction.md index 54b054fc47ec24dc8fac450c214728e4cb80d3ef..6db24b53841e6e449ee578c00560819fee8e0776 100644 --- a/inferredbugs-0200/instruction.md +++ b/inferredbugs-0200/instruction.md @@ -269,19 +269,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0201/instruction.md b/inferredbugs-0201/instruction.md index 0f686ba17b280c30e44bc913cdd3912f0b5ed09d..abacfe002e3e7a48a8f6917cd00f80d9160f68b0 100644 --- a/inferredbugs-0201/instruction.md +++ b/inferredbugs-0201/instruction.md @@ -266,19 +266,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0209/instruction.md b/inferredbugs-0209/instruction.md index 9fc8c1249605802b40c6b50af5067c604fb43d61..c4247a32baf5f787ea1235e3b120754a8f52db96 100644 --- a/inferredbugs-0209/instruction.md +++ b/inferredbugs-0209/instruction.md @@ -441,19 +441,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0456/instruction.md b/inferredbugs-0456/instruction.md index 367bbef8ed064dc7ba596be63f2295fab78935cf..fc4cbdd824c1c0279b30997ff1bb0ac3160271a3 100644 --- a/inferredbugs-0456/instruction.md +++ b/inferredbugs-0456/instruction.md @@ -443,19 +443,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0665/instruction.md b/inferredbugs-0665/instruction.md index 4217336837269b89b7f146cb43c0c62880af77db..4ad7f7a5198b66245b8ac21a8be5e859123067d3 100644 --- a/inferredbugs-0665/instruction.md +++ b/inferredbugs-0665/instruction.md @@ -98,19 +98,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0690/instruction.md b/inferredbugs-0690/instruction.md index 7040f33e500cc03dfb0ecea1874ec9eda913bb06..bf6f9c2a7723e1d668cd9f2e221fdde7e9c41cc4 100644 --- a/inferredbugs-0690/instruction.md +++ b/inferredbugs-0690/instruction.md @@ -70,19 +70,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-0699/instruction.md b/inferredbugs-0699/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3526a47fdb68652c02e865debbc69ec918bcb2fa --- /dev/null +++ b/inferredbugs-0699/instruction.md @@ -0,0 +1,92 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** python-language-server +**Bug ID:** 7 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System.IO; +using FluentAssertions; +using Microsoft.Python.Core.Text; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using TestUtilities; + +namespace Microsoft.Python.Parsing.Tests { + /// + /// Test cases to verify that the tokenizer maintains expected behaviour. + /// + [TestClass] + public class TokenizerTests { + public TestContext TestContext { get; set; } + + [TestInitialize] + public void TestInitialize() => TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}"); + + [TestCleanup] + public void TestCleanup() => TestEnvironmentImpl.TestCleanup(); + + internal static readonly PythonLanguageVersion[] AllVersions = new[] { PythonLanguageVersion.V26, PythonLanguageVersion.V27, PythonLanguageVersion.V30, PythonLanguageVersion.V31, PythonLanguageVersion.V32, PythonLanguageVersion.V33, PythonLanguageVersion.V34, PythonLanguageVersion.V35, PythonLanguageVersion.V36, PythonLanguageVersion.V37 }; + + [TestMethod, Priority(0)] + public void AbsoluteTokenizerIndex() { + foreach (var version in AllVersions) { + var tokenizer = MakeTokenizer(version, TokenizerOptions.None, "x = 1", new SourceLocation(5, 100, 3)); + + // Read 'x' token + var tokenInfo = tokenizer.ReadToken(); + tokenizer.TokenSpan.Should().Be(new IndexSpan(5, 1)); + tokenizer.CurrentPosition.Should().BeEquivalentTo(new SourceLocation(6, 100, 4)); + + // Read '=' token + tokenInfo = tokenizer.ReadToken(); + tokenizer.TokenSpan.Should().Be(new IndexSpan(7, 1)); + tokenizer.CurrentPosition.Should().BeEquivalentTo(new SourceLocation(8, 100, 6)); + } + } + + private Tokenizer MakeTokenizer(PythonLanguageVersion version, TokenizerOptions optionSet, string text, + SourceLocation? initialSourceLocation = null) { + var tokenizer = new Tokenizer(version, options: optionSet); + + tokenizer.Initialize(null, new StringReader(text), initialSourceLocation ?? SourceLocation.MinValue); + return tokenizer; + } + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of System.IO.StringReader::.ctor() at Line 44) of type System.IO.StringReader in method "Tokenizer TokenizerTests.MakeTokenizer(PythonLanguageVersion,TokenizerOptions,String,Nullable`1)". + +### Severity: +ERROR + +### Procedure: +Tokenizer TokenizerTests.MakeTokenizer(PythonLanguageVersion,TokenizerOptions,String,Nullable`1) + +### File: +src/Parsing/Test/TokenizerTest.cs + +### Key: +TokenizerTest.cs|MakeTokenizer|DOTNET_RESOURCE_LEAK + +### Hash: +43dc3763912e60450bbd61087d22fac0 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-0807/instruction.md b/inferredbugs-0807/instruction.md index 139e668b96a9aaac09e62d93c2d74b09fa0f82ee..c8cd0472c36b6bfa29c908041cb25710ca6e554f 100644 --- a/inferredbugs-0807/instruction.md +++ b/inferredbugs-0807/instruction.md @@ -113,19 +113,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10110/instruction.md b/inferredbugs-10110/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a71a071383729d3050e4da1bfd49b2550a2c299d --- /dev/null +++ b/inferredbugs-10110/instruction.md @@ -0,0 +1,150 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jadb +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package se.vidstige.jadb; + + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; + +public class JadbConnection implements ITransportFactory { + + private final String host; + private final int port; + + private static final int DEFAULTPORT = 5037; + + public JadbConnection() { + this("localhost", DEFAULTPORT); + } + + public JadbConnection(String host, int port) { + this.host = host; + this.port = port; + } + + public Transport createTransport() throws IOException { + return new Transport(new Socket(host, port)); + } + + public String getHostVersion() throws IOException, JadbException { + Transport main = createTransport(); + main.send("host:version"); + main.verifyResponse(); + String version = main.readString(); + main.close(); + return version; + } + + public InetSocketAddress connectToTcpDevice(InetSocketAddress inetSocketAddress) + throws IOException, JadbException, ConnectionToRemoteDeviceException { + Transport transport = createTransport(); + try { + return new HostConnectToRemoteTcpDevice(transport).connect(inetSocketAddress); + } finally { + transport.close(); + } + } + + public InetSocketAddress disconnectFromTcpDevice(InetSocketAddress tcpAddressEntity) + throws IOException, JadbException, ConnectionToRemoteDeviceException { + Transport transport = createTransport(); + try { + return new HostDisconnectFromRemoteTcpDevice(transport).disconnect(tcpAddressEntity); + } finally { + transport.close(); + } + } + + public List getDevices() throws IOException, JadbException { + Transport devices = createTransport(); + devices.send("host:devices"); + devices.verifyResponse(); + String body = devices.readString(); + devices.close(); + return parseDevices(body); + } + + public DeviceWatcher createDeviceWatcher(DeviceDetectionListener listener) throws IOException, JadbException { + Transport transport = createTransport(); + transport.send("host:track-devices"); + transport.verifyResponse(); + return new DeviceWatcher(transport, listener, this); + } + + public List parseDevices(String body) { + String[] lines = body.split("\n"); + ArrayList devices = new ArrayList<>(lines.length); + for (String line : lines) { + String[] parts = line.split("\t"); + if (parts.length > 1) { + devices.add(new JadbDevice(parts[0], this)); // parts[1] is type + } + } + return devices; + } + + public JadbDevice getAnyDevice() { + return JadbDevice.createAny(this); + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `se.vidstige.jadb.Transport` acquired to `devices` by call to `createTransport()` at line 60 is not released after line 65. +**Note**: potential exception at line 61 + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +List JadbConnection.getDevices() + +### Procedure Id: +se.vidstige.jadb.JadbConnection.getDevices():java.util.List.57bed4e3693000d7b8ab7ac2a7b70518 + +### File: +src/se/vidstige/jadb/JadbConnection.java + +### Key: +JadbConnection.java|getDevices|RESOURCE_LEAK + +### Node Key: +48815eab4c26cee962db00712b67bbd0 + +### Hash: +3e4fa90d088841029c9931270a4d8892 + +### Bug Type Hum: +Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-10119/instruction.md b/inferredbugs-10119/instruction.md index 5fa8d24241ca88f46a69c2ca5bfce39855e6851d..3b3817ccc140d0eebac4b052e416f58a79e82fc2 100644 --- a/inferredbugs-10119/instruction.md +++ b/inferredbugs-10119/instruction.md @@ -146,19 +146,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10322/instruction.md b/inferredbugs-10322/instruction.md index 05101030347d29079cc439f6ae1a091980cc049d..391a13d0d3640ddc5f88713b2c0ca8869b1694a8 100644 --- a/inferredbugs-10322/instruction.md +++ b/inferredbugs-10322/instruction.md @@ -409,19 +409,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10580/instruction.md b/inferredbugs-10580/instruction.md index 1b5f19438e151cd991cf4302ae0b41d4362b928d..5b6a4780b4541812b12821ef3c4a2f2fb4a9a752 100644 --- a/inferredbugs-10580/instruction.md +++ b/inferredbugs-10580/instruction.md @@ -276,19 +276,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10588/instruction.md b/inferredbugs-10588/instruction.md index de09c3e0fc25de3b38d28139f2ef992c66d3e13b..91352ffc29b2757672b01cb9c0cc16b525d8f77f 100644 --- a/inferredbugs-10588/instruction.md +++ b/inferredbugs-10588/instruction.md @@ -99,19 +99,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10589/instruction.md b/inferredbugs-10589/instruction.md index a7015204a8fcd8517a2e271d4967da59449a89ca..bdf0a42a38758c42271ff4bb27e5cd95378a6211 100644 --- a/inferredbugs-10589/instruction.md +++ b/inferredbugs-10589/instruction.md @@ -204,19 +204,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10746/instruction.md b/inferredbugs-10746/instruction.md index 5f15c58884e8faae2dedbd6797a7429aa7e843ef..6697877a9996e6a76095c6ca2a6260d2663bbf1e 100644 --- a/inferredbugs-10746/instruction.md +++ b/inferredbugs-10746/instruction.md @@ -235,19 +235,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-10925/instruction.md b/inferredbugs-10925/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5f5b4a36f55c6314c2db2259398c078273712807 --- /dev/null +++ b/inferredbugs-10925/instruction.md @@ -0,0 +1,2467 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** rxjava2-jdbc +**Bug ID:** 98 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.davidmoten.rx.jdbc; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.sql.Blob; +import java.sql.Clob; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLSyntaxErrorException; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.log4j.Level; +import org.apache.log4j.LogManager; +import org.davidmoten.rx.jdbc.annotations.Column; +import org.davidmoten.rx.jdbc.annotations.Index; +import org.davidmoten.rx.jdbc.annotations.Query; +import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException; +import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException; +import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException; +import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException; +import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException; +import org.davidmoten.rx.jdbc.exceptions.QueryAnnotationMissingException; +import org.davidmoten.rx.jdbc.pool.DatabaseCreator; +import org.davidmoten.rx.jdbc.pool.NonBlockingConnectionPool; +import org.davidmoten.rx.jdbc.pool.Pools; +import org.davidmoten.rx.jdbc.tuple.Tuple2; +import org.davidmoten.rx.jdbc.tuple.Tuple3; +import org.davidmoten.rx.jdbc.tuple.Tuple4; +import org.davidmoten.rx.jdbc.tuple.Tuple5; +import org.davidmoten.rx.jdbc.tuple.Tuple6; +import org.davidmoten.rx.jdbc.tuple.Tuple7; +import org.davidmoten.rx.jdbc.tuple.TupleN; +import org.davidmoten.rx.pool.PoolClosedException; +import org.h2.jdbc.JdbcSQLException; +import org.hsqldb.jdbc.JDBCBlobFile; +import org.hsqldb.jdbc.JDBCClobFile; +import org.junit.Assert; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.davidmoten.guavamini.Lists; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.reactivex.Completable; +import io.reactivex.Flowable; +import io.reactivex.Observable; +import io.reactivex.Scheduler; +import io.reactivex.Single; +import io.reactivex.functions.Predicate; +import io.reactivex.schedulers.Schedulers; +import io.reactivex.schedulers.TestScheduler; +import io.reactivex.subscribers.TestSubscriber; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class DatabaseTest { + + private static final long FRED_REGISTERED_TIME = 1442515672690L; + private static final int NAMES_COUNT_BIG = 5163; + private static final Logger log = LoggerFactory.getLogger(DatabaseTest.class); + private static final int TIMEOUT_SECONDS = 2; + + private static Database db() { + return DatabaseCreator.create(1); + } + + private static Database blocking() { + return DatabaseCreator.createBlocking(); + } + + private static Database db(int poolSize) { + return DatabaseCreator.create(poolSize); + } + + private static Database big(int poolSize) { + return DatabaseCreator.create(poolSize, true, Schedulers.computation()); + } + + @Test + public void testSelectUsingQuestionMark() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNamedParameterList() { + try (Database db = db()) { + db.select("select score from person where name=:name") // + .parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameters() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterStream(Flowable.just("FRED", "JOSEPH")) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersInLists() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED"), Arrays.asList("JOSEPH"))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testDrivingSelectWithoutParametersUsingParameterStream() { + try (Database db = db()) { + db.select("select count(*) from person") // + .parameters(1, 2, 3) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParametersTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterStream(Flowable.just("FRED", 21, "JOSEPH", 34)) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkFlowableParameterListsTwoParametersPerQuery() { + try (Database db = db()) { + db.select("select score from person where name=? and score = ?") // + .parameterListStream( + Flowable.just(Arrays.asList("FRED", 21), Arrays.asList("JOSEPH", 34))) // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingQuestionMarkWithPublicTestingDatabase() { + try (Database db = Database.test()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSize() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(2) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test + public void testSelectWithFetchSizeZero() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(0) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34, 25) // + .assertComplete(); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectWithFetchSizeNegative() { + try (Database db = db()) { + db.select("select score from person order by name") // + .fetchSize(-1); + } + } + + @Test + public void testSelectUsingNonBlockingBuilder() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(1, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) // + .checkoutRetryInterval(1, TimeUnit.SECONDS) // + .healthy(c -> c.prepareStatement("select 1").execute()) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) // + .maxPoolSize(3) // + .build(); + + try (Database db = Database.from(pool)) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test(timeout = 40000) + public void testSelectUsingNonBlockingBuilderConcurrencyTest() + throws InterruptedException, TimeoutException { + info(); + try { + try (Database db = db(3)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(50)); + int n = 10000; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } else { + // log.debug(iCopy + " succeeded"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + } + if (!latch.await(20, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test(timeout = 5000) + public void testSelectConcurrencyTest() throws InterruptedException, TimeoutException { + debug(); + try { + try (Database db = db(1)) { + Scheduler scheduler = Schedulers.from(Executors.newFixedThreadPool(2)); + int n = 2; + CountDownLatch latch = new CountDownLatch(n); + AtomicInteger count = new AtomicInteger(); + for (int i = 0; i < n; i++) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .subscribeOn(scheduler) // + .toList() // + .doOnSuccess(x -> { + if (!x.equals(Lists.newArrayList(21, 34))) { + throw new RuntimeException("run broken"); + } + }) // + .doOnSuccess(x -> { + count.incrementAndGet(); + latch.countDown(); + }) // + .doOnError(x -> latch.countDown()) // + .subscribe(); + log.info("submitted " + i); + } + if (!latch.await(5000, TimeUnit.SECONDS)) { + throw new TimeoutException("timeout"); + } + assertEquals(n, count.get()); + } + } finally { + debug(); + } + } + + @Test + public void testDatabaseClose() { + try (Database db = db()) { + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingName() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(21, 34) // + .assertComplete(); + } + } + + @Test + public void testSelectUsingNameNotGiven() { + try (Database db = db()) { + db // + .select("select score from person where name=:name and name<>:name2") // + .parameter("name", "FRED") // + .parameter("name", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterMissingException.class) // + .assertNoValues(); + } + } + + @Test + public void testSelectUsingParameterNameNullNameWhenSqlHasNoNames() { + db() // + .select("select score from person where name=?") // + .parameter(Parameter.create("name", "FRED")) // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(NamedParameterFoundButSqlDoesNotHaveNamesException.class) // + .assertNoValues(); + } + + @Test + public void testUpdateWithNull() { + try (Database db = db()) { + db // + .update("update person set date_of_birth = :dob") // + .parameter(Parameter.create("dob", null)) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithNull() { + try (Database db = db()) { + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", Database.NULL_CLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithClob() throws SQLException { + try (Database db = db()) { + Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", clob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateClobWithReader() throws FileNotFoundException { + try (Database db = db()) { + Reader reader = new FileReader(new File("src/test/resources/big.txt")); + insertNullClob(db); + db // + .update("update person_clob set document = :doc") // + .parameter("doc", reader) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithBlob() throws SQLException { + try (Database db = db()) { + Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt")); + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", blob) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateBlobWithNull() { + try (Database db = db()) { + insertPersonBlob(db); + db // + .update("update person_blob set document = :doc") // + .parameter("doc", Database.NULL_BLOB) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test(expected = NullPointerException.class) + public void testSelectUsingNullNameInParameter() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameter(null, "FRED"); // + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameDoesNotExist() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("nam", "FRED"); + } + } + + @Test(expected = IllegalArgumentException.class) + public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() { + try (Database db = db()) { + db // + .select("select score from person where name=:name") // + .parameters("FRED", "JOSEPH"); + } + } + + @Test + public void testSelectTransacted() { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value()))) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedAnnotatedTransacted() { + try (Database db = db()) { + db // + .select(Person10.class) // + .transacted() // + .valuesOnly() // + .get().test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransactedValuesOnly() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .valuesOnly() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testSelectAutomappedTransacted() { + try (Database db = db()) { + db // + .select("select name, score from person") // + .transacted() // + .autoMap(Person2.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + } + + @Test + public void testSelectTransactedTuple2() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + } + } + + @Test + public void testSelectTransactedTuple3() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + } + } + + @Test + public void testSelectTransactedTuple4() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + } + } + + @Test + public void testSelectTransactedTuple5() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + } + } + + @Test + public void testSelectTransactedTuple6() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + } + } + + @Test + public void testSelectTransactedTuple7() { + try (Database db = db()) { + Tx> t = db // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values().get(0); + assertEquals("FRED", t.value()._1()); + assertEquals(21, (int) t.value()._2()); + assertEquals("FRED", t.value()._3()); + assertEquals(21, (int) t.value()._4()); + assertEquals("FRED", t.value()._5()); + assertEquals(21, (int) t.value()._6()); + assertEquals("FRED", t.value()._7()); + } + } + + @Test + public void testSelectTransactedTupleN() { + List>> list = db() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .transacted() // + .getTupleN() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertEquals("FRED", list.get(0).value().values().get(0)); + assertEquals(21, (int) list.get(0).value().values().get(1)); + assertTrue(list.get(1).isComplete()); + assertEquals(2, list.size()); + } + + @Test + public void testSelectTransactedCount() { + db() // + .select("select name, score, name, score, name, score, name from person where name=?") // + .parameters("FRED") // + .transacted() // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAs() { + db() // + .select("select name from person") // + .transacted() // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(4) // + .assertComplete(); + } + + @Test + public void testSelectTransactedGetAsOptional() { + List>> list = db() // + .select("select name from person where name=?") // + .parameters("FRED") // + .transacted() // + .getAsOptional(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(2) // + .assertComplete() // + .values(); + assertTrue(list.get(0).isValue()); + assertEquals("FRED", list.get(0).value().get()); + assertTrue(list.get(1).isComplete()); + } + + @Test + public void testDatabaseFrom() { + Database.from(DatabaseCreator.nextUrl(), 3) // + .select("select name from person") // + .getAs(String.class) // + .count() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertError(JdbcSQLException.class); + } + + @Test + public void testSelectTransactedChained() throws Exception { + try (Database db = db()) { + db // + .select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transacted() // + .transactedValuesOnly() // + .getAs(Integer.class) // + .doOnNext(tx -> log + .debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))// + .flatMap(tx -> tx // + .select("select name from person where score = ?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + } + + @Test + public void databaseIsAutoCloseable() { + try (Database db = db()) { + log.debug(db.toString()); + } + } + + @Test + public void testSelectChained() { + try (Database db = db(1)) { + // we can do this with 1 connection only! + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .doOnNext(System.out::println) // + .concatMap(score -> { + log.info("score={}", score); + return db // + .select("select name from person where score = ?") // + .parameter(score) // + .getAs(String.class) // + .doOnComplete( + () -> log.info("completed select where score=" + score)); + }) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); // + } + } + + @Test + @SuppressFBWarnings + public void testReadMeFragment1() { + try (Database db = db()) { + db.select("select name from person") // + .getAs(String.class) // + .forEach(System.out::println); + } + } + + @Test + public void testReadMeFragmentColumnDoesNotExistEmitsSqlSyntaxErrorException() { + try (Database db = Database.test()) { + db.select("select nam from person") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(SQLSyntaxErrorException.class); + } + } + + @Test + public void testReadMeFragmentDerbyHealthCheck() { + try (Database db = Database.test()) { + db.select("select 'a' from sysibm.sysdummy1") // + .getAs(String.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("a") // + .assertComplete(); + } + } + + @Test + @SuppressFBWarnings + public void testTupleSupport() { + try (Database db = db()) { + db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .forEach(System.out::println); + } + } + + @Test + public void testDelayedCallsAreNonBlocking() throws InterruptedException { + List list = new CopyOnWriteArrayList(); + try (Database db = db(1)) { // + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> Thread.sleep(1000)) // + .subscribeOn(Schedulers.io()) // + .subscribe(); + Thread.sleep(100); + CountDownLatch latch = new CountDownLatch(1); + db.select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .doOnNext(x -> list.add("emitted")) // + .doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) // + .doOnNext(x -> latch.countDown()) // + .subscribe(); + list.add("subscribed"); + assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); + assertEquals(Arrays.asList("subscribed", "emitted"), list); + } + } + + @Test + public void testAutoMapToInterface() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(Person.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValueCount(3) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithoutAnnotationstsError() { + try (Database db = db()) { + db // + .select("select name from person") // + .autoMap(PersonNoAnnotation.class) // + .map(p -> p.name()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(AnnotationsNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithTwoMethods() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person2.class) // + .firstOrError() // + .map(Person2::score) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person3.class) // + .firstOrError() // + .map(Person3::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person4.class) // + .firstOrError() // + .map(Person4::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnNotFoundException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndex() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person5.class) // + .firstOrError() // + .map(Person5::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooLarge() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person6.class) // + .firstOrError() // + .map(Person6::examScore) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapToInterfaceWithIndexTooSmall() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person7.class) // + .firstOrError() // + .map(Person7::examScore) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ColumnIndexOutOfRangeException.class); + } + } + + @Test + public void testAutoMapWithUnmappableColumnType() { + try (Database db = db()) { + db // + .select("select name from person order by name") // + .autoMap(Person8.class) // + .map(p -> p.name()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(ClassCastException.class); + } + } + + @Test + public void testAutoMapWithMixIndexAndName() { + try (Database db = db()) { + db // + .select("select name, score from person order by name") // + .autoMap(Person9.class) // + .firstOrError() // + .map(Person9::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testAutoMapWithQueryInAnnotation() { + try (Database db = db()) { + db.select(Person10.class) // + .get() // + .firstOrError() // + .map(Person10::score) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(21) // + .assertComplete(); + } + } + + @Test + @Ignore + public void testAutoMapForReadMe() { + Database // + .test() // + .select(Person10.class) // + .get(Person10::name) // + .blockingForEach(System.out::println); + } + + @Test(expected = QueryAnnotationMissingException.class) + public void testAutoMapWithoutQueryInAnnotation() { + try (Database db = db()) { + db.select(Person.class); + } + } + + @Test + public void testSelectWithoutWhereClause() { + try (Database db = db()) { + Assert.assertEquals(3, (long) db.select("select name from person") // + .count() // + .blockingGet()); + } + } + + @Test + public void testTuple3() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple3.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple4() { + try (Database db = db()) { + db // + .select("select name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(Tuple4.create("FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple5() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTuple6() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); // + } + } + + @Test + public void testTuple7() { + try (Database db = db()) { + db // + .select("select name, score, name, score, name, score, name from person order by name") // + .getAs(String.class, Integer.class, String.class, Integer.class, String.class, + Integer.class, String.class) // + .firstOrError() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() + .assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); // + } + } + + @Test + public void testTupleN() { + try (Database db = db()) { + db // + .select("select name, score, name from person order by name") // + .getTupleN() // + .firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertComplete() // + .assertValue(TupleN.create("FRED", 21, "FRED")); // + } + } + + @Test + public void testHealthCheck() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + return !once.compareAndSet(true, false); + }); + } + + @Test + public void testHealthCheckThatThrows() throws InterruptedException { + AtomicBoolean once = new AtomicBoolean(true); + testHealthCheck(c -> { + log.debug("doing health check"); + if (!once.compareAndSet(true, false)) + return true; + else + throw new RuntimeException("health check failed"); + }); + } + + @Test + public void testUpdateOneRow() { + try (Database db = db()) { + db.update("update person set score=20 where name='FRED'") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateThreeRows() { + try (Database db = db()) { + db.update("update person set score=20") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameter() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameter("FRED").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithParameterTwoRuns() { + try (Database db = db()) { + db.update("update person set score=20 where name=?") // + .parameters("FRED", "JOSEPH").counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + } + } + + @Test + public void testUpdateAllWithParameterFourRuns() { + try (Database db = db()) { + db.update("update person set score=?") // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize2() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(2) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithBatchSize3GreaterThanNumRecords() { + try (Database db = db()) { + db.update("update person set score=?") // + .batchSize(3) // + .parameters(1, 2, 3, 4) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 3, 3, 3) // + .assertComplete(); + } + } + + @Test + public void testInsert() { + try (Database db = db()) { + db.update("insert into person(name, score) values(?,?)") // + .parameters("DAVE", 12, "ANNE", 18) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1) // + .assertComplete(); + List> list = db.select("select name, score from person") // + .getAs(String.class, Integer.class) // + .toList() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingGet(); + assertTrue(list.contains(Tuple2.create("DAVE", 12))); + assertTrue(list.contains(Tuple2.create("ANNE", 18))); + } + } + + @Test + public void testReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testReturnGeneratedKeysDerby() { + Database db = DatabaseCreator.createDerby(1); + + // note is a table with auto increment + db.update("insert into note2(text) values(?)") // + .parameters("HI", "THERE") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors().assertValues(1, 3) // + .assertComplete(); + + db.update("insert into note2(text) values(?)") // + .parameters("ME", "TOO") // + .returnGeneratedKeys() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(5, 7) // + .assertComplete(); + } + + @Test(expected = IllegalArgumentException.class) + public void testReturnGeneratedKeysWithBatchSizeShouldThrow() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .batchSize(2) // + .returnGeneratedKeys(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys() { + try (Database db = db()) { + // note is a table with auto increment + db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2) // + .assertComplete(); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3, 4) // + .assertComplete(); + } + } + + @Test + public void testTransactedReturnGeneratedKeys2() { + try (Database db = db()) { + // note is a table with auto increment + Flowable a = db.update("insert into note(text) values(?)") // + .parameters("HI", "THERE") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class); + + db.update("insert into note(text) values(?)") // + .parameters("ME", "TOO") // + .transacted() // + .returnGeneratedKeys() // + .valuesOnly() // + .getAs(Integer.class)// + .startWith(a) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 2, 3, 4) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransaction() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnFlowable() { + try (Database db = db()) { + Flowable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnObservable() { + try (Database db = db()) { + Observable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().toObservable(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnOnSingle() { + try (Database db = db()) { + Single a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().count(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testSelectDependsOnCompletable() { + try (Database db = db()) { + Completable a = db.update("update person set score=100 where name=?") // + .parameter("FRED") // + .counts().ignoreElements(); + db.select("select score from person where name=?") // + .parameter("FRED") // + .dependsOn(a) // + .getAs(Integer.class)// + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(100) // + .assertComplete(); + } + } + + @Test + public void testUpdateWithinTransactionBatchSize0() { + try (Database db = db()) { + db // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .doOnNext(System.out::println) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(0) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(1, 1, 1) // + .assertComplete(); + } + } + + private static void info() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + private static void debug() { + LogManager.getRootLogger().setLevel(Level.INFO); + } + + @Test + public void testCreateBig() { + info(); + big(5).select("select count(*) from person") // + .getAs(Integer.class) // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue(5163) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBig() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(1) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testTxWithBigInputBatchSize2000() { + info(); + big(1) // + .select("select name from person") // + .transactedValuesOnly() // + .getAs(String.class) // + .flatMap(tx -> tx// + .update("update person set score=-1 where name=:name") // + .batchSize(2000) // + .parameter("name", tx.value()) // + .valuesOnly() // + .counts()) // + .count() // + .test().awaitDone(20, TimeUnit.SECONDS) // + .assertValue((long) NAMES_COUNT_BIG) // + .assertComplete(); + debug(); + } + + @Test + public void testInsertNullClobAndReadClobAsString() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document from person_clob where name='FRED'") // + .getAsOptional(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Optional.empty()) // + .assertComplete(); + } + } + + private static void insertNullClob(Database db) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", Database.NULL_CLOB) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testClobMethod() { + assertEquals(Database.NULL_CLOB, Database.clob(null)); + } + + @Test + public void testBlobMethod() { + assertEquals(Database.NULL_BLOB, Database.blob(null)); + } + + @Test + public void testClobMethodPresent() { + assertEquals("a", Database.clob("a")); + } + + @Test + public void testBlobMethodPresent() { + byte[] b = new byte[1]; + assertEquals(b, Database.blob(b)); + } + + @Test + public void testDateOfBirthNullableForReadMe() { + Database.test() // + .select("select date_of_birth from person where name='FRED'") // + .getAsOptional(Instant.class) // + .blockingForEach(System.out::println); + } + + @Test + public void testInsertNullClobAndReadClobAsTuple2() { + try (Database db = db()) { + insertNullClob(db); + db.select("select document, document from person_clob where name='FRED'") // + .getAs(String.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(Tuple2.create(null, null)) // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobAsString() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some + // text + // here") + // // + .assertComplete(); + } + } + + @Test + public void testInsertClobAndReadClobUsingReader() { + try (Database db = db()) { + db.update("insert into person_clob(name,document) values(?,?)") // + .parameters("FRED", "some text here") // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_clob where name='FRED'") // + .getAs(Reader.class) // + .map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + @Test + public void testInsertBlobAndReadBlobAsByteArray() { + try (Database db = db()) { + insertPersonBlob(db); + db.select("select document from person_blob where name='FRED'") // + .getAs(byte[].class) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static void insertPersonBlob(Database db) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", bytes) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testInsertBlobAndReadBlobAsInputStream() { + try (Database db = db()) { + byte[] bytes = "some text here".getBytes(); + db.update("insert into person_blob(name,document) values(?,?)") // + .parameters("FRED", new ByteArrayInputStream(bytes)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select document from person_blob where name='FRED'") // + .getAs(InputStream.class) // + .map(is -> read(is)) // + .map(b -> new String(b)) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue("some text here") // + .assertComplete(); + } + } + + private static String read(Reader reader) throws IOException { + StringBuffer s = new StringBuffer(); + char[] ch = new char[128]; + int n = 0; + while ((n = reader.read(ch)) != -1) { + s.append(ch, 0, n); + } + reader.close(); + return s.toString(); + } + + private static byte[] read(InputStream is) throws IOException { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + byte[] b = new byte[128]; + int n = 0; + while ((n = is.read(b)) != -1) { + bytes.write(b, 0, n); + } + is.close(); + return bytes.toByteArray(); + } + + private void testHealthCheck(Predicate healthy) throws InterruptedException { + TestScheduler scheduler = new TestScheduler(); + + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .maxIdleTime(10, TimeUnit.MINUTES) // + .idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) // + .healthy(healthy) // + .returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) // + .scheduler(scheduler) // + .maxPoolSize(1) // + .build(); + + try (Database db = Database.from(pool)) { + TestSubscriber ts0 = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test(); + ts0.assertValueCount(0) // + .assertNotComplete(); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + ts0.assertValueCount(1) // + .assertComplete(); + TestSubscriber ts = db.select( // + "select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test() // + .assertValueCount(0); + log.debug("done2"); + scheduler.advanceTimeBy(1, TimeUnit.MINUTES); + Thread.sleep(200); + ts.assertValueCount(1); + Thread.sleep(200); + ts.assertValue(21) // + .assertComplete(); + } + } + + @Test + public void testShutdownBeforeUse() { + NonBlockingConnectionPool pool = Pools // + .nonBlocking() // + .connectionProvider(DatabaseCreator.connectionProvider()) // + .scheduler(Schedulers.io()) // + .maxPoolSize(1) // + .build(); + pool.close(); + Database.from(pool) // + .select("select score from person where name=?") // + .parameter("FRED") // + .getAs(Integer.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(PoolClosedException.class); + } + + @Test + public void testFewerColumnsMappedThanAvailable() { + db().select("select name, score from person where name='FRED'") // + .getAs(String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues("FRED") // + .assertComplete(); + } + + @Test + public void testMoreColumnsMappedThanAvailable() { + db() // + .select("select name, score from person where name='FRED'") // + .getAs(String.class, Integer.class, String.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoValues() // + .assertError(MoreColumnsRequestedThanExistException.class); + } + + @Test + public void testSelectTimestamp() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsDate() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Date.class) // + .map(d -> d.getTime()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testSelectTimestampAsInstant() { + db() // + .select("select registered from person where name='FRED'") // + .getAs(Instant.class) // + .map(d -> d.toEpochMilli()) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + + @Test + public void testUpdateCalendarParameter() { + Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z")); + try (Database db = db()) { + db.update("update person set registered=?") // + .parameter(c) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(c.getTimeInMillis()) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimeParameter() { + try (Database db = db()) { + Time t = new Time(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampParameter() { + try (Database db = db()) { + Timestamp t = new Timestamp(1234); + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateSqlDateParameter() { + try (Database db = db()) { + java.sql.Date t = new java.sql.Date(1234); + + db.update("update person set registered=?") // + .parameter(t) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) // + // TODO make a more accurate comparison using the current TZ + .assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) // + .assertComplete(); + } + } + + @Test + public void testUpdateUtilDateParameter() { + try (Database db = db()) { + Date d = new Date(1234); + db.update("update person set registered=?") // + .parameter(d) // + .counts() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(3) // + .assertComplete(); + db.select("select registered from person") // + .getAs(Long.class) // + .firstOrError() // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1234L) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsInstant() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testUpdateTimestampAsZonedDateTime() { + try (Database db = db()) { + db.update("update person set registered=? where name='FRED'") // + .parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME), + ZoneOffset.UTC.normalized())) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + db.select("select registered from person where name='FRED'") // + .getAs(Long.class) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(FRED_REGISTERED_TIME) // + .assertComplete(); + } + } + + @Test + public void testCompleteCompletes() { + Database db = db(1); + db // + .update("update person set score=-3 where name='FRED'") // + .complete() // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingAwait(); + + int score = db.select("select score from person where name='FRED'") // + .getAs(Integer.class) // + .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .blockingFirst(); + assertEquals(-3, score); + } + + @Test + public void testComplete() throws InterruptedException { + Database db = db(1); + Completable a = db // + .update("update person set score=-3 where name='FRED'") // + .complete(); + db.update("update person set score=-4 where score = -3") // + .dependsOn(a) // + .counts() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testCountsOnlyInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .countsOnly() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValues(3) // + .assertComplete(); + } + + @Test + public void testCountsInTransaction() { + db().update("update person set score = -3") // + .transacted() // + .counts() // + .doOnNext(System.out::println) // + .toList() // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3 + && list.get(1).isComplete() && list.size() == 2) // + .assertComplete(); + } + + @Test + public void testTx() throws InterruptedException { + Database db = db(3); + Single> transaction = db // + .update("update person set score=-3 where name='FRED'") // + .transaction(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = -3") // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testTxAfterSelect() { + Database db = db(3); + Single> transaction = db // + .select("select score from person where name='FRED'") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .firstOrError(); + + transaction // + .doOnDispose(() -> log.debug("disposing")) // + .doOnSuccess(System.out::println) // + .flatMapPublisher(tx -> { + log.debug("flatmapping"); + return tx // + .update("update person set score = -4 where score = ?") // + .parameter(tx.value()) // + .countsOnly() // + .doOnSubscribe(s -> log.debug("subscribed")) // + .doOnNext(num -> log.debug("num=" + num)); + }) // + .test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValue(1) // + .assertComplete(); + } + + @Test + public void testSingleFlatMap() { + Single.just(1).flatMapPublisher(n -> Flowable.just(1)).test(1).assertValue(1) + .assertComplete(); + } + + @Test + public void testAutomappedInstanceHasMeaningfulToStringMethod() { + info(); + String s = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.toString()) // + .blockingSingle(); + assertEquals("Person2[name=FRED, score=21]", s); + } + + @Test + public void testAutomappedEquals() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(x)) // + .blockingSingle(); + assertTrue(b); + } + + @Test + public void testAutomappedDoesNotEqualNull() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(null)) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedDoesNotEqual() { + boolean b = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .map(x -> x.equals(new Object())) // + .blockingSingle(); + assertFalse(b); + } + + @Test + public void testAutomappedHashCode() { + Person2 p = Database.test() // + .select("select name, score from person where name=?") // + .parameterStream(Flowable.just("FRED")) // + .autoMap(Person2.class) // + .blockingSingle(); + assertTrue(p.hashCode() != 0); + } + + @Test + public void testAutomappedWithParametersThatProvokesMoreThanOneQuery() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(2) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsAndHashCodeIsDistinctOnValues() { + Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED", "FRED") // + .autoMap(Person2.class) // + .distinct() // + .doOnNext(System.out::println) // + .test() // + .awaitDone(2000, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValueCount(1) // + .assertComplete(); + } + + @Test + public void testAutomappedObjectsEqualsDifferentiatesDifferentInterfacesWithSameMethodNamesAndValues() { + PersonDistinct1 p1 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct1.class) // + .blockingFirst(); + + PersonDistinct2 p2 = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonDistinct2.class) // + .blockingFirst(); + + assertNotEquals(p1, p2); + } + + @Test + public void testAutomappedObjectsWhenDefaultMethodInvoked() { + PersonWithDefaultMethod p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethod.class) // + .blockingFirst(); + assertEquals("fred", p.nameLower()); + } + + // @Test + // public void testDefaultMethod() throws NoSuchMethodException, + // IllegalAccessException { + // MethodHandles.lookup().findSpecial(PersonWithDefaultMethod.class, + // "nameLower", + // MethodType.methodType(String.class, new Class[] {}), + // PersonWithDefaultMethod.class) + //// .bindTo(x); + // } + + @Test(expected = AutomappedInterfaceInaccessibleException.class) + public void testAutomappedObjectsWhenDefaultMethodInvokedAndIsNonPublicThrows() { + PersonWithDefaultMethodNonPublic p = Database.test() // + .select("select name, score from person where name=?") // + .parameters("FRED") // + .autoMap(PersonWithDefaultMethodNonPublic.class) // + .blockingFirst(); + p.nameLower(); + } + + @Test + public void testBlockingDatabase() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .getAs(Integer.class) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransacted() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .map(x -> x.value()) // + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues(21, 34) // + .assertComplete(); + } + + @Test + public void testBlockingDatabaseTransactedNested() { + Database db = blocking(); + db.select("select score from person where name=?") // + .parameters("FRED", "JOSEPH") // + .transactedValuesOnly() // + .getAs(Integer.class) // + .flatMap(tx -> tx.select("select name from person where score=?") // + .parameter(tx.value()) // + .valuesOnly() // + .getAs(String.class)) + .test() // + .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // + .assertNoErrors() // + .assertValues("FRED", "JOSEPH") // + .assertComplete(); + } + + public interface PersonWithDefaultMethod { + @Column + String name(); + + @Column + int score(); + + public default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonWithDefaultMethodNonPublic { + @Column + String name(); + + @Column + int score(); + + default String nameLower() { + return name().toLowerCase(); + } + } + + interface PersonDistinct1 { + @Column + String name(); + + @Column + int score(); + + } + + interface PersonDistinct2 { + @Column + String name(); + + @Column + int score(); + + } + + interface Score { + @Column + int score(); + } + + interface Person { + @Column + String name(); + } + + interface Person2 { + @Column + String name(); + + @Column + int score(); + } + + interface Person3 { + @Column("name") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person4 { + @Column("namez") + String fullName(); + + @Column("score") + int examScore(); + } + + interface Person5 { + @Index(1) + String fullName(); + + @Index(2) + int examScore(); + } + + interface Person6 { + @Index(1) + String fullName(); + + @Index(3) + int examScore(); + } + + interface Person7 { + @Index(1) + String fullName(); + + @Index(0) + int examScore(); + } + + interface Person8 { + @Column + int name(); + } + + interface Person9 { + @Column + String name(); + + @Index(2) + int score(); + } + + interface PersonNoAnnotation { + String name(); + } + + @Query("select name, score from person order by name") + interface Person10 { + + @Column + String name(); + + @Column + int score(); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.davidmoten.rx.jdbc.Database` acquired by call to `db(...)` at line 2012 is not released after line 2017. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DatabaseTest.testComplete() + +### Procedure Id: +org.davidmoten.rx.jdbc.DatabaseTest.testComplete():void.8e875fdd03f5b5357bf561b3a17ad835 + +### File: +src/test/java/org/davidmoten/rx/jdbc/DatabaseTest.java + +### Key: +DatabaseTest.java|testComplete|RESOURCE_LEAK + +### Node Key: +0dd0b11dc7f32655df35487085033d4e + +### Hash: +56d795b57b1c2397e3da2d6286723e45 + +### Bug Type Hum: +Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-11006/instruction.md b/inferredbugs-11006/instruction.md index 18a08fade84fd6460cc2062115963891ff8da333..2dd6fb7a8ad2db17b04f4298f7ad358d8c1c3390 100644 --- a/inferredbugs-11006/instruction.md +++ b/inferredbugs-11006/instruction.md @@ -244,19 +244,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-11036/instruction.md b/inferredbugs-11036/instruction.md index 5f5202631c6afcf2cbd056d72d7a5eab6bf279ec..99c5049847cdce8b5bdf5358e64bde752d180556 100644 --- a/inferredbugs-11036/instruction.md +++ b/inferredbugs-11036/instruction.md @@ -251,19 +251,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-1114/instruction.md b/inferredbugs-1114/instruction.md index 4d8d9f5fd309afe801340396dca46e465f9cabb2..df14400ddc08cc35df38392504dd2e91c22acbe6 100644 --- a/inferredbugs-1114/instruction.md +++ b/inferredbugs-1114/instruction.md @@ -393,19 +393,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-1326/instruction.md b/inferredbugs-1326/instruction.md index a9f18f837cb2d22927a0e3cac0df89b8eb2e0b41..9f405968a365d0996faeb0bcd33016e18ff45eae 100644 --- a/inferredbugs-1326/instruction.md +++ b/inferredbugs-1326/instruction.md @@ -5185,19 +5185,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-1570/instruction.md b/inferredbugs-1570/instruction.md index ba999d4440bb477dda6a0a63392aa2b4a6bd1ec3..5e969800478faa047e2b852b03c784cf647e0bb6 100644 --- a/inferredbugs-1570/instruction.md +++ b/inferredbugs-1570/instruction.md @@ -88,19 +88,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-1579/instruction.md b/inferredbugs-1579/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..90ab3b1c98b270cfd48319ffb62d64cfdc113b72 --- /dev/null +++ b/inferredbugs-1579/instruction.md @@ -0,0 +1,570 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** CliWrap +**Bug ID:** 1 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CliWrap.Builders; +using CliWrap.Exceptions; +using CliWrap.Utils; +using CliWrap.Utils.Extensions; + +namespace CliWrap +{ + /// + /// Represents a shell command. + /// + public partial class Command : ICommandConfiguration + { + /// + /// File path of the executable, batch file, or script, that this command runs on. + /// + public string TargetFilePath { get; } + + /// + /// Arguments passed on the command line. + /// + public string Arguments { get; } + + /// + /// Working directory path. + /// + public string WorkingDirPath { get; } + + /// + /// User credentials set for the underlying process. + /// + public Credentials Credentials { get; } + + /// + /// Environment variables set for the underlying process. + /// + public IReadOnlyDictionary EnvironmentVariables { get; } + + /// + /// Configured result validation options. + /// + public CommandResultValidation Validation { get; } + + /// + /// Configured standard input pipe source. + /// + public PipeSource StandardInputPipe { get; } + + /// + /// Configured standard output pipe target. + /// + public PipeTarget StandardOutputPipe { get; } + + /// + /// Configured standard error pipe target. + /// + public PipeTarget StandardErrorPipe { get; } + + /// + /// Initializes an instance of . + /// + public Command( + string targetFilePath, + string arguments, + string workingDirPath, + Credentials credentials, + IReadOnlyDictionary environmentVariables, + CommandResultValidation validation, + PipeSource standardInputPipe, + PipeTarget standardOutputPipe, + PipeTarget standardErrorPipe) + { + TargetFilePath = targetFilePath; + Arguments = arguments; + WorkingDirPath = workingDirPath; + Credentials = credentials; + EnvironmentVariables = environmentVariables; + Validation = validation; + StandardInputPipe = standardInputPipe; + StandardOutputPipe = standardOutputPipe; + StandardErrorPipe = standardErrorPipe; + } + + /// + /// Initializes an instance of . + /// + public Command(string targetFilePath) : this( + targetFilePath, + string.Empty, + Directory.GetCurrentDirectory(), + Credentials.Default, + new Dictionary(), + CommandResultValidation.ZeroExitCode, + PipeSource.Null, + PipeTarget.Null, + PipeTarget.Null) + { + } + + /// + /// Creates a copy of this command, setting the arguments to the specified value. + /// + public Command WithArguments(string arguments) => new( + TargetFilePath, + arguments, + WorkingDirPath, + Credentials, + EnvironmentVariables, + Validation, + StandardInputPipe, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the arguments to the value configured by the specified delegate. + /// + public Command WithArguments(Action configure) + { + var builder = new ArgumentsBuilder(); + configure(builder); + + return WithArguments(builder.Build()); + } + + /// + /// Creates a copy of this command, setting the arguments to the value obtained by formatting the specified enumeration. + /// + public Command WithArguments(IEnumerable arguments, bool escape) => + WithArguments(args => args.Add(arguments, escape)); + + /// + /// Creates a copy of this command, setting the arguments to the value obtained by formatting the specified enumeration. + /// + // TODO: (breaking change) remove in favor of optional parameter + public Command WithArguments(IEnumerable arguments) => + WithArguments(arguments, true); + + /// + /// Creates a copy of this command, setting the working directory path to the specified value. + /// + public Command WithWorkingDirectory(string workingDirPath) => new( + TargetFilePath, + Arguments, + workingDirPath, + Credentials, + EnvironmentVariables, + Validation, + StandardInputPipe, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the credentials to the specified value. + /// + public Command WithCredentials(Credentials credentials) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + credentials, + EnvironmentVariables, + Validation, + StandardInputPipe, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the credentials to the value configured by the specified delegate. + /// + public Command WithCredentials(Action configure) + { + var builder = new CredentialsBuilder(); + configure(builder); + + return WithCredentials(builder.Build()); + } + + /// + /// Creates a copy of this command, setting the environment variables to the specified value. + /// + public Command WithEnvironmentVariables(IReadOnlyDictionary environmentVariables) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + Credentials, + environmentVariables, + Validation, + StandardInputPipe, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the environment variables to the value configured by the specified delegate. + /// + public Command WithEnvironmentVariables(Action configure) + { + var builder = new EnvironmentVariablesBuilder(); + configure(builder); + + return WithEnvironmentVariables(builder.Build()); + } + + /// + /// Creates a copy of this command, setting the validation options to the specified value. + /// + public Command WithValidation(CommandResultValidation validation) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + Credentials, + EnvironmentVariables, + validation, + StandardInputPipe, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the standard input pipe to the specified source. + /// + public Command WithStandardInputPipe(PipeSource source) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + Credentials, + EnvironmentVariables, + Validation, + source, + StandardOutputPipe, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the standard output pipe to the specified target. + /// + public Command WithStandardOutputPipe(PipeTarget target) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + Credentials, + EnvironmentVariables, + Validation, + StandardInputPipe, + target, + StandardErrorPipe + ); + + /// + /// Creates a copy of this command, setting the standard error pipe to the specified target. + /// + public Command WithStandardErrorPipe(PipeTarget target) => new( + TargetFilePath, + Arguments, + WorkingDirPath, + Credentials, + EnvironmentVariables, + Validation, + StandardInputPipe, + StandardOutputPipe, + target + ); + + private ProcessStartInfo GetStartInfo() + { + var result = new ProcessStartInfo + { + FileName = TargetFilePath, + Arguments = Arguments, + WorkingDirectory = WorkingDirPath, + UserName = Credentials.UserName, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + + // Domain and password are only supported on Windows + if (Credentials.Domain is not null || Credentials.Password is not null) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + result.Domain = Credentials.Domain; + result.Password = Credentials.Password?.ToSecureString(); + } + else + { + throw new NotSupportedException( + "Starting a process using a custom domain and password is only supported on Windows." + ); + } + } + + foreach (var (key, value) in EnvironmentVariables) + result.Environment[key] = value; + + return result; + } + + private async Task PipeStandardInputAsync(ProcessEx process, CancellationToken cancellationToken = default) + { + try + { + // Some streams do not support cancellation, so we add a fallback that + // drops the task and returns early. + // Doing so does leave the original piping task still alive, which is + // unfortunate, but still better than having everything freeze up. + // This is important with stdin because the process might finish before + // the pipe completes, and in case with infinite input stream it would + // normally result in a deadlock. + await StandardInputPipe.CopyToAsync(process.StdIn, cancellationToken) + .WithDangerousCancellation(cancellationToken) + .ConfigureAwait(false); + } + catch (IOException) + { + // IOException: The pipe has been ended. + // This may happen if the process terminated before the pipe could complete. + // It's not an exceptional situation because the process may not need + // the entire stdin to complete successfully. + } + finally + { + await process.StdIn.DisposeAsync().ConfigureAwait(false); + } + } + + private async Task PipeStandardOutputAsync(ProcessEx process, CancellationToken cancellationToken = default) + { + try + { + await StandardOutputPipe.CopyFromAsync(process.StdOut, cancellationToken) + .ConfigureAwait(false); + } + finally + { + await process.StdOut.DisposeAsync().ConfigureAwait(false); + } + } + + private async Task PipeStandardErrorAsync(ProcessEx process, CancellationToken cancellationToken = default) + { + try + { + await StandardErrorPipe.CopyFromAsync(process.StdErr, cancellationToken) + .ConfigureAwait(false); + } + finally + { + await process.StdErr.DisposeAsync().ConfigureAwait(false); + } + } + + private async Task ExecuteAsync(ProcessEx process, CancellationToken cancellationToken = default) + { + // Additional cancellation for stdin in case the process terminates early and doesn't fully exhaust it + using var stdInCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + + // Setup and start process + using var _1 = process; + process.Start(); + using var _2 = cancellationToken.Register(process.Kill); + + // Start piping in parallel + var pipingTask = Task.WhenAll( + PipeStandardInputAsync(process, stdInCts.Token), + PipeStandardOutputAsync(process, cancellationToken), + PipeStandardErrorAsync(process, cancellationToken) + ); + + // Wait until the process terminates or gets killed + await process.WaitUntilExitAsync().ConfigureAwait(false); + + // Cancel stdin in case the process terminated early and doesn't need it anymore + stdInCts.Cancel(); + + try + { + // Wait until piping is done and propagate exceptions + await pipingTask.ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + // Don't throw if cancellation happened internally and not by user request + } + + // Validate exit code if required + if (process.ExitCode != 0 && Validation.IsZeroExitCodeValidationEnabled()) + { + throw CommandExecutionException.ExitCodeValidation( + this, + process.ExitCode + ); + } + + return new CommandResult( + process.ExitCode, + process.StartTime, + process.ExitTime + ); + } + + /// + /// Executes the command asynchronously. + /// This method can be awaited. + /// + public CommandTask ExecuteAsync(CancellationToken cancellationToken = default) + { + var process = new ProcessEx(GetStartInfo()); + var task = ExecuteAsync(process, cancellationToken); + + return new CommandTask(task, process.Id); + } + + /// + [ExcludeFromCodeCoverage] + public override string ToString() => $"{TargetFilePath} {Arguments}"; + } + + // Pipe operators + public partial class Command + { + /// + /// Creates a new command that pipes its standard output to the specified target. + /// + public static Command operator |(Command source, PipeTarget target) => + source.WithStandardOutputPipe(target); + + /// + /// Creates a new command that pipes its standard output to the specified stream. + /// + public static Command operator |(Command source, Stream target) => + source | PipeTarget.ToStream(target); + + /// + /// Creates a new command that pipes its standard output to the specified string builder. + /// Uses to decode the string from byte stream. + /// + public static Command operator |(Command source, StringBuilder target) => + source | PipeTarget.ToStringBuilder(target); + + /// + /// Creates a new command that pipes its standard output line-by-line to the specified delegate. + /// Uses to decode the string from byte stream. + /// + public static Command operator |(Command source, Action target) => + source | PipeTarget.ToDelegate(target); + + /// + /// Creates a new command that pipes its standard output line-by-line to the specified delegate. + /// Uses to decode the string from byte stream. + /// + public static Command operator |(Command source, Func target) => + source | PipeTarget.ToDelegate(target); + + /// + /// Creates a new command that pipes its standard output and standard error to the specified targets. + /// + public static Command operator |(Command source, ValueTuple target) => + source + .WithStandardOutputPipe(target.Item1) + .WithStandardErrorPipe(target.Item2); + + /// + /// Creates a new command that pipes its standard output and standard error to the specified streams. + /// + public static Command operator |(Command source, ValueTuple target) => + source | (PipeTarget.ToStream(target.Item1), PipeTarget.ToStream(target.Item2)); + + /// + /// Creates a new command that pipes its standard output and standard error to the specified string builders. + /// Uses to decode the string from byte stream. + /// + public static Command operator |(Command source, ValueTuple target) => + source | (PipeTarget.ToStringBuilder(target.Item1), PipeTarget.ToStringBuilder(target.Item2)); + + /// + /// Creates a new command that pipes its standard output and standard error line-by-line to the specified delegates. + /// Uses to decode the strings from byte streams. + /// + public static Command operator |(Command source, ValueTuple, Action> target) => + source | (PipeTarget.ToDelegate(target.Item1), PipeTarget.ToDelegate(target.Item2)); + + /// + /// Creates a new command that pipes its standard output and standard error line-by-line to the specified delegates. + /// Uses to decode the strings from byte streams. + /// + public static Command operator |(Command source, ValueTuple, Func> target) => + source | (PipeTarget.ToDelegate(target.Item1), PipeTarget.ToDelegate(target.Item2)); + + /// + /// Creates a new command that pipes its standard input from the specified source. + /// + public static Command operator |(PipeSource source, Command target) => + target.WithStandardInputPipe(source); + + /// + /// Creates a new command that pipes its standard input from the specified stream. + /// + public static Command operator |(Stream source, Command target) => + PipeSource.FromStream(source) | target; + + /// + /// Creates a new command that pipes its standard input from the specified string. + /// Uses to encode the string into byte stream. + /// + public static Command operator |(string source, Command target) => + PipeSource.FromString(source) | target; + + /// + /// Creates a new command that pipes its standard input from the standard output of the specified other command. + /// + public static Command operator |(Command source, Command target) => + PipeSource.FromCommand(source) | target; + } +} +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (returned from System.Security.SecureString CliWrap.Utils.Extensions.StringExtensions::ToSecureString(System.String) at Line 295) of type System.Security.SecureString in method "ProcessStartInfo Command.GetStartInfo()". + +### Severity: +ERROR + +### Procedure: +ProcessStartInfo Command.GetStartInfo() + +### File: +CliWrap/Command.cs + +### Key: +Command.cs|GetStartInfo|DOTNET_RESOURCE_LEAK + +### Hash: +7a33454b8cbeef67d47f4ca6276cc620 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-1742/instruction.md b/inferredbugs-1742/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5579e4303b043aedf6a4d9743a06541bc93987d --- /dev/null +++ b/inferredbugs-1742/instruction.md @@ -0,0 +1,141 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** netmq +**Bug ID:** 8 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using NUnit.Framework; +using NetMQ.Security; +using NetMQ.Security.V0_1; + +namespace NetMQ.Tests +{ + [TestFixture] + class SecurityTests + { + private void DoHandshake(out SecureChannel clientSecureChannel, + out SecureChannel serverSecureChannel) + { + X509Certificate2 certificate = new X509Certificate2("NetMQ.Testing.pfx", "1"); + + serverSecureChannel = new SecureChannel(ConnectionEnd.Server); + serverSecureChannel.Certificate = certificate; + + clientSecureChannel = new SecureChannel(ConnectionEnd.Client); + + IList clientOutgoingMessages = new List(); + IList serverOutgoingMessages = new List(); + + bool serverComplete = false; + + bool clientComplete = clientSecureChannel.ProcessMessage(null, clientOutgoingMessages); + + while (!serverComplete || !clientComplete) + { + if (!serverComplete) + { + foreach (var message in clientOutgoingMessages) + { + serverComplete = serverSecureChannel.ProcessMessage(message, serverOutgoingMessages); + + if (serverComplete) + { + break; + } + } + + clientOutgoingMessages.Clear(); + } + + if (!clientComplete) + { + foreach (var message in serverOutgoingMessages) + { + clientComplete = clientSecureChannel.ProcessMessage(message, clientOutgoingMessages); + + if (clientComplete) + { + break; + } + } + + serverOutgoingMessages.Clear(); + } + } + } + + [Test] + public void Encrypt() + { + SecureChannel clientSecureChannel; + SecureChannel serverSecureChannel; + + DoHandshake(out clientSecureChannel, out serverSecureChannel); + + string text = "hellohello-hello1"; + + NetMQMessage message = new NetMQMessage(); + message.Append(text); + + NetMQMessage encryptedMessage = clientSecureChannel.EncryptApplicationMessage(message); + + NetMQMessage dycryptedMessage = serverSecureChannel.DecryptApplicationMessage(encryptedMessage); + + string result = dycryptedMessage[0].ConvertToString(); + + Assert.AreEqual(text, result); + } + + [Test] + public void Handshake() + { + + + } + + } +} + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource certificate of type System.Security.Cryptography.X509Certificates.X509Certificate2 in method "Void SecurityTests.DoHandshake(SecureChannel&,SecureChannel&)". + +### Severity: +ERROR + +### Procedure: +Void SecurityTests.DoHandshake(SecureChannel&,SecureChannel&) + +### File: +src/NetMQ.Tests/SecurityTests.cs + +### Key: +SecurityTests.cs|DoHandshake|DOTNET_RESOURCE_LEAK + +### Hash: +8e23b8dcb68237092d1e5d5355328e24 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-1921/instruction.md b/inferredbugs-1921/instruction.md index 60b0621ead5f0d463eda5a4085e60d54df8dd0a1..5f19cecf27cff05a53dc86c0eb8fe7c12a98851c 100644 --- a/inferredbugs-1921/instruction.md +++ b/inferredbugs-1921/instruction.md @@ -2304,19 +2304,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-1928/instruction.md b/inferredbugs-1928/instruction.md index f97bf8c4604eaa7507b73930d0d163f1658cc1ba..77ccc58d2984297576fee080773739d54c609db0 100644 --- a/inferredbugs-1928/instruction.md +++ b/inferredbugs-1928/instruction.md @@ -2506,19 +2506,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2308/instruction.md b/inferredbugs-2308/instruction.md index 8dba56fe1425a576814e6fd6f3093acaf6873914..bd6512c4644483d66509e7bfb7facfd9b537c734 100644 --- a/inferredbugs-2308/instruction.md +++ b/inferredbugs-2308/instruction.md @@ -594,19 +594,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2338/instruction.md b/inferredbugs-2338/instruction.md index 9dc214ddf8c2d4cc316432c0c8ba90377faa7ddc..fda8d184428674a88d0236a7f0dd6dac160938d3 100644 --- a/inferredbugs-2338/instruction.md +++ b/inferredbugs-2338/instruction.md @@ -148,19 +148,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2557/instruction.md b/inferredbugs-2557/instruction.md index 55a3dca6512d908f776a4e648f0db89bbc863f65..0b1f367b0fc1eb4a4aaf0f7dcd15622fce9f25ae 100644 --- a/inferredbugs-2557/instruction.md +++ b/inferredbugs-2557/instruction.md @@ -142,19 +142,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2764/instruction.md b/inferredbugs-2764/instruction.md index 47262bb897540fbab92751b4302c25581166c909..e0dbe18423e7c8048e0a6184a9d977e37740cee0 100644 --- a/inferredbugs-2764/instruction.md +++ b/inferredbugs-2764/instruction.md @@ -73,19 +73,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2765/instruction.md b/inferredbugs-2765/instruction.md index 5a84b42a69ee1273e3818b1c9febddd59d789dbb..f862fd7eb18bdd49de534553f3b688317e4d05e7 100644 --- a/inferredbugs-2765/instruction.md +++ b/inferredbugs-2765/instruction.md @@ -352,19 +352,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-2791/instruction.md b/inferredbugs-2791/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2bfe02d4d8b4cce916d07e21ba691e42e9014863 --- /dev/null +++ b/inferredbugs-2791/instruction.md @@ -0,0 +1,285 @@ +# InferredBugs Task - Csharp + +## Project Information + +**Project:** couchbase-net-client +**Bug ID:** 18 +**Language:** csharp + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```csharp +using Common.Logging; +using Couchbase.Authentication.SASL; +using Couchbase.Configuration; +using Couchbase.Configuration.Client; +using Couchbase.Configuration.Server.Providers; +using Couchbase.Configuration.Server.Providers.CarrierPublication; +using Couchbase.Configuration.Server.Providers.Streaming; +using Couchbase.Configuration.Server.Serialization; +using Couchbase.Core.Buckets; +using Couchbase.IO; +using Couchbase.IO.Strategies; +using Couchbase.IO.Strategies.Async; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Security.Authentication; + +namespace Couchbase.Core +{ + internal sealed class ClusterManager : IClusterManager + { + private readonly static ILog Log = LogManager.GetCurrentClassLogger(); + private readonly ClientConfiguration _clientConfig; + private readonly ConcurrentDictionary _buckets = new ConcurrentDictionary(); + private readonly List _configProviders = new List(); + private readonly Func _ioStrategyFactory; + private readonly Func _connectionPoolFactory; + private readonly Func _saslFactory; + private bool _disposed; + + public ClusterManager(ClientConfiguration clientConfig) + : this(clientConfig, + (pool, sm) => new DefaultIOStrategy(pool, sm), + (config, endpoint) => + { + IConnectionPool connectionPool = null; + if (config.EncryptTraffic) + { + connectionPool = new ConnectionPool(config, endpoint); + } + else + { + connectionPool = new ConnectionPool(config, endpoint); + } + return connectionPool; + }, + SaslFactory.GetFactory3()) + { + } + + public ClusterManager(ClientConfiguration clientConfig, Func ioStrategyFactory) + : this(clientConfig, + ioStrategyFactory, + (config, endpoint) => + { + IConnectionPool connectionPool = null; + if (config.EncryptTraffic) + { + connectionPool = new ConnectionPool(config, endpoint); + } + else + { + connectionPool = new ConnectionPool(config, endpoint); + } + return connectionPool; + }, SaslFactory.GetFactory3()) + { + } + + public ClusterManager(ClientConfiguration clientConfig, Func ioStrategyFactory, Func connectionPoolFactory, Func saslFactory) + { + _clientConfig = clientConfig; + _ioStrategyFactory = ioStrategyFactory; + _connectionPoolFactory = connectionPoolFactory; + _saslFactory = saslFactory; + Initialize(); + } + + public List ConfigProviders { get { return _configProviders; } } + + //TODO possibly make providers instantiation configurable...maybe. perhaps. + private void Initialize() + { + //_configProviders.Add(new CarrierPublicationProvider(_clientConfig, _ioStrategyFactory, _connectionPoolFactory, _saslFactory)); + _configProviders.Add(new HttpStreamingProvider(_clientConfig, _ioStrategyFactory, _connectionPoolFactory, _saslFactory)); + } + + public IConfigProvider GetProvider(string name) + { + throw new NotImplementedException(); + } + + public IBucket CreateBucket(string bucketName) + { + return CreateBucket(bucketName, string.Empty); + } + + public IBucket CreateBucket(string bucketName, string password) + { + //note we probably want to treat this whole process as an aggregate and not log + //until the process has completed with success or failure then logged along with + //the sequence of events that occurred. + var success = false; + IBucket bucket = null; + foreach (var provider in _configProviders) + { + try + { + Log.DebugFormat("Trying to boostrap with {0}.", provider); + var config = provider.GetConfig(bucketName, password); + switch (config.NodeLocator) + { + case NodeLocatorEnum.VBucket: + bucket = new CouchbaseBucket(this, bucketName); + break; + + case NodeLocatorEnum.Ketama: + bucket = new MemcachedBucket(this, bucketName); + break; + + default: + throw new ArgumentOutOfRangeException(); + } + + var configObserver = bucket as IConfigObserver; + if (provider.ObserverExists(configObserver)) + { + Log.DebugFormat("Using existing bootstrap {0}.", provider); + configObserver.NotifyConfigChanged(config); + success = true; + break; + } + if (provider.RegisterObserver(configObserver) && + _buckets.TryAdd(bucket.Name, bucket)) + { + Log.DebugFormat("Successfully boostrap using {0}.", provider); + configObserver.NotifyConfigChanged(config); + success = true; + break; + } + } + catch (BucketNotFoundException e) + { + Log.Warn(e); + } + catch (ConfigException e) + { + Log.Warn(e); + } + catch (AuthenticationException e) + { + Log.Warn(e); + break; + } + } + + if (!success) + { + throw new ConfigException("Could not bootstrap {0}. See log for details.", bucketName); + } + return bucket; + } + + public void NotifyConfigPublished(IBucketConfig bucketConfig) + { + var provider = _configProviders.FirstOrDefault(x => x is CarrierPublicationProvider); + if (provider != null) + { + var carrierPublicationProvider = provider as CarrierPublicationProvider; + if (carrierPublicationProvider != null) + { + carrierPublicationProvider.UpdateConfig(bucketConfig); + } + } + } + + public void DestroyBucket(IBucket bucket) + { + IBucket temp; + if (_buckets.TryRemove(bucket.Name, out temp)) + { + var configObserver = temp as IConfigObserver; + foreach (var configProvider in ConfigProviders) + { + configProvider.UnRegisterObserver(configObserver); + } + } + } + + public void Dispose() + { + Dispose(true); + } + + public void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + GC.SuppressFinalize(this); + } + foreach (var pair in _buckets) + { + DestroyBucket(pair.Value); + } + _disposed = true; + } + } + + ~ClusterManager() + { + Dispose(false); + } + } +} + +#region [ License information ] + +/* ************************************************************ + * + * @author Couchbase + * @copyright 2014 Couchbase, 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. + * + * ************************************************************/ + +#endregion + +``` + +### Bug Type: +DOTNET_RESOURCE_LEAK + +### Qualifier: +Leaked resource (output of Couchbase.Configuration.Server.Providers.Streaming.HttpStreamingProvider::.ctor() at Line 87) of type Couchbase.Configuration.Server.Providers.Streaming.HttpStreamingProvider in method "Void ClusterManager.Initialize()". + +### Severity: +ERROR + +### Procedure: +Void ClusterManager.Initialize() + +### File: +Src/Couchbase/Core/ClusterManager.cs + +### Key: +ClusterManager.cs|Initialize|DOTNET_RESOURCE_LEAK + +### Hash: +c21e99b052315c5eb0e5503ccbb555a4 + +### Bug Type Hum: +Dotnet Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-2906/instruction.md b/inferredbugs-2906/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..faceefb0e309cf4ac2c26d52ac0eece7960e4443 --- /dev/null +++ b/inferredbugs-2906/instruction.md @@ -0,0 +1,167 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** ShiroJwt +**Bug ID:** 2 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package com.wang.config.shiro.cache; + +import com.wang.util.JwtUtil; +import com.wang.util.JedisUtil; +import com.wang.model.common.Constant; +import com.wang.util.common.PropertiesUtil; +import com.wang.util.common.SerializableUtil; +import org.apache.shiro.cache.Cache; +import org.apache.shiro.cache.CacheException; + +import java.util.*; + +/** + * 重写Shiro的Cache保存读取 + * @author Wang926454 + * @date 2018/9/4 17:31 + */ +public class CustomCache implements Cache { + + /** + * 缓存的key名称获取为shiro:cache:account + * @param key + * @return java.lang.String + * @author Wang926454 + * @date 2018/9/4 18:33 + */ + private String getKey(Object key) { + return Constant.PREFIX_SHIRO_CACHE + JwtUtil.getClaim(key.toString(), Constant.ACCOUNT); + } + + /** + * 获取缓存 + */ + @Override + public Object get(Object key) throws CacheException { + if(!JedisUtil.exists(this.getKey(key))){ + return null; + } + return JedisUtil.getObject(this.getKey(key)); + } + + /** + * 保存缓存 + */ + @Override + public Object put(Object key, Object value) throws CacheException { + // 读取配置文件,获取Redis的Shiro缓存过期时间 + PropertiesUtil.readProperties("config.properties"); + String shiroCacheExpireTime = PropertiesUtil.getProperty("shiroCacheExpireTime"); + // 设置Redis的Shiro缓存 + return JedisUtil.setObject(this.getKey(key), value, Integer.parseInt(shiroCacheExpireTime)); + } + + /** + * 移除缓存 + */ + @Override + public Object remove(Object key) throws CacheException { + if(!JedisUtil.exists(this.getKey(key))){ + return null; + } + JedisUtil.delKey(this.getKey(key)); + return null; + } + + /** + * 清空所有缓存 + */ + @Override + public void clear() throws CacheException { + JedisUtil.getJedis().flushDB(); + } + + /** + * 缓存的个数 + */ + @Override + public int size() { + Long size = JedisUtil.getJedis().dbSize(); + return size.intValue(); + } + + /** + * 获取所有的key + */ + @Override + public Set keys() { + Set keys = JedisUtil.getJedis().keys(new String("*").getBytes()); + Set set = new HashSet(); + for (byte[] bs : keys) { + set.add(SerializableUtil.unserializable(bs)); + } + return set; + } + + /** + * 获取所有的value + */ + @Override + public Collection values() { + Set keys = this.keys(); + List values = new ArrayList(); + for (Object key : keys) { + values.add(JedisUtil.getObject(this.getKey(key))); + } + return values; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `getJedis()` could be null and is dereferenced at line 71. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void CustomCache.clear() + +### Procedure Id: +com.wang.config.shiro.cache.CustomCache.clear():void.5d6055720bf4779284e68e83ceaa6608 + +### File: +src/main/java/com/wang/config/shiro/cache/CustomCache.java + +### Key: +CustomCache.java|clear|NULL_DEREFERENCE + +### Node Key: +f17711d6e64f2c443a0f2eb1b1bb0871 + +### Hash: +d05900a21e0cdaf409f251f46dcd9b2c + +### Bug Type Hum: +Null Dereference + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-2936/instruction.md b/inferredbugs-2936/instruction.md index 00623f80f2d88ba9a1b18e9b3ce203bfa39af752..a17565ece6b01509751dd1419321b8c986d5522d 100644 --- a/inferredbugs-2936/instruction.md +++ b/inferredbugs-2936/instruction.md @@ -1003,19 +1003,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3015/instruction.md b/inferredbugs-3015/instruction.md index ff32d5856527477de60533d0867b2cc86a434157..327c40e7b71665e29a7e7e36629df0c2b93c4a69 100644 --- a/inferredbugs-3015/instruction.md +++ b/inferredbugs-3015/instruction.md @@ -325,19 +325,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3227/instruction.md b/inferredbugs-3227/instruction.md index 711c0b17ad97b1f7867cac97c98717e7aa1f63d8..3ff71f7b3bc2d88dcd53088fee0d3ef812bf8184 100644 --- a/inferredbugs-3227/instruction.md +++ b/inferredbugs-3227/instruction.md @@ -183,19 +183,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3471/instruction.md b/inferredbugs-3471/instruction.md index 7a327a5b05cfd1c06eba6be63aee9a7e9ae582ef..0372622394fa2453337abdde172a90d374f733bc 100644 --- a/inferredbugs-3471/instruction.md +++ b/inferredbugs-3471/instruction.md @@ -246,19 +246,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3478/instruction.md b/inferredbugs-3478/instruction.md index 3319250cb4c99bd9f191b66d40a3c58e830cf932..03b5d90aedf571f4fb1e46ef9ffe98a71dd3f074 100644 --- a/inferredbugs-3478/instruction.md +++ b/inferredbugs-3478/instruction.md @@ -189,19 +189,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3484/instruction.md b/inferredbugs-3484/instruction.md index f1a69900cc9d680209650dff1e2ed7fd99099c45..30e4681342d5595cd4adbb41f513582980f36fc1 100644 --- a/inferredbugs-3484/instruction.md +++ b/inferredbugs-3484/instruction.md @@ -440,19 +440,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3485/instruction.md b/inferredbugs-3485/instruction.md index ecb05a64d7226aadfa33a111d872eb934e8feee9..067fc2240e6322542367f3effec1cd1429eb915b 100644 --- a/inferredbugs-3485/instruction.md +++ b/inferredbugs-3485/instruction.md @@ -348,19 +348,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3643/instruction.md b/inferredbugs-3643/instruction.md index 6f0b39b80e6f6ab9e9b2b0513c5c143696561d71..c3bf1014ff0662c024c4408676249406b70fcd05 100644 --- a/inferredbugs-3643/instruction.md +++ b/inferredbugs-3643/instruction.md @@ -377,19 +377,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3820/instruction.md b/inferredbugs-3820/instruction.md index d4d83cecb0ad373fa312c4edef3b76dc938cd7b9..674f8061b02404f408dc0958395f26d874f62935 100644 --- a/inferredbugs-3820/instruction.md +++ b/inferredbugs-3820/instruction.md @@ -899,19 +899,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-3829/instruction.md b/inferredbugs-3829/instruction.md index 0fde64254043bdcf8fa3f9f749bd2bb484f843ea..d67b38acecaecf5dde7a1c9fb4119a44f3da247a 100644 --- a/inferredbugs-3829/instruction.md +++ b/inferredbugs-3829/instruction.md @@ -843,19 +843,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4002/instruction.md b/inferredbugs-4002/instruction.md index 7627ec8dd373f350bddfcd4d49db57c87efc70ce..2f1f296de408ec3cd82d7fe75fd07eb7133ea7ac 100644 --- a/inferredbugs-4002/instruction.md +++ b/inferredbugs-4002/instruction.md @@ -509,19 +509,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4230/instruction.md b/inferredbugs-4230/instruction.md index bbc9906018b2767f95e4fea902ce19cf2ca0936a..0feeb8771717bde5f2910966b09bfb852f190d3e 100644 --- a/inferredbugs-4230/instruction.md +++ b/inferredbugs-4230/instruction.md @@ -569,19 +569,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4239/instruction.md b/inferredbugs-4239/instruction.md index d84315e3235f1cf6eee7324c7b48e80cd314f34c..510e6901be31306dbdc040aecd988103920eeda1 100644 --- a/inferredbugs-4239/instruction.md +++ b/inferredbugs-4239/instruction.md @@ -212,19 +212,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4466/instruction.md b/inferredbugs-4466/instruction.md index 382308e162acd021e7958303e5a13bd361e7cccf..91ff1b0d7e9bb23652306d745539e5e137bc6bca 100644 --- a/inferredbugs-4466/instruction.md +++ b/inferredbugs-4466/instruction.md @@ -112,19 +112,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4493/instruction.md b/inferredbugs-4493/instruction.md index 4f7e81f771eb4c9e549492a5c60ebe94fd57fbfd..2cb5e439657f9500424ad02c651b0708fd65dc0b 100644 --- a/inferredbugs-4493/instruction.md +++ b/inferredbugs-4493/instruction.md @@ -392,19 +392,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4654/instruction.md b/inferredbugs-4654/instruction.md index 61e71a53b074c60cf2d593abbaf29471822d32fe..80c1849a753cab8314824b79819bb1110cec2a28 100644 --- a/inferredbugs-4654/instruction.md +++ b/inferredbugs-4654/instruction.md @@ -127,19 +127,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4699/instruction.md b/inferredbugs-4699/instruction.md index 9d3f0b575d88a6bae5ffea6c868f54b94d4d565c..18fea06d627150c18fe5ba487b740fe5d8634a93 100644 --- a/inferredbugs-4699/instruction.md +++ b/inferredbugs-4699/instruction.md @@ -330,19 +330,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-4837/instruction.md b/inferredbugs-4837/instruction.md index 71e42ace74408855ad8a6ab8cbe9a028f4a9960a..d404e4994e2cd1da1e9b8d12023d269817d5f5ca 100644 --- a/inferredbugs-4837/instruction.md +++ b/inferredbugs-4837/instruction.md @@ -110,19 +110,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5124/instruction.md b/inferredbugs-5124/instruction.md index c8756ef11de449eb01e66019dab3c50c467f0f2a..bb18fb97c535519afbc474420bbedf77e9855ace 100644 --- a/inferredbugs-5124/instruction.md +++ b/inferredbugs-5124/instruction.md @@ -970,19 +970,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5316/instruction.md b/inferredbugs-5316/instruction.md index 7c89ab5783aeb4f8d753ccea1618ed6e31867f11..d07c05fad4228f7c7f301b30eeeadde3c739685c 100644 --- a/inferredbugs-5316/instruction.md +++ b/inferredbugs-5316/instruction.md @@ -366,19 +366,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5317/instruction.md b/inferredbugs-5317/instruction.md index 34473496eae64435cccbfa60437059144a9344c0..6ffa8c1e1c299b0c5b1c4de8440f33a27b00e936 100644 --- a/inferredbugs-5317/instruction.md +++ b/inferredbugs-5317/instruction.md @@ -366,19 +366,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5540/instruction.md b/inferredbugs-5540/instruction.md index e15b5c2b374d6fa862fbce5f21e945f1f253bfc0..d4de22047a4fd0172603254821685d15dd883ccf 100644 --- a/inferredbugs-5540/instruction.md +++ b/inferredbugs-5540/instruction.md @@ -238,19 +238,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5541/instruction.md b/inferredbugs-5541/instruction.md index 209c0dc42f23655f6e02e99764d8c689698c0e2f..fd3652d54fa4f3a87cf7758a5e34283705a58004 100644 --- a/inferredbugs-5541/instruction.md +++ b/inferredbugs-5541/instruction.md @@ -336,19 +336,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5549/instruction.md b/inferredbugs-5549/instruction.md index ba4e31ec38e5e8dccadd53196688e2c224c05c5c..aad81115f06d535c045e686aed8401a15bc246ba 100644 --- a/inferredbugs-5549/instruction.md +++ b/inferredbugs-5549/instruction.md @@ -193,19 +193,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5576/instruction.md b/inferredbugs-5576/instruction.md index 11f0cf3124af565f7a41492c663101ef8f822599..7b4e143634e26c86816f4cdf24426566f88dc0eb 100644 --- a/inferredbugs-5576/instruction.md +++ b/inferredbugs-5576/instruction.md @@ -281,19 +281,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5772/instruction.md b/inferredbugs-5772/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b23f0ec7c62ef3a7a9bf3da53d4280a6223749e --- /dev/null +++ b/inferredbugs-5772/instruction.md @@ -0,0 +1,216 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** johm +**Bug ID:** 12 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package redis.clients.johm.collections; + +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +import redis.clients.johm.JOhm; +import redis.clients.johm.JOhmUtils; +import redis.clients.johm.Model; +import redis.clients.johm.Nest; + +/** + * RedisMap is a JOhm-internal Map implementation to serve as a proxy for the + * Redis persisted hash and provide lazy-loading semantics to minimize datastore + * network traffic. It does a best-effort job of minimizing hash staleness but + * does so without any locking and is not thread-safe. Only add and remove + * operations trigger a remote-sync of local internal storage. + */ +public class RedisMap extends RedisBaseCollection implements + Map { + private final Nest nest; + private final Class keyClazz; + private final Class valueClazz; + private final Map backingMap; + + public RedisMap(final Class keyClazz, + final Class valueClazz, final Nest nest) { + this.keyClazz = keyClazz; + this.valueClazz = valueClazz; + this.nest = nest; + backingMap = new LinkedHashMap(); + } + + @Override + public void clear() { + Map savedHash = nest.hgetAll(); + for (Map.Entry entry : savedHash.entrySet()) { + V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue())); + value.delete(); + nest.hdel(entry.getKey()); + } + nest.del(); + refreshStorage(true); + } + + @Override + public boolean containsKey(Object key) { + return backingMap.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return backingMap.containsValue(value); + } + + @Override + public Set> entrySet() { + return backingMap.entrySet(); + } + + @Override + public V get(Object key) { + V value = null; + String valueKey = nest.hget(key.toString()); + if (!JOhmUtils.isNullOrEmpty(valueKey)) { + value = JOhm.get(valueClazz, Integer.parseInt(valueKey)); + } + return value; + } + + @Override + public boolean isEmpty() { + return this.size() == 0; + } + + @SuppressWarnings("unchecked") + @Override + public Set keySet() { + Set keys = new LinkedHashSet(); + for (String key : nest.hkeys()) { + keys.add((K) JOhmUtils.Convertor.convert(keyClazz, key)); + } + return keys; + } + + @Override + public V put(K key, V value) { + V previousValue = get(key); + internalPut(key, value, true); + return previousValue; + } + + @Override + public void putAll(Map mapToCopyIn) { + for (Map.Entry entry : mapToCopyIn.entrySet()) { + internalPut(entry.getKey(), entry.getValue(), false); + } + refreshStorage(true); + } + + @Override + public V remove(Object key) { + V value = get(key); + value.delete(); + nest.hdel(key.toString()); + return value; + } + + @Override + public int size() { + int repoSize = nest.hlen(); + if (repoSize != backingMap.size()) { + refreshStorage(true); + } + return repoSize; + } + + @Override + public Collection values() { + return backingMap.values(); + } + + private V internalPut(final K key, final V value, boolean refreshStorage) { + value.save(); + Map hash = new LinkedHashMap(); + hash.put(key.toString(), value.getId().toString()); + nest.hmset(hash); + if (refreshStorage) { + refreshStorage(true); + } + + return value; + } + + protected synchronized void purgeScrollStorage() { + backingMap.clear(); + scrollElements(); + } + + @SuppressWarnings("unchecked") + private synchronized Map scrollElements() { + if (backingMap.isEmpty()) { + Map savedHash = nest.hgetAll(); + for (Map.Entry entry : savedHash.entrySet()) { + K savedKey = (K) JOhmUtils.Convertor.convert(keyClazz, entry + .getKey()); + V savedValue = JOhm.get(valueClazz, Integer.parseInt(entry + .getValue())); + backingMap.put(savedKey, savedValue); + } + } + return backingMap; + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +THREAD_SAFETY_VIOLATION + +### Qualifier: +Unprotected write. Non-private method `redis.clients.johm.collections.RedisMap.clear` indirectly writes to field `this.redis.clients.johm.collections.RedisMap.nest.redis.clients.johm.Nest.sb` 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 RedisMap.clear() + +### Procedure Id: +redis.clients.johm.collections.RedisMap.clear():void.8b6cacc6f959135a3e377dabb35c1d69 + +### File: +src/main/java/redis/clients/johm/collections/RedisMap.java + +### Key: +RedisMap.java|clear|THREAD_SAFETY_VIOLATION + +### Node Key: +9c5d6d9028928346cc4fb44cced5dea1 + +### Hash: +b88c02118e8a8fc1bb7edd345358764e + +### Bug Type Hum: +Thread Safety Violation + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-5773/instruction.md b/inferredbugs-5773/instruction.md index 0eb59bbe4681d4bfe1b1339b9b1e647672207351..a9c09c29c83b69f61ffb9ece6d28f291978f4708 100644 --- a/inferredbugs-5773/instruction.md +++ b/inferredbugs-5773/instruction.md @@ -293,19 +293,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5786/instruction.md b/inferredbugs-5786/instruction.md index e39654c59a5cb353bf170c74ad566a973c1f8486..a4d08e4b916795aed14fb771aa7c8f6202029ef5 100644 --- a/inferredbugs-5786/instruction.md +++ b/inferredbugs-5786/instruction.md @@ -954,19 +954,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5918/instruction.md b/inferredbugs-5918/instruction.md index e4c988993c65bb6959825c3ecc6c7b78e05d8a7a..72000bdb5da5c94e9d5f682be7c47d2911fd5abd 100644 --- a/inferredbugs-5918/instruction.md +++ b/inferredbugs-5918/instruction.md @@ -176,19 +176,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-5921/instruction.md b/inferredbugs-5921/instruction.md index 6829bc34f32d26fcb0651fbcd6de55efeb912f50..fec0e7814adcc8f27877841423ec2ec433674b70 100644 --- a/inferredbugs-5921/instruction.md +++ b/inferredbugs-5921/instruction.md @@ -189,19 +189,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-6331/instruction.md b/inferredbugs-6331/instruction.md index 29a65a5554186d8da254767cf35b474601ae2ddd..fa69f32b4ea3ea61dc2f3aed65a0d6f5cd021516 100644 --- a/inferredbugs-6331/instruction.md +++ b/inferredbugs-6331/instruction.md @@ -226,19 +226,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-6338/instruction.md b/inferredbugs-6338/instruction.md index 7a635e3f6087e02d98c37e37d9a2d88ec4c38659..e131706da5a7cb6f32edb586e6003197813e235b 100644 --- a/inferredbugs-6338/instruction.md +++ b/inferredbugs-6338/instruction.md @@ -479,19 +479,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-6755/instruction.md b/inferredbugs-6755/instruction.md index a959cb07f89828704b46175716e20c6e23770ff9..5f757fd672e49a64bc2a009be63b82fae2061146 100644 --- a/inferredbugs-6755/instruction.md +++ b/inferredbugs-6755/instruction.md @@ -481,19 +481,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-6798/instruction.md b/inferredbugs-6798/instruction.md index 9e6abee32855f76c9cc95da9fbc9396b20b68e88..04f42f5e83bbeba15daa5e19cb6fd542193877e0 100644 --- a/inferredbugs-6798/instruction.md +++ b/inferredbugs-6798/instruction.md @@ -511,19 +511,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-6936/instruction.md b/inferredbugs-6936/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e46a057629f5a3f65bd5a4ffb6bf30f1eb47114d --- /dev/null +++ b/inferredbugs-6936/instruction.md @@ -0,0 +1,108 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** jboot +**Bug ID:** 38 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +/** + * Copyright (c) 2015-2018, 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.component.shiro.processer; + +import com.jfinal.kit.Ret; + +/** + * 认证处理器 执行后的认证结果。 + */ +public class AuthorizeResult extends Ret { + + /** + * 未进行身份认证 + */ + public static final int ERROR_CODE_UNAUTHENTICATED = 1; + + /** + * 没有权限访问 + */ + public static final int ERROR_CODE_UNAUTHORIZATION = 2; + + + public static AuthorizeResult ok() { + return (AuthorizeResult) new AuthorizeResult().setOk(); + } + + + public static AuthorizeResult fail(int errorCode) { + return (AuthorizeResult) new AuthorizeResult().setFail().set("errorCode", errorCode); + } + + public int getErrorCode() { + return (int) get("errorCode"); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `get("errorCode")` could be null and is dereferenced at line 46. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +int AuthorizeResult.getErrorCode() + +### Procedure Id: +io.jboot.component.shiro.processer.AuthorizeResult.getErrorCode():int.fc420aa421d6f5314b7db4a402e66fcc + +### File: +src/main/java/io/jboot/component/shiro/processer/AuthorizeResult.java + +### Key: +AuthorizeResult.java|getErrorCode|NULL_DEREFERENCE + +### Node Key: +aef15f436bc21a6a19eb4bec819df767 + +### Hash: +79e6597aa641ac00b92f8c509558d2cc + +### Bug Type Hum: +Null Dereference + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-7024/instruction.md b/inferredbugs-7024/instruction.md index 4e25e58d25ca44c3e7bf017d61e39f748f5a825b..4a6889a26c0db1245884360be98c14e5d9872efa 100644 --- a/inferredbugs-7024/instruction.md +++ b/inferredbugs-7024/instruction.md @@ -501,19 +501,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7025/instruction.md b/inferredbugs-7025/instruction.md index 69833947d58b249fb1c0a868dccc7addcfa57e1f..3123d7a0e02ec3e0d750813431d487f6b94695a7 100644 --- a/inferredbugs-7025/instruction.md +++ b/inferredbugs-7025/instruction.md @@ -501,19 +501,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7216/instruction.md b/inferredbugs-7216/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48fd65818ff02a25a4b28c6ff0d7bcba20026b39 --- /dev/null +++ b/inferredbugs-7216/instruction.md @@ -0,0 +1,335 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 48 +**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 245. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestWorkflowScheduler.testMinusWorkdaysFromSunday() + +### Procedure Id: +org.imixs.workflow.engine.TestWorkflowScheduler.testMinusWorkdaysFromSunday():void.33887f6c128d5dabea201891c8b92149 + +### File: +imixs-workflow-engine/src/test/java/org/imixs/workflow/engine/TestWorkflowScheduler.java + +### Key: +TestWorkflowScheduler.java|testMinusWorkdaysFromSunday|NULL_DEREFERENCE + +### Node Key: +15891b12c6ce50257e480adc810587ae + +### Hash: +40a7675f67d57f8136ec8e2f7fdde49f + +### Bug Type Hum: +Null Dereference + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-7217/instruction.md b/inferredbugs-7217/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67804656d807c8100d34f767d469eaeaf28d8e9b --- /dev/null +++ b/inferredbugs-7217/instruction.md @@ -0,0 +1,1131 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** imixs-workflow +**Bug ID:** 24 +**Language:** java + +## Bug Information + +### File-Level Changes: + +**Before (Buggy File):** +```java +package org.imixs.workflow; + +import java.awt.Color; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Vector; + +import org.imixs.workflow.xml.XMLDocument; +import org.imixs.workflow.xml.XMLDocumentAdapter; +import org.junit.Assert; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +/** + * Test class for itemCollection object + * + * @author rsoika + * + */ +public class TestItemCollection { + + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testItemCollection() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("txtTitel", "Hello"); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), "Hello"); + } + + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testRemoveItem() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("txtTitel", "Hello"); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), "Hello"); + Assert.assertTrue(itemCollection.hasItem("txtTitel")); + itemCollection.removeItem("TXTtitel"); + Assert.assertFalse(itemCollection.hasItem("txtTitel")); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), ""); + } + + /** + * This test verifies if the method getItemValueDouble returns the expected + * values + */ + @Test + public void testGetItemValueDouble() { + Double d; + Long l; + Float f; + String s; + ItemCollection itemCollection = new ItemCollection(); + + // test double with digits.... + d = 1.234; + itemCollection.replaceItemValue("double", d); + Assert.assertTrue(itemCollection.isItemValueDouble("double")); + Assert.assertEquals(1.234, itemCollection.getItemValueDouble("double"), 0); + + // test double with no digits + d = (double) 7; + itemCollection.replaceItemValue("double", d); + Assert.assertEquals(7, itemCollection.getItemValueDouble("double"), 0); + + // test with long value + l = (long) 4; + itemCollection.replaceItemValue("long", l); + Assert.assertEquals(4, itemCollection.getItemValueDouble("long"), 0); + + // test with float value - can not be cast exactly back to double! + f = (float) 4.777; + itemCollection.replaceItemValue("float", f); + Assert.assertFalse(itemCollection.isItemValueDouble("float")); + + // test String.... + d = 9.712; + itemCollection.replaceItemValue("double", d); + Assert.assertEquals("9.712", itemCollection.getItemValueString("double")); + + // test cast back from string.... + s = "9.723"; + itemCollection.replaceItemValue("string", s); + Assert.assertFalse(itemCollection.isItemValueDouble("string")); + Assert.assertEquals(9.723, itemCollection.getItemValueDouble("string"), 0); + + } + + /** + * This test verifies if the method getItemValueFloat returns the expected + * values + */ + @Test + public void testGetItemValueFloat() { + String s; + Float f; + ItemCollection itemCollection = new ItemCollection(); + + // test with float value + f = (float) 4.777; + itemCollection.replaceItemValue("float", f); + Assert.assertTrue(itemCollection.isItemValueFloat("float")); + Float fTest = (float) 4.777; + Assert.assertTrue(fTest.equals(itemCollection.getItemValueFloat("float"))); + + // test cast back from string.... + s = "9.723"; + itemCollection.replaceItemValue("string", s); + Assert.assertFalse(itemCollection.isItemValueDouble("string")); + // not possible to cast back exactly! + // Assert.assertEquals(9.723, + // itemCollection.getItemValueFloat("string"), + // 0); + + // test Double to Float... + double d = 50.777; + itemCollection.replaceItemValue("double", d); + Assert.assertEquals(d, itemCollection.getItemValueDouble("double"), 0); + // test float ... + float f1 = itemCollection.getItemValueFloat("double"); + Assert.assertEquals("50.777", "" + f1); + + } + + /** + * This test verifies if the method getItemValueInteger returns the expected + * values + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void testGetItemValueInteger() { + Double d; + Long l; + Float f; + Integer i; + Vector v; + ItemCollection itemCollection = new ItemCollection(); + + // test integer + i = 7; + itemCollection.replaceItemValue("integer", i); + Assert.assertTrue(itemCollection.isItemValueInteger("integer")); + Assert.assertEquals(7, itemCollection.getItemValueInteger("integer"), 0); + + // test long + l = (long) 8; + itemCollection.replaceItemValue("long", l); + Assert.assertFalse(itemCollection.isItemValueInteger("long")); + Assert.assertTrue(itemCollection.isItemValueLong("long")); + Assert.assertEquals(8, itemCollection.getItemValueInteger("long"), 0); + + // test long in vector + v = new Vector(); + l = (long) 8; + v.add(l); + itemCollection.replaceItemValue("long", v); + // should return false... + Assert.assertFalse(itemCollection.isItemValueInteger("long")); + Assert.assertTrue(itemCollection.isItemValueLong("long")); + Assert.assertEquals(8, itemCollection.getItemValueInteger("long"), 0); + + // test double + d = 8.765; + itemCollection.replaceItemValue("double", d); + Assert.assertFalse(itemCollection.isItemValueInteger("double")); + Assert.assertTrue(itemCollection.isItemValueDouble("double")); + Assert.assertEquals(8, itemCollection.getItemValueInteger("double"), 0); + + // test float + f = (float) 8.765; + itemCollection.replaceItemValue("float", f); + Assert.assertFalse(itemCollection.isItemValueInteger("float")); + Assert.assertTrue(itemCollection.isItemValueFloat("float")); + Assert.assertEquals(8, itemCollection.getItemValueInteger("float"), 0); + + } + + /** + * This test verifies the equals method for a ItemCollection + */ + @Test + public void testEquals() { + + ItemCollection itemCollection1 = new ItemCollection(); + ItemCollection itemCollection2 = new ItemCollection(); + + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection2.replaceItemValue("txtname", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + itemCollection2.replaceItemValue("numID", new Integer(20)); + + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // compare not equals + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection2.replaceItemValue("txtname", "Manfred1"); + + Assert.assertFalse(itemCollection1.equals(itemCollection2)); + itemCollection2.replaceItemValue("txtname", "Manfred"); + itemCollection2.replaceItemValue("numID", new Integer(21)); + Assert.assertFalse(itemCollection1.equals(itemCollection2)); + Assert.assertNotSame(itemCollection1, itemCollection2); + + } + + /** + * This test verifies the behavior when copy the elements of another + * ItemCollection + * + */ + @Test + public void testCopyValues() { + + ItemCollection itemCollection1 = new ItemCollection(); + ItemCollection itemCollection2 = new ItemCollection(); + + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + + // copy values + itemCollection2.replaceAllItems(itemCollection1.getAllItems()); + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // change value of itemcol2 + itemCollection2.replaceItemValue("txtName", "Anna"); + Assert.assertEquals("Manfred", itemCollection1.getItemValueString("txtName")); + Assert.assertEquals("Anna", itemCollection2.getItemValueString("txtName")); + + Assert.assertFalse(itemCollection1.equals(itemCollection2)); + Assert.assertNotSame(itemCollection1, itemCollection2); + + } + + /** + * This test verifies the behavior when copy the elements of another + * ItemCollection with embedded collections! + * + */ + @Test + public void testCopyItemCollection() { + + ItemCollection itemCollection1 = new ItemCollection(); + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + + ItemCollection itemCollection2 = new ItemCollection(itemCollection1); + + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // change valud of itemcol2 + itemCollection2.replaceItemValue("txtName", "Anna"); + Assert.assertEquals("Manfred", itemCollection1.getItemValueString("txtName")); + Assert.assertEquals("Anna", itemCollection2.getItemValueString("txtName")); + + } + + /** + * This test verifies the behavior when copy the elements of another + * ItemCollection with embedded collections! + * + */ + @SuppressWarnings("unused") + @Test + public void testCopyValuesWithEmbeddedCollection() { + + ItemCollection itemCollection1 = new ItemCollection(); + ItemCollection itemCollection2 = new ItemCollection(); + ItemCollection child1 = new ItemCollection(); + + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + + child1.replaceItemValue("txtName", "Thor"); + child1.replaceItemValue("numID", new Integer(2)); + + try { + itemCollection1.replaceItemValue("child", XMLDocumentAdapter.getDocument(child1)); + } catch (Exception e) { + + Assert.fail(); + } + + // copy values + itemCollection2.replaceAllItems(itemCollection1.getAllItems()); + Assert.assertEquals(itemCollection1, itemCollection2); + + Assert.assertNotSame(itemCollection1, itemCollection2); + + XMLDocument xmlChild = (XMLDocument) itemCollection1.getItemValue("child").get(0); + + ItemCollection testChild = XMLDocumentAdapter.putDocument(xmlChild); + Assert.assertEquals(2, testChild.getItemValueInteger("numID")); + + // manipulate child1 and repeat the test! + child1.replaceItemValue("numID", new Integer(3)); + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // Now its the same object ! + Assert.assertNotSame(child1, testChild); + + // test child1 form itemcol1 + xmlChild = (XMLDocument) itemCollection1.getItemValue("child").get(0); + + testChild = XMLDocumentAdapter.putDocument(xmlChild); + + // expected id is not 3! + Assert.assertEquals(2, testChild.getItemValueInteger("numID")); + + // change value of itemcol2 + itemCollection2.replaceItemValue("txtName", "Anna"); + Assert.assertEquals("Manfred", itemCollection1.getItemValueString("txtName")); + Assert.assertEquals("Anna", itemCollection2.getItemValueString("txtName")); + + Assert.assertFalse(itemCollection1.equals(itemCollection2)); + Assert.assertNotSame(itemCollection1, itemCollection2); + + } + + /** + * Same as testCopyValuesWithEmbeddedCollection but now we add a list of + * ItemCollections into a ItemCollection! + * + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testCopyValuesWithEmbeddedCollectionList() { + + ItemCollection itemCollection1 = new ItemCollection(); + ItemCollection itemCollection2 = new ItemCollection(); + ItemCollection child1 = new ItemCollection(); + ItemCollection child2 = new ItemCollection(); + + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + + child1.replaceItemValue("txtName", "Thor"); + child1.replaceItemValue("numID", new Integer(2)); + child2.replaceItemValue("txtName", "Ilias"); + child2.replaceItemValue("numID", new Integer(3)); + List childs = new ArrayList<>(); + try { + childs.add(XMLDocumentAdapter.getDocument(child1)); + childs.add(XMLDocumentAdapter.getDocument(child2)); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(); + } + itemCollection1.replaceItemValue("childs", childs); + + // copy values + itemCollection2.replaceAllItems(itemCollection1.getAllItems()); + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // now manipulate child1 + child1.replaceItemValue("numID", 101); + + // repeat test! + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // get child 1 from itemcol2 + List v = itemCollection2.getItemValue("childs"); + XMLDocument xmlct1 = (XMLDocument) v.get(0); + ItemCollection ct1 = XMLDocumentAdapter.putDocument(xmlct1); + Assert.assertEquals("Thor", ct1.getItemValueString("txtName")); + Assert.assertEquals(2, ct1.getItemValueInteger("numID")); + + Assert.assertEquals(101, child1.getItemValueInteger("numID")); + + XMLDocument xmlct2 = (XMLDocument) v.get(1); + ItemCollection ct2 = XMLDocumentAdapter.putDocument(xmlct2); + Assert.assertEquals("Ilias", ct2.getItemValueString("txtName")); + Assert.assertEquals(3, ct2.getItemValueInteger("numID")); + + // test size + Assert.assertTrue(v.size() == 2); + + } + + /** + * Same as testCopyValuesWithEmbeddedCollection but now we test the behavior + * with map interfaces + * + * here we can see that a map is copied by reference! + * + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Test + public void testCopyValuesWithEmbeddedMap() { + + ItemCollection itemCollection1 = new ItemCollection(); + ItemCollection itemCollection2 = new ItemCollection(); + Map child1 = new HashMap(); + + itemCollection1.replaceItemValue("txtName", "Manfred"); + itemCollection1.replaceItemValue("numID", new Integer(20)); + + child1.put("txtName", "Thor"); + child1.put("numID", new Integer(2)); + + itemCollection1.replaceItemValue("child", child1); + + // copy values + itemCollection2.replaceAllItems(itemCollection1.getAllItems()); + Assert.assertEquals(itemCollection1, itemCollection2); + Assert.assertNotSame(itemCollection1, itemCollection2); + Map testChild = (Map) itemCollection1.getItemValue("child").get(0); + Assert.assertEquals(2, testChild.get("numID")); + + // manipulate child1 and repeat the test! + child1.put("numID", new Integer(3)); + Assert.assertFalse(itemCollection1.equals(itemCollection2)); + Assert.assertNotSame(itemCollection1, itemCollection2); + + // its the same object ! + Assert.assertSame(child1, testChild); + + } + + /** + * This test verifies the imixs workflow basic attributes + * + */ + @Test + public void testBasicAttributes() { + + ItemCollection itemCollection1 = new ItemCollection(); + + itemCollection1.replaceItemValue(WorkflowKernel.MODELVERSION, "1.0.0"); + itemCollection1.replaceItemValue(WorkflowKernel.TASKID, 100); + itemCollection1.replaceItemValue(WorkflowKernel.EVENTID, 10); + itemCollection1.replaceItemValue(WorkflowKernel.TYPE, "workitem_test"); + itemCollection1.replaceItemValue(WorkflowKernel.UNIQUEID, "ABC-123"); + + Assert.assertEquals("1.0.0", itemCollection1.getModelVersion()); + Assert.assertEquals(10, itemCollection1.getEventID()); + Assert.assertEquals(100, itemCollection1.getTaskID()); + Assert.assertEquals("workitem_test", itemCollection1.getType()); + Assert.assertEquals("ABC-123", itemCollection1.getUniqueID()); + + } + + /** + * This method verifies if null values will be removed from lists. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void testNullValues() { + + Vector v1 = new Vector(); + v1.add(null); + v1.add(""); + v1.add(null); + v1.add("anna"); + + Vector v2 = new Vector(); + v1.add(null); + + ItemCollection itemCol = new ItemCollection(); + itemCol.replaceItemValue("a", v1); + itemCol.replaceItemValue("b", v2); + + List l1 = itemCol.getItemValue("a"); + List l2 = itemCol.getItemValue("b"); + + // test if the null values are removed... + Assert.assertEquals(2, l1.size()); + Assert.assertEquals("", l1.get(0)); + Assert.assertEquals("anna", l1.get(1)); + + Assert.assertEquals(0, l2.size()); + + } + + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testItemCollectionItemNameList() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("_subject", "Hello"); + itemCollection.replaceItemValue("_dummy", "Hello"); + itemCollection.replaceItemValue("_title", "Hello"); + + List itemNames = itemCollection.getItemNames(); + Assert.assertEquals(3, itemNames.size()); + + itemCollection.removeItem("_dummy"); + itemNames = itemCollection.getItemNames(); + Assert.assertEquals(2, itemNames.size()); + + } + + /** + * This method verifies the clone interface + */ + @Test + public void testCloning() { + + ItemCollection itemCol1 = new ItemCollection(); + itemCol1.replaceItemValue("a", 1); + itemCol1.replaceItemValue("b", "hello"); + itemCol1.replaceItemValue("c", "world"); + + // clone only some attributes + List attributes = new ArrayList(); + attributes.add("a"); + attributes.add("b"); + ItemCollection itemCol2 = itemCol1.clone(attributes); + + Assert.assertNotNull(itemCol2); + + // test values of clone + Assert.assertEquals(1, itemCol2.getItemValueInteger("a")); + Assert.assertEquals("hello", itemCol2.getItemValueString("b")); + Assert.assertEquals("", itemCol2.getItemValueString("c")); + + // test full clone + ItemCollection itemCol3 = null; + + if (itemCol1 instanceof Cloneable) { + itemCol3 = (ItemCollection) itemCol1.clone(); + } + Assert.assertNotNull(itemCol3); + Assert.assertEquals(1, itemCol3.getItemValueInteger("a")); + Assert.assertEquals("hello", itemCol3.getItemValueString("b")); + Assert.assertEquals("world", itemCol3.getItemValueString("c")); + + // itemCol2 should be equals to itemCol1 + Assert.assertNotSame(itemCol2, itemCol1); + // itemCol3 should be equals to itemCol1 + Assert.assertNotSame(itemCol3, itemCol1); + // itemCol3 should be equals to itemCol1 + Assert.assertEquals(itemCol1, itemCol3); + // itemCol2 should be equals to itemCol1 + Assert.assertFalse(itemCol1.equals(itemCol2)); + + // now we change some values of itemCol1 to see if this affects itemCol2 + // and itemCol3.... + itemCol1.replaceItemValue("c", "Imixs"); + Assert.assertEquals("", itemCol2.getItemValueString("c")); + Assert.assertEquals("world", itemCol3.getItemValueString("c")); + + } + + /** + * This method verifies the clone interface in conjunction with byte arrays as + * used in the $file field + */ + @Test + public void testCloningByteArrays() { + + ItemCollection itemCol1 = new ItemCollection(); + itemCol1.replaceItemValue("a", 1); + itemCol1.replaceItemValue("b", "hello"); + itemCol1.replaceItemValue("c", "world"); + byte[] empty = { 0 }; + // add a dummy file + itemCol1.addFile(empty, "test1.txt", "application/xml"); + + ItemCollection itemCol2 = (ItemCollection) itemCol1.clone(); + + Assert.assertNotNull(itemCol2); + + // test values of clone + Assert.assertEquals(1, itemCol2.getItemValueInteger("a")); + Assert.assertEquals("hello", itemCol2.getItemValueString("b")); + // test the byte content of itemcol2 + Map> conedFilesTest = itemCol2.getFiles(); + List fileContentTest = conedFilesTest.get("test1.txt"); + byte[] file1DataTest = (byte[]) fileContentTest.get(1); + + Assert.assertArrayEquals(empty, file1DataTest); + + // ------------------- + // Now we change file content in itemcol1 + byte[] dummy = { 1, 2, 3 }; + itemCol1.removeFile("test1.txt"); + itemCol1.addFile(dummy, "test1.txt", "application/xml"); + + // test the byte content of itemCol1 + Map> conedFiles1 = itemCol1.getFiles(); + List fileContent1 = conedFiles1.get("test1.txt"); + byte[] file1Data1 = (byte[]) fileContent1.get(1); + // we expect the new dummy array { 1, 2, 3 } + Assert.assertArrayEquals(dummy, file1Data1); + + // test the clone + Map> conedFiles2 = itemCol2.getFiles(); + List fileContent2 = conedFiles2.get("test1.txt"); + byte[] file1Data2 = (byte[]) fileContent2.get(1); + // we expect still the empty array + Assert.assertArrayEquals(empty, file1Data2); + + } + + /** + * This method just test the time difference between clone and copy a + * ItemCollection hashmap + * + */ + @Test + public void testPerformanceCloning() { + + ItemCollection itemCol1 = new ItemCollection(); + itemCol1.replaceItemValue("a", 1); + itemCol1.replaceItemValue("b", "hello"); + itemCol1.replaceItemValue("c", "world"); + + // clone + long l = System.currentTimeMillis(); + ItemCollection itemCol2 = (ItemCollection) itemCol1.clone(); + System.out.println("Performancetest ItemCollecton clone: " + (System.currentTimeMillis() - l) + "ms"); + Assert.assertNotNull(itemCol2); + + // copy + l = System.currentTimeMillis(); + ItemCollection itemCol3 = new ItemCollection(); + itemCol3.setAllItems(itemCol1.getAllItems()); + System.out.println("Performancetest ItemCollecton clone: " + (System.currentTimeMillis() - l) + "ms"); + Assert.assertNotNull(itemCol3); + + } + + /** + * This getItemValue hasItem with invalid string patterns + * + */ + @Test + public void testGetItemByName() { + + ItemCollection itemCol1 = new ItemCollection(); + itemCol1.replaceItemValue(" a", "hello"); + itemCol1.replaceItemValue(" b ", "world"); + itemCol1.replaceItemValue("c", "of"); + itemCol1.replaceItemValue("d", "Imixs-Worklfow"); + + Assert.assertEquals("hello", itemCol1.getItemValueString("a")); + Assert.assertEquals("hello", itemCol1.getItemValueString(" a")); + Assert.assertEquals("world", itemCol1.getItemValueString(" b")); + Assert.assertEquals("of", itemCol1.getItemValueString(" c ")); + + Assert.assertTrue(itemCol1.hasItem(" a ")); + Assert.assertTrue(itemCol1.hasItem(" a")); + Assert.assertTrue(itemCol1.hasItem("a")); + + Assert.assertFalse(itemCol1.hasItem(null)); + } + + /** + * Test the append method + */ + @SuppressWarnings("rawtypes") + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testItemCollectionAppend() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("txtTitel", "Hello"); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), "Hello"); + + itemCollection.appendItemValue("txttitel", "World"); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), "Hello"); + List values = itemCollection.getItemValue("txtTitel"); + Assert.assertEquals(2, values.size()); + + itemCollection.appendItemValue("txttitel", "World"); + Assert.assertEquals(itemCollection.getItemValueString("txttitel"), "Hello"); + values = itemCollection.getItemValue("txtTitel"); + Assert.assertEquals(3, values.size()); + + } + + /** + * Test no basic type + */ + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testItemCollectionNoBasictype() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("txtTitel", "Hello"); + try { + itemCollection.replaceItemValue("color", new Color(1, 1, 1)); + Assert.fail(); + } catch (Exception e) { + if (e instanceof RuntimeException) { + // expected + } else { + Assert.fail(); + + } + } + + } + + /** + * Test raw type int, double, boolean + */ + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testItemCollectionRawtype() { + ItemCollection itemCollection = new ItemCollection(); + itemCollection.replaceItemValue("txtTitel", "Hello"); + double d = 5.20; + itemCollection.replaceItemValue("price", d); + + byte[] bytes = "Some Data".getBytes(); + itemCollection.replaceItemValue("data", bytes); + + Assert.assertNotNull(itemCollection); + + } + + /** + * Test the fileData methods + */ + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testFileData() { + ItemCollection itemColSource = new ItemCollection(); + + // add a dummy file + byte[] empty = { 0 }; + itemColSource.addFile(empty, "test1.txt", "application/xml"); + + ItemCollection itemColTarget = new ItemCollection(); + + itemColTarget.addFileData(itemColSource.getFileData("test1.txt")); + + FileData filedata = itemColTarget.getFileData("test1.txt"); + Assert.assertNotNull(filedata); + Assert.assertEquals("test1.txt", filedata.getName()); + Assert.assertEquals("application/xml", filedata.getContentType()); + + // test the byte content of itemColSource + Map> conedFiles1 = itemColSource.getFiles(); + List fileContent1 = conedFiles1.get("test1.txt"); + byte[] file1Data1 = (byte[]) fileContent1.get(1); + // we expect the new dummy array { 1, 2, 3 } + Assert.assertArrayEquals(empty, file1Data1); + + // test the byte content of itemColTarget + conedFiles1 = itemColTarget.getFiles(); + fileContent1 = conedFiles1.get("test1.txt"); + file1Data1 = (byte[]) fileContent1.get(1); + // we expect the new dummy array { 1, 2, 3 } + Assert.assertArrayEquals(empty, file1Data1); + + } + + /* + * Test the fluent code interface. + */ + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testFluentInterface() { + ItemCollection itemCollection = new ItemCollection().model("1.0.0").task(1).event(10); + + Assert.assertEquals("1.0.0", itemCollection.getModelVersion()); + Assert.assertEquals(1, itemCollection.getTaskID()); + Assert.assertEquals(10, itemCollection.getEventID()); + + // set group + itemCollection = new ItemCollection().workflowGroup("Ticket").task(1).event(10); + Assert.assertEquals("Ticket", itemCollection.getWorkflowGroup()); + Assert.assertEquals(1, itemCollection.getTaskID()); + Assert.assertEquals(10, itemCollection.getEventID()); + + } + + /* + * Test fluent event interface with a event list + */ + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testFluentInterfaceFollowUpEvents() { + ItemCollection itemCollection = new ItemCollection().model("1.0.0").task(1).event(10).event(11); + Assert.assertEquals("1.0.0", itemCollection.getModelVersion()); + Assert.assertEquals(1, itemCollection.getTaskID()); + Assert.assertEquals(10, itemCollection.getEventID()); + @SuppressWarnings("unchecked") + List followups = itemCollection.getItemValue(WorkflowKernel.ACTIVITYIDLIST); + Assert.assertEquals(1, followups.size()); + Assert.assertEquals(11, followups.get(0).intValue()); + } + + /** + * Test issue #383, #384 + */ + @SuppressWarnings("deprecation") + @Test + @Category(org.imixs.workflow.ItemCollection.class) + public void testDeprecatedFieldProcessID() { + + Assert.assertEquals("$processid", WorkflowKernel.PROCESSID); + Assert.assertEquals("$taskid", WorkflowKernel.TASKID); + + ItemCollection itemColSource = new ItemCollection(); + + itemColSource.replaceItemValue("$processid", 42); + Assert.assertEquals(42, itemColSource.getTaskID()); + Assert.assertEquals(42, itemColSource.getProcessID()); + Assert.assertEquals(42, itemColSource.getItemValueInteger("$processid")); + + // test setter + itemColSource = new ItemCollection(); + itemColSource.setTaskID(43); + Assert.assertEquals(43, itemColSource.getTaskID()); + Assert.assertEquals(43, itemColSource.getProcessID()); + Assert.assertEquals(43, itemColSource.getItemValueInteger("$processid")); + + // test direct setting + itemColSource = new ItemCollection(); + itemColSource.replaceItemValue("$taskid", 44); + Assert.assertEquals(44, itemColSource.getTaskID()); + Assert.assertEquals(44, itemColSource.getProcessID()); + // !!! + Assert.assertEquals(0, itemColSource.getItemValueInteger("$processid")); + } + + /** + * Test the methods setItemValue and getItemValue with type String + */ + @Test + public void testGetItemValueTypeString() { + + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("txtname", "hello"); + itemCol.setItemValue("numage", 7); + + // test String values + String s = itemCol.getItemValue("txtname", String.class); + Assert.assertEquals("hello", s); + + // test non existing value + Assert.assertNull(itemCol.getItemValue("txtname2", String.class)); + + } + + /** + * Test the methods setItemValue and getItemValue with type Integer/int + */ + @Test + public void testGetItemValueTypeInt() { + + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("txtname", "hello"); + itemCol.setItemValue("numage", 7); + + // test int values.... + int i1 = itemCol.getItemValue("numage", Integer.class); + Assert.assertEquals(7, i1); + + int i2 = itemCol.getItemValue("numage", int.class); + Assert.assertEquals(7, i2); + + Integer i3 = itemCol.getItemValue("numage", Integer.class); + Assert.assertEquals(7, i3.intValue()); + + // test non existing value + Assert.assertNull(itemCol.getItemValue("txtname2", String.class)); + + } + + /** + * Test the methods setItemValue and getItemValue with type Long/long + */ + @Test + public void testGetItemValueTypeLong() { + + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("txtname", "hello"); + itemCol.setItemValue("numage", new Long(7)); + + // test int values.... + long l1 = itemCol.getItemValue("numage", Long.class); + Assert.assertEquals(7, l1); + + long l2 = itemCol.getItemValue("numage", long.class); + Assert.assertEquals(7, l2); + + Long l3 = itemCol.getItemValue("numage", long.class); + Assert.assertEquals(7, l3.longValue()); + + // test non existing value + Assert.assertNull(itemCol.getItemValue("txtname2", String.class)); + + } + + /** + * Test the fluent code interface for the method setItemValue. + */ + @Test + public void testSetItemValueFluent() { + + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("team", "Anna").appendItemValue("team", "Mark").appendItemValue("team", "Jo"); + + String s = itemCol.getItemValue("team", String.class); + Assert.assertEquals("Anna", s); + + @SuppressWarnings("unchecked") + List vaules = itemCol.getItemValue("team"); + + Assert.assertEquals(3, vaules.size()); + Assert.assertEquals("Mark", vaules.get(1)); + Assert.assertEquals("Jo", vaules.get(2)); + + } + + /** + * Test the methods getItemValue with convertign type + */ + @Test + public void testGetItemValueTypeMixedValues() { + + ItemCollection itemCol = new ItemCollection(); + // number as string + itemCol.setItemValue("_a", "5"); + itemCol.setItemValue("_b", 7); // int + + // test string + String s = itemCol.getItemValue("_a", String.class); + Assert.assertEquals("5", s); + + // test int + int i = itemCol.getItemValue("_a", int.class); + Assert.assertEquals(5, i); + + // test long + long l = itemCol.getItemValue("_a", long.class); + Assert.assertEquals(5, l); + + // test string of _b + s = itemCol.getItemValue("_b", String.class); + Assert.assertEquals("7", s); + } + + /** + * Test the method getItemValueList. Test mixed types and the convertion into + * the expected object type. + */ + @Test + public void testGetItemValueListType() { + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("txtname", "hello"); + itemCol.appendItemValue("txtname", "world"); + itemCol.appendItemValue("txtname", new Integer(47)); + + // test String list... + List slist = itemCol.getItemValueList("txtname", String.class); + Assert.assertEquals(3, slist.size()); + Assert.assertEquals("hello", slist.get(0)); + Assert.assertEquals("world", slist.get(1)); + Assert.assertEquals("47", slist.get(2)); + + // test int list + List integerlist = itemCol.getItemValueList("txtname", Integer.class); + Assert.assertEquals(3, integerlist.size()); + Assert.assertEquals(new Integer(0), integerlist.get(0)); + Assert.assertEquals(new Integer(0), integerlist.get(1)); + Assert.assertEquals(new Integer(47), integerlist.get(2)); + + // test int list + List intlist = itemCol.getItemValueList("txtname", int.class); + Assert.assertEquals(3, intlist.size()); + Assert.assertEquals(new Integer(0), intlist.get(0)); + Assert.assertEquals(new Integer(0), intlist.get(1)); + Assert.assertEquals(new Integer(47), intlist.get(2)); + + } + + /** + * Test the method getItemValueList with an empty list + */ + @Test + public void testGetItemValueListEmpty() { + ItemCollection itemCol = new ItemCollection(); + + List slist = itemCol.getItemValueList("txtname", String.class); + // we expect an empty list + Assert.assertNotNull(slist); + Assert.assertEquals(0, slist.size()); + } + + /** + * Test the method getItemValueList with a non convertible type. + */ + @Test + public void testGetItemValueListNonConvertable() { + ItemCollection itemCol = new ItemCollection(); + itemCol.setItemValue("txtname", "hello"); + itemCol.appendItemValue("txtname", new Integer(47)); + Map map = new HashMap(); + map.put("_subject", "some data"); + itemCol.appendItemValue("txtname", map); + + // test String list... + List slist = itemCol.getItemValueList("txtname", String.class); + Assert.assertEquals(3, slist.size()); + Assert.assertEquals("hello", slist.get(0)); + Assert.assertEquals("47", slist.get(1)); + Assert.assertEquals("{_subject=some data}", slist.get(2)); // map toString + + // test int list + List integerlist = itemCol.getItemValueList("txtname", Integer.class); + Assert.assertEquals(3, integerlist.size()); + Assert.assertEquals(new Integer(0), integerlist.get(0)); + Assert.assertEquals(new Integer(47), integerlist.get(1)); + Assert.assertEquals(new Integer(0), integerlist.get(2)); + + // test int list + List intlist = itemCol.getItemValueList("txtname", int.class); + Assert.assertEquals(3, intlist.size()); + Assert.assertEquals(new Integer(0), intlist.get(0)); + Assert.assertEquals(new Integer(47), intlist.get(1)); + Assert.assertEquals(new Integer(0), intlist.get(2)); + + } + + /** + * Test the method getItemValue for number types null + */ + @Test + public void testGetItemValueNumberNull() { + ItemCollection itemCol = new ItemCollection(); + + // integer + Integer i = itemCol.getItemValue("unkonw", Integer.class); + Assert.assertNotNull(i); + Assert.assertEquals(0, i.intValue()); + + // int + int ii = itemCol.getItemValue("unkonw", int.class); + Assert.assertNotNull(ii); + Assert.assertEquals(0, ii); + + // Float + Float f = itemCol.getItemValue("unkonw", Float.class); + Assert.assertNotNull(f); + Assert.assertEquals(0, f.intValue()); + + // float + float ff = itemCol.getItemValue("unkonw", float.class); + Assert.assertNotNull(ff); + Assert.assertEquals(0, ff, 0); + + // Long + Long l = itemCol.getItemValue("unkonw", Long.class); + Assert.assertNotNull(l); + Assert.assertEquals(0, l.intValue()); + + // long + long ll = itemCol.getItemValue("unkonw", long.class); + Assert.assertNotNull(ll); + Assert.assertEquals(0, ll); + + // Double + Double d = itemCol.getItemValue("unkonw", Double.class); + Assert.assertNotNull(d); + Assert.assertEquals(0, d.intValue()); + + // double + double dd = itemCol.getItemValue("unkonw", double.class); + Assert.assertNotNull(dd); + Assert.assertEquals(0, dd, 0); + + } +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object `filedata` last assigned on line 733 could be null and is dereferenced at line 735. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void TestItemCollection.testFileData() + +### Procedure Id: +org.imixs.workflow.TestItemCollection.testFileData():void.774f8e4218f6d66e68ea4ddf03ca3175 + +### File: +imixs-workflow-core/src/test/java/org/imixs/workflow/TestItemCollection.java + +### Key: +TestItemCollection.java|testFileData|NULL_DEREFERENCE + +### Node Key: +032299521a58ea574b18a1357a739565 + +### Hash: +6f731e820d8ec806a25f107b20c9d0d4 + +### Bug Type Hum: +Null Dereference + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-7221/instruction.md b/inferredbugs-7221/instruction.md index 386fe21fb092604663aecce867c08bf22eba8384..dc97582682a88ea438892e79070d8c375cd0bf7e 100644 --- a/inferredbugs-7221/instruction.md +++ b/inferredbugs-7221/instruction.md @@ -153,19 +153,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7448/instruction.md b/inferredbugs-7448/instruction.md index 7c1cfa0521cad3e3d5e40583c88b5a3da5c11874..618e613ce72f80854dd3702cabc112983e7b630c 100644 --- a/inferredbugs-7448/instruction.md +++ b/inferredbugs-7448/instruction.md @@ -659,19 +659,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7478/instruction.md b/inferredbugs-7478/instruction.md index b83d6c2fa95e9d9669b1cb9c26712f08d1c7b2c7..4f41f506baba758d9f8c23d8850d5ba93cca529c 100644 --- a/inferredbugs-7478/instruction.md +++ b/inferredbugs-7478/instruction.md @@ -380,19 +380,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7673/instruction.md b/inferredbugs-7673/instruction.md index c871df7e4e513a1958b15ea784a223313f32c2dd..4132e535c3f73f0a166a4818b4c7ff6cce0222ad 100644 --- a/inferredbugs-7673/instruction.md +++ b/inferredbugs-7673/instruction.md @@ -276,19 +276,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7810/instruction.md b/inferredbugs-7810/instruction.md index 7ff1ad3aea4de2256ce71729f72879305dc96e29..27972103e828cd956b726c32cd87e6bd02ffc5a8 100644 --- a/inferredbugs-7810/instruction.md +++ b/inferredbugs-7810/instruction.md @@ -1054,19 +1054,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-7819/instruction.md b/inferredbugs-7819/instruction.md index a90e0f34e43458b10707597aab017c36f5683ec4..bef760f3bb6cda59210c825fc4fbe6b3e228d0f6 100644 --- a/inferredbugs-7819/instruction.md +++ b/inferredbugs-7819/instruction.md @@ -621,19 +621,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8064/instruction.md b/inferredbugs-8064/instruction.md index 679eabbc4437f21ad0dea50e1e3afb9cc589c353..81a408675acdbdf07b4efbd9ee791410b9cc2436 100644 --- a/inferredbugs-8064/instruction.md +++ b/inferredbugs-8064/instruction.md @@ -564,19 +564,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8090/instruction.md b/inferredbugs-8090/instruction.md index 07c27329e69d399010b44f09e265b6af7ce9c8a9..4b348e95e296afd48c0e8ded9a46324800101edd 100644 --- a/inferredbugs-8090/instruction.md +++ b/inferredbugs-8090/instruction.md @@ -2644,19 +2644,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8099/instruction.md b/inferredbugs-8099/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0835b18b87d6cc0fc237fd8ba46911a095b9d23 --- /dev/null +++ b/inferredbugs-8099/instruction.md @@ -0,0 +1,2647 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** sqlline +**Bug ID:** 28 +**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 1220 is not released after line 1227. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void SqlLineArgsTest.testSetNonIntValuesToIntProperties() + +### Procedure Id: +sqlline.SqlLineArgsTest.testSetNonIntValuesToIntProperties():void.644e5773da227b2655e9495cf7755871 + +### File: +src/test/java/sqlline/SqlLineArgsTest.java + +### Key: +SqlLineArgsTest.java|testSetNonIntValuesToIntProperties|RESOURCE_LEAK + +### Node Key: +94c5f50b10fccff84f035869475ce2be + +### Hash: +18f2a2e91c6ce51a38a61025c60c9f07 + +### Bug Type Hum: +Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-8256/instruction.md b/inferredbugs-8256/instruction.md index 373fcefc9699ecb1a52ad722b519192ee6bce5de..f8384563ae8d2480396060d84268afcaae698f7f 100644 --- a/inferredbugs-8256/instruction.md +++ b/inferredbugs-8256/instruction.md @@ -421,19 +421,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8269/instruction.md b/inferredbugs-8269/instruction.md index 4def4ac9cb4f66767a240adb2fa37228fe281373..bd5e03471317214c4a2ab7a6fa0a3e4a29a0f7d0 100644 --- a/inferredbugs-8269/instruction.md +++ b/inferredbugs-8269/instruction.md @@ -753,19 +753,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8400/instruction.md b/inferredbugs-8400/instruction.md index 1c2a499870a56a7d55d7a1f972cd570fcaad2f25..2ea9fc6b734ffdc4de5baa2fb7f6910aced4c5d4 100644 --- a/inferredbugs-8400/instruction.md +++ b/inferredbugs-8400/instruction.md @@ -407,19 +407,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8430/instruction.md b/inferredbugs-8430/instruction.md index 8960df3301e4b6d58d366f3221c579572b7d61e6..de639d87350b8b839b766d2e98fbbaa9bb5d1005 100644 --- a/inferredbugs-8430/instruction.md +++ b/inferredbugs-8430/instruction.md @@ -252,19 +252,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8602/instruction.md b/inferredbugs-8602/instruction.md index 63ab67fa23a48956a60b261a073f55ed3716cdff..816ca58b7cd5ddcf722baf83c8294f54b5572fb1 100644 --- a/inferredbugs-8602/instruction.md +++ b/inferredbugs-8602/instruction.md @@ -295,19 +295,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8632/instruction.md b/inferredbugs-8632/instruction.md index f8aa59595f48c701b3959320d2aff393901dcff7..21df1fe83105cca773408c65a85ae3925248b948 100644 --- a/inferredbugs-8632/instruction.md +++ b/inferredbugs-8632/instruction.md @@ -117,19 +117,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8850/instruction.md b/inferredbugs-8850/instruction.md index 44b1759460a597c837abd6096a67323085caf1d3..87db0bec357d41afb0fd87ae99b55a88c49fecce 100644 --- a/inferredbugs-8850/instruction.md +++ b/inferredbugs-8850/instruction.md @@ -187,19 +187,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-8851/instruction.md b/inferredbugs-8851/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b242ce027a8eb270b429ee5b11678ee3d2fd9ae5 --- /dev/null +++ b/inferredbugs-8851/instruction.md @@ -0,0 +1,828 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-imaging +**Bug ID:** 18 +**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.imaging.formats.tiff; + +import java.awt.Dimension; +import java.awt.Rectangle; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.commons.imaging.FormatCompliance; +import org.apache.commons.imaging.ImageFormat; +import org.apache.commons.imaging.ImageFormats; +import org.apache.commons.imaging.ImageInfo; +import org.apache.commons.imaging.ImageParser; +import org.apache.commons.imaging.ImageReadException; +import org.apache.commons.imaging.ImageWriteException; +import org.apache.commons.imaging.common.ByteOrder; +import org.apache.commons.imaging.common.IImageMetadata; +import org.apache.commons.imaging.common.ImageBuilder; +import org.apache.commons.imaging.common.bytesource.ByteSource; +import org.apache.commons.imaging.formats.tiff.TiffDirectory.ImageDataElement; +import org.apache.commons.imaging.formats.tiff.constants.TiffConstants; +import org.apache.commons.imaging.formats.tiff.constants.TiffEpTagConstants; +import org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants; +import org.apache.commons.imaging.formats.tiff.datareaders.DataReader; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreter; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterBiLevel; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterCieLab; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterCmyk; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterLogLuv; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterPalette; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterRgb; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterYCbCr; +import org.apache.commons.imaging.formats.tiff.write.TiffImageWriterLossy; + +public class TiffImageParser extends ImageParser implements TiffConstants { + private static final String DEFAULT_EXTENSION = ".tif"; + private static final String ACCEPTED_EXTENSIONS[] = { ".tif", ".tiff", }; + + public TiffImageParser() { + // setDebug(true); + } + + @Override + public String getName() { + return "Tiff-Custom"; + } + + @Override + public String getDefaultExtension() { + return DEFAULT_EXTENSION; + } + + @Override + protected String[] getAcceptedExtensions() { + return ACCEPTED_EXTENSIONS; + } + + @Override + protected ImageFormat[] getAcceptedTypes() { + return new ImageFormat[] { ImageFormats.TIFF, // + }; + } + + @Override + public byte[] getICCProfileBytes(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffContents contents = new TiffReader(isStrict(params)) + .readFirstDirectory(byteSource, params, false, formatCompliance); + final TiffDirectory directory = contents.directories.get(0); + + return directory.getFieldValue(TiffEpTagConstants.EXIF_TAG_INTER_COLOR_PROFILE, + false); + } + + @Override + public Dimension getImageSize(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffContents contents = new TiffReader(isStrict(params)) + .readFirstDirectory(byteSource, params, false, formatCompliance); + final TiffDirectory directory = contents.directories.get(0); + + final TiffField widthField = directory.findField( + TiffTagConstants.TIFF_TAG_IMAGE_WIDTH, true); + final TiffField heightField = directory.findField( + TiffTagConstants.TIFF_TAG_IMAGE_LENGTH, true); + + if ((widthField == null) || (heightField == null)) { + throw new ImageReadException("TIFF image missing size info."); + } + + final int height = heightField.getIntValue(); + final int width = widthField.getIntValue(); + + return new Dimension(width, height); + } + + public byte[] embedICCProfile(final byte image[], final byte profile[]) { + return null; + } + + @Override + public boolean embedICCProfile(final File src, final File dst, final byte profile[]) { + return false; + } + + @Override + public IImageMetadata getMetadata(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffReader tiffReader = new TiffReader(isStrict(params)); + final TiffContents contents = tiffReader.readContents(byteSource, params, + formatCompliance); + + final List directories = contents.directories; + + final TiffImageMetadata result = new TiffImageMetadata(contents); + + for (int i = 0; i < directories.size(); i++) { + final TiffDirectory dir = directories.get(i); + + final TiffImageMetadata.Directory metadataDirectory = new TiffImageMetadata.Directory( + tiffReader.getByteOrder(), dir); + + final List entries = dir.getDirectoryEntries(); + + for (int j = 0; j < entries.size(); j++) { + final TiffField entry = entries.get(j); + metadataDirectory.add(entry); + } + + result.add(metadataDirectory); + } + + return result; + } + + @Override + public ImageInfo getImageInfo(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffContents contents = new TiffReader(isStrict(params)) + .readDirectories(byteSource, false, formatCompliance); + final TiffDirectory directory = contents.directories.get(0); + + final TiffField widthField = directory.findField( + TiffTagConstants.TIFF_TAG_IMAGE_WIDTH, true); + final TiffField heightField = directory.findField( + TiffTagConstants.TIFF_TAG_IMAGE_LENGTH, true); + + if ((widthField == null) || (heightField == null)) { + throw new ImageReadException("TIFF image missing size info."); + } + + final int height = heightField.getIntValue(); + final int width = widthField.getIntValue(); + + // ------------------- + + final TiffField resolutionUnitField = directory + .findField(TiffTagConstants.TIFF_TAG_RESOLUTION_UNIT); + int resolutionUnit = 2; // Inch + if ((resolutionUnitField != null) + && (resolutionUnitField.getValue() != null)) { + resolutionUnit = resolutionUnitField.getIntValue(); + } + + double unitsPerInch = -1; + switch (resolutionUnit) { + case 1: + break; + case 2: // Inch + unitsPerInch = 1.0; + break; + case 3: // Centimeter + unitsPerInch = 2.54; + break; + default: + break; + + } + final TiffField xResolutionField = directory + .findField(TiffTagConstants.TIFF_TAG_XRESOLUTION); + final TiffField yResolutionField = directory + .findField(TiffTagConstants.TIFF_TAG_YRESOLUTION); + + int physicalWidthDpi = -1; + float physicalWidthInch = -1; + int physicalHeightDpi = -1; + float physicalHeightInch = -1; + + if (unitsPerInch > 0) { + if ((xResolutionField != null) + && (xResolutionField.getValue() != null)) { + final double XResolutionPixelsPerUnit = xResolutionField + .getDoubleValue(); + physicalWidthDpi = (int) Math + .round((XResolutionPixelsPerUnit * unitsPerInch)); + physicalWidthInch = (float) (width / (XResolutionPixelsPerUnit * unitsPerInch)); + } + if ((yResolutionField != null) + && (yResolutionField.getValue() != null)) { + final double YResolutionPixelsPerUnit = yResolutionField + .getDoubleValue(); + physicalHeightDpi = (int) Math + .round((YResolutionPixelsPerUnit * unitsPerInch)); + physicalHeightInch = (float) (height / (YResolutionPixelsPerUnit * unitsPerInch)); + } + } + + // ------------------- + + final TiffField bitsPerSampleField = directory + .findField(TiffTagConstants.TIFF_TAG_BITS_PER_SAMPLE); + + int bitsPerSample = 1; + if ((bitsPerSampleField != null) + && (bitsPerSampleField.getValue() != null)) { + bitsPerSample = bitsPerSampleField.getIntValueOrArraySum(); + } + + final int bitsPerPixel = bitsPerSample; // assume grayscale; + // dunno if this handles colormapped images correctly. + + // ------------------- + + final List comments = new ArrayList(); + final List entries = directory.entries; + for (int i = 0; i < entries.size(); i++) { + final TiffField field = entries.get(i); + final String comment = field.toString(); + comments.add(comment); + } + + final ImageFormat format = ImageFormats.TIFF; + final String formatName = "TIFF Tag-based Image File Format"; + final String mimeType = "image/tiff"; + final int numberOfImages = contents.directories.size(); + // not accurate ... only reflects first + final boolean isProgressive = false; + // is TIFF ever interlaced/progressive? + + final String formatDetails = "Tiff v." + contents.header.tiffVersion; + + final boolean isTransparent = false; // TODO: wrong + boolean usesPalette = false; + final TiffField colorMapField = directory + .findField(TiffTagConstants.TIFF_TAG_COLOR_MAP); + if (colorMapField != null) { + usesPalette = true; + } + + final int colorType = ImageInfo.COLOR_TYPE_RGB; + + final int compression = 0xffff & directory + .getSingleFieldValue(TiffTagConstants.TIFF_TAG_COMPRESSION); + String compressionAlgorithm; + + switch (compression) { + case TIFF_COMPRESSION_UNCOMPRESSED_1: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_NONE; + break; + case TIFF_COMPRESSION_CCITT_1D: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_CCITT_1D; + break; + case TIFF_COMPRESSION_CCITT_GROUP_3: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_CCITT_GROUP_3; + break; + case TIFF_COMPRESSION_CCITT_GROUP_4: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_CCITT_GROUP_4; + break; + case TIFF_COMPRESSION_LZW: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_LZW; + break; + case TIFF_COMPRESSION_JPEG: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_JPEG; + break; + case TIFF_COMPRESSION_UNCOMPRESSED_2: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_NONE; + break; + case TIFF_COMPRESSION_PACKBITS: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_PACKBITS; + break; + default: + compressionAlgorithm = ImageInfo.COMPRESSION_ALGORITHM_UNKNOWN; + break; + } + + final ImageInfo result = new ImageInfo(formatDetails, bitsPerPixel, comments, + format, formatName, height, mimeType, numberOfImages, + physicalHeightDpi, physicalHeightInch, physicalWidthDpi, + physicalWidthInch, width, isProgressive, isTransparent, + usesPalette, colorType, compressionAlgorithm); + + return result; + } + + @Override + public String getXmpXml(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffContents contents = new TiffReader(isStrict(params)) + .readDirectories(byteSource, false, formatCompliance); + final TiffDirectory directory = contents.directories.get(0); + + final byte bytes[] = directory.getFieldValue(TiffTagConstants.TIFF_TAG_XMP, + false); + if (bytes == null) { + return null; + } + + try { + // segment data is UTF-8 encoded xml. + final String xml = new String(bytes, "utf-8"); + return xml; + } catch (final UnsupportedEncodingException e) { + throw new ImageReadException("Invalid JPEG XMP Segment."); + } + } + + @Override + public boolean dumpImageFile(final PrintWriter pw, final ByteSource byteSource) + throws ImageReadException, IOException { + try { + pw.println("tiff.dumpImageFile"); + + { + final ImageInfo imageData = getImageInfo(byteSource); + if (imageData == null) { + return false; + } + + imageData.toString(pw, ""); + } + + pw.println(""); + + // try + { + final FormatCompliance formatCompliance = FormatCompliance + .getDefault(); + final Map params = null; + final TiffContents contents = new TiffReader(true).readContents( + byteSource, params, formatCompliance); + + final List directories = contents.directories; + + if (directories == null) { + return false; + } + + for (int d = 0; d < directories.size(); d++) { + final TiffDirectory directory = directories.get(d); + + final List entries = directory.entries; + + if (entries == null) { + return false; + } + + // Debug.debug("directory offset", directory.offset); + + for (int i = 0; i < entries.size(); i++) { + final TiffField field = entries.get(i); + + field.dump(pw, Integer.toString(d)); + } + } + + pw.println(""); + } + // catch (Exception e) + // { + // Debug.debug(e); + // pw.println(""); + // return false; + // } + + return true; + } finally { + pw.println(""); + } + } + + @Override + public FormatCompliance getFormatCompliance(final ByteSource byteSource) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final Map params = null; + new TiffReader(isStrict(params)).readContents(byteSource, params, + formatCompliance); + return formatCompliance; + } + + public List collectRawImageData(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffContents contents = new TiffReader(isStrict(params)) + .readDirectories(byteSource, true, formatCompliance); + + final List result = new ArrayList(); + for (int i = 0; i < contents.directories.size(); i++) { + final TiffDirectory directory = contents.directories.get(i); + final List dataElements = directory + .getTiffRawImageDataElements(); + for (int j = 0; j < dataElements.size(); j++) { + final TiffDirectory.ImageDataElement element = dataElements.get(j); + final byte bytes[] = byteSource.getBlock(element.offset, + element.length); + result.add(bytes); + } + } + return result; + } + + /** + * Gets a buffered image specified by the byte source. + * The TiffImageParser class features support for a number of options that + * are unique to the TIFF format. These options can be specified by + * supplying the appropriate parameters using the keys from the + * TiffConstants class and the params argument for this method. + *

Loading Partial Images

+ * The TIFF parser includes support for loading partial images without + * committing significantly more memory resources than are necessary + * to store the image. This feature is useful for conserving memory + * in applications that require a relatively small sub image from a + * very large TIFF file. The specifications for partial images are + * as follows: + *
+     *   HashMap params = new HashMap();
+     *   params.put(TiffConstants.PARAM_KEY_SUBIMAGE_X, new Integer(x));
+     *   params.put(TiffConstants.PARAM_KEY_SUBIMAGE_Y, new Integer(y));
+     *   params.put(TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, new Integer(width));
+     *   params.put(TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, new Integer(height));
+     * 
+ * Note that the arguments x, y, width, and height must specify a + * valid rectangular region that is fully contained within the + * source TIFF image. + * @param byteSource A valid instance of ByteSource + * @param params Optional instructions for special-handling or + * interpretation of the input data (null objects are permitted and + * must be supported by implementations). + * @return A valid instance of BufferedImage. + * @throws ImageReadException In the event that the the specified + * content does not conform to the format of the specific parser + * implementation. + * @throws IOException In the event of unsuccessful read or + * access operation. + */ + @Override + public BufferedImage getBufferedImage(final ByteSource byteSource, final Map params) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffReader reader = new TiffReader(isStrict(params)); + final TiffContents contents = reader.readFirstDirectory(byteSource, params, + true, formatCompliance); + final ByteOrder byteOrder = reader.getByteOrder(); + final TiffDirectory directory = contents.directories.get(0); + final BufferedImage result = directory.getTiffImage(byteOrder, params); + if (null == result) { + throw new ImageReadException("TIFF does not contain an image."); + } + return result; + } + + @Override + public List getAllBufferedImages(final ByteSource byteSource) + throws ImageReadException, IOException { + final FormatCompliance formatCompliance = FormatCompliance.getDefault(); + final TiffReader tiffReader = new TiffReader(true); + final TiffContents contents = tiffReader.readDirectories(byteSource, true, + formatCompliance); + final List results = new ArrayList(); + for (int i = 0; i < contents.directories.size(); i++) { + final TiffDirectory directory = contents.directories.get(i); + final BufferedImage result = directory.getTiffImage( + tiffReader.getByteOrder(), null); + if (result != null) { + results.add(result); + } + } + return results; + } + + private Integer getIntegerParameter( + final String key, final Mapparams) + throws ImageReadException + { + if (params == null) { + return null; + } + + if(!params.containsKey(key)) { + return null; + } + + final Object obj = params.get(key); + + if(obj instanceof Integer){ + return (Integer)obj; + } + throw new ImageReadException( + "Non-Integer parameter "+key); + } + + private Rectangle checkForSubImage( + final Map params) + throws ImageReadException + { + Integer ix0, iy0, iwidth, iheight; + ix0 = getIntegerParameter( + TiffConstants.PARAM_KEY_SUBIMAGE_X, params); + iy0 = getIntegerParameter( + TiffConstants.PARAM_KEY_SUBIMAGE_Y, params); + iwidth = getIntegerParameter( + TiffConstants.PARAM_KEY_SUBIMAGE_WIDTH, params); + iheight = getIntegerParameter( + TiffConstants.PARAM_KEY_SUBIMAGE_HEIGHT, params); + if (ix0 == null && iy0 == null && iwidth == null && iheight == null) { + return null; + } + + final StringBuilder sb = new StringBuilder(); + if (ix0 == null) { + sb.append(" x0,"); + } + if (iy0 == null) { + sb.append(" y0,"); + } + if (iwidth == null) { + sb.append(" width,"); + } + if (iheight == null) { + sb.append(" height,"); + } + if (sb.length() > 0) { + sb.setLength(sb.length() - 1); + throw new ImageReadException( + "Incomplete subimage parameters, missing" + + sb.toString()); + } + + return new Rectangle(ix0, iy0, iwidth, iheight); + } + + protected BufferedImage getBufferedImage(final TiffDirectory directory, + final ByteOrder byteOrder, final Map params) + throws ImageReadException, IOException + { + final List entries = directory.entries; + + if (entries == null) { + throw new ImageReadException("TIFF missing entries"); + } + + final int photometricInterpretation = 0xffff & directory.getSingleFieldValue( + TiffTagConstants.TIFF_TAG_PHOTOMETRIC_INTERPRETATION); + final int compression = 0xffff & directory.getSingleFieldValue( + TiffTagConstants.TIFF_TAG_COMPRESSION); + final int width = directory.getSingleFieldValue( + TiffTagConstants.TIFF_TAG_IMAGE_WIDTH); + final int height = directory.getSingleFieldValue( + TiffTagConstants.TIFF_TAG_IMAGE_LENGTH); + Rectangle subImage = checkForSubImage(params); + if(subImage!=null){ + // Check for valid subimage specification. The following checks + // are consistent with BufferedImage.getSubimage() + if (subImage.width <= 0) { + throw new ImageReadException("negative or zero subimage width"); + } + if (subImage.height <= 0) { + throw new ImageReadException("negative or zero subimage height"); + } + if(subImage.x<0 || subImage.x>=width){ + throw new ImageReadException("subimage x is outside raster"); + } + if(subImage.x+subImage.width>width){ + throw new ImageReadException( + "subimage (x+width) is outside raster"); + } + if(subImage.y<0 || subImage.y>=height){ + throw new ImageReadException("subimage y is outside raster"); + } + if(subImage.y+subImage.height>height){ + throw new ImageReadException( + "subimage (y+height) is outside raster"); + } + + // if the subimage is just the same thing as the whole + // image, suppress the subimage processing + if(subImage.x==0 + && subImage.y==0 + && subImage.width==width + && subImage.height==height){ + subImage = null; + } + } + + + int samplesPerPixel = 1; + final TiffField samplesPerPixelField = directory.findField( + TiffTagConstants.TIFF_TAG_SAMPLES_PER_PIXEL); + if (samplesPerPixelField != null) { + samplesPerPixel = samplesPerPixelField.getIntValue(); + } + int bitsPerSample[] = { 1 }; + int bitsPerPixel = samplesPerPixel; + final TiffField bitsPerSampleField = directory.findField( + TiffTagConstants.TIFF_TAG_BITS_PER_SAMPLE); + if (bitsPerSampleField != null) { + bitsPerSample = bitsPerSampleField.getIntArrayValue(); + bitsPerPixel = bitsPerSampleField.getIntValueOrArraySum(); + } + + // int bitsPerPixel = getTagAsValueOrArraySum(entries, + // TIFF_TAG_BITS_PER_SAMPLE); + + int predictor = -1; + { + // dumpOptionalNumberTag(entries, TIFF_TAG_FILL_ORDER); + // dumpOptionalNumberTag(entries, TIFF_TAG_FREE_BYTE_COUNTS); + // dumpOptionalNumberTag(entries, TIFF_TAG_FREE_OFFSETS); + // dumpOptionalNumberTag(entries, TIFF_TAG_ORIENTATION); + // dumpOptionalNumberTag(entries, TIFF_TAG_PLANAR_CONFIGURATION); + final TiffField predictorField = directory.findField( + TiffTagConstants.TIFF_TAG_PREDICTOR); + if (null != predictorField) { + predictor = predictorField.getIntValueOrArraySum(); + } + } + + if (samplesPerPixel != bitsPerSample.length) { + throw new ImageReadException("Tiff: samplesPerPixel (" + + samplesPerPixel + ")!=fBitsPerSample.length (" + + bitsPerSample.length + ")"); + } + + + + final PhotometricInterpreter photometricInterpreter = getPhotometricInterpreter( + directory, photometricInterpretation, bitsPerPixel, + bitsPerSample, predictor, samplesPerPixel, width, height); + + final TiffImageData imageData = directory.getTiffImageData(); + + final DataReader dataReader = imageData.getDataReader(directory, + photometricInterpreter, bitsPerPixel, bitsPerSample, predictor, + samplesPerPixel, width, height, compression, byteOrder); + + BufferedImage result = null; + if (subImage != null) { + result = dataReader.readImageData(subImage); + } else { + final boolean hasAlpha = false; + final ImageBuilder imageBuilder = new ImageBuilder(width, height, hasAlpha); + + dataReader.readImageData(imageBuilder); + result = imageBuilder.getBufferedImage(); + } + photometricInterpreter.dumpstats(); + return result; + } + + private PhotometricInterpreter getPhotometricInterpreter( + final TiffDirectory directory, final int photometricInterpretation, + final int bitsPerPixel, final int bitsPerSample[], final int predictor, + final int samplesPerPixel, final int width, final int height) + throws ImageReadException { + switch (photometricInterpretation) { + case 0: + case 1: + final boolean invert = photometricInterpretation == 0; + + return new PhotometricInterpreterBiLevel(bitsPerPixel, + samplesPerPixel, bitsPerSample, predictor, width, height, + invert); + case 3: // Palette + { + final int colorMap[] = directory.findField( + TiffTagConstants.TIFF_TAG_COLOR_MAP, true) + .getIntArrayValue(); + + final int expected_colormap_size = 3 * (1 << bitsPerPixel); + + if (colorMap.length != expected_colormap_size) { + throw new ImageReadException("Tiff: fColorMap.length (" + + colorMap.length + ")!=expected_colormap_size (" + + expected_colormap_size + ")"); + } + + return new PhotometricInterpreterPalette(samplesPerPixel, + bitsPerSample, predictor, width, height, colorMap); + } + case 2: // RGB + return new PhotometricInterpreterRgb(samplesPerPixel, + bitsPerSample, predictor, width, height); + case 5: // CMYK + return new PhotometricInterpreterCmyk(samplesPerPixel, + bitsPerSample, predictor, width, height); + case 6: // + { + final double yCbCrCoefficients[] = directory.findField( + TiffTagConstants.TIFF_TAG_YCBCR_COEFFICIENTS, true) + .getDoubleArrayValue(); + + final int yCbCrPositioning[] = directory.findField( + TiffTagConstants.TIFF_TAG_YCBCR_POSITIONING, true) + .getIntArrayValue(); + final int yCbCrSubSampling[] = directory.findField( + TiffTagConstants.TIFF_TAG_YCBCR_SUB_SAMPLING, true) + .getIntArrayValue(); + + final double referenceBlackWhite[] = directory.findField( + TiffTagConstants.TIFF_TAG_REFERENCE_BLACK_WHITE, true) + .getDoubleArrayValue(); + + return new PhotometricInterpreterYCbCr(yCbCrCoefficients, + yCbCrPositioning, yCbCrSubSampling, referenceBlackWhite, + samplesPerPixel, bitsPerSample, predictor, width, height); + } + + case 8: + return new PhotometricInterpreterCieLab(samplesPerPixel, + bitsPerSample, predictor, width, height); + + case 32844: + case 32845: { + final boolean yonly = (photometricInterpretation == 32844); + return new PhotometricInterpreterLogLuv(samplesPerPixel, + bitsPerSample, predictor, width, height, yonly); + } + + default: + throw new ImageReadException( + "TIFF: Unknown fPhotometricInterpretation: " + + photometricInterpretation); + } + } + + @Override + public void writeImage(final BufferedImage src, final OutputStream os, final Map params) + throws ImageWriteException, IOException { + new TiffImageWriterLossy().writeImage(src, os, params); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +NULL_DEREFERENCE + +### Qualifier: +object returned by `directory.findField(org.apache.commons.imaging.formats.tiff.constants.TiffTagConstants.TIFF_TAG_YCBCR_COEFFICIENTS,1)` could be null and is dereferenced at line 727. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +PhotometricInterpreter TiffImageParser.getPhotometricInterpreter(TiffDirectory,int,int,int[],int,int,int,int) + +### Procedure Id: +org.apache.commons.imaging.formats.tiff.TiffImageParser.getPhotometricInterpreter(org.apache.commons.756decac972a081fec566f59afe9a027 + +### File: +src/main/java/org/apache/commons/imaging/formats/tiff/TiffImageParser.java + +### Key: +TiffImageParser.java|getPhotometricInterpreter|NULL_DEREFERENCE + +### Node Key: +555eb4653f57a9c18c7378b53476017b + +### Hash: +b8928b02848aeebf754c09336334a4bf + +### Bug Type Hum: +Null Dereference + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-8858/instruction.md b/inferredbugs-8858/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..47bba25ab6beb37f97237632155f7f9506549ee7 --- /dev/null +++ b/inferredbugs-8858/instruction.md @@ -0,0 +1,298 @@ +# InferredBugs Task - Java + +## Project Information + +**Project:** commons-imaging +**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.imaging.formats.tiff.datareaders; + +import java.awt.Rectangle; +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.ByteOrder; + +import org.apache.commons.imaging.ImageReadException; +import org.apache.commons.imaging.common.ImageBuilder; +import org.apache.commons.imaging.formats.tiff.TiffDirectory; +import org.apache.commons.imaging.formats.tiff.TiffElement.DataElement; +import org.apache.commons.imaging.formats.tiff.TiffImageData; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreter; +import org.apache.commons.imaging.formats.tiff.photometricinterpreters.PhotometricInterpreterRgb; + +public final class DataReaderTiled extends ImageDataReader { + + private final int tileWidth; + private final int tileLength; + + private final int bitsPerPixel; + + private final int compression; + private final ByteOrder byteOrder; + + private final TiffImageData.Tiles imageData; + + public DataReaderTiled(final TiffDirectory directory, + final PhotometricInterpreter photometricInterpreter, final int tileWidth, + final int tileLength, final int bitsPerPixel, final int[] bitsPerSample, + final int predictor, final int samplesPerPixel, final int width, final int height, + final int compression, final ByteOrder byteOrder, final TiffImageData.Tiles imageData) { + super(directory, photometricInterpreter, bitsPerSample, predictor, + samplesPerPixel, width, height); + + this.tileWidth = tileWidth; + this.tileLength = tileLength; + + this.bitsPerPixel = bitsPerPixel; + this.compression = compression; + + this.imageData = imageData; + this.byteOrder = byteOrder; + } + + private void interpretTile(final ImageBuilder imageBuilder, final byte[] bytes, + final int startX, final int startY, final int xLimit, final int yLimit) throws ImageReadException, IOException { + // changes introduced May 2012 + // The following block of code implements changes that + // reduce image loading time by using special-case processing + // instead of the general-purpose logic from the original + // implementation. For a detailed discussion, see the comments for + // a similar treatment in the DataReaderStrip class + // + + // verify that all samples are one byte in size + final boolean allSamplesAreOneByte = isHomogenous(8); + + if (predictor != 2 && bitsPerPixel == 24 && allSamplesAreOneByte) { + int k = 0; + final int i0 = startY; + int i1 = startY + tileLength; + if (i1 > yLimit) { + // the tile is padded past bottom of image + i1 = yLimit; + } + final int j0 = startX; + int j1 = startX + tileWidth; + if (j1 > xLimit) { + // the tile is padded to beyond the tile width + j1 = xLimit; + } + if (photometricInterpreter instanceof PhotometricInterpreterRgb) { + for (int i = i0; i < i1; i++) { + k = (i - i0) * tileWidth * 3; + for (int j = j0; j < j1; j++, k += 3) { + final int rgb = 0xff000000 + | (((bytes[k] << 8) | (bytes[k + 1] & 0xff)) << 8) + | (bytes[k + 2] & 0xff); + imageBuilder.setRGB(j, i, rgb); + } + } + } else { + final int[] samples = new int[3]; + for (int i = i0; i < i1; i++) { + k = (i - i0) * tileWidth * 3; + for (int j = j0; j < j1; j++) { + samples[0] = bytes[k++] & 0xff; + samples[1] = bytes[k++] & 0xff; + samples[2] = bytes[k++] & 0xff; + photometricInterpreter.interpretPixel(imageBuilder, + samples, j, i); + } + } + } + return; + } + + // End of May 2012 changes + + final BitInputStream bis = new BitInputStream(new ByteArrayInputStream(bytes), byteOrder); + + final int pixelsPerTile = tileWidth * tileLength; + + int tileX = 0; + int tileY = 0; + + int[] samples = new int[bitsPerSampleLength]; + resetPredictor(); + for (int i = 0; i < pixelsPerTile; i++) { + + final int x = tileX + startX; + final int y = tileY + startY; + + getSamplesAsBytes(bis, samples); + + if ((x < xLimit) && (y < yLimit)) { + samples = applyPredictor(samples); + photometricInterpreter.interpretPixel(imageBuilder, samples, x, + y); + } + + tileX++; + + if (tileX >= tileWidth) { + tileX = 0; + resetPredictor(); + tileY++; + bis.flushCache(); + if (tileY >= tileLength) { + break; + } + } + + } + } + + @Override + public void readImageData(final ImageBuilder imageBuilder) + throws ImageReadException, IOException { + final int bitsPerRow = tileWidth * bitsPerPixel; + final int bytesPerRow = (bitsPerRow + 7) / 8; + final int bytesPerTile = bytesPerRow * tileLength; + int x = 0; + int y = 0; + + for (final DataElement tile2 : imageData.tiles) { + final byte[] compressed = tile2.getData(); + + final byte[] decompressed = decompress(compressed, compression, + bytesPerTile, tileWidth, tileLength); + + interpretTile(imageBuilder, decompressed, x, y, width, height); + + x += tileWidth; + if (x >= width) { + x = 0; + y += tileLength; + if (y >= height) { + break; + } + } + + } + } + + @Override + public BufferedImage readImageData(final Rectangle subImage) + throws ImageReadException, IOException + { + final int bitsPerRow = tileWidth * bitsPerPixel; + final int bytesPerRow = (bitsPerRow + 7) / 8; + final int bytesPerTile = bytesPerRow * tileLength; + int x = 0; + int y = 0; + + // tileWidth is the width of the tile + // tileLength is the height of the tile + final int col0 = subImage.x / tileWidth; + final int col1 = (subImage.x + subImage.width - 1) / tileWidth; + final int row0 = subImage.y / tileLength; + final int row1 = (subImage.y + subImage.height - 1) / tileLength; + + final int nCol = col1 - col0 + 1; + final int nRow = row1 - row0 + 1; + final int workingWidth = nCol * tileWidth; + final int workingHeight = nRow * tileLength; + + final int nColumnsOfTiles = (width + tileWidth - 1) / tileWidth; + + final int x0 = col0 * tileWidth; + final int y0 = row0 * tileLength; + + final ImageBuilder workingBuilder = + new ImageBuilder(workingWidth, workingHeight, false); + + for (int iRow = row0; iRow <= row1; iRow++) { + for (int iCol = col0; iCol <= col1; iCol++) { + final int tile = iRow * nColumnsOfTiles + iCol; + final byte[] compressed = imageData.tiles[tile].getData(); + final byte[] decompressed = decompress(compressed, compression, + bytesPerTile, tileWidth, tileLength); + x = iCol * tileWidth - x0; + y = iRow * tileLength - y0; + interpretTile(workingBuilder, decompressed, x, y, workingWidth, workingHeight); + } + } + + if (subImage.x == x0 + && subImage.y == y0 + && subImage.width == workingWidth + && subImage.height == workingHeight) { + return workingBuilder.getBufferedImage(); + } + return workingBuilder.getSubimage( + subImage.x - x0, + subImage.y - y0, + subImage.width, + subImage.height); + } + +} + +``` + +### Bug Class: +PROVER + +### Kind: +ERROR + +### Bug Type: +RESOURCE_LEAK + +### Qualifier: +resource of type `org.apache.commons.imaging.formats.tiff.datareaders.BitInputStream` acquired to `bis` by call to `new()` at line 118 is not released after line 127. + +### Severity: +HIGH + +### Visibility: +user + +### Procedure: +void DataReaderTiled.interpretTile(ImageBuilder,byte[],int,int,int,int) + +### Procedure Id: +org.apache.commons.imaging.formats.tiff.datareaders.DataReaderTiled.interpretTile(org.apache.commons.43505a9fc1eacb7681ebab08005c38e2 + +### File: +src/main/java/org/apache/commons/imaging/formats/tiff/datareaders/DataReaderTiled.java + +### Key: +DataReaderTiled.java|interpretTile|RESOURCE_LEAK + +### Node Key: +02dd4a8ff24f75027dc24dd024275405 + +### Hash: +8114b55673d9e737869f6afa337b5864 + +### Bug Type Hum: +Resource Leak + +## Task + +Fix the bug in the code. diff --git a/inferredbugs-9142/instruction.md b/inferredbugs-9142/instruction.md index 53548ceb29ce638233a083724fe0957ec534a1fa..8b39ef38afcb184e53677e3712807203558446a9 100644 --- a/inferredbugs-9142/instruction.md +++ b/inferredbugs-9142/instruction.md @@ -385,19 +385,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9186/instruction.md b/inferredbugs-9186/instruction.md index 9b82c96b8848afa787e174bffc918d339ecd2c00..8b270bfe2ed459bd512890c6368109fbe2fa6a06 100644 --- a/inferredbugs-9186/instruction.md +++ b/inferredbugs-9186/instruction.md @@ -240,19 +240,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9370/instruction.md b/inferredbugs-9370/instruction.md index fc9f3037672e459d6e4dccde821c636f8c8cca97..00a7e218c5ca8fdea31877b96bba879f934c1ce6 100644 --- a/inferredbugs-9370/instruction.md +++ b/inferredbugs-9370/instruction.md @@ -1427,19 +1427,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9379/instruction.md b/inferredbugs-9379/instruction.md index fe1e0c679eaea1552f688926a331a2920ded337f..10ffbbd8e3d173970c74920db7ad62e6745611fa 100644 --- a/inferredbugs-9379/instruction.md +++ b/inferredbugs-9379/instruction.md @@ -243,19 +243,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9384/instruction.md b/inferredbugs-9384/instruction.md index 9b2c704135b10326572f51e6362472de2b955ed8..17e84611a3f741378c25ab575017913a38cbda59 100644 --- a/inferredbugs-9384/instruction.md +++ b/inferredbugs-9384/instruction.md @@ -117,19 +117,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9526/instruction.md b/inferredbugs-9526/instruction.md index 5d9330dbb91d27c52ff2c48b13fc584b4c663080..2a23389d20a67b7d2fa47cf528df6df18a417c7c 100644 --- a/inferredbugs-9526/instruction.md +++ b/inferredbugs-9526/instruction.md @@ -180,19 +180,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9714/instruction.md b/inferredbugs-9714/instruction.md index 405a18e399bec9878c1de5aa9ea3bbeccdd56275..63b47b6ae78564d9c9a2d89012a2485459f7b981 100644 --- a/inferredbugs-9714/instruction.md +++ b/inferredbugs-9714/instruction.md @@ -149,19 +149,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9977/instruction.md b/inferredbugs-9977/instruction.md index 2dabb4a5c1edcbccc7f3462f36d0cf4133bbff8e..267b73b6ff291f5e3232383a7b5495c571889252 100644 --- a/inferredbugs-9977/instruction.md +++ b/inferredbugs-9977/instruction.md @@ -194,19 +194,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9982/instruction.md b/inferredbugs-9982/instruction.md index a473406f9f96e3e2573dbc646a75f3a32bf5fdc5..f23b36d56a72f2b7b25d61e680ab64e8861ba271 100644 --- a/inferredbugs-9982/instruction.md +++ b/inferredbugs-9982/instruction.md @@ -275,19 +275,4 @@ 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. +Fix the bug in the code. diff --git a/inferredbugs-9983/instruction.md b/inferredbugs-9983/instruction.md index ddc65e438e8b359f04e136d57effeb77d8819adf..ad3d0e2a6176c32873be77005ccf65de4f9a2279 100644 --- a/inferredbugs-9983/instruction.md +++ b/inferredbugs-9983/instruction.md @@ -495,19 +495,4 @@ 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. +Fix the bug in the code.