input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Override public String readFile(final String path) throws FileNotFoundException { return new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8").useDelimiter("\\Z").next().toString(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String readFile(final String path) throws FileNotFoundException { try (Scanner scanner = new java.util.Scanner(new java.io.File(this.fileBase, path), "UTF-8")) { return scanner.useDelimiter("\\Z").next().toString(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createJarFromClassPathResources(final FileOutputStream fos, final String location) throws IOException { final Manifest m = new Manifest(); m.clear(); final Attributes global = m.getMainAttributes(); if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); } final File mylocation = new File(location); global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); global.putValue(AGENT_CLASS, AGENT_CLASS_NAME); global.putValue(CAN_REDEFINE_CLASSES, "true"); global.putValue(CAN_RETRANSFORM_CLASSES, "true"); global.putValue(CAN_SET_NATIVE_METHOD, "true"); final JarOutputStream jos = new JarOutputStream(fos, m); addClass(Agent.class, jos); addClass(CodeCoverageStore.class, jos); addClass(InvokeReceiver.class, jos); jos.close(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void createJarFromClassPathResources(final FileOutputStream fos, final String location) throws IOException { final Manifest m = new Manifest(); m.clear(); final Attributes global = m.getMainAttributes(); if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) { global.put(Attributes.Name.MANIFEST_VERSION, "1.0"); } final File mylocation = new File(location); global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation)); global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME); global.putValue(AGENT_CLASS, AGENT_CLASS_NAME); global.putValue(CAN_REDEFINE_CLASSES, "true"); global.putValue(CAN_RETRANSFORM_CLASSES, "true"); global.putValue(CAN_SET_NATIVE_METHOD, "true"); try(JarOutputStream jos = new JarOutputStream(fos, m)) { addClass(Agent.class, jos); addClass(CodeCoverageStore.class, jos); addClass(InvokeReceiver.class, jos); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { try { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); final BufferedInputStream stream = new BufferedInputStream( resource.openStream()); final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } stream.close(); return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); try(BufferedInputStream stream = new BufferedInputStream( resource.openStream())) { final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Tokenizer create(Reader reader) { logger.info(seg_type); Seg seg_method=null; if(seg_type.equals("max_word")){ seg_method = new MaxWordSeg(dic); }else if(seg_type.equals("complex")){ seg_method = new ComplexSeg(dic); }else if(seg_type.equals("simple")){ seg_method =new SimpleSeg(dic); } logger.info(seg_method.toString()); return new MMSegTokenizer(seg_method,reader); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Tokenizer create(Reader reader) { Seg seg_method=null; if(seg_type.equals("max_word")){ seg_method = new MaxWordSeg(dic); }else if(seg_type.equals("complex")){ seg_method = new ComplexSeg(dic); }else if(seg_type.equals("simple")){ seg_method =new SimpleSeg(dic); } return new MMSegTokenizer(seg_method,reader); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean register(HttpServletResponse response , String userName , String passWord , String salt) { MiaoshaUser miaoShaUser = new MiaoshaUser(); miaoShaUser.setNickname(userName); String DBPassWord = MD5Utils.formPassToDBPass(passWord , salt); miaoShaUser.setPassword(DBPassWord); miaoShaUser.setRegisterDate(new Date()); miaoShaUser.setSalt(salt); miaoShaUser.setNickname(userName); try { miaoShaUserDao.insertMiaoShaUser(miaoShaUser); MiaoshaUser user = miaoShaUserDao.getById(miaoShaUser.getId()); if(user == null){ return false; } //生成cookie 将session返回游览器 分布式session String token= UUIDUtil.uuid(); addCookie(response, token, user); } catch (Exception e) { logger.error("注册失败",e); return false; } return true; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean register(HttpServletResponse response , String userName , String passWord , String salt) { MiaoshaUser miaoShaUser = new MiaoshaUser(); miaoShaUser.setNickname(userName); String DBPassWord = MD5Utils.formPassToDBPass(passWord , salt); miaoShaUser.setPassword(DBPassWord); miaoShaUser.setRegisterDate(new Date()); miaoShaUser.setSalt(salt); miaoShaUser.setNickname(userName); try { miaoShaUserDao.insertMiaoShaUser(miaoShaUser); MiaoshaUser user = miaoShaUserDao.getById(Long.valueOf(miaoShaUser.getNickname())); if(user == null){ return false; } //生成cookie 将session返回游览器 分布式session String token= UUIDUtil.uuid(); addCookie(response, token, user); } catch (Exception e) { logger.error("注册失败",e); return false; } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); // return entityManagerFactory.createEntityManager(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); // return entityManagerFactory.createEntityManager(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static EntityManager createEntityManager() { init(false); return PersistUtilHelper.getEntityManager(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void setValue(Integer value, boolean fireEvents) { if (value == null) { GWT.log("Value must be null", new RuntimeException()); return; } if (value < getMin()) { GWT.log("Value must not be less than the minimum range value.", new RuntimeException()); return; } if (value > getMax()) { GWT.log("Value must not be greater than the maximum range value", new RuntimeException()); return; } setIntToRangeElement(VALUE, value); super.setValue(value, fireEvents); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void setValue(Integer value, boolean fireEvents) { try { checkRangeValue(value); setIntToRangeElement(VALUE, value); } catch(Exception e) { getLogger().log(Level.SEVERE, e.getMessage()); } super.setValue(value, fireEvents); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (alwaysShowActivator || !isFixed()) { String style = activator.getAttribute("style"); activator.setAttribute("style", style + "; display: block !important"); activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); if (!isFixed()) { String style = activator.getAttribute("style"); if (alwaysShowActivator) { activator.setAttribute("style", style + "; display: block !important"); } else { activator.setAttribute("style", style + "; display: none !important"); } activator.removeClassName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void add(Widget child) { if(child instanceof MaterialImage) { child.getElement().getStyle().setProperty("border", "1px solid #e9e9e9"); child.getElement().getStyle().setProperty("textAlign", "center"); } boolean collapsible = child instanceof MaterialCollapsible; if(collapsible) { // Since the collapsible is separ ((MaterialCollapsible)child).addClearActiveHandler(new ClearActiveHandler() { @Override public void onClearActive(ClearActiveEvent event) { clearActive(); } }); } if(!(child instanceof ListItem)) { // Direct list item not collapsible final ListItem listItem = new ListItem(); if(child instanceof MaterialCollapsible) { listItem.getElement().getStyle().setBackgroundColor("transparent"); } if(child instanceof HasWaves) { listItem.setWaves(((HasWaves) child).getWaves()); ((HasWaves) child).setWaves(null); } listItem.add(child); child = listItem; } // Collapsible's should not be selectable final Widget finalChild = child; if(!collapsible) { // Active click handler finalChild.addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearActive(); finalChild.addStyleName("active"); } }, ClickEvent.getType()); } child.getElement().getStyle().setDisplay(Style.Display.BLOCK); super.add(child); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void add(Widget child) { super.add(wrap(child)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void setValue(Integer value, boolean fireEvents) { if (value == null) { GWT.log("Value must be null", new RuntimeException()); return; } if (value < getMin()) { GWT.log("Value must not be less than the minimum range value.", new RuntimeException()); return; } if (value > getMax()) { GWT.log("Value must not be greater than the maximum range value", new RuntimeException()); return; } setIntToRangeElement(VALUE, value); super.setValue(value, fireEvents); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void setValue(Integer value, boolean fireEvents) { try { checkRangeValue(value); setIntToRangeElement(VALUE, value); } catch(Exception e) { getLogger().log(Level.SEVERE, e.getMessage()); } super.setValue(value, fireEvents); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void applyOverlayType() { setShowOnAttach(false); getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code protected void applyOverlayType() { setShowOnAttach(false); if (overlayOpeningHandler == null) { overlayOpeningHandler = addOpeningHandler(event -> { Scheduler.get().scheduleDeferred(() -> $("#sidenav-overlay").css("visibility", "visible")); }); } $("header").css("paddingLeft", "0px"); $("main").css("paddingLeft", "0px"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = new MaterialWidget(activator); navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } activator.removeClassName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code protected void initialize(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && getType() != SideNavType.FIXED) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException("Could not setup MaterialSideNav please ensure you have MaterialNavBar with an activator setup to match this widgets id."); } } SideNavType type = getType(); processType(type); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off("side-nav-closing"); element.on("side-nav-closing", e1 -> { onClosing(); return true; }); element.off("side-nav-closed"); element.on("side-nav-closed", e1 -> { onClosed(); return true; }); element.off("side-nav-opening"); element.on("side-nav-opening", e1 -> { onOpening(); return true; }); element.off("side-nav-opened"); element.on("side-nav-opened", e1 -> { onOpened(); return true; }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); getNavMenu().setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { getNavMenu().setShowOn(ShowOn.SHOW_ON_LARGE); } else { getNavMenu().setHideOn(HideOn.HIDE_ON_LARGE); } getNavMenu().removeStyleName(CssName.NAVMENU_PERMANENT); } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code protected void load(boolean strict) { try { activator = DOMHelper.getElementByAttribute("data-activates", getId()); MaterialWidget navMenu = getNavMenu(); if (navMenu != null) { navMenu.setShowOn(ShowOn.SHOW_ON_MED_DOWN); if (alwaysShowActivator && !getTypeMixin().getStyle().equals(SideNavType.FIXED.getCssName())) { navMenu.setShowOn(ShowOn.SHOW_ON_LARGE); } else { navMenu.setHideOn(HideOn.HIDE_ON_LARGE); } navMenu.removeStyleName(CssName.NAVMENU_PERMANENT); } } catch (Exception ex) { if (strict) { throw new IllegalArgumentException( "Could not setup MaterialSideNav please ensure you have " + "MaterialNavBar with an activator setup to match this widgets id.", ex); } } setup(); setupDefaultOverlayStyle(); JsSideNavOptions options = new JsSideNavOptions(); options.menuWidth = width; options.edge = edge != null ? edge.getCssName() : null; options.closeOnClick = closeOnClick; JsMaterialElement element = $(activator); element.sideNav(options); element.off(SideNavEvents.SIDE_NAV_CLOSING); element.on(SideNavEvents.SIDE_NAV_CLOSING, e1 -> { onClosing(); return true; }); element.off(SideNavEvents.SIDE_NAV_CLOSED); element.on(SideNavEvents.SIDE_NAV_CLOSED, e1 -> { onClosed(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENING); element.on(SideNavEvents.SIDE_NAV_OPENING, e1 -> { onOpening(); return true; }); element.off(SideNavEvents.SIDE_NAV_OPENED); element.on(SideNavEvents.SIDE_NAV_OPENED, e1 -> { onOpened(); return true; }); element.off(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED); element.on(SideNavEvents.SIDE_NAV_OVERLAY_ATTACHED, e1 -> { onOverlayAttached(); return true; }); $(".collapsible-header").on("click", (e, param1) -> { //e.stopPropagation(); return true; }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void add(Widget child) { if(child instanceof MaterialImage) { child.getElement().getStyle().setProperty("border", "1px solid #e9e9e9"); child.getElement().getStyle().setProperty("textAlign", "center"); } boolean collapsible = child instanceof MaterialCollapsible; if(collapsible) { // Since the collapsible is separ ((MaterialCollapsible)child).addClearActiveHandler(new ClearActiveHandler() { @Override public void onClearActive(ClearActiveEvent event) { clearActive(); } }); } if(!(child instanceof ListItem)) { // Direct list item not collapsible final ListItem listItem = new ListItem(); if(child instanceof MaterialCollapsible) { listItem.getElement().getStyle().setBackgroundColor("transparent"); } if(child instanceof HasWaves) { listItem.setWaves(((HasWaves) child).getWaves()); ((HasWaves) child).setWaves(null); } listItem.add(child); child = listItem; } // Collapsible's should not be selectable final Widget finalChild = child; if(!collapsible) { // Active click handler finalChild.addDomHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { clearActive(); finalChild.addStyleName("active"); } }, ClickEvent.getType()); } child.getElement().getStyle().setDisplay(Style.Display.BLOCK); super.add(child); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void add(Widget child) { super.add(wrap(child)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void doRender(RunTemplate runTemplate, NumbericRenderData numbericData, XWPFTemplate template) throws Exception { NiceXWPFDocument doc = template.getXWPFDocument(); XWPFRun run = runTemplate.getRun(); List<TextRenderData> datas = numbericData.getNumbers(); Style fmtStyle = numbericData.getFmtStyle(); BigInteger numID = doc.addNewNumbericId(numbericData.getNumFmt()); XWPFParagraph paragraph; XWPFRun newRun; for (TextRenderData line : datas) { paragraph = doc.insertNewParagraph(run); paragraph.setNumID(numID); CTP ctp = paragraph.getCTP(); CTPPr pPr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr(); CTParaRPr pr = pPr.isSetRPr() ? pPr.getRPr() : pPr.addNewRPr(); StyleUtils.styleRpr(pr, fmtStyle); newRun = paragraph.createRun(); StyleUtils.styleRun(newRun, line.getStyle()); newRun.setText(line.getText()); } // 成功后清除标签 clearPlaceholder(run); IRunBody parent = run.getParent(); if (parent instanceof XWPFParagraph) { ((XWPFParagraph) parent).removeRun(runTemplate.getRunPos()); // To do: 更好的列表样式 // ((XWPFParagraph) parent).setSpacingBetween(0, // LineSpacingRule.AUTO); } } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void doRender(RunTemplate runTemplate, NumbericRenderData numbericData, XWPFTemplate template) throws Exception { NiceXWPFDocument doc = template.getXWPFDocument(); XWPFRun run = runTemplate.getRun(); List<TextRenderData> datas = numbericData.getNumbers(); Style fmtStyle = numbericData.getFmtStyle(); BigInteger numID = doc.addNewNumbericId(numbericData.getNumFmt()); XWPFParagraph paragraph; XWPFRun newRun; for (TextRenderData line : datas) { paragraph = doc.insertNewParagraph(run); paragraph.setNumID(numID); CTP ctp = paragraph.getCTP(); CTPPr pPr = ctp.isSetPPr() ? ctp.getPPr() : ctp.addNewPPr(); CTParaRPr pr = pPr.isSetRPr() ? pPr.getRPr() : pPr.addNewRPr(); StyleUtils.styleRpr(pr, fmtStyle); newRun = paragraph.createRun(); StyleUtils.styleRun(newRun, line.getStyle()); newRun.setText(line.getText()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeToFile(String path) throws IOException { FileOutputStream out = new FileOutputStream(path); this.write(out); this.close(); out.flush(); out.close(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void writeToFile(String path) throws IOException { FileOutputStream out = null; try { out = new FileOutputStream(path); this.write(out); out.flush(); } finally { PoitlIOUtils.closeQuietlyMulti(this.doc, out); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] getUrlByteArray(String urlPath) { return toByteArray(getUrlPictureStream(urlPath)); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] getUrlByteArray(String urlPath) { try { return toByteArray(getUrlPictureStream(urlPath)); } catch (IOException e) { logger.error("getUrlPictureStream error,{},{}", urlPath, e); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void afterRender(RenderContext context) { XWPFRun run = ((RunTemplate) context.getEleTemplate()).getRun(); clearPlaceholder(context); IRunBody parent = run.getParent(); if (parent instanceof XWPFParagraph) { ((XWPFParagraph) parent).removeRun(((RunTemplate) context.getEleTemplate()).getRunPos()); // To do: 更好的列表样式 // ((XWPFParagraph) parent).setSpacingBetween(0, // LineSpacingRule.AUTO); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void afterRender(RenderContext context) { clearPlaceholder(context, true); // IRunBody parent = run.getParent(); // if (parent instanceof XWPFParagraph) { // ((XWPFParagraph) parent).removeRun(((RunTemplate) context.getEleTemplate()).getRunPos()); // // To do: 更好的列表样式 // // ((XWPFParagraph) parent).setSpacingBetween(0, // // LineSpacingRule.AUTO); // } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(iterableTemplate); Object compute = renderDataCompute.compute(iterableTemplate.getStartMark().getTagName()); int times = conditionTimes(compute); if (TIMES_ONCE == times) { RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(compute); new DocumentProcessor(this.template, dataCompute).process(iterableTemplate.getTemplates()); } else if (TIMES_N == times) { RunTemplate start = iterableTemplate.getStartMark(); RunTemplate end = iterableTemplate.getEndMark(); XWPFRun startRun = start.getRun(); XWPFRun endRun = end.getRun(); XWPFParagraph currentParagraph = (XWPFParagraph) startRun.getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = start.getRunPos(); Integer endRunPos = end.getRunPos(); CTR endCtr = endRun.getCTR(); Iterable<?> model = (Iterable<?>) compute; Iterator<?> iterator = model.iterator(); while (iterator.hasNext()) { // copy position cursor int insertPostionCursor = end.getRunPos(); // copy content List<XWPFRun> runs = currentParagraph.getRuns(); List<XWPFRun> copies = new ArrayList<XWPFRun>(); for (int i = startRunPos + 1; i < endRunPos; i++) { insertPostionCursor = end.getRunPos(); XWPFRun xwpfRun = runs.get(i); XWPFRun insertNewRun = paragraphWrapper.insertNewRun(xwpfRun, insertPostionCursor); XWPFRun xwpfRun2 = paragraphWrapper.createRun(xwpfRun, (IRunBody)currentParagraph); paragraphWrapper.setAndUpdateRun(xwpfRun2, insertNewRun, insertPostionCursor); XmlCursor newCursor = endCtr.newCursor(); newCursor.toPrevSibling(); XmlObject object = newCursor.getObject(); XWPFRun copy = paragraphWrapper.createRun(object, (IRunBody)currentParagraph); copies.add(copy); paragraphWrapper.setAndUpdateRun(copy, xwpfRun2, insertPostionCursor); } // re-parse List<MetaTemplate> templates = template.getResolver().resolveXWPFRuns(copies); // render RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(iterator.next()); new DocumentProcessor(this.template, dataCompute).process(templates); } // clear self iterable template for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } else { XWPFParagraph currentParagraph = (XWPFParagraph) iterableTemplate.getStartRun().getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = iterableTemplate.getStartMark().getRunPos(); Integer endRunPos = iterableTemplate.getEndMark().getRunPos(); for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } bodyContainer.clearPlaceholder(iterableTemplate.getStartRun()); bodyContainer.clearPlaceholder(iterableTemplate.getEndRun()); } #location 65 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); super.visit((IterableTemplate) iterableTemplate); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); BodyContainer bodyContainer = BodyContainerFactory.getBodyContainer(iterableTemplate); Object compute = renderDataCompute.compute(iterableTemplate.getStartMark().getTagName()); int times = conditionTimes(compute); if (TIMES_ONCE == times) { RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(compute); new DocumentProcessor(this.template, dataCompute).process(iterableTemplate.getTemplates()); } else if (TIMES_N == times) { RunTemplate start = iterableTemplate.getStartMark(); RunTemplate end = iterableTemplate.getEndMark(); XWPFRun startRun = start.getRun(); XWPFRun endRun = end.getRun(); XWPFParagraph currentParagraph = (XWPFParagraph) startRun.getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = start.getRunPos(); Integer endRunPos = end.getRunPos(); CTR endCtr = endRun.getCTR(); Iterable<?> model = (Iterable<?>) compute; Iterator<?> iterator = model.iterator(); while (iterator.hasNext()) { // copy position cursor int insertPostionCursor = end.getRunPos(); // copy content List<XWPFRun> runs = currentParagraph.getRuns(); List<XWPFRun> copies = new ArrayList<XWPFRun>(); for (int i = startRunPos + 1; i < endRunPos; i++) { insertPostionCursor = end.getRunPos(); XWPFRun xwpfRun = runs.get(i); XWPFRun insertNewRun = paragraphWrapper.insertNewRun(xwpfRun, insertPostionCursor); XWPFRun xwpfRun2 = paragraphWrapper.createRun(xwpfRun, (IRunBody)currentParagraph); paragraphWrapper.setAndUpdateRun(xwpfRun2, insertNewRun, insertPostionCursor); XmlCursor newCursor = endCtr.newCursor(); newCursor.toPrevSibling(); XmlObject object = newCursor.getObject(); XWPFRun copy = paragraphWrapper.createRun(object, (IRunBody)currentParagraph); copies.add(copy); paragraphWrapper.setAndUpdateRun(copy, xwpfRun2, insertPostionCursor); } // re-parse List<MetaTemplate> templates = template.getResolver().resolveXWPFRuns(copies); // render RenderDataCompute dataCompute = template.getConfig().getRenderDataComputeFactory().newCompute(iterator.next()); new DocumentProcessor(this.template, dataCompute).process(templates); } // clear self iterable template for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } else { XWPFParagraph currentParagraph = (XWPFParagraph) iterableTemplate.getStartRun().getParent(); XWPFParagraphWrapper paragraphWrapper = new XWPFParagraphWrapper(currentParagraph); Integer startRunPos = iterableTemplate.getStartMark().getRunPos(); Integer endRunPos = iterableTemplate.getEndMark().getRunPos(); for (int i = endRunPos - 1; i > startRunPos; i--) { paragraphWrapper.removeRun(i); } } bodyContainer.clearPlaceholder(iterableTemplate.getStartRun()); bodyContainer.clearPlaceholder(iterableTemplate.getEndRun()); } #location 65 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void visit(InlineIterableTemplate iterableTemplate) { logger.info("Process InlineIterableTemplate:{}", iterableTemplate); super.visit((IterableTemplate) iterableTemplate); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { if (null == data) return; XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); // validate combo if (chartSeries.size() >= 2) { long nullCount = data.getSeriesDatas().stream().filter(d -> null == d.getComboType()).count(); if (nullCount > 0) throw new RenderException("Combo chart must set comboType field of series!"); } // hack for poi 4.1.1+: repair seriesCount value, int totalSeriesCount = chartSeries.stream().mapToInt(XDDFChartData::getSeriesCount).sum(); Field field = ReflectionUtils.findField(XDDFChart.class, "seriesCount"); field.setAccessible(true); field.set(chart, totalSeriesCount); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> seriesDatas = null; if (chartSeries.size() <= 1) { // ignore combo type seriesDatas = data.getSeriesDatas(); } else { seriesDatas = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(seriesDatas); int seriesSize = seriesDatas.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < seriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, seriesDatas.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = seriesDatas.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, seriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void doRender(ChartTemplate eleTemplate, ChartMultiSeriesRenderData data, XWPFTemplate template) throws Exception { XWPFChart chart = eleTemplate.getChart(); List<XDDFChartData> chartSeries = chart.getChartSeries(); validate(chartSeries, data); int totalSeriesCount = ensureSeriesCount(chart, chartSeries); int valueCol = 0; List<SeriesRenderData> usedSeriesDatas = new ArrayList<>(); for (XDDFChartData chartData : chartSeries) { int orignSize = chartData.getSeriesCount(); List<SeriesRenderData> currentSeriesData = null; if (chartSeries.size() <= 1) { // ignore combo type currentSeriesData = data.getSeriesDatas(); } else { currentSeriesData = obtainSeriesData(chartData.getClass(), data.getSeriesDatas()); } usedSeriesDatas.addAll(currentSeriesData); int currentSeriesSize = currentSeriesData.size(); XDDFDataSource<?> categoriesData = createCategoryDataSource(chart, data.getCategories()); for (int i = 0; i < currentSeriesSize; i++) { XDDFNumericalDataSource<? extends Number> valuesData = createValueDataSource(chart, currentSeriesData.get(i).getValues(), valueCol); XDDFChartData.Series currentSeries = null; if (i < orignSize) { currentSeries = chartData.getSeries(i); currentSeries.replaceData(categoriesData, valuesData); } else { // add series, should copy series with style currentSeries = chartData.addSeries(categoriesData, valuesData); processNewSeries(chartData, currentSeries); } String name = currentSeriesData.get(i).getName(); currentSeries.setTitle(name, chart.setSheetTitle(name, valueCol + VALUE_START_COL)); valueCol++; } // clear extra series removeExtraSeries(chartData, orignSize, currentSeriesSize); } XSSFSheet sheet = chart.getWorkbook().getSheetAt(0); updateCTTable(sheet, usedSeriesDatas); removeExtraSheetCell(sheet, data.getCategories().length, totalSeriesCount, usedSeriesDatas.size()); for (XDDFChartData chartData : chartSeries) { plot(chart, chartData); } chart.setTitleText(data.getChartTitle()); chart.setTitleOverlay(false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<NiceXWPFDocument> getMergedDocxs(DocxRenderData data, Configure configure) { List<NiceXWPFDocument> docs = new ArrayList<NiceXWPFDocument>(); File docx = data.getDocx(); List<?> dataList = data.getDataList(); if (null == dataList || dataList.isEmpty()) { try { // 待合并的文档不是模板 docs.add(new NiceXWPFDocument(new FileInputStream(docx))); } catch (Exception e) { logger.error("Cannot get the merged docx.", e); } } else { for (int i = 0; i < dataList.size(); i++) { XWPFTemplate temp = XWPFTemplate.compile(docx, configure); temp.render(dataList.get(i)); docs.add(temp.getXWPFDocument()); } } return docs; } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code private List<NiceXWPFDocument> getMergedDocxs(DocxRenderData data, Configure configure) throws IOException { List<NiceXWPFDocument> docs = new ArrayList<NiceXWPFDocument>(); byte[] docx = data.getDocx(); List<?> dataList = data.getDataList(); if (null == dataList || dataList.isEmpty()) { try { // 待合并的文档不是模板 docs.add(new NiceXWPFDocument(new ByteArrayInputStream(docx))); } catch (Exception e) { logger.error("Cannot get the merged docx.", e); } } else { for (int i = 0; i < dataList.size(); i++) { XWPFTemplate temp = XWPFTemplate.compile(new ByteArrayInputStream(docx) , configure); temp.render(dataList.get(i)); docs.add(temp.getXWPFDocument()); } } return docs; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); final byte[] bytes = new byte[(int) response.getEntity().getContentLength()]; new DataInputStream(response.getEntity().getContent()).readFully(bytes); assertThat(new String(bytes, UTF_8), is("Hello, world!")); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void shouldAddHeader() throws IOException { driver.addExpectation(onRequestTo("/") .withHeader("X-Trace-ID", "16c38974-7530-11e5-bb35-10ddb1ee7671") .withHeader("X-Request-ID", "2e7a3324-7530-11e5-ad30-10ddb1ee7671"), giveResponse("Hello, world!", "text/plain")); try (CloseableHttpResponse response = client.execute(new HttpGet(driver.getBaseUrl()))) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat(EntityUtils.toString(response.getEntity()), is("Hello, world!")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void jdk() { Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test void jdk() throws IOException, ScriptException { String script = new String(Files.readAllBytes(new File("../dist/bundle.js").toPath())); ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js"); //js.eval(script); V8 v8 = V8.createV8Runtime(); v8.registerJavaMethod(System.out,"println","print",new Class[]{Object.class}); v8.executeVoidScript("console={log:function(a){print(a);}};setTimeout=function(a){print(a);};clearTimeout=function(a){print(a);};"+ "setInterval=function(a){print(a);};clearInterval=function(a){print(a);};"+script); Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void simple() throws IOException { Graphviz.fromString("graph{a--b}") .scale(2) .filter(new RoughFilter()) .render(Format.PNG) .toFile(new File("target/out.png")); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test void simple() throws IOException { FontTools.availableFontNamesGraph(new File("fonts.png")); final Graph g = graph("ex7").directed() .with( graph().cluster() .nodeAttr().with(Style.FILLED, Color.WHITE) .graphAttr().with(Style.FILLED, Color.LIGHTGREY, Label.of("process #1")) .with(node("a0").link(node("a1").link(node("a2").link(node("a3"))))), graph("x").cluster() .nodeAttr().with(Style.FILLED) .graphAttr().with(Color.BLUE, Label.of("process #2")) .with(node("b0").link(node("b1").link(node("b2").link(node("b3"))))), node("start").with(Shape.mDiamond("", "")).link("a0", "b0"), node("a1").link("b3"), node("b2").link("a3"), node("a3").link("a0"), node("a3").link("end"), node("b3").link("end"), node("end").with(Shape.mSquare("", "")) ); Graphviz.fromGraph(g) // .scale(2) // .filter(new RoughFilter()) .render(Format.PNG) .toFile(new File("target/out.png")); Graphviz.fromGraph(g) // .scale(2) .filter(new RoughFilter().bowing(5).roughness(2).font("*serif","Comic Sans MS")) .render(Format.PNG) .toFile(new File("target/outf.png")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void ex8() throws IOException { //## image Graphviz.useEngine(new GraphvizV8Engine()); Graphviz g = Graphviz.fromGraph(graph() .with(node(" ").with(Size.std().margin(.8, .7), Image.of("graphviz.png")))); g.basedir(new File("example")).render(Format.PNG).toFile(new File("example/ex8.png")); //## image } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test void ex8() throws IOException { //## image Graphviz g = Graphviz.fromGraph(graph() .with(node(" ").with(Size.std().margin(.8, .7), Image.of("graphviz.png")))); g.basedir(new File("example")).render(Format.PNG).toFile(new File("example/ex8.png")); //## image }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void jdk() throws IOException, ScriptException { String script = new String(Files.readAllBytes(new File("../dist/bundle.js").toPath())); ScriptEngine js = new ScriptEngineManager().getEngineByExtension("js"); //js.eval(script); V8 v8 = V8.createV8Runtime(); v8.registerJavaMethod(System.out, "println", "print", new Class[]{Object.class}); v8.executeVoidScript("console={log:function(a){print(a);}};setTimeout=function(a){print(a);};clearTimeout=function(a){print(a);};" + "setInterval=function(a){print(a);};clearInterval=function(a){print(a);};" + script); Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test void jdk() { Graphviz.useEngine(new GraphvizJdkEngine()); assertThat(Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(), startsWith(START1_7)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void cmdLineOutputDotFile() throws IOException, InterruptedException { final File dotFile = setUpFakeDotFile(); final CommandLineExecutor cmdExecutor = setUpFakeStubCommandExecutor(); final String envPath = dotFile.getParent(); final File dotOutputFolder = new File(temp, "out"); dotOutputFolder.mkdir(); final String dotOutputName = "test123"; // Configure engine to output the dotFile to dotOutputFolder final GraphvizCmdLineEngine engine = new GraphvizCmdLineEngine(envPath, cmdExecutor); engine.setDotOutputFile(dotOutputFolder.getAbsolutePath(), dotOutputName); Graphviz.useEngine(engine); // Do execution Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(); assertTrue(new File(dotOutputFolder.getAbsolutePath(), dotOutputName + ".dot").exists()); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test void cmdLineOutputDotFile() throws IOException, InterruptedException { final File dotOutputFolder = new File(temp, "out"); dotOutputFolder.mkdir(); final String dotOutputName = "test123"; // Configure engine to output the dotFile to dotOutputFolder final GraphvizCmdLineEngine engine = new GraphvizCmdLineEngine() .searchPath(setUpFakeDotFile().getParent()) .executor(setUpFakeStubCommandExecutor()); engine.setDotOutputFile(dotOutputFolder.getAbsolutePath(), dotOutputName); Graphviz.useEngine(engine); // Do execution Graphviz.fromString("graph g {a--b}").render(SVG_STANDALONE).toString(); assertTrue(new File(dotOutputFolder.getAbsolutePath(), dotOutputName + ".dot").exists()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void releaseEngine() { if (engine != null) { try { engine.close(); } catch (Exception e) { throw new GraphvizException("Problem closing engine", e); } } engine = null; engineQueue = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void releaseEngine() { synchronized (Graphviz.class) { if (engine != null) { doReleaseEngine(engine); } if (engineQueue != null) { for (final GraphvizEngine engine : engineQueue) { doReleaseEngine(engine); } } } engine = null; engineQueue = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void releaseEngine() { if (engine != null) { try { engine.close(); } catch (Exception e) { throw new GraphvizException("Problem closing engine", e); } } engine = null; engineQueue = null; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void releaseEngine() { synchronized (Graphviz.class) { if (engine != null) { doReleaseEngine(engine); } if (engineQueue != null) { for (final GraphvizEngine engine : engineQueue) { doReleaseEngine(engine); } } } engine = null; engineQueue = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void useDefaultEngines() { useEngine(new GraphvizCmdLineEngine(), new GraphvizV8Engine(), new GraphvizServerEngine(), new GraphvizJdkEngine()); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public static void useDefaultEngines() { useEngine(AVAILABLE_ENGINES); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void start(List<GraphvizEngine> engines) throws IOException { final boolean windows = System.getProperty("os.name").contains("windows"); final String executable = windows ? "java.exe" : "java"; final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static void start(List<GraphvizEngine> engines) throws IOException { final String executable = SystemUtils.executableName("java"); final List<String> cmd = new ArrayList<>(Arrays.asList( System.getProperty("java.home") + "/bin/" + executable, "-cp", System.getProperty("java.class.path"), GraphvizServer.class.getName())); cmd.addAll(engines.stream().map(e -> e.getClass().getName()).collect(toList())); new ProcessBuilder(cmd).inheritIO().start(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 19 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } downloader.setThread(threadNum); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site.toTask()); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Spider thread(int threadNum) { checkIfRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Spider thread(int threadNum) { checkIfRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetHtmlCharset() throws IOException { HttpClientDownloader downloader = new HttpClientDownloader(); Site site = Site.me(); CloseableHttpClient httpClient = new HttpClientGenerator().getClient(site); // encoding in http header Content-Type Request requestGBK = new Request("http://sports.163.com/14/0514/13/9S7986F300051CA1.html#p=9RGQDGGH0AI90005"); CloseableHttpResponse httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestGBK, site, null)); String charset = downloader.getHtmlCharset(httpResponse); assertEquals(charset, "GBK"); // encoding in meta Request requestUTF_8 = new Request("http://preshing.com/"); httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestUTF_8, site, null)); charset = downloader.getHtmlCharset(httpResponse); assertEquals(charset, "utf-8"); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetHtmlCharset() throws Exception { HttpServer server = httpserver(12306); server.get(by(uri("/header"))).response(header("Content-Type", "text/html; charset=gbk")); server.get(by(uri("/meta4"))).response(with(text("<html>\n" + " <head>\n" + " <meta charset='gbk'/>\n" + " </head>\n" + " <body></body>\n" + "</html>")),header("Content-Type","")); server.get(by(uri("/meta5"))).response(with(text("<html>\n" + " <head>\n" + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=gbk\" />\n" + " </head>\n" + " <body></body>\n" + "</html>")),header("Content-Type","")); Runner.running(server, new Runnable() { @Override public void run() { String charset = getCharsetByUrl("http://127.0.0.1:12306/header"); assertEquals(charset, "gbk"); charset = getCharsetByUrl("http://127.0.0.1:12306/meta4"); assertEquals(charset, "gbk"); charset = getCharsetByUrl("http://127.0.0.1:12306/meta5"); assertEquals(charset, "gbk"); } private String getCharsetByUrl(String url) { HttpClientDownloader downloader = new HttpClientDownloader(); Site site = Site.me(); CloseableHttpClient httpClient = new HttpClientGenerator().getClient(site); // encoding in http header Content-Type Request requestGBK = new Request(url); CloseableHttpResponse httpResponse = null; try { httpResponse = httpClient.execute(downloader.getHttpUriRequest(requestGBK, site, null)); } catch (IOException e) { e.printStackTrace(); } String charset = null; try { byte[] contentBytes = IOUtils.toByteArray(httpResponse.getEntity().getContent()); charset = downloader.getHtmlCharset(httpResponse,contentBytes); } catch (IOException e) { e.printStackTrace(); } return charset; } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void checkComponent() { if (downloader == null) { this.downloader = new HttpClientDownloader(); } if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } downloader.setThread(threadNum); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (executorService == null) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 50 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (threadNum <= 1) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); Page page = null; page.getJson().jsonPath("$.name").get(); page.getJson().removePadding("callback").jsonPath("$.name").get(); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testRemovePadding() throws Exception { String name = new Json(text).removePadding("callback").jsonPath("$.name").get(); assertThat(name).isEqualTo("json"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = HttpClientPool.getInstance(poolSize).getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadPool.getThreadAlive() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadPool.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); onSuccess(requestFinal); } catch (Exception e) { onError(requestFinal); logger.error("process request " + requestFinal + " error", e); } finally { if (site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) requestFinal.getExtra(Request.PROXY), (Integer) requestFinal .getExtra(Request.STATUS_CODE)); } pageCount.incrementAndGet(); signalNewUrl(); } } }); } } stat.set(STAT_STOPPED); // release some resources if (destroyWhenExit) { close(); } } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadPool.getThreadAlive() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadPool.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); onSuccess(requestFinal); } catch (Exception e) { onError(requestFinal); logger.error("process request " + requestFinal + " error", e); } finally { pageCount.incrementAndGet(); signalNewUrl(); } } }); } } stat.set(STAT_STOPPED); // release some resources if (destroyWhenExit) { close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 68 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Spider thread(int threadNum) { checkIfNotRunning(); if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (downloader==null || downloader instanceof HttpClientDownloader){ downloader = new HttpClientDownloader(threadNum); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Spider thread(int threadNum) { checkIfNotRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void setThread(int thread) { poolSize = thread; httpClientPool = new HttpClientPool(thread); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void setThread(int thread) { poolSize = thread; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void pushWhenNoDuplicate(Request request, Task task) { if (!inited.get()) { init(task); } queue.add(request); fileUrlWriter.println(request.getUrl()); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void pushWhenNoDuplicate(Request request, Task task) { /* if (!inited.get()) { init(task); }*/ queue.add(request); fileUrlWriter.println(request.getUrl()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void setThread(int thread) { poolSize = thread; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void setThread(int thread) { httpClientGenerator.setPoolSize(thread); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } if (site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) request.getExtra(Request.PROXY), (Integer) request .getExtra(Request.STATUS_CODE)); } } } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (executorService == null) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING) && !stat.compareAndSet(STAT_STOPPED, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } startUrls.clear(); } Request request = scheduler.poll(this); //single thread if (threadNum <= 1) { while (request != null && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { processRequest(request); request = scheduler.poll(this); } } else { synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true && stat.compareAndSet(STAT_RUNNING, STAT_RUNNING)) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code private void readCursorFile() throws IOException { BufferedReader fileCursorReader = null; try { new BufferedReader(new FileReader(getFileName(fileCursor))); String line; //read the last number while ((line = fileCursorReader.readLine()) != null) { cursor = new AtomicInteger(NumberUtils.toInt(line)); } } finally { if (fileCursorReader != null) { IOUtils.closeQuietly(fileCursorReader); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Page handleResponse(Request request, String charset, HttpResponse httpResponse, Task task) throws IOException { String content = IOUtils.toString(httpResponse.getEntity().getContent(), charset); Page page = new Page(); page.setHtml(new Html(UrlUtils.fixAllRelativeHrefs(content, request.getUrl()))); page.setUrl(new PlainText(request.getUrl())); page.setRequest(request); return page; } #location 2 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code protected Page handleResponse(Request request, String charset, HttpResponse httpResponse, Task task) throws IOException { String content = EntityUtils.toString(httpResponse.getEntity(), charset); Page page = new Page(); page.setHtml(new Html(UrlUtils.fixAllRelativeHrefs(content, request.getUrl()))); page.setUrl(new PlainText(request.getUrl())); page.setRequest(request); return page; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int getThreadAlive() { return threadAlive; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public int getThreadAlive() { return threadAlive.get(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); if (pipelines.isEmpty()) { pipelines.add(new ConsolePipeline()); } //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { if (!stat.compareAndSet(STAT_INIT, STAT_RUNNING)) { throw new IllegalStateException("Spider is already running!"); } checkComponent(); if (startUrls != null) { for (String startUrl : startUrls) { scheduler.push(new Request(startUrl), this); } } Request request = scheduler.poll(this); //singel thread if (executorService == null) { while (request != null) { processRequest(request); request = scheduler.poll(this); } } else { //multi thread final AtomicInteger threadAlive = new AtomicInteger(0); while (true) { if (request == null) { //when no request found but some thread is alive, sleep a while. try { Thread.sleep(100); } catch (InterruptedException e) { } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { processRequest(requestFinal); threadAlive.decrementAndGet(); } }); } request = scheduler.poll(this); if (threadAlive.get() == 0) { request = scheduler.poll(this); if (request == null) { break; } } } executorService.shutdown(); } stat.compareAndSet(STAT_RUNNING, STAT_STOPPED); //release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Spider thread(int threadNum) { checkIfNotRunning(); if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (downloader==null || downloader instanceof HttpClientDownloader){ downloader = new HttpClientDownloader(threadNum); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Spider thread(int threadNum) { checkIfNotRunning(); this.threadNum = threadNum; if (threadNum <= 0) { throw new IllegalArgumentException("threadNum should be more than one!"); } if (threadNum == 1) { return this; } synchronized (this) { this.executorService = ThreadUtils.newFixedThreadPool(threadNum); } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpHost proxyHost = null; Proxy proxy = null; //TODO if (site.getHttpProxyPool() != null && site.getHttpProxyPool().isEnable()) { proxy = site.getHttpProxyFromPool(); proxyHost = proxy.getHttpHost(); } else if(site.getHttpProxy()!= null){ proxyHost = site.getHttpProxy(); } HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers, proxyHost);//���������˴��� httpResponse = getHttpClient(site, proxy).execute(httpUriRequest);//getHttpClient�������˴�����֤ statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpHost proxyHost = null; Proxy proxy = null; //TODO if (site.getHttpProxyPool() != null && site.getHttpProxyPool().isEnable()) { proxy = site.getHttpProxyFromPool(); proxyHost = proxy.getHttpHost(); } else if(site.getHttpProxy()!= null){ proxyHost = site.getHttpProxy(); } HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers, proxyHost);//���������˴��� httpResponse = getHttpClient(site, proxy).execute(httpUriRequest);//getHttpClient�������˴�����֤ statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("get page {} error, status code {} ",request.getUrl(),statusCode); return null; } } catch (IOException e) { logger.warn("download page {} error", request.getUrl(), e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); if (site.getHttpProxyPool()!=null && site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) request.getExtra(Request.PROXY), (Integer) request .getExtra(Request.STATUS_CODE)); } try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = WMCollections.newHashSet(200); } logger.info("downloading page {}", request.getUrl()); CloseableHttpResponse httpResponse = null; int statusCode=0; try { HttpHost proxyHost = null; Proxy proxy = null; //TODO if (site.getHttpProxyPool() != null && site.getHttpProxyPool().isEnable()) { proxy = site.getHttpProxyFromPool(); proxyHost = proxy.getHttpHost(); } else if(site.getHttpProxy()!= null){ proxyHost = site.getHttpProxy(); } HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers, proxyHost);//���������˴��� httpResponse = getHttpClient(site, proxy).execute(httpUriRequest);//getHttpClient�������˴�����֤ statusCode = httpResponse.getStatusLine().getStatusCode(); request.putExtra(Request.STATUS_CODE, statusCode); if (statusAccept(acceptStatCode, statusCode)) { Page page = handleResponse(request, charset, httpResponse, task); onSuccess(request); return page; } else { logger.warn("get page {} error, status code {} ",request.getUrl(),statusCode); return null; } } catch (IOException e) { logger.warn("download page {} error", request.getUrl(), e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } onError(request); return null; } finally { request.putExtra(Request.STATUS_CODE, statusCode); if (site.getHttpProxyPool()!=null && site.getHttpProxyPool().isEnable()) { site.returnHttpProxyToPool((HttpHost) request.getExtra(Request.PROXY), (Integer) request .getExtra(Request.STATUS_CODE)); } try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}" , request.getUrl()); RequestBuilder requestBuilder = RequestBuilder.get().setUri(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(site.getTimeOut()) .setSocketTimeout(site.getTimeOut()) .setConnectTimeout(site.getTimeOut()) .setCookieSpec(CookieSpecs.BEST_MATCH); if (site != null && site.getHttpProxy() != null) { requestConfigBuilder.setProxy(site.getHttpProxy()); } requestBuilder.setConfig(requestConfigBuilder.build()); CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(requestBuilder.build()); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page {}" , request.getUrl()); CloseableHttpResponse httpResponse = null; try { HttpUriRequest httpUriRequest = getHttpUriRequest(request, site, headers); httpResponse = getHttpClient(site).execute(httpUriRequest); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusAccept(acceptStatCode, statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { //ensure the connection is released back to pool EntityUtils.consume(httpResponse.getEntity()); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void pushWhenNoDuplicate(Request request, Task task) { if (!inited.get()) { init(task); } if(urls.contains(request.getUrl())) //已存在此URL 表示已抓取过 跳过 return; queue.add(request); fileUrlWriter.println(request.getUrl()); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void pushWhenNoDuplicate(Request request, Task task) { if (!inited.get()) { init(task); } queue.add(request); fileUrlWriter.println(request.getUrl()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added try { newUrlLock.lock(); try { newUrlCondition.await(); } catch (InterruptedException e) { } } finally { newUrlLock.unlock(); } } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void run() { checkRunningStat(); initComponent(); logger.info("Spider " + getUUID() + " started!"); final AtomicInteger threadAlive = new AtomicInteger(0); while (!Thread.currentThread().isInterrupted() && stat.get() == STAT_RUNNING) { Request request = scheduler.poll(this); if (request == null) { if (threadAlive.get() == 0 && exitWhenComplete) { break; } // wait until new url added waitNewUrl(); } else { final Request requestFinal = request; threadAlive.incrementAndGet(); executorService.execute(new Runnable() { @Override public void run() { try { processRequest(requestFinal); } catch (Exception e) { logger.error("download " + requestFinal + " error", e); } finally { threadAlive.decrementAndGet(); signalNewUrl(); } } }); } } executorService.shutdown(); stat.set(STAT_STOPPED); // release some resources destroy(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } int retryTimes = 0; Set<Integer> acceptStatCode; String charset = null; Map<String,String> headers = null; if (site != null) { retryTimes = site.getRetryTimes(); acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpClient httpClient = getHttpClientPool().getClient(site); try { HttpGet httpGet = new HttpGet(request.getUrl()); if (headers!=null){ for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(),headerEntry.getValue()); } } if (!httpGet.containsHeader("Accept-Encoding")) { httpGet.addHeader("Accept-Encoding", "gzip"); } HttpResponse httpResponse = null; int tried = 0; boolean retry; do { try { httpResponse = httpClient.execute(httpGet); retry = false; } catch (IOException e) { tried++; if (tried > retryTimes) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { Page page = new Page(); Object cycleTriedTimesObject = request.getExtra(Request.CYCLE_TRIED_TIMES); if (cycleTriedTimesObject == null) { page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } else { int cycleTriedTimes = (Integer) cycleTriedTimesObject; cycleTriedTimes++; if (cycleTriedTimes >= site.getCycleRetryTimes()) { return null; } page.addTargetRequest(request.setPriority(0).putExtra(Request.CYCLE_TRIED_TIMES, 1)); } return page; } return null; } logger.info("download page " + request.getUrl() + " error, retry the " + tried + " time!"); retry = true; } } while (retry); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { handleGzip(httpResponse); //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); } } catch (Exception e) { logger.warn("download page " + request.getUrl() + " error", e); } return null; } #location 38 #vulnerability type INTERFACE_NOT_THREAD_SAFE
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = new HashSet<Integer>(); acceptStatCode.add(200); } logger.info("downloading page " + request.getUrl()); HttpGet httpGet = new HttpGet(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { httpGet.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(httpGet); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Ignore @Test public void testCookie() { Site site = Site.me().setDomain("www.diandian.com").addCookie("t", "yct7q7e6v319wpg4cpxqduu5m77lcgix"); HttpClientDownloader httpClientDownloader = new HttpClientDownloader(); Page download = httpClientDownloader.download(new Request("http://www.diandian.com"), site.toTask()); Assert.assertTrue(download.getHtml().toString().contains("flashsword30")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page " + request.getUrl()); RequestBuilder requestBuilder = RequestBuilder.get().setUri(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(site.getTimeOut()) .setConnectTimeout(site.getTimeOut()) .setCookieSpec(CookieSpecs.BEST_MATCH); if (site.getHttpProxy() != null) { requestConfigBuilder.setProxy(site.getHttpProxy()); } requestBuilder.setConfig(requestConfigBuilder.build()); CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(requestBuilder.build()); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } } #location 34 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public Page download(Request request, Task task) { Site site = null; if (task != null) { site = task.getSite(); } Set<Integer> acceptStatCode; String charset = null; Map<String, String> headers = null; if (site != null) { acceptStatCode = site.getAcceptStatCode(); charset = site.getCharset(); headers = site.getHeaders(); } else { acceptStatCode = Sets.newHashSet(200); } logger.info("downloading page " + request.getUrl()); RequestBuilder requestBuilder = RequestBuilder.get().setUri(request.getUrl()); if (headers != null) { for (Map.Entry<String, String> headerEntry : headers.entrySet()) { requestBuilder.addHeader(headerEntry.getKey(), headerEntry.getValue()); } } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom() .setConnectionRequestTimeout(site.getTimeOut()) .setConnectTimeout(site.getTimeOut()) .setCookieSpec(CookieSpecs.BEST_MATCH); if (site != null && site.getHttpProxy() != null) { requestConfigBuilder.setProxy(site.getHttpProxy()); } requestBuilder.setConfig(requestConfigBuilder.build()); CloseableHttpResponse httpResponse = null; try { httpResponse = getHttpClient(site).execute(requestBuilder.build()); int statusCode = httpResponse.getStatusLine().getStatusCode(); if (acceptStatCode.contains(statusCode)) { //charset if (charset == null) { String value = httpResponse.getEntity().getContentType().getValue(); charset = UrlUtils.getCharset(value); } return handleResponse(request, charset, httpResponse, task); } else { logger.warn("code error " + statusCode + "\t" + request.getUrl()); return null; } } catch (IOException e) { logger.warn("download page " + request.getUrl() + " error", e); if (site.getCycleRetryTimes() > 0) { return addToCycleRetry(request, site); } return null; } finally { try { if (httpResponse != null) { httpResponse.close(); } } catch (IOException e) { logger.warn("close response fail", e); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processRequest(Request request) { Page page = downloader.download(request, this); if (page == null) { sleep(site.getSleepTime()); onError(request); } // for cycle retry if (page.isNeedCycleRetry()) { extractAndAddRequests(page, true); sleep(site.getSleepTime()); return; } pageProcessor.process(page); extractAndAddRequests(page, spawnUrl); if (!page.getResultItems().isSkip()) { for (Pipeline pipeline : pipelines) { pipeline.process(page.getResultItems(), this); } } sleep(site.getSleepTime()); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code protected void processRequest(Request request) { Page page = downloader.download(request, this); if (page == null) { sleep(site.getSleepTime()); onError(request); return; } // for cycle retry if (page.isNeedCycleRetry()) { extractAndAddRequests(page, true); sleep(site.getSleepTime()); return; } pageProcessor.process(page); extractAndAddRequests(page, spawnUrl); if (!page.getResultItems().isSkip()) { for (Pipeline pipeline : pipelines) { pipeline.process(page.getResultItems(), this); } } sleep(site.getSleepTime()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { ReentrantLock lock = queueLock; Object p = current; E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } exhausted = ((current = p) == null); if (e != null) { action.accept(e); return true; } } return false; } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { E e = null; ReentrantLock lock = queueLock; lock.lock(); try { Object p; if ((p = current) != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); exhausted = ((current = p) == null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) { action.accept(e); return true; } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int i, hi; // hoist accesses and checks from loop Vector<E> lst = list; Object[] a; if ((hi = fence) < 0) { synchronized (lst) { expectedModCount = getModCount(lst); a = array = getData(lst); hi = fence = getSize(lst); } } else { a = array; } if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) { action.accept((E) a[i++]); } if (expectedModCount == getModCount(lst)) { return; } } throw new ConcurrentModificationException(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int hi = getFence(); Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) { action.accept((E) a[i]); } if (getModCount(list) != expectedModCount) { throw new ConcurrentModificationException(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int i, hi; // hoist accesses and checks from loop Vector<E> lst = list; Object[] a; if ((hi = fence) < 0) { synchronized (lst) { expectedModCount = getModCount(lst); a = array = getData(lst); hi = fence = getSize(lst); } } else { a = array; } if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) { action.accept((E) a[i++]); } if (expectedModCount == getModCount(lst)) { return; } } throw new ConcurrentModificationException(); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int hi = getFence(); Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) { action.accept((E) a[i]); } if (getModCount(list) != expectedModCount) { throw new ConcurrentModificationException(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; if (!exhausted) { E e = null; lock.lock(); try { if (current == null) { current = getQueueFirst(q); } while (current != null) { e = getNodeItem(current); current = getNextNode(current); if (e != null) { break; } } } finally { lock.unlock(); } if (current == null) { exhausted = true; } if (e != null) { action.accept(e); return true; } } return false; } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (exhausted) return false; LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; Object p = current; E e = null; lock.lock(); try { if ((p != null && p != getNextNode(p)) || (p = getQueueFirst(q)) != null) { e = getNodeItem(p); p = getNextNode(p); } } finally { lock.unlock(); } exhausted = ((current = p) == null); if (e == null) return false; action.accept(e); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { ReentrantLock lock = queueLock; Object p = current; E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } exhausted = ((current = p) == null); if (e != null) { action.accept(e); return true; } } return false; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { E e = null; ReentrantLock lock = queueLock; lock.lock(); try { Object p; if ((p = current) != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); exhausted = ((current = p) == null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) { action.accept(e); return true; } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int i, hi; // hoist accesses and checks from loop Vector<E> lst = list; Object[] a; if ((hi = fence) < 0) { synchronized (lst) { expectedModCount = getModCount(lst); a = array = getData(lst); hi = fence = getSize(lst); } } else { a = array; } if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) { action.accept((E) a[i++]); } if (expectedModCount == getModCount(lst)) { return; } } throw new ConcurrentModificationException(); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int hi = getFence(); Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) { action.accept((E) a[i]); } if (getModCount(list) != expectedModCount) { throw new ConcurrentModificationException(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; ReentrantLock lock = queueLock; Object p = current; current = null; do { E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) action.accept(e); } while (p != null); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; Object p = current; current = null; forEachFrom(action, p); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; ReentrantLock lock = queueLock; Object p = current; current = null; do { E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) action.accept(e); } while (p != null); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; Object p = current; current = null; forEachFrom(action, p); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; ReentrantLock lock = queueLock; Object p = current; current = null; do { E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) action.accept(e); } while (p != null); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; Object p = current; current = null; forEachFrom(action, p); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int i, hi; // hoist accesses and checks from loop Vector<E> lst = list; Object[] a; if ((hi = fence) < 0) { synchronized (lst) { expectedModCount = getModCount(lst); a = array = getData(lst); hi = fence = getSize(lst); } } else { a = array; } if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) { action.accept((E) a[i++]); } if (expectedModCount == getModCount(lst)) { return; } } throw new ConcurrentModificationException(); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); int hi = getFence(); Object[] a = array; int i; for (i = index, index = hi; i < hi; i++) { action.accept((E) a[i]); } if (getModCount(list) != expectedModCount) { throw new ConcurrentModificationException(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; ReentrantLock lock = queueLock; Object p = current; current = null; do { E e = null; lock.lock(); try { if (p != null || (p = getQueueFirst(queue)) != null) do { e = getNodeItem(p); p = succ(p); } while (e == null && p != null); } finally { // checkInvariants(); lock.unlock(); } if (e != null) action.accept(e); } while (p != null); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); if (!exhausted) { exhausted = true; Object p = current; current = null; forEachFrom(action, p); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; if (!exhausted) { E e = null; lock.lock(); try { if (current == null) { current = getQueueFirst(q); } while (current != null) { e = getNodeItem(current); current = getNextNode(current); if (e != null) { break; } } } finally { lock.unlock(); } if (current == null) { exhausted = true; } if (e != null) { action.accept(e); return true; } } return false; } #location 24 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean tryAdvance(Consumer<? super E> action) { Objects.requireNonNull(action); if (exhausted) return false; LinkedBlockingDeque<E> q = queue; ReentrantLock lock = queueLock; Object p = current; E e = null; lock.lock(); try { if ((p != null && p != getNextNode(p)) || (p = getQueueFirst(q)) != null) { e = getNodeItem(p); p = getNextNode(p); } } finally { lock.unlock(); } exhausted = ((current = p) == null); if (e == null) return false; action.accept(e); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } return result; } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { String[] strings = line.trim().split("\\s+"); if (strings.length < 1) { continue; } int pid = Integer.parseInt(strings[0]); if (pid == currentPid) { continue; } if (strings.length >= 2 && strings[1].equals("Jps")) { // skip jps continue; } result.put(pid, line); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader, new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { process.write(new String(cbuf, off, len)); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } } #location 51 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); File jps = findJps(); if (jps == null) { return result; } String[] command = null; if (v) { command = new String[] { jps.getAbsolutePath(), "-v" }; } else { command = new String[] { jps.getAbsolutePath() }; } ProcessBuilder pb = new ProcessBuilder(command); try { Process proc = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); // read the output from the command String line = null; int currentPid = Integer.parseInt(ProcessUtils.getPid()); while ((line = stdInput.readLine()) != null) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } } catch (Throwable e) { // ignore } return result; } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static List<String> listNames(File dir) { List<String> names = new ArrayList<String>(); for (File file : dir.listFiles()) { String name = file.getName(); if (name.startsWith(".") || file.isFile()) { continue; } names.add(name); } return names; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private static List<String> listNames(File dir) { List<String> names = new ArrayList<String>(); if (!dir.exists()) { return names; } File[] files = dir.listFiles(); if (files == null) { return names; } for (File file : files) { String name = file.getName(); if (name.startsWith(".") || file.isFile()) { continue; } names.add(name); } return names; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader, new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { process.write(new String(cbuf, off, len)); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } } #location 68 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void process(final CommandProcess process) { int exitCode = 0; RowAffect affect = new RowAffect(); try { Instrumentation inst = process.session().getInstrumentation(); ClassLoader classloader = null; if (hashCode == null) { classloader = ClassLoader.getSystemClassLoader(); } else { classloader = ClassLoaderUtils.getClassLoader(inst, hashCode); if (classloader == null) { process.write("Can not find classloader with hashCode: " + hashCode + ".\n"); exitCode = -1; return; } } DynamicCompiler dynamicCompiler = new DynamicCompiler(classloader); Charset charset = Charset.defaultCharset(); if (encoding != null) { charset = Charset.forName(encoding); } for (String sourceFile : sourcefiles) { String sourceCode = FileUtils.readFileToString(new File(sourceFile), charset); String name = new File(sourceFile).getName(); if (name.endsWith(".java")) { name = name.substring(0, name.length() - ".java".length()); } dynamicCompiler.addSource(name, sourceCode); } Map<String, byte[]> byteCodes = dynamicCompiler.buildByteCodes(); File outputDir = null; if (this.directory != null) { outputDir = new File(this.directory); } else { outputDir = new File("").getAbsoluteFile(); } process.write("Memory compiler output:\n"); for (Entry<String, byte[]> entry : byteCodes.entrySet()) { File byteCodeFile = new File(outputDir, entry.getKey().replace('.', '/') + ".class"); FileUtils.writeByteArrayToFile(byteCodeFile, entry.getValue()); process.write(byteCodeFile.getAbsolutePath() + '\n'); affect.rCnt(1); } } catch (Throwable e) { logger.warn("Memory compiler error", e); process.write("Memory compiler error, exception message: " + e.getMessage() + ", please check $HOME/logs/arthas/arthas.log for more details. \n"); exitCode = -1; } finally { process.write(affect + "\n"); process.end(exitCode); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); File jps = findJps(); if (jps == null) { return result; } String[] command = null; if (v) { command = new String[] { jps.getAbsolutePath(), "-v" }; } else { command = new String[] { jps.getAbsolutePath() }; } ProcessBuilder pb = new ProcessBuilder(command); try { Process proc = pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); // read the output from the command String line = null; int currentPid = Integer.parseInt(ProcessUtils.getPid()); while ((line = stdInput.readLine()) != null) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } } catch (Throwable e) { // ignore } return result; } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code private static Map<Integer, String> listProcessByJps(boolean v) { Map<Integer, String> result = new LinkedHashMap<Integer, String>(); String jps = "jps"; File jpsFile = findJps(); if (jpsFile != null) { jps = jpsFile.getAbsolutePath(); } String[] command = null; if (v) { command = new String[] { jps, "-v" }; } else { command = new String[] { jps }; } List<String> lines = ExecutingCommand.runNative(command); int currentPid = Integer.parseInt(ProcessUtils.getPid()); for (String line : lines) { int pid = new Scanner(line).nextInt(); if (pid == currentPid) { continue; } result.put(pid, line); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExplicitevaluate() { ExpressionFlipStrategy efs = new ExpressionFlipStrategy(); Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), null)); Assert.assertTrue(efs.evaluate("TOTO", ff4j.getStore(), null)); FlippingExecutionContext fex = new FlippingExecutionContext(); fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "D"); Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), fex)); fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "TOTO"); Assert.assertFalse(efs.evaluate("D", ff4j.getStore(), fex)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testExplicitevaluate() { ExpressionFlipStrategy efs = new ExpressionFlipStrategy(); Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), null)); Assert.assertTrue(efs.evaluate("TOTO", ff4j.getStore(), null)); FlippingExecutionContext fex = new FlippingExecutionContext(); fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "D"); Assert.assertTrue(efs.evaluate("D", ff4j.getStore(), fex)); fex.putString(ExpressionFlipStrategy.PARAM_EXPRESSION, "TOTO"); Assert.assertFalse(efs.evaluate("D", ff4j.getStore(), fex)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void write(String content, File output) throws IOException { FileOutputStream out = new FileOutputStream(output); OutputStreamWriter w = new OutputStreamWriter(out); try { w.write(content); w.flush(); } finally { out.close(); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static void write(String content, File output) throws IOException { try (final FileOutputStream out = new FileOutputStream(output); final OutputStreamWriter w = new OutputStreamWriter(out)) { w.write(content); w.flush(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void removeExecutable(Distribution distribution, File executable) { FileWithCounter fileWithCounter; synchronized (_lock) { fileWithCounter = _distributionFiles.get(distribution); } fileWithCounter.free(executable); //_delegate.removeExecutable(executable); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void removeExecutable(Distribution distribution, File executable) { FileWithCounter fileWithCounter; synchronized (_lock) { fileWithCounter = _distributionFiles.get(distribution); } if (fileWithCounter!=null) { fileWithCounter.free(executable); } else { _logger.warning("Allready removed "+executable+" for "+distribution+", emergency shutdown?"); } }
Below is the vulnerable code, please generate the patch based on the following information.