output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code @Test public void testInitArgsForUserNameAndPasswordWithSpaces() { try { final DatabaseConnection[] databaseConnection = new DatabaseConnection[1]; new MockUp<sqlline.DatabaseConnections>() { @Mock public void setConnection(DatabaseConnection c...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInitArgsForUserNameAndPasswordWithSpaces() { try { final SqlLine sqlLine = new SqlLine(); final DatabaseConnection[] databaseConnection = new DatabaseConnection[1]; new MockUp<sqlline.DatabaseConnections>() { @Mock ...
#fixed code @Test public void testConnectWithDbPropertyAsParameter() { try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { SqlLine.Status status = begin(sqlLine, os, false, "-e", "!set maxwidth 80"); assertThat(status, equalTo(SqlLine.Status.OK)); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConnectWithDbPropertyAsParameter() { SqlLine beeLine = new SqlLine(); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { SqlLine.Status status = begin(beeLine, os, false, "-e", "!set maxwidth 80"); assertTh...
#fixed code @Test public void testGetDeclaredFields() throws Exception { String javaVersion = System.getProperty("java.specification.version"); if (javaVersion.startsWith("9") || javaVersion.startsWith("10")) { assertThat(ReflectionUtils.getDeclaredFields(...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetDeclaredFields() throws Exception { if (System.getProperty("java.specification.version").startsWith("9")) { assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22); } else { assertThat(...
#fixed code @Test public void testJPopulatorFactoryBeanWithCustomRandomizers() { Populator populator = getPopulatorFromSpringContext("/application-context-with-custom-randomizers.xml"); // the populator managed by spring should be correctly configured assert...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testJPopulatorFactoryBeanWithCustomRandomizers() { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/application-context-with-custom-randomizers.xml"); Populator populator = (Populator) a...
#fixed code @Test public void testScriptString() throws Exception { File file = tmpDir.newFile(); String line = "hello world"; executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w << '" + ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testScriptString() throws Exception { File file = tmpDir.newFile(); String line = "hello world"; executeMojo.scripts = new String[] { "new File('" + file.getAbsolutePath().replaceAll("\\\\", "/") + "').withWriter { w -> w <<...
#fixed code public void execute() throws MojoExecutionException, MojoFailureException { logGroovyVersion("execute"); try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); //...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void execute() throws MojoExecutionException, MojoFailureException { logGroovyVersion("execute"); try { // get classes we need with reflection Class<?> groovyShellClass = Class.forName("groovy.lang.GroovyShell"); ...
#fixed code CppGenerator(String name, ArrayList<JFile> ilist, ArrayList<JRecord> rlist, File outputDirectory) { this.outputDirectory = outputDirectory; mName = (new File(name)).getName(); mInclFiles = ilist; mRecList = rlist; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void genCode() throws IOException { outputDirectory.mkdirs(); FileWriter cc = new FileWriter(new File(outputDirectory, mName+".cc")); FileWriter hh = new FileWriter(new File(outputDirectory, mName+".hh")); hh.write("#ifndef __"+mName.toUp...
#fixed code public static void getTraceMask(String host, int port) { Socket s = null; try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void getTraceMask(String host, int port) { try { byte[] reqBytes = new byte[12]; ByteBuffer req = ByteBuffer.wrap(reqBytes); req.putInt(ByteBuffer.wrap("gtmk".getBytes()).getInt()); Socket s = null; ...
#fixed code private KeyValuePair rdbLoadObject(int rdbtype) throws IOException { switch (rdbtype) { /* * | <content> | * | string contents | */ case RDB_TYPE_STRING: KeyStringValueStr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private KeyValuePair rdbLoadObject(int rdbtype) throws IOException { switch (rdbtype) { /* * | <content> | * | string contents | */ case REDIS_RDB_TYPE_STRING: KeySt...
#fixed code @Test public void test() throws Exception { String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj"; ByteArray bytes = new ByteArray(str.getBytes().length, 10); byte[] b1 = str.getBytes(); int i = 0; for (byte b : b1) { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() throws Exception { String str = "sdajkl;jlqwjqejqweq89080c中jlxczksaouwq9823djadj"; ByteArray bytes = new ByteArray(str.getBytes().length, 10); byte[] b1 = str.getBytes(); int i = 0; for (byte b : b1) ...
#fixed code @Test public void testSync() throws Exception { //socket RedisSocketReplicator replicator = new RedisSocketReplicator("127.0.0.1", 6379, Configuration.defaultSetting().setAuthPassword("test")); replicator.addRdbListener(new RdbListener.Adaptor() { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSync() throws Exception { //socket RedisReplicator replicator = new RedisReplicator("127.0.0.1", 6379, Configuration.defaultSetting()); replicator.open(); } #location 5 ...
#fixed code public static void main(String[] args) throws IOException, URISyntaxException { final OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("/path/to/dump.rdb"))); final RawByteListener rawByteListener = new RawByteListener() { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { final FileOutputStream out = new FileOutputStream(new File("./src/test/resources/dump.rdb")); final RawByteListener rawByteListener = new RawByteListener() { @Override p...
#fixed code @Override public void open() throws IOException { try { doOpen(); } finally { close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void open() throws IOException { for (int i = 0; i < configuration.getRetries() || configuration.getRetries() <= 0; i++) { try { connect(); if (configuration.getAuthPassword() != null) auth(config...
#fixed code @Test public void testFileV6() throws IOException, InterruptedException { Replicator redisReplicator = new RedisReplicator( RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"), FileType.RDB, Configurat...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFileV6() throws IOException, InterruptedException { Replicator redisReplicator = new RedisReplicator( RedisSocketReplicatorTest.class.getClassLoader().getResourceAsStream("dumpV6.rdb"), Configuration.defa...
#fixed code public DuplicateResult findDuplicates(State state) { DuplicateResult result = new DuplicateResult(parameters); List<FileState> fileStates = new ArrayList<>(state.getFileStates()); Collections.sort(fileStates, hashComparator); List<FileState> duplicatedFiles = new Arra...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public DuplicateResult findDuplicates(State state) { DuplicateResult result = new DuplicateResult(parameters); List<FileState> fileStates = new ArrayList<>(state.getFileStates()); Collections.sort(fileStates, fullHashComparator); FileHash previousHash = new File...
#fixed code public CompareResult displayChanges() { if (lastState != null) { System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); if (lastState.getComment().length() > 0) { System.out.println("Comment: " + lastState....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public CompareResult displayChanges() { if (lastState != null) { System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); if (lastState.getComment().length() > 0) { System.out.println("Comment: " + last...
#fixed code public CompareResult displayChanges() { if (lastState != null) { System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); if (lastState.getComment().length() > 0) { System.out.println("Comment: " + lastState....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public CompareResult displayChanges() { if (lastState != null) { System.out.printf("Comparing with the last committed state from %s%n", formatDate(lastState.getTimestamp())); if (lastState.getComment().length() > 0) { System.out.println("Comment: " + last...
#fixed code private Object loadContent(){ Object[] shape = getShape(); Object descr = getDescr(); byte[] data = (byte[])getData(); if(descr instanceof DType){ DType dType = (DType)descr; descr = dType.toDescr(); } try { InputStream is = new ByteArrayInputStream(data)...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Object loadContent(){ Object[] shape = getShape(); Object descr = getDescr(); byte[] data = (byte[])getData(); try { InputStream is = new ByteArrayInputStream(data); try { return NDArrayUtil.parseData(is, descr, shape); } finally { is.clo...
#fixed code @Override public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){ List<?> data = getData(); ClassDictUtil.checkSize(1, ids, features); final InvalidValueTreatmentMethod invalidValueTreatment = DomainUtil.parseInvalidValue...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<Feature> encodeFeatures(List<String> ids, List<Feature> features, SkLearnEncoder encoder){ List<?> data = getData(); if(ids.size() != 1 || features.size() != 1){ throw new IllegalArgumentException(); } final InvalidValueTreatmentMethod...
#fixed code static public List<?> getContent(NDArray array, String key){ Map<String, ?> content = (Map<String, ?>)array.getContent(); return asJavaList(array, (List<?>)content.get(key)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static public List<?> getContent(NDArray array, String key){ Map<String, ?> data = (Map<String, ?>)array.getContent(); return asJavaList(array, (List<?>)data.get(key)); } #location 5 #vulnerability type NULL_...
#fixed code static public List<?> getArray(ClassDict dict, String name){ Object object = dict.get(name); if(object instanceof HasArray){ HasArray hasArray = (HasArray)object; return hasArray.getArrayContent(); } // End if if(object instanceof Number){ return Collections...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static public List<?> getArray(ClassDict dict, String name){ Object object = unwrap(dict.get(name)); if(object instanceof NDArray){ NDArray array = (NDArray)object; return NDArrayUtil.getContent(array); } else if(object instanceof CSRMatrix){ CSRMatrix...
#fixed code @Test public void test1() { long l = System.currentTimeMillis() / 1000; LocalDateTime localDateTime = DateUtil.fromTimeStamp(l); System.out.print(DateUtil.localDateTimeFormatyMdHms(localDateTime)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test1() { long l = System.currentTimeMillis() / 1000; LocalDateTime localDateTime = DateUtil.fromTimeStamp(l); System.out.printf(DateUtil.localDateTimeFormatyMdHms(localDateTime)); } #locatio...
#fixed code @ApiMethod(name = "processSignResponse") public List<String> processSignResponse( @Named("responseData") String responseData, User user) throws OAuthRequestException, ResponseException { if (user == null) { throw new OAuthRequestException("User is not au...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @ApiMethod(name = "processSignResponse") public List<String> processSignResponse( @Named("responseData") String responseData, User user) throws OAuthRequestException, ResponseException { if (user == null) { throw new OAuthRequestException("User is ...
#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.getC...
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(...
#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.findE...
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>...
#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 =...
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 is...
#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 Plug...
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);...
#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 Asser...
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 ...
#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" + " \"_\":\"156...
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" + " \"_\"...
#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) { currentWorkf...
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) { curren...
#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) { Asse...
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) { ...
#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(10...
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().getEv...
#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 ...
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 -> THUR...
#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 ov...
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 * process...
#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()); ...
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())...
#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("D...
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.de...
#fixed code ChannelManager(AsteriskServerImpl server) { this.server = server; }
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 (...
#fixed code public boolean getPaused() { return isPaused(); }
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 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 ...
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("orig...
#fixed code public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR"); System.out.println("默认使用TessOCR,选择后回车,不能为空"); String...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("请选择您要使用的文字识别方式\n1.TessOCR\n2.百度OCR"); System.out.println("默认使用TessOCR,选择后回车"); OCR o...
#fixed code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection(); con.setReadTimeout(60000); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection(); con.setReadTimeout(60000); con.setConnect...
#fixed code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { getReference(ViewScopeManager.class).preDestroyView(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView(); } } #location 4 ...
#fixed code @SuppressWarnings("unchecked") public static <T> void destroy(BeanManager beanManager, T instance) { if (instance instanceof Class) { // Java prefers T over Class<T> when varargs is not specified :( destroy(beanManager, (Class<T>) instance, new Annotation[0]); } else {...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") public static <T> void destroy(BeanManager beanManager, T instance) { if (instance instanceof Class) { destroy(beanManager, (Class<T>) instance, new Annotation[0]); } else if (instance instanceof Bean) { destroy(beanManager, (Bea...
#fixed code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); EagerBeansRepository.getInstance().instantiateApplicationScoped(); FacesViews.addMappings(event.getServletContext()); CacheInitializer.loadProviderAndRegisterFilter(event.getServl...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); BeanManager.INSTANCE.getReference(EagerBeansRepository.class).instantiateApplicationScoped(); FacesViews.addMappings(event.getServletContext()); CacheInitializer.loadProvide...
#fixed code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channel = getChannel(); if (channel =...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channel = getChannel(); if (cha...
#fixed code public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) throws IOException { BufferedWriter svmDataFile = null; try { FileWriter fstream = new FileWriter(filePath); svmDataFile = new BufferedWriter...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) { try { FileWriter fstream = new FileWriter(filePath); BufferedWriter svmDataFile = new BufferedWriter(fstream); for (TrainingEl...
#fixed code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } ...
#fixed code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRootA, 1...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRo...
#fixed code public Template include(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Template include(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = ...
#fixed code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) ...
#fixed code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So constructor par...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @CheckForNull @Override public CNode describe(T instance) throws Exception { // Here we assume a correctly designed DataBound Object will have required attributes set by DataBoundConstructor // and all others using DataBoundSetters. So construct...
#fixed code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recover() { final List<MmapFile> mappedFiles = this.dataFileQueue.getMappedFiles(); if (mappedFiles.isEmpty()) { this.indexFileQueue.updateWherePosition(0); this.indexFileQueue.truncateDirtyFiles(0); return...
#fixed code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLeaderId...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public DLegerEntry get(Long index) { PreConditions.check(index <= legerEndIndex && index >= legerBeginIndex, DLegerException.Code.INDEX_OUT_OF_RANGE, String.format("%d should between %d-%d", index, legerBeginIndex, legerEndIndex), memberState.getLe...
#fixed code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) { zipFile.close(); return...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] loadJarData(String path, String fileName) { ZipFile zipFile; ZipEntry entry; int size; try { zipFile = new ZipFile(new File(path)); entry = zipFile.getEntry(fileName); if (entry == null) return null; size = (int) ent...
#fixed code @Test public void testConstructor2() { NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE); assertEquals(MSG, e.getMessage()); assertEquals(PROCESSOR, e.getOffendingProcessor()); assertEquals(THROWABLE, e.getCause()); e.printStackTrace(); // ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConstructor2() { NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE); assertEquals(CONCATENATED_MSG, e.getMessage()); assertEquals(PROCESSOR, e.getOffendingProcessor()); assertEquals(THROWABLE, e.getCause()); e.printSta...
#fixed code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weight(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws IOException { Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() { @Nullable @Override public Integer apply(@Nullable LookupResult input) { return input.weig...
#fixed code private Set<T> aggregateSet() { if (areAllInitial(changeNotifiers)) { return ChangeNotifiers.initialEmptyDataInstance(); } ImmutableSet.Builder<T> records = ImmutableSet.builder(); for (final ChangeNotifier<T> changeNotifier : changeNotifiers) { rec...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Set<T> aggregateSet() { ImmutableSet.Builder<T> records = ImmutableSet.builder(); for (final ChangeNotifier<T> changeNotifier : changeNotifiers) { records.addAll(changeNotifier.current()); } return records.build(); } ...
#fixed code @Override public void addConfigListener(String dataId, ConfigChangeListener listener) { configListenersMap.putIfAbsent(dataId, new ArrayList<>()); configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>()); ConfigChangeNotifier configChangeNot...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void addConfigListener(String dataId, ConfigChangeListener listener) { configListenersMap.putIfAbsent(dataId, new ArrayList<>()); configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>()); ConfigChangeNotifier configCha...
#fixed code public static void main(String[] args) { ProtocolV1Client client = new ProtocolV1Client(); client.connect("127.0.0.1", 8811, 500); Map<String, String> head = new HashMap<>(); head.put("tracerId", "xxadadadada"); head.put("token", "adad...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException { ProtocolV1Client client = new ProtocolV1Client(); client.connect("127.0.0.1", 8811, 500); Map<String, String> head = new HashMap<>(); ...
#fixed code @Test @SuppressWarnings("unchecked") public void integrationTest() throws Exception { String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR; JobReport jobReport = aNewJob() .rea...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @SuppressWarnings("unchecked") public void integrationTest() throws Exception { String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR; JobReport jobReport = aNewJob() ...
#fixed code @Override public String validateRecord(Record record) { String error = super.validateRecord(record); if (error == null){//no errors after applying declared validators on each field => all fields are valid //add custom validation : field 2 con...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String validateRecord(Record record) { String error = super.validateRecord(record); if (error.length() == 0){//no errors after applying declared validators on each field => all fields are valid //add custom validation :...
#fixed code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().crea...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBzip2Unarchive() throws Exception { final File output = new File(dir, "test-entpackt.txt"); System.out.println(dir); final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile()); final InputStream is = new File...
#fixed code public void testCBZip2InputStreamClose() throws Exception { final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" ); final File outputFile = getOutputFile( ".tar.bz2" ); final OutputStream output = new FileOutputStream( outputFi...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCBZip2InputStreamClose() throws Exception { final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" ); final File outputFile = getOutputFile( ".tar.bz2" ); final OutputStream output = new FileOutputStream( ou...
#fixed code protected File createArchive(String archivename) throws Exception { ArchiveOutputStream out = null; OutputStream stream = null; try { archive = File.createTempFile("test", "." + archivename); archiveList = new ArrayList(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected File createArchive(String archivename) throws Exception { ArchiveOutputStream out = null; OutputStream stream = null; try { archive = File.createTempFile("test", "." + archivename); stream = new FileOutputStream...
#fixed code public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes(); assertEquals(bytes.length, 99); final Fi...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testTarArchiveLongNameCreation() throws Exception { String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml"; byte[] bytes = name.getBytes(); assertEquals(bytes.length, 99); fi...
#fixed code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory().crea...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBzip2Unarchive() throws Exception { final File input = getFile("bla.txt.bz2"); final File output = new File(dir, "bla.txt"); final InputStream is = new FileInputStream(input); final CompressorInputStream in = new CompressorStreamFactory(...
#fixed code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputSt...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCpioUnarchive() throws Exception { final File output = new File(dir, "bla.cpio"); { final File file1 = getFile("test1.xml"); final File file2 = getFile("test2.xml"); final OutputStream out = new FileOutputStream(output); final Arch...
#fixed code @PreAuthorize("hasPermission(#user, 'edit')") @Validated(BaseUser.UpdateValidation.class) @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public U updateUser(U user, @Valid U updatedUser) { SaUtil.validate(user != null, "userNotFound"); SaUtil.validate...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @PreAuthorize("hasPermission(#user, 'edit')") @Validated(BaseUser.UpdateValidation.class) @Transactional(propagation=Propagation.REQUIRED, readOnly=false) public U updateUser(U user, @Valid U updatedUser) { SaUtil.validate(user != null, "userNotFound"); user.setN...
#fixed code @Nullable public String extendPath(@NotNull String name) { if (name.endsWith(".py")) { name = Util.moduleNameFor(name); } if (path.equals("")) { return name; } String sep; switch (scopeType) { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Nullable public String extendPath(@NotNull String name) { if (name.endsWith(".py")) { name = Util.moduleNameFor(name); } if (path.equals("")) { return name; } String sep; switch (scopeType) { ...
#fixed code @NotNull public List<Entry> generate(@NotNull Scope scope, @NotNull String path) { List<Entry> result = new ArrayList<Entry>(); Set<Binding> entries = new TreeSet<Binding>(); for (Binding b : scope.values()) { if (!b.isSynthetic() ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @NotNull public List<Entry> generate(@NotNull Scope scope, @NotNull String path) { List<Entry> result = new ArrayList<Entry>(); Set<Binding> entries = new TreeSet<Binding>(); for (Binding b : scope.values()) { if (!b.isSynthetic(...
#fixed code public int compareTo(@NotNull Object o) { return getSingle().getStart() - ((Binding)o).getSingle().getStart(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int compareTo(@NotNull Object o) { return getFirstNode().getStart() - ((Binding)o).getFirstNode().getStart(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code boolean checkBindingExist(List<Binding> bs, String file, int start, int end) { if (bs == null) { return false; } for (Binding b : bs) { if (((b.getFile() == null && file == null) || (b.getFile() != null && f...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean checkBindingExist(List<Binding> bs, String name, String file, int start) { if (bs == null) { return false; } for (Binding b : bs) { String actualFile = b.getFile(); if (b.getName().equals(name) && ...
#fixed code @Test public void authEnabled() throws IOException { greenMail.getManagers().getUserManager().setAuthRequired(true); withConnection((printStream, reader) -> { assertThat(reader.readLine()).startsWith("+OK POP3 GreenMail Server v"); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void authEnabled() throws IOException, UserException { try (Socket socket = new Socket(hostAddress, port)) { assertThat(socket.isConnected()).isTrue(); PrintStream printStream = new PrintStream(socket.getOutputStream()); ...
#fixed code @Override public List<FileDto> queryFiles(@RequestBody FileDto fileDto) { //return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class); List<FileDto> fileDtos = new ArrayList<>(); Strin...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<FileDto> queryFiles(@RequestBody FileDto fileDto) { //return BeanConvertUtil.covertBeanList(fileServiceDaoImpl.getFiles(BeanConvertUtil.beanCovertMap(fileDto)), FileDto.class); List<FileDto> fileDtos = new ArrayList<>(); ...
#fixed code @Override protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) { //JSONObject outParam = null; ResponseEntity<String> responseEntity = null; Map<String, String> reqHeader = context.getRequestHeaders()...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) { JSONObject outParam = null; ResponseEntity<String> responseEntity = null; Map<String, String> reqHeader = context.getRequestHeade...
#fixed code private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException { final URLClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, fil...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Class<?>> loadClasses(StandardJavaFileManager fileManager, File classOutputFolder, List<JavaFile> classFiles) throws ClassNotFoundException, MalformedURLException { final ClassLoader loader = new URLClassLoader(new URL[] {classOutputFolder.toURI().toURL()}, ...
#fixed code public Object call(String method, Object[] params) throws XMLRPCException { return new Caller().call(method, params); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object call(String method, Object[] params) throws XMLRPCException { try { Call c = createCall(method, params); URLConnection conn = this.url.openConnection(); if(!(conn instanceof HttpURLConnection)) { throw new IllegalArgumentException("The UR...
#fixed code public int run() throws Throwable { ClassLoader jenkins = createJenkinsWarClassLoader(); ClassLoader setup = createSetupClassLoader(jenkins); Thread.currentThread().setContextClassLoader(setup); // or should this be 'jenkins'? Class<?> c =...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int run() throws Throwable { ClassLoader jenkins = createJenkinsWarClassLoader(); ClassLoader setup = createSetupClassLoader(jenkins); Class<?> c = setup.loadClass("io.jenkins.jenkinsfile.runner.App"); return (int)c.getMethod("run...
#fixed code public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter String description, @QueryParameter int executors, @QueryParameter String remoteFsRoot, @QueryParameter ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doCreateSlave(StaplerRequest req, StaplerResponse rsp, @QueryParameter String name, @QueryParameter String description, @QueryParameter int executors, @QueryParameter String remoteFsRoot, @QueryPara...
#fixed code private Node getNodeByName(String name, StaplerResponse rsp) throws IOException { Jenkins jenkins = Jenkins.get(); try { Node n = jenkins.getNode(name); if (n == null) { rsp.setStatus(SC_NOT_FOUND); rsp...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Node getNodeByName(String name, StaplerResponse rsp) throws IOException { Jenkins jenkins = Jenkins.getInstance(); try { Node n = jenkins.getNode(name); if (n == null) { rsp.setStatus(SC_NOT_FOUND); ...
#fixed code @Test public void testDeploymentFailure() throws Exception { final long start = System.currentTimeMillis(); assertThat(testResult(TempJobFailureTestImpl.class), hasSingleFailureContaining("AssertionError: Unexpected job state")); final long end = S...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDeploymentFailure() throws Exception { final long start = System.currentTimeMillis(); assertThat(testResult(TempJobFailureTestImpl.class), hasSingleFailureContaining("AssertionError: Unexpected job state")); final long e...
#fixed code @Override protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, Interr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, ...
#fixed code @Override protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, Interr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected int runWithJobId(final Namespace options, final HeliosClient client, final PrintStream out, final boolean json, final JobId jobId, final BufferedReader stdin) throws ExecutionException, ...
#fixed code private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id, final CountDownLatch zkRegistrationSignal) { ACLProvider aclProvider = null; List<AuthInfo> authorization = null; if (config.isZoo...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ZooKeeperClient setupZookeeperClient(final AgentConfig config, final String id, final CountDownLatch zkRegistrationSignal) { ACLProvider aclProvider = null; List<AuthInfo> authorization = null; if (config...
#fixed code @Override public HttpRequest withBody() throws IOException { body = ByteStreams.toByteArray(super.getInputStream()); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpRequest withBody() throws IOException { body = ByteStreams.toByteArray(getInputStream()); return this; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public PaginationDTO list(Integer page, Integer size) { PaginationDTO paginationDTO = new PaginationDTO(); Integer totalPage; Integer totalCount = questionMapper.count(); if (totalCount % size == 0) { totalPage = totalCount / si...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public PaginationDTO list(Integer page, Integer size) { PaginationDTO paginationDTO = new PaginationDTO(); Integer totalCount = questionMapper.count(); paginationDTO.setPagination(totalCount, page, size); if (page < 1) { pa...
#fixed code public Index read() throws IOException { if(version == -1) { readVersion(); } IndexReaderImpl reader = getReader(input, version); if (reader == null) { input.close(); throw new UnsupportedVersion("Version: " ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Index read() throws IOException { PackedDataInputStream stream = new PackedDataInputStream(new BufferedInputStream(input)); if (stream.readInt() != MAGIC) { stream.close(); throw new IllegalArgumentException("Not a jandex i...
#fixed code public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance(); // ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] { n...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { WikipediaApiInterface wikiAPI = SingletonWikipediaApi.getInstance(); ExperimentTaskConfiguration taskConfigs[] = new ExperimentTaskConfiguration[] ...
#fixed code public void handleReference(Reference<?> ref) { poolLock.lock(); try { if (ref instanceof BasicPoolEntryRef) { // check if the GCed pool entry was still in use //@@@ find a way to detect this without lookup ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleReference(Reference<?> ref) { poolLock.lock(); try { if (ref instanceof BasicPoolEntryRef) { // check if the GCed pool entry was still in use //@@@ find a way to detect this without lookup ...
#fixed code public void shutdown() { this.isShutDown = true; synchronized (this) { try { if (uniquePoolEntry != null) // and connection open? uniquePoolEntry.shutdown(); } catch (IOException iox) { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void shutdown() { this.isShutDown = true; ConnAdapter conn = managedConn; if (conn != null) conn.detach(); synchronized (this) { try { if (uniquePoolEntry != null) // and connection open? ...
#fixed code @Test public void testReleaseConnectionWithTimeLimits() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final HttpRou...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReleaseConnectionWithTimeLimits() throws Exception { final PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(); mgr.setMaxTotal(1); final HttpHost target = getServerHttp(); final H...
#fixed code public void disconnect(int reason, String msg) throws IOException { Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT); buffer.putInt(reason); buffer.putString(msg); buffer.putString(""); WriteFuture f = writePacket(b...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void disconnect(int reason, String msg) throws IOException { Buffer buffer = createBuffer(SshConstants.Message.SSH_MSG_DISCONNECT); buffer.putInt(reason); buffer.putString(msg); buffer.putString(""); WriteFuture f = writePa...
#fixed code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.setException(new SshException(msg)); this....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleOpenFailure(Buffer buffer) { int reason = buffer.getInt(); String msg = buffer.getString(); synchronized (lock) { this.openFailureReason = reason; this.openFailureMsg = msg; this.openFuture.se...
#fixed code protected void doHandleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doHandleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(...
#fixed code protected void doHandleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void doHandleMessage(Buffer buffer) throws Exception { SshConstants.Message cmd = buffer.getCommand(); log.debug("Received packet {}", cmd); switch (cmd) { case SSH_MSG_DISCONNECT: { int code = buffer.getInt(...
#fixed code public OutputStream createOutputStream(final long offset) throws IOException { // permission check if (!isWritable()) { throw new IOException("No write permission : " + file.getName()); } // move to the appropriate off...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public OutputStream createOutputStream(final long offset) throws IOException { // permission check if (!isWritable()) { throw new IOException("No write permission : " + file.getName()); } // create output stream ...
#fixed code public void handleEof() throws IOException { log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id); eof = true; notifyStateChanged(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleEof() throws IOException { log.debug("Received SSH_MSG_CHANNEL_EOF on channel {}", id); synchronized (lock) { eof = true; lock.notifyAll(); } } #location 2 ...
#fixed code public void check(int maxFree) throws IOException { synchronized (lock) { if ((size < maxFree) && (maxFree - size > packetSize * 3 || size < maxFree / 2)) { if (log.isDebugEnabled()) { log.debug("Increase " + name + " by...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(int maxFree) throws IOException { int threshold = Math.min(packetSize * 8, maxSize / 4); synchronized (lock) { if ((maxFree - size) > packetSize && (maxFree - size > threshold || size < threshold)) { if (log....
#fixed code public void handleClose() throws IOException { log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id); closedByOtherSide = !closing.get(); if (closedByOtherSide) { close(false); } else { close(false).setClosed(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleClose() throws IOException { log.debug("Received SSH_MSG_CHANNEL_CLOSE on channel {}", id); synchronized (lock) { closedByOtherSide = !closing; if (closedByOtherSide) { close(false); }...
#fixed code @Test public void freemarkerEngineTest() { // 字符串模板 TemplateEngine engine = TemplateUtil.createEngine( new TemplateConfig("templates", ResourceMode.STRING).setCustomEngine(FreemarkerEngine.class)); Template template = engine.getTemplate("hello,${name}"); String resu...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void freemarkerEngineTest() { // 字符串模板 TemplateEngine engine = new FreemarkerEngine(new TemplateConfig("templates", ResourceMode.STRING)); Template template = engine.getTemplate("hello,${name}"); String result = template.render(Dict.create().set("name...