input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
@Test(expected = UnsupportedOperationException.class)
public void testChildEntriesUnmodifiable() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = root.getChildEntries();
// Should not be allowed, as it modifies the internal structure
children.remove(children.first());
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test(expected = UnsupportedOperationException.class)
public void testChildEntriesUnmodifiable() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = root.getChildEntries();
// Should not be allowed, as it modifies the internal structure
children.remove(children.first());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * image.getColorModel().getPixelSize() + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
#location 91
#vulnerability type RESOURCE_LEAK
|
#fixed code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
int samplesPerPixel = (Integer) entries.get(TIFF.TAG_SAMPLES_PER_PIXEL).getValue();
int bitPerSample = ((short[]) entries.get(TIFF.TAG_BITS_PER_SAMPLE).getValue())[0];
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * samplesPerPixel * bitPerSample + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testContents() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testContents() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = new TreeSet<Entry>(root.getChildEntries());
assertEquals(25, children.size());
// Weirdness in the file format, name is *written backwards* 1-24 + Catalog
for (String name : "1,2,3,4,5,6,7,8,9,01,02,11,12,21,22,31,32,41,42,51,61,71,81,91,Catalog".split(",")) {
assertEquals(name, children.first().getName());
children.remove(children.first());
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadThumbsCatalogFile() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testReadThumbsCatalogFile() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static ColorSpace getColorSpace(int colorSpace) {
ICC_Profile profile;
switch (colorSpace) {
case CS_ADOBE_RGB_1998:
synchronized (ColorSpaces.class) {
profile = adobeRGB1998.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("ADOBE_RGB_1998"));
if (profile == null) {
// Fall back to the bundled ClayRGB1998 public domain Adobe RGB 1998 compatible profile,
// which is identical for all practical purposes
profile = readProfileFromClasspathResource("/profiles/ClayRGB1998.icc");
if (profile == null) {
// Should never happen given we now bundle fallback profile...
throw new IllegalStateException("Could not read AdobeRGB1998 profile");
}
}
adobeRGB1998 = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
case CS_GENERIC_CMYK:
synchronized (ColorSpaces.class) {
profile = genericCMYK.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("GENERIC_CMYK"));
if (profile == null) {
if (DEBUG) {
System.out.println("Using fallback profile");
}
// Fall back to generic CMYK ColorSpace, which is *insanely slow* using ColorConvertOp... :-P
return CMYKColorSpace.getInstance();
}
genericCMYK = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
default:
// Default cases for convenience
return ColorSpace.getInstance(colorSpace);
}
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public static ColorSpace getColorSpace(int colorSpace) {
ICC_Profile profile;
switch (colorSpace) {
case CS_ADOBE_RGB_1998:
synchronized (ColorSpaces.class) {
profile = adobeRGB1998.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("ADOBE_RGB_1998"));
if (profile == null) {
// Fall back to the bundled ClayRGB1998 public domain Adobe RGB 1998 compatible profile,
// which is identical for all practical purposes
profile = readProfileFromClasspathResource("/profiles/ClayRGB1998.icc");
if (profile == null) {
// Should never happen given we now bundle fallback profile...
throw new IllegalStateException("Could not read AdobeRGB1998 profile");
}
}
if (profile.getColorSpaceType() != ColorSpace.TYPE_RGB) {
throw new IllegalStateException("Configured AdobeRGB1998 profile is not TYPE_RGB");
}
adobeRGB1998 = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
case CS_GENERIC_CMYK:
synchronized (ColorSpaces.class) {
profile = genericCMYK.get();
if (profile == null) {
// Try to get system default or user-defined profile
profile = readProfileFromPath(Profiles.getPath("GENERIC_CMYK"));
if (profile == null) {
if (DEBUG) {
System.out.println("Using fallback profile");
}
// Fall back to generic CMYK ColorSpace, which is *insanely slow* using ColorConvertOp... :-P
return CMYKColorSpace.getInstance();
}
if (profile.getColorSpaceType() != ColorSpace.TYPE_CMYK) {
throw new IllegalStateException("Configured Generic CMYK profile is not TYPE_CMYK");
}
genericCMYK = new WeakReference<>(profile);
}
}
return createColorSpace(profile);
default:
// Default cases for convenience
return ColorSpace.getInstance(colorSpace);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * image.getColorModel().getPixelSize() + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), image.getTile(0, 0).getNumBands(), image.getColorModel().getComponentSize(0), imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
#location 91
#vulnerability type RESOURCE_LEAK
|
#fixed code
private DataOutput createCompressorStream(final RenderedImage image, final ImageWriteParam param, final Map<Integer, Entry> entries) {
/*
36 MB test data:
No compression:
Write time: 450 ms
output.length: 36000226
PackBits:
Write time: 688 ms
output.length: 30322187
Deflate, BEST_SPEED (1):
Write time: 1276 ms
output.length: 14128866
Deflate, 2:
Write time: 1297 ms
output.length: 13848735
Deflate, 3:
Write time: 1594 ms
output.length: 13103224
Deflate, 4:
Write time: 1663 ms
output.length: 13380899 (!!)
5
Write time: 1941 ms
output.length: 13171244
6
Write time: 2311 ms
output.length: 12845101
7: Write time: 2853 ms
output.length: 12759426
8:
Write time: 4429 ms
output.length: 12624517
Deflate: DEFAULT_COMPRESSION (6?):
Write time: 2357 ms
output.length: 12845101
Deflate, BEST_COMPRESSION (9):
Write time: 4998 ms
output.length: 12600399
*/
int samplesPerPixel = (Integer) entries.get(TIFF.TAG_SAMPLES_PER_PIXEL).getValue();
int bitPerSample = ((short[]) entries.get(TIFF.TAG_BITS_PER_SAMPLE).getValue())[0];
// Use predictor by default for LZW and ZLib/Deflate
// TODO: Unless explicitly disabled in TIFFImageWriteParam
int compression = (int) entries.get(TIFF.TAG_COMPRESSION).getValue();
OutputStream stream;
switch (compression) {
case TIFFBaseline.COMPRESSION_NONE:
return imageOutput;
case TIFFBaseline.COMPRESSION_PACKBITS:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new PackBitsEncoder(), true);
// NOTE: PackBits + Predictor is possible, but not generally supported, disable it by default
// (and probably not even allow it, see http://stackoverflow.com/questions/20337400/tiff-packbits-compression-with-predictor-step)
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_ZLIB:
case TIFFExtension.COMPRESSION_DEFLATE:
// NOTE: This interpretation does the opposite of the JAI TIFFImageWriter, but seems more correct.
// API Docs says:
// A compression quality setting of 0.0 is most generically interpreted as "high compression is important,"
// while a setting of 1.0 is most generically interpreted as "high image quality is important."
// However, the JAI TIFFImageWriter uses:
// if (param & compression etc...) {
// float quality = param.getCompressionQuality();
// deflateLevel = (int)(1 + 8*quality);
// } else {
// deflateLevel = Deflater.DEFAULT_COMPRESSION;
// }
// (in other words, 0.0 means 1 == BEST_SPEED, 1.0 means 9 == BEST_COMPRESSION)
// PS: PNGImageWriter just uses hardcoded BEST_COMPRESSION... :-P
int deflateSetting = Deflater.BEST_SPEED; // This is consistent with default compression quality being 1.0 and 0 meaning max compression...
if (param.getCompressionMode() == ImageWriteParam.MODE_EXPLICIT) {
deflateSetting = Deflater.BEST_COMPRESSION - Math.round((Deflater.BEST_COMPRESSION - 1) * param.getCompressionQuality());
}
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new DeflaterOutputStream(stream, new Deflater(deflateSetting), 1024);
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFExtension.COMPRESSION_LZW:
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new EncoderStream(stream, new LZWEncoder((image.getTileWidth() * image.getTileHeight() * samplesPerPixel * bitPerSample + 7) / 8));
if (entries.containsKey(TIFF.TAG_PREDICTOR) && entries.get(TIFF.TAG_PREDICTOR).getValue().equals(TIFFExtension.PREDICTOR_HORIZONTAL_DIFFERENCING)) {
stream = new HorizontalDifferencingStream(stream, image.getTileWidth(), samplesPerPixel, bitPerSample, imageOutput.getByteOrder());
}
return new DataOutputStream(stream);
case TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE:
case TIFFExtension.COMPRESSION_CCITT_T4:
case TIFFExtension.COMPRESSION_CCITT_T6:
long option = 0L;
if (compression != TIFFBaseline.COMPRESSION_CCITT_MODIFIED_HUFFMAN_RLE) {
option = (long) entries.get(compression == TIFFExtension.COMPRESSION_CCITT_T4 ? TIFF.TAG_GROUP3OPTIONS : TIFF.TAG_GROUP4OPTIONS).getValue();
}
Entry fillOrderEntry = entries.get(TIFF.TAG_FILL_ORDER);
int fillOrder = (int) (fillOrderEntry != null ? fillOrderEntry.getValue() : TIFFBaseline.FILL_LEFT_TO_RIGHT);
stream = IIOUtil.createStreamAdapter(imageOutput);
stream = new CCITTFaxEncoderStream(stream, image.getTileWidth(), image.getTileHeight(), compression, fillOrder, option);
return new DataOutputStream(stream);
}
throw new IllegalArgumentException(String.format("Unsupported TIFF compression: %d", compression));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private CompoundDirectory getExif() throws IOException {
List<Application> exifSegments = getAppSegments(JPEG.APP1, "Exif");
if (!exifSegments.isEmpty()) {
Application exif = exifSegments.get(0);
InputStream data = exif.data();
if (data.read() == -1) { // Read pad
processWarningOccurred("Exif chunk has no data.");
}
else {
ImageInputStream stream = new MemoryCacheImageInputStream(data);
return (CompoundDirectory) new TIFFReader().read(stream);
// TODO: Directory offset of thumbnail is wrong/relative to container stream, causing trouble for the TIFFReader...
}
}
return null;
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
private CompoundDirectory getExif() throws IOException {
List<Application> exifSegments = getAppSegments(JPEG.APP1, "Exif");
if (!exifSegments.isEmpty()) {
Application exif = exifSegments.get(0);
int offset = exif.identifier.length() + 2; // Incl. pad
if (exif.data.length <= offset) {
processWarningOccurred("Exif chunk has no data.");
}
else {
// TODO: Consider returning ByteArrayImageInputStream from Segment.data()
try (ImageInputStream stream = new ByteArrayImageInputStream(exif.data, offset, exif.data.length - offset)) {
return (CompoundDirectory) new TIFFReader().read(stream);
}
}
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test(expected = UnsupportedOperationException.class)
public void testChildEntriesUnmodifiable() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = root.getChildEntries();
// Should not be allowed, as it modifies the internal structure
children.remove(children.first());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test(expected = UnsupportedOperationException.class)
public void testChildEntriesUnmodifiable() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
SortedSet<Entry> children = root.getChildEntries();
// Should not be allowed, as it modifies the internal structure
children.remove(children.first());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static ICC_ColorSpace createColorSpace(final ICC_Profile profile) {
Validate.notNull(profile, "profile");
byte[] profileHeader = profile.getData(ICC_Profile.icSigHead);
ICC_ColorSpace cs = getInternalCS(profile.getColorSpaceType(), profileHeader);
if (cs != null) {
return cs;
}
// Special case for color profiles with rendering intent != 0, see isOffendingColorProfile method
// NOTE: Rendering intent is really a 4 byte value, but legal values are 0-3 (ICC1v42_2006_05_1.pdf, 7.2.15, p. 19)
if (profileHeader[ICC_Profile.icHdrRenderingIntent] != 0) {
profileHeader[ICC_Profile.icHdrRenderingIntent] = 0;
// Test again if this is an internal CS
cs = getInternalCS(profile.getColorSpaceType(), profileHeader);
if (cs != null) {
return cs;
}
// Fix profile before lookup/create
profileCleaner.fixProfile(profile, profileHeader);
}
else {
profileCleaner.fixProfile(profile, null);
}
return getCachedOrCreateCS(profile, profileHeader);
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public static ICC_ColorSpace createColorSpace(final ICC_Profile profile) {
Validate.notNull(profile, "profile");
// Fix profile before lookup/create
profileCleaner.fixProfile(profile);
byte[] profileHeader = getProfileHeaderWithProfileId(profile);
ICC_ColorSpace cs = getInternalCS(profile.getColorSpaceType(), profileHeader);
if (cs != null) {
return cs;
}
return getCachedOrCreateCS(profile, profileHeader);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadThumbsCatalogFile() throws IOException {
CompoundDocument document = createTestDocument();
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testReadThumbsCatalogFile() throws IOException {
try (CompoundDocument document = createTestDocument()) {
Entry root = document.getRootEntry();
assertNotNull(root);
assertEquals(25, root.getChildEntries().size());
Entry catalog = root.getChildEntry("Catalog");
assertNotNull(catalog);
assertNotNull("Input stream may not be null", catalog.getInputStream());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public int getWidth() throws IOException {
if (compression == 1) { // 1 = no compression
Entry width = ifd.getEntryById(TIFF.TAG_IMAGE_WIDTH);
if (width == null) {
throw new IIOException("Missing dimensions for RAW EXIF thumbnail");
}
return ((Number) width.getValue()).intValue();
}
else if (compression == 6) { // 6 = JPEG compression
return readJPEGCached(false).getWidth();
}
else {
throw new IIOException("Unsupported EXIF thumbnail compression: " + compression);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public int getWidth() throws IOException {
if (compression == 1) { // 1 = no compression
Entry width = ifd.getEntryById(TIFF.TAG_IMAGE_WIDTH);
if (width == null) {
throw new IIOException("Missing dimensions for unknown EXIF thumbnail");
}
return ((Number) width.getValue()).intValue();
}
else if (compression == 6) { // 6 = JPEG compression
return readJPEGCached(false).getWidth();
}
else {
throw new IIOException("Unsupported EXIF thumbnail compression (expected 1 or 6): " + compression);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.getReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.findReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void printVersionTable(OutputStream out) {
try {
StringBuffer buffer = new StringBuffer();
List<String> col = modelService.getAllModelVersions();
buffer.append("<table>");
buffer.append("<tr><th>Version</th><th>Workflow Group</th><th>Updated</th></tr>");
for (String aversion : col) {
// now check groups...
List<String> groupList = modelService.getAllWorkflowGroups(aversion);
for (String group : groupList) {
buffer.append("<tr>");
buffer.append("<td>" + aversion + "</td>");
buffer.append("<td><a href=\"./model/" + aversion
+ "/groups/" + group + "\">" + group + "</a></td>");
// get update date...
List<ItemCollection> processList = null;
logger.severe("NOT IMPLEMENTED");
//modelService.getAllModelVersions()
// .getAllProcessEntitiesByGroup(group,
// aversion);
if (processList.size() > 0) {
ItemCollection process = processList.get(0);
Date dat = process.getItemValueDate("$Modified");
SimpleDateFormat formater = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
buffer.append("<td>" + formater.format(dat) + "</td>");
}
buffer.append("</tr>");
}
}
buffer.append("</table>");
out.write(buffer.toString().getBytes());
} catch (Exception e) {
// no opp!
try {
out.write("No model definition found.".getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void printVersionTable(OutputStream out) {
try {
StringBuffer buffer = new StringBuffer();
List<String> modelVersionList = modelService.getAllModelVersions();
buffer.append("<table>");
buffer.append("<tr><th>Version</th><th>Workflow Group</th><th>Uploaded</th></tr>");
for (String modelVersion : modelVersionList) {
Model model=modelService.getModel(modelVersion);
ItemCollection modelEntity=modelService.loadModelEntity(modelVersion);
// now check groups...
List<String> groupList = model.getGroups();
for (String group : groupList) {
buffer.append("<tr>");
buffer.append("<td>" + modelVersion + "</td>");
buffer.append("<td><a href=\"./model/" + modelVersion
+ "/groups/" + group + "\">" + group + "</a></td>");
// print upload date...
if (modelEntity!=null) {
Date dat = modelEntity.getItemValueDate("$Modified");
SimpleDateFormat formater = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
buffer.append("<td>" + formater.format(dat) + "</td>");
} else {
buffer.append("<td> - </td>");
}
buffer.append("</tr>");
}
}
buffer.append("</table>");
out.write(buffer.toString().getBytes());
} catch (Exception e) {
// no opp!
try {
out.write("No model definition found.".getBytes());
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testComplexWorkitem() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/workitem.json");
ItemCollection itemCol = JSONParser.parseWorkitem(inputStream);
Assert.assertNotNull(itemCol);
Assert.assertEquals("worklist", itemCol.getItemValueString("txtworkflowresultmessage"));
Assert.assertEquals("14194929161-1003e42a", itemCol.getItemValueString("$UniqueID"));
List<?> list=itemCol.getItemValue("txtworkflowpluginlog");
Assert.assertEquals(7, list.size());
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testComplexWorkitem() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/workitem.json");
ItemCollection itemCol = null;
try {
itemCol = JSONParser.parseWorkitem(inputStream,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(itemCol);
Assert.assertEquals("worklist", itemCol.getItemValueString("txtworkflowresultmessage"));
Assert.assertEquals("14194929161-1003e42a", itemCol.getItemValueString("$UniqueID"));
List<?> list=itemCol.getItemValue("txtworkflowpluginlog");
Assert.assertEquals(7, list.size());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
//e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
}
#location 41
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
#location 37
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Calendar cal=Calendar.getInstance();
cal.setTime(document.getItemValueDate("_modified"));
Assert.assertEquals(7,cal.get(Calendar.MONTH));
Assert.assertEquals(31,cal.get(Calendar.DAY_OF_MONTH));
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void processWorkList(ItemCollection activityEntity) throws Exception {
// get processID
int iProcessID = activityEntity.getItemValueInteger("numprocessid");
// get Modelversion
String sModelVersion = activityEntity
.getItemValueString("$modelversion");
// if a query is defined in the activityEntity then use the EQL
// statement
// to query the items. Otherwise use standard method
// getWorklistByProcessID()
String sQuery = activityEntity.getItemValueString("txtscheduledview");
// get all workitems...
Collection<ItemCollection> worklist = null;
if (sQuery != null && !"".equals(sQuery)) {
logger.fine("[WorkflowSchedulerService] Query=" + sQuery);
worklist = entityService.findAllEntities(sQuery, 0, -1);
} else {
logger.fine("[WorkflowSchedulerService] get WorkList for ProcessID:"
+ iProcessID);
worklist = workflowService.getWorkListByProcessID(iProcessID, 0,
-1, null, 0);
}
logger.fine("[WorkflowSchedulerService] " + worklist.size()
+ " workitems found");
iScheduledWorkItems += worklist.size();
for (ItemCollection workitem : worklist) {
// verify processID
if (iProcessID == workitem.getItemValueInteger("$processid")) {
// verify modelversion
if (sModelVersion.equals(workitem
.getItemValueString("$modelversion"))) {
// verify due date
if (workItemInDue(workitem, activityEntity)) {
int iActivityID = activityEntity
.getItemValueInteger("numActivityID");
workitem.replaceItemValue("$activityid", iActivityID);
processWorkitem(workitem);
iProcessWorkItems++;
}
}
}
}
}
#location 32
#vulnerability type NULL_DEREFERENCE
|
#fixed code
Timer createTimerOnInterval(ItemCollection configItemCollection) {
// Create an interval timer
Date startDate = configItemCollection.getItemValueDate("datstart");
Date endDate = configItemCollection.getItemValueDate("datstop");
long interval = configItemCollection.getItemValueInteger("numInterval");
// if endDate is in the past we do not start the timer!
Calendar calNow = Calendar.getInstance();
Calendar calEnd = Calendar.getInstance();
if (endDate != null)
calEnd.setTime(endDate);
if (calNow.after(calEnd)) {
logger.warning("[WorkflowSchedulerService] "
+ configItemCollection.getItemValueString("txtName")
+ " stop-date is in the past");
endDate = startDate;
}
Timer timer = timerService.createTimer(startDate, interval,
configItemCollection);
return timer;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int run(ItemCollection adocumentContext, ItemCollection adocumentActivity) throws PluginException {
documentContext = adocumentContext;
// evaluate new items....
ItemCollection evalItemCollection = new ItemCollection();
evalItemCollection=adocumentContext=evaluateWorkflowResult(adocumentActivity,documentContext);
// copy values
documentContext.replaceAllItems(evalItemCollection.getAllItems());
return Plugin.PLUGIN_OK;
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public int run(ItemCollection adocumentContext, ItemCollection adocumentActivity) throws PluginException {
documentContext = adocumentContext;
// evaluate new items....
ItemCollection evalItemCollection = new ItemCollection();
evalItemCollection=adocumentContext=evaluateWorkflowResult(adocumentActivity,documentContext);
// copy values
if (evalItemCollection!=null) {
documentContext.replaceAllItems(evalItemCollection.getAllItems());
}
return Plugin.PLUGIN_OK;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
boolean flushEventLogByCount(int count) {
Date lastEventDate = null;
boolean cacheIsEmpty = true;
IndexWriter indexWriter = null;
long l = System.currentTimeMillis();
logger.finest("......flush eventlog cache....");
List<org.imixs.workflow.engine.jpa.Document> documentList = eventLogService.findEvents(count + 1,
EVENTLOG_TOPIC_ADD, EVENTLOG_TOPIC_REMOVE);
if (documentList != null && documentList.size() > 0) {
try {
indexWriter = createIndexWriter();
int _counter = 0;
for (org.imixs.workflow.engine.jpa.Document eventLogEntry : documentList) {
String topic = null;
String id = eventLogEntry.getId();
// cut prafix...
if (id.startsWith(EVENTLOG_TOPIC_ADD)) {
id = id.substring(EVENTLOG_TOPIC_ADD.length() + 1);
topic = EVENTLOG_TOPIC_ADD;
}
if (id.startsWith(EVENTLOG_TOPIC_REMOVE)) {
id = id.substring(EVENTLOG_TOPIC_REMOVE.length() + 1);
topic = EVENTLOG_TOPIC_REMOVE;
}
// lookup the workitem...
org.imixs.workflow.engine.jpa.Document doc = manager
.find(org.imixs.workflow.engine.jpa.Document.class, id);
Term term = new Term("$uniqueid", id);
// if the document was found we add/update the index. Otherwise we remove the
// document form the index.
if (doc != null && EVENTLOG_TOPIC_ADD.equals(topic)) {
// add workitem to search index....
long l2 = System.currentTimeMillis();
ItemCollection workitem = new ItemCollection();
workitem.setAllItems(doc.getData());
if (!workitem.getItemValueBoolean(DocumentService.NOINDEX)) {
indexWriter.updateDocument(term, createDocument(workitem));
logger.finest("......lucene add/update workitem '" + id + "' to index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
} else {
long l2 = System.currentTimeMillis();
indexWriter.deleteDocuments(term);
logger.finest("......lucene remove workitem '" + id + "' from index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
// remove the eventLogEntry.
lastEventDate = eventLogEntry.getCreated().getTime();
manager.remove(eventLogEntry);
// break?
_counter++;
if (_counter >= count) {
// we skipp the last one if the maximum was reached.
cacheIsEmpty = false;
break;
}
}
} catch (IOException luceneEx) {
logger.warning("...unable to flush lucene event log: " + luceneEx.getMessage());
// We just log a warning here and close the flush mode to no longer block the
// writer.
// NOTE: maybe throwing a IndexException would be an alternative:
//
// throw new IndexException(IndexException.INVALID_INDEX, "Unable to update
// lucene search index",
// luceneEx);
return true;
} finally {
// close writer!
if (indexWriter != null) {
logger.finest("......lucene close IndexWriter...");
try {
indexWriter.close();
} catch (CorruptIndexException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
} catch (IOException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
}
}
}
}
logger.fine("...flushEventLog - " + documentList.size() + " events in " + (System.currentTimeMillis() - l)
+ " ms - last log entry: " + lastEventDate);
return cacheIsEmpty;
}
#location 90
#vulnerability type NULL_DEREFERENCE
|
#fixed code
boolean flushEventLogByCount(int count) {
Date lastEventDate = null;
boolean cacheIsEmpty = true;
IndexWriter indexWriter = null;
long l = System.currentTimeMillis();
logger.finest("......flush eventlog cache....");
List<EventLogEntry> events = eventLogService.findEvents(count + 1,
EVENTLOG_TOPIC_ADD, EVENTLOG_TOPIC_REMOVE);
if (events != null && events.size() > 0) {
try {
indexWriter = createIndexWriter();
int _counter = 0;
for (EventLogEntry eventLogEntry : events) {
Term term = new Term("$uniqueid", eventLogEntry.getUniqueID());
// lookup the Document Entity...
org.imixs.workflow.engine.jpa.Document doc = manager
.find(org.imixs.workflow.engine.jpa.Document.class, eventLogEntry.getUniqueID());
// if the document was found we add/update the index. Otherwise we remove the
// document form the index.
if (doc != null && EVENTLOG_TOPIC_ADD.equals(eventLogEntry.getTopic())) {
// add workitem to search index....
long l2 = System.currentTimeMillis();
ItemCollection workitem = new ItemCollection();
workitem.setAllItems(doc.getData());
if (!workitem.getItemValueBoolean(DocumentService.NOINDEX)) {
indexWriter.updateDocument(term, createDocument(workitem));
logger.finest("......lucene add/update workitem '" + doc.getId() + "' to index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
} else {
long l2 = System.currentTimeMillis();
indexWriter.deleteDocuments(term);
logger.finest("......lucene remove workitem '" + term + "' from index in "
+ (System.currentTimeMillis() - l2) + "ms");
}
// remove the eventLogEntry.
lastEventDate = eventLogEntry.getModified().getTime();
eventLogService.removeEvent(eventLogEntry);
// break?
_counter++;
if (_counter >= count) {
// we skipp the last one if the maximum was reached.
cacheIsEmpty = false;
break;
}
}
} catch (IOException luceneEx) {
logger.warning("...unable to flush lucene event log: " + luceneEx.getMessage());
// We just log a warning here and close the flush mode to no longer block the
// writer.
// NOTE: maybe throwing a IndexException would be an alternative:
//
// throw new IndexException(IndexException.INVALID_INDEX, "Unable to update
// lucene search index",
// luceneEx);
return true;
} finally {
// close writer!
if (indexWriter != null) {
logger.finest("......lucene close IndexWriter...");
try {
indexWriter.close();
} catch (CorruptIndexException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
} catch (IOException e) {
throw new IndexException(IndexException.INVALID_INDEX, "Unable to close lucene IndexWriter: ",
e);
}
}
}
}
logger.fine("...flushEventLog - " + events.size() + " events in " + (System.currentTimeMillis() - l)
+ " ms - last log entry: " + lastEventDate);
return cacheIsEmpty;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 37
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
//e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testComplexPluginException() throws ScriptException {
ItemCollection adocumentContext = new ItemCollection();
ItemCollection adocumentActivity = new ItemCollection();
// 1) invalid returning one messsage
String script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorCode='MY_ERROR';"
+ " var errorMessage='Somehing go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// test excption
Assert.assertEquals("MY_ERROR", e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(1, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
}
// 2) invalid returning 2 messages in an array
script = "var a=1;var b=2;var isValid = (a>b);"
+ " var errorMessage = new Array();"
+ " errorMessage[0]='Somehing go wrong!';"
+ " errorMessage[1]='Somehingelse go wrong!';";
System.out.println("Script=" + script);
adocumentActivity.replaceItemValue("txtBusinessRUle", script);
try {
rulePlugin.run(adocumentContext, adocumentActivity);
Assert.fail();
} catch (PluginException e) {
// e.printStackTrace();
// test exception
Assert.assertEquals(RulePlugin.VALIDATION_ERROR, e.getErrorCode());
Object[] params = e.getErrorParameters();
Assert.assertEquals(2, params.length);
Assert.assertEquals("Somehing go wrong!", params[0].toString());
Assert.assertEquals("Somehingelse go wrong!", params[1].toString());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void removeWorkitem(String uniqueID) throws PluginException {
IndexWriter awriter = null;
Properties prop = propertyService.getProperties();
if (!prop.isEmpty()) {
try {
awriter = createIndexWriter(prop);
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (LockObtainFailedException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (IOException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
}
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void removeWorkitem(String uniqueID) throws PluginException {
IndexWriter awriter = null;
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (LockObtainFailedException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
} catch (IOException e) {
throw new PluginException(LucenePlugin.class.getSimpleName(), INVALID_INDEX,
"Unable to remove workitem '" + uniqueID + "' from search index", e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 73
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void removeDocument(String uniqueID) throws LuceneException {
IndexWriter awriter = null;
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (LockObtainFailedException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void removeDocument(String uniqueID) throws LuceneException {
IndexWriter awriter = null;
long ltime = System.currentTimeMillis();
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (LockObtainFailedException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
}
finally {
// close writer!
if (awriter != null) {
logger.fine("lucene close IndexWriter...");
try {
awriter.close();
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to close lucene IndexWriter: ", e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to close lucene IndexWriter: ", e);
}
}
}
logger.fine("lucene removeDocument in " + (System.currentTimeMillis() - ltime) + " ms");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> 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);
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
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
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.getReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.findReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 36
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 60
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public List<ItemCollection> getActivities() {
if (activityList != null)
return activityList;
activityList = new ArrayList<ItemCollection>();
if (getWorkitem() == null)
return activityList;
int processId = getWorkitem().getItemValueInteger("$processid");
if (processId == 0)
return activityList;
String sversion = getWorkitem().getItemValueString("$modelversion");
// get Workflow-Activities by version if provided by the workitem
List<ItemCollection> col = null;
if (sversion != null && !"".equals(sversion))
col = this.getModelService().getPublicActivities(processId,
sversion);
for (ItemCollection aworkitem : col) {
activityList.add(aworkitem);
}
return activityList;
}
#location 23
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public List<ItemCollection> getActivities() {
if (activityList != null)
return activityList;
activityList = new ArrayList<ItemCollection>();
if (getWorkitem() == null)
return activityList;
int processId = getWorkitem().getItemValueInteger("$processid");
if (processId == 0)
return activityList;
// verify if modelversion is defined by workitem
String sversion = getWorkitem().getItemValueString("$modelversion");
if (sversion == null || "".equals(sversion)) {
try {
// try to get latest version...
sversion = this.getModelService().getLatestVersionByWorkitem(
getWorkitem());
} catch (ModelException e) {
logger.warning("[WorkflwoControler] unable to getactivitylist: "
+ e.getMessage());
}
}
// get Workflow-Activities by version
List<ItemCollection> col = null;
col = this.getModelService().getPublicActivities(processId, sversion);
if (col == null || col.size() == 0) {
// try to upgrade model version
try {
sversion = this.getModelService().getLatestVersionByWorkitem(
getWorkitem());
col = this.getModelService().getPublicActivities(processId,
sversion);
} catch (ModelException e) {
logger.warning("[WorkflwoControler] unable to getactivitylist: "
+ e.getMessage());
}
}
for (ItemCollection aworkitem : col) {
activityList.add(aworkitem);
}
return activityList;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ItemCollection load(String id) {
long lLoadTime = System.currentTimeMillis();
Document persistedDocument = null;
if (id==null || id.isEmpty()) {
return null;
}
persistedDocument = manager.find(Document.class, id);
// create instance of ItemCollection
if (persistedDocument != null && isCallerReader(persistedDocument)) {
ItemCollection result = null;// new ItemCollection();
if (persistedDocument.isPending()) {
// we clone but do not detach
logger.finest("......clone manged entity '" + id + "' pending status=" + persistedDocument.isPending());
result = new ItemCollection(persistedDocument.getData());
} else {
// the document is not managed, so we detach it
result = new ItemCollection();
result.setAllItems(persistedDocument.getData());
manager.detach(persistedDocument);
}
// if disable Optimistic Locking is TRUE we do not add the version
// number
if (disableOptimisticLocking) {
result.removeItem("$Version");
} else {
result.replaceItemValue("$Version", persistedDocument.getVersion());
}
// update the $isauthor flag
result.replaceItemValue("$isauthor", isCallerAuthor(persistedDocument));
// fire event
if (events != null) {
events.fire(new DocumentEvent(result, DocumentEvent.ON_DOCUMENT_LOAD));
} else {
logger.warning("Missing CDI support for Event<DocumentEvent> !");
}
logger.fine(
"...'" + result.getUniqueID() + "' loaded in " + (System.currentTimeMillis() - lLoadTime) + "ms");
return result;
} else
return null;
}
#location 43
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public ItemCollection load(String id) {
long lLoadTime = System.currentTimeMillis();
Document persistedDocument = null;
if (id == null || id.isEmpty()) {
return null;
}
persistedDocument = manager.find(Document.class, id);
// create instance of ItemCollection
if (persistedDocument != null && isCallerReader(persistedDocument)) {
ItemCollection result = null;// new ItemCollection();
if (persistedDocument.isPending()) {
// we clone but do not detach
logger.finest("......clone manged entity '" + id + "' pending status=" + persistedDocument.isPending());
result = new ItemCollection(persistedDocument.getData());
} else {
// the document is not managed, so we detach it
result = new ItemCollection();
result.setAllItems(persistedDocument.getData());
manager.detach(persistedDocument);
}
// if disable Optimistic Locking is TRUE we do not add the version
// number
if (disableOptimisticLocking) {
result.removeItem("$Version");
} else {
result.replaceItemValue("$Version", persistedDocument.getVersion());
}
// update the $isauthor flag
result.replaceItemValue("$isauthor", isCallerAuthor(persistedDocument));
// fire event
if (documentEvents != null) {
documentEvents.fire(new DocumentEvent(result, DocumentEvent.ON_DOCUMENT_LOAD));
} else {
logger.warning("Missing CDI support for Event<DocumentEvent> !");
}
logger.fine(
"...'" + result.getUniqueID() + "' loaded in " + (System.currentTimeMillis() - lLoadTime) + "ms");
return result;
} else
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
#location 36
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Calendar cal=Calendar.getInstance();
cal.setTime(document.getItemValueDate("_modified"));
Assert.assertEquals(7,cal.get(Calendar.MONTH));
Assert.assertEquals(31,cal.get(Calendar.DAY_OF_MONTH));
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
public void replaceAllItems(Map<String, List<Object>> map) {
// make a deep copy of the map
Map<String, List<Object>> clonedMap = (Map<String, List<Object>>) deepCopyOfMap(map);
Iterator<?> it = clonedMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, List<Object>> entry = (Map.Entry<String, List<Object>>) it.next();
replaceItemValue(entry.getKey().toString(), entry.getValue());
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
public void replaceAllItems(Map<String, List<Object>> map) {
if (map == null) {
return;
}
// make a deep copy of the map
Map<String, List<Object>> clonedMap = (Map<String, List<Object>>) deepCopyOfMap(map);
if (clonedMap != null) {
Iterator<?> it = clonedMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, List<Object>> entry = (Map.Entry<String, List<Object>>) it.next();
replaceItemValue(entry.getKey().toString(), entry.getValue());
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@GET
@Path("/{name}.ixr")
public Response getExcecuteReport(@PathParam("name") String name, @DefaultValue("0") @QueryParam("start") int start,
@DefaultValue("10") @QueryParam("count") int count,
@DefaultValue("") @QueryParam("encoding") String encoding, @Context UriInfo uriInfo) {
Collection<ItemCollection> col = null;
String reportName = null;
String sXSL;
String sContentType;
try {
reportName = name + ".ixr";
ItemCollection itemCol = reportService.getReport(reportName);
sXSL = itemCol.getItemValueString("txtXSL").trim();
sContentType = itemCol.getItemValueString("txtcontenttype");
if ("".equals(sContentType))
sContentType = "text/html";
// if no encoding is provided by the query string than the encoding
// from the report will be taken
if ("".equals(encoding))
encoding = itemCol.getItemValueString("txtencoding");
// no encoding defined so take a default encoding
// (UTF-8)
if ("".equals(encoding))
encoding = "UTF-8";
// execute report
Map<String, String> params = getQueryParams(uriInfo);
col = reportService.executeReport(reportName, start, count, params, null);
// if no XSL is provided return standard html format...?
if ("".equals(sXSL)) {
Response.ResponseBuilder builder = Response.ok(XMLItemCollectionAdapter.putCollection(col),
"text/html");
return builder.build();
}
// Transform XML per XSL and generate output
DocumentCollection xmlCol = XMLItemCollectionAdapter.putCollection(col);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(DocumentCollection.class);
Marshaller m = context.createMarshaller();
m.setProperty("jaxb.encoding", encoding);
m.marshal(xmlCol, writer);
// create a ByteArray Output Stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
// test if FOP Tranformation
if ("application/pdf".equals(sContentType.toLowerCase()))
ReportRestService.fopTranformation(writer.toString(), sXSL, encoding, outputStream);
else
ReportRestService.xslTranformation(writer.toString(), sXSL, encoding, outputStream);
} finally {
outputStream.close();
}
/*
* outputStream.toByteArray() did not work here because the encoding
* will not be considered. For that reason we use the
* toString(encoding) method here.
*
* 8.9.2012:
*
* after some tests we see that only toByteArray will work on things
* like fop processing. So for that reason we switched back to the
* toByteArray method again. But we still need to solve the encoding
* issue
*/
Response.ResponseBuilder builder = Response.ok(outputStream.toByteArray(), sContentType);
// Response.ResponseBuilder builder = Response.ok(
// outputStream.toString(encoding), sContentType);
return builder.build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@GET
@Path("/{name}.ixr")
public Response getExcecuteReport(@PathParam("name") String name, @DefaultValue("0") @QueryParam("start") int start,
@DefaultValue("10") @QueryParam("count") int count,
@DefaultValue("") @QueryParam("encoding") String encoding, @Context UriInfo uriInfo) {
Collection<ItemCollection> col = null;
String reportName = null;
String sXSL;
String sContentType;
try {
reportName = name + ".ixr";
ItemCollection itemCol = reportService.getReport(reportName);
if (itemCol==null) {
logger.severe("Report '" +reportName + "' not defined!");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
sXSL = itemCol.getItemValueString("txtXSL").trim();
sContentType = itemCol.getItemValueString("txtcontenttype");
if ("".equals(sContentType))
sContentType = "text/html";
// if no encoding is provided by the query string than the encoding
// from the report will be taken
if ("".equals(encoding))
encoding = itemCol.getItemValueString("txtencoding");
// no encoding defined so take a default encoding
// (UTF-8)
if ("".equals(encoding))
encoding = "UTF-8";
// execute report
Map<String, String> params = getQueryParams(uriInfo);
col = reportService.executeReport(reportName, start, count, params, null);
// if no XSL is provided return standard html format...?
if ("".equals(sXSL)) {
Response.ResponseBuilder builder = Response.ok(XMLItemCollectionAdapter.putCollection(col),
"text/html");
return builder.build();
}
// Transform XML per XSL and generate output
DocumentCollection xmlCol = XMLItemCollectionAdapter.putCollection(col);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(DocumentCollection.class);
Marshaller m = context.createMarshaller();
m.setProperty("jaxb.encoding", encoding);
m.marshal(xmlCol, writer);
// create a ByteArray Output Stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
// test if FOP Tranformation
if ("application/pdf".equals(sContentType.toLowerCase()))
ReportRestService.fopTranformation(writer.toString(), sXSL, encoding, outputStream);
else
ReportRestService.xslTranformation(writer.toString(), sXSL, encoding, outputStream);
} finally {
outputStream.close();
}
/*
* outputStream.toByteArray() did not work here because the encoding
* will not be considered. For that reason we use the
* toString(encoding) method here.
*
* 8.9.2012:
*
* after some tests we see that only toByteArray will work on things
* like fop processing. So for that reason we switched back to the
* toByteArray method again. But we still need to solve the encoding
* issue
*/
Response.ResponseBuilder builder = Response.ok(outputStream.toByteArray(), sContentType);
// Response.ResponseBuilder builder = Response.ok(
// outputStream.toString(encoding), sContentType);
return builder.build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 42
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 66
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 38
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> 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);
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
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
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
}
#location 23
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
if (mailMessage == null) {
logger.warning("[MailPlugin] mailMessage = null");
return Plugin.PLUGIN_WARNING;
}
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putCollection(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putDocuments(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
#location 48
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// test orign ref
Assert.assertEquals(orignUniqueID,subprocess.getItemValueString(SplitAndJoinPlugin.ORIGIN_REF));
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int compare(ItemCollection a, ItemCollection b) {
// date compare?
if (a.isItemValueDate(itemName)) {
Date dateA = a.getItemValueDate(itemName);
Date dateB = b.getItemValueDate(itemName);
int result = dateB.compareTo(dateA);
if (!this.ascending) {
result = -result;
}
return result;
}
// integer compare?
if (a.isItemValueInteger(itemName)) {
int result = a.getItemValueInteger(itemName)
- b.getItemValueInteger(itemName);
if (!this.ascending) {
result = -result;
}
return result;
}
// String compare
int result = this.collator.compare(a.getItemValueString(itemName),
b.getItemValueString(itemName));
if (!this.ascending) {
result = -result;
}
return result;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public int compare(ItemCollection a, ItemCollection b) {
// date compare?
if (a.isItemValueDate(itemName)) {
Date dateA = a.getItemValueDate(itemName);
Date dateB = b.getItemValueDate(itemName);
if (dateA==null && dateB !=null) {
return 1;
}
if (dateB==null && dateA !=null) {
return -1;
}
if (dateB==null && dateA ==null) {
return 0;
}
int result = dateB.compareTo(dateA);
if (!this.ascending) {
result = -result;
}
return result;
}
// integer compare?
if (a.isItemValueInteger(itemName)) {
int result = a.getItemValueInteger(itemName)
- b.getItemValueInteger(itemName);
if (!this.ascending) {
result = -result;
}
return result;
}
// String compare
int result = this.collator.compare(a.getItemValueString(itemName),
b.getItemValueString(itemName));
if (!this.ascending) {
result = -result;
}
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
#location 42
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Calendar cal=Calendar.getInstance();
cal.setTime(document.getItemValueDate("_modified"));
Assert.assertEquals(7,cal.get(Calendar.MONTH));
Assert.assertEquals(31,cal.get(Calendar.DAY_OF_MONTH));
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void readResponse(URLConnection urlConnection) throws IOException {
// get content of result
logger.fine("[RestClient] readResponse....");
StringWriter writer = new StringWriter();
BufferedReader in = null;
try {
// test if content encoding is provided
String sContentEncoding = urlConnection.getContentEncoding();
if (sContentEncoding == null || sContentEncoding.isEmpty()) {
// no so lets see if the client has defined an encoding..
if (encoding != null && !encoding.isEmpty())
sContentEncoding = encoding;
}
// if an encoding is provided read stream with encoding.....
if (sContentEncoding != null && !sContentEncoding.isEmpty())
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), sContentEncoding));
else
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
logger.fine(inputLine);
writer.write(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
in.close();
}
setContent(writer.toString());
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void readResponse(URLConnection urlConnection) throws IOException {
// get content of result
logger.finest("...... readResponse....");
StringWriter writer = new StringWriter();
BufferedReader in = null;
try {
// test if content encoding is provided
String sContentEncoding = urlConnection.getContentEncoding();
if (sContentEncoding == null || sContentEncoding.isEmpty()) {
// no so lets see if the client has defined an encoding..
if (encoding != null && !encoding.isEmpty())
sContentEncoding = encoding;
}
// if an encoding is provided read stream with encoding.....
if (sContentEncoding != null && !sContentEncoding.isEmpty())
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), sContentEncoding));
else
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
logger.finest("......"+inputLine);
writer.write(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
in.close();
}
setContent(writer.toString());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> 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);
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
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
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testSimple() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/simple.json");
ItemCollection itemCol = JSONParser.parseWorkitem(inputStream);
Assert.assertNotNull(itemCol);
Assert.assertEquals("Anna", itemCol.getItemValueString("$readaccess"));
List<?> list=itemCol.getItemValue("txtLog");
Assert.assertEquals(3, list.size());
Assert.assertEquals("C", list.get(2));
Assert.assertEquals(10, itemCol.getItemValueInteger("$ActivityID"));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testSimple() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/simple.json");
ItemCollection itemCol=null;
try {
itemCol = JSONParser.parseWorkitem(inputStream,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(itemCol);
Assert.assertEquals("Anna", itemCol.getItemValueString("$readaccess"));
List<?> list=itemCol.getItemValue("txtLog");
Assert.assertEquals(3, list.size());
Assert.assertEquals("C", list.get(2));
Assert.assertEquals(10, itemCol.getItemValueInteger("$ActivityID"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@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));
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@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));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewChannelEvent(NewChannelEvent event)
{
final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
if (event.getChannel() == null)
{
logger.info("Ignored NewChannelEvent with empty channel name (uniqueId=" + event.getUniqueId() + ")");
}
else
{
addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), event.getAccountCode());
}
}
else
{
// channel had already been created probably by a NewCallerIdEvent
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int[] getVersion(String file) throws ManagerCommunicationException
{
String fileVersion = null;
String[] parts;
int[] intParts;
initializeIfNeeded();
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = sendAction(new CommandAction(SHOW_VERSION_FILES_COMMAND));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = map.get(file);
versions = map;
}
else
{
logger.error("Response to CommandAction(\""
+ SHOW_VERSION_FILES_COMMAND
+ "\") was not a CommandResponse but " + response);
}
}
catch (Exception e)
{
logger.warn("Unable to send '" + SHOW_VERSION_FILES_COMMAND + "' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public int[] getVersion(String file) throws ManagerCommunicationException
{
String fileVersion = null;
String[] parts;
int[] intParts;
initializeIfNeeded();
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
final String command;
if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6))
{
command = SHOW_VERSION_FILES_1_6_COMMAND;
}
else
{
command = SHOW_VERSION_FILES_COMMAND;
}
response = sendAction(new CommandAction(command));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = map.get(file);
versions = map;
}
else
{
logger.error("Response to CommandAction(\""
+ SHOW_VERSION_FILES_COMMAND
+ "\") was not a CommandResponse but " + response);
}
}
catch (Exception e)
{
logger.warn("Unable to send '" + SHOW_VERSION_FILES_COMMAND + "' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum++);
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int[] getVersion(String file)
{
String fileVersion = null;
String[] parts;
int[] intParts;
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = eventConnection.sendAction(new CommandAction(
"show version files"));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = (String) result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = (String) map.get(file);
versions = map;
}
}
catch (Exception e)
{
logger.warn("Unable to send 'show version files' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public int[] getVersion(String file)
{
String fileVersion = null;
String[] parts;
int[] intParts;
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = sendAction(new CommandAction("show version files"));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = (String) result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = (String) map.get(file);
versions = map;
}
}
catch (Exception e)
{
logger.warn("Unable to send 'show version files' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException,
IllegalStateException
{
long start;
long timeSpent;
ResponseHandlerResult result;
ManagerResponseHandler callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultResponseHandler(result, Thread
.currentThread());
sendAction(action, callbackHandler);
start = System.currentTimeMillis();
timeSpent = 0;
while (result.getResponse() == null)
{
try
{
Thread.sleep(timeout - timeSpent);
}
catch (InterruptedException ex)
{
}
// still no response and timed out?
timeSpent = System.currentTimeMillis() - start;
if (result.getResponse() == null && timeSpent > timeout)
{
throw new TimeoutException("Timeout waiting for response to "
+ action.getAction());
}
}
return result.getResponse();
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseHandlerResult result;
ManagerResponseHandler callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultResponseHandler(result);
synchronized (result)
{
sendAction(action, callbackHandler);
try
{
result.wait(timeout);
}
catch (InterruptedException ex)
{
//TODO fix logging
System.err.println("Interrupted!");
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to "
+ action.getAction());
}
return result.getResponse();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 78
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException,
NoSuchChannelException
{
ManagerResponse response;
if (linkedChannel == null)
{
response = server.sendAction(new RedirectAction(name, context, exten, priority));
}
else
{
response = server.sendAction(new RedirectAction(name, linkedChannel.getName(), context, exten, priority,
context, exten, priority));
}
if (response instanceof ManagerError)
{
throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage());
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException,
NoSuchChannelException
{
ManagerResponse response;
if (linkedChannels.isEmpty())
{
response = server.sendAction(new RedirectAction(name, context, exten, priority));
}
else
{
response = server.sendAction(new RedirectAction(name, linkedChannels.get(0).getName(), context, exten, priority,
context, exten, priority));
}
if (response instanceof ManagerError)
{
throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 127
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public AsteriskChannel getLinkedChannel()
{
return linkedChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public AsteriskChannel getLinkedChannel()
{
synchronized(linkedChannels) {
if (linkedChannels.isEmpty()) return null;
return linkedChannels.get(0);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result;
SendActionCallback callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultSendActionCallback(result);
synchronized (result)
{
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.wait(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result = new ResponseHandlerResult();
SendActionCallback callbackHandler = new DefaultSendActionCallback(result);
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.await(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 66
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to readerThread
// After sending the DisconnectThread that thread will die anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override public void shutdown() {
if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) {
try {
eventConnection.logoff();
} catch (Exception ignore) {}
}
if (managerEventListenerProxy != null) {
if (eventConnection != null) {
eventConnection.removeEventListener(managerEventListenerProxy);
}
managerEventListenerProxy.shutdown();
}
if (eventConnection != null && eventListener != null) {
eventConnection.removeEventListener(eventListener);
}
managerEventListenerProxy = null;
eventListener = null;
if (initialized) {//incredible, but it happened
handleDisconnectEvent(null);
}//i
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override public void shutdown() {
if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) {
try {
eventConnection.logoff();
} catch (Exception ignore) {}
}
if (managerEventListenerProxy != null) {
if (eventConnection != null) {
eventConnection.removeEventListener(managerEventListenerProxy);
}
managerEventListenerProxy.shutdown();
}
if (eventConnection != null && eventListener != null) {
eventConnection.removeEventListener(eventListener);
}
managerEventListenerProxy = null;
eventListener = null;
if (initialized) {//incredible, but it happened
handleDisconnectEvent(null);
}//i
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (String name : parameterMap.keySet())
{
List<String> values;
String[] valueArray;
values = parameterMap.get(name);
valueArray = new String[values.size()];
result.put(name, values.toArray(valueArray));
}
return result;
}
#location 72
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (Map.Entry<String, List<String>> entry : parameterMap.entrySet())
{
String[] valueArray;
valueArray = new String[entry.getValue().size()];
result.put(entry.getKey(), entry.getValue().toArray(valueArray));
}
return result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public String getProtocolIdentifier()
{
return protocolIdentifier.value;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public String getProtocolIdentifier()
{
return protocolIdentifier.getValue();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException, NoSuchChannelException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public boolean getPaused()
{
return paused;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public boolean getPaused()
{
return isPaused();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.