auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public ContractInput toContractInput() { final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput(); contractInput.setName(field.getName()); contractInput.setType(toContractInputType()); <START> contractInput.setMultiple(field.isCollection()); <END> contractInput.setMandatory(!field.isNullable()); return contractInput; }</code><technical_language>Becarefull field.isCollection() null (here a Boolean a boolean, handle null case (with a default value)</technical_language>

Target:
public ContractInput toContractInput() { final ContractInput contractInput = ProcessFactory.eINSTANCE.createContractInput(); contractInput.setName(field.getName()); contractInput.setType(toContractInputType()); setMultiple(contractInput); setMandatory(contractInput); return contractInput; }
Source:
<code>private void handleNewFile(final String fileName) { <START> mHandler.postDelayed( <END> new Runnable() { @Override public void run() { mInstantUploadsHandler.handleNewFile(fileName, mConfiguration, mContext); } }, HANDLE_DELAY_IN_MS ); }</code><technical_language>it, thank for explanation</technical_language>

Target:
private void handleNewFile(final String fileName) { mInstantUploadsHandler.handleNewFile(fileName, mConfiguration, mContext); }
Source:
<code>protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { ArrayList<String> pathStrings = new ArrayList<>(); for (Path path : srcs) { pathStrings.add(path.toString()); } if (pathStrings.size() > 0) { ImmutableList.Builder<String> commandBuilder = ImmutableList.<String>builder() .addAll(compilerCommandPrefix) .add("-p", packageName.toString()) .add("-pack") .add("-trimpath", workingDirectory.toString()) .add("-nolocalimports") .addAll(flags) .add("-o", output.toString()); for (Path dir : includeDirectories) { commandBuilder.add("-I", dir.toString()); } <START> for (Map.Entry<Path, Path> importMap : importPathMap.entrySet()) { <END> commandBuilder.add("-importmap", importMap.getKey() + "=" + importMap.getValue()); } if (asmHeaderPath.isPresent()) { commandBuilder.add("-asmhdr", asmHeaderPath.get().toString()); } if (!allowExternalReferences) { commandBuilder.add("-complete"); } commandBuilder.addAll(pathStrings); return commandBuilder.build(); } else { return ImmutableList.of("echo", "No source files found in " + workingDirectory); } }</code><technical_language>rename importMap reflects purpose of this object? a map</technical_language>

Target:
protected ImmutableList<String> getShellCommandInternal(ExecutionContext context) { ArrayList<String> pathStrings = new ArrayList<>(); for (Path path : srcs) { pathStrings.add(path.toString()); } if (pathStrings.size() > 0) { ImmutableList.Builder<String> commandBuilder = ImmutableList.<String>builder() .addAll(compilerCommandPrefix) .add("-p", packageName.toString()) .add("-pack") .add("-trimpath", workingDirectory.toString()) .add("-nolocalimports") .addAll(flags) .add("-o", output.toString()); for (Path dir : includeDirectories) { commandBuilder.add("-I", dir.toString()); } for (Map.Entry<Path, Path> entry : importPathMap.entrySet()) { commandBuilder.add("-importmap", entry.getKey() + "=" + entry.getValue()); } if (asmHeaderPath.isPresent()) { commandBuilder.add("-asmhdr", asmHeaderPath.get().toString()); } if (!allowExternalReferences) { commandBuilder.add("-complete"); } commandBuilder.addAll(pathStrings); return commandBuilder.build(); } else { LOG.warn("No source files found in " + workingDirectory); return ImmutableList.of(); } }
Source:
<code>public void store(String key, Object value) { LOGGER.trace("Entering: store - key: {}", key); try (OutputStream file = new FileOutputStream(getMapStoreFilePath(key).toFile()); OutputStream buffer = new BufferedOutputStream(file); ObjectOutput output = new ObjectOutputStream(buffer)) { <START> LOGGER.debug("file name: {}/{}{}", persistencePath, key, SER); <END> output.writeObject(value); } catch (IOException e) { LOGGER.debug("IOException storing value in cache with key = " + key, e); } LOGGER.trace("Exiting: store"); }</code><technical_language>EXTENSION EXT instead of SER</technical_language>

Target:
public void store(String key, Object value) { LOGGER.trace("Entering: store - key: {}", key); try (ObjectOutput output = new ObjectOutputStream( new BufferedOutputStream(new FileOutputStream(getMapStoreFile(key))))) { LOGGER.debug("file name: {}/{}{}", persistencePath, key, EXT); output.writeObject(value); } catch (IOException e) { LOGGER.debug("IOException storing value in cache with key = " + key, e); } LOGGER.trace("Exiting: store"); }
Source:
<code>public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if (Display.getDefault().getFocusControl() == null || (event.stateMask & SWT.BUTTON_MASK) != 0 || (event.stateMask & SWT.KEY_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); <START> for (Control child : fTipViewer.getChildren()) { child.dispose(); } <END> fToolTipContent.append("<body><table>"); fill(control, event, pt); fToolTipContent.append("</table></body>"); String html = fToolTipContent.toString(); if (elementCount == 0) { return; } fTipViewer.setText(html); fTipShell.setLayout(new FillLayout()); fTipShell.setSize(Math.min(longestString * 12, 440), Math.min(500, elementCount * 22 + 24)); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fFocusLostListener); } }); }</code><technical_language>necessary, Browser children</technical_language>

Target:
public void activateHoverHelp(final Control control) { control.addMouseTrackListener(new MouseTrackAdapter() { @Override public void mouseHover(MouseEvent event) { if (Display.getDefault().getFocusControl() == null || (event.stateMask & SWT.BUTTON_MASK) != 0 || (event.stateMask & SWT.KEY_MASK) != 0) { return; } Point pt = new Point(event.x, event.y); Control timeGraphControl = (Control) event.widget; Point ptInDisplay = control.toDisplay(event.x, event.y); fInitialDeadzone = new Rectangle(ptInDisplay.x - MOUSE_DEADZONE, ptInDisplay.y - MOUSE_DEADZONE, 2 * MOUSE_DEADZONE, 2 * MOUSE_DEADZONE); createTooltipShell(timeGraphControl.getShell()); fToolTipContent.append("<body><table>"); fill(control, event, pt); fToolTipContent.append("</table></body>"); String html = fToolTipContent.toString(); if (fElementCount == 0) { return; } fTipViewer.setText(html); fTipShell.setLayout(new FillLayout()); int w = fLongestString * 12 + 12; int h = fElementCount * 23 + 24; fTipShell.setSize(Math.min(w, 440), Math.min(700, h)); Point tipPosition = control.toDisplay(pt); setHoverLocation(fTipShell, tipPosition); fTipShell.setVisible(true); Display display = Display.getDefault(); display.addFilter(SWT.MouseMove, fListener); display.addFilter(SWT.FocusOut, fFocusLostListener); } }); }
Source:
<code>private Vm bestFitCloudletToVmMapper(final Cloudlet cloudlet) { if (cloudlet.isBindToVm()) { <START> if(broker0.getVmExecList().contains(cloudlet.getVm())) { <END> return cloudlet.getVm(); } return Vm.NULL; } return cloudlet .getBroker() .getVmCreatedList() .stream() .filter(vm -> vm.getNumberOfPes() >= cloudlet.getNumberOfPes()) .min(Comparator.comparingLong(Vm::getNumberOfPes)) .orElse(broker0.getDefaultVmMapper().apply(cloudlet)); }</code><technical_language>highly improve performance of this line calling Vm.isCreated() method. Check issue #188 for details. suggestion if(broker0.equals(vm.getBroker()) && vm.isCreated()) {</technical_language>

Target:
private Vm bestFitCloudletToVmMapper(final Cloudlet cloudlet) { if (cloudlet.isBindToVm()) { if(broker0.equals(cloudlet.getVm().getBroker()) && cloudlet.getVm().isCreated()) { return cloudlet.getVm(); } } return cloudlet .getBroker() .getVmCreatedList() .stream() .filter(vm -> vm.getNumberOfPes() >= cloudlet.getNumberOfPes()) .min(Comparator.comparingLong(Vm::getNumberOfPes)) .orElse(broker0.defaultVmMapper(cloudlet)); }
Source:
<code>public void testCustomDeliveryOverride() { Context context = ApplicationProvider.getApplicationContext(); config = generateConfiguration(); Delivery customDelivery = new Delivery() { @NotNull @Override <START> public DeliveryStatus deliver(@NotNull EventPayload report, <END> @NotNull DeliveryParams deliveryParams) { return DeliveryStatus.DELIVERED; } @NotNull @Override public DeliveryStatus deliver(@NotNull SessionPayload payload, @NotNull DeliveryParams deliveryParams) { return DeliveryStatus.DELIVERED; } }; config.setDelivery(customDelivery); client = new Client(context, config); assertEquals(customDelivery, client.getConfig().getDelivery()); }</code><technical_language>suggestion public DeliveryStatus deliver(@NotNull EventPayload payload,</technical_language>

Target:
public void testCustomDeliveryOverride() { Context context = ApplicationProvider.getApplicationContext(); config = generateConfiguration(); Delivery customDelivery = new Delivery() { @NotNull @Override public DeliveryStatus deliver(@NotNull EventPayload payload, @NotNull DeliveryParams deliveryParams) { return DeliveryStatus.DELIVERED; } @NotNull @Override public DeliveryStatus deliver(@NotNull SessionPayload payload, @NotNull DeliveryParams deliveryParams) { return DeliveryStatus.DELIVERED; } }; config.setDelivery(customDelivery); client = new Client(context, config); assertEquals(customDelivery, client.getConfig().getDelivery()); }
Source:
<code>public int compare(AbstractComponent o1, AbstractComponent o2) { if(o1.getComponentId() == null) { <START> if(o2.getComponentId() == null) <END> return 0; else return -1; } else { if(o2.getComponentId() == null) return 1; else return o1.getComponentId().compareTo(o2.getComponentId()); } }</code><technical_language>This is a nit, (at in PR) white space a (looks if indented tabs, other spaces, similar) Also, add curly-braces nested ifs (for consistency), express ternary conditionals</technical_language>

Target:
public int compare(AbstractComponent o1, AbstractComponent o2) { if (o1.getComponentId() == null) { if (o2.getComponentId() == null) { return 0; } else { return -1; } } else { if (o2.getComponentId() == null) { return 1; } else { return o1.getComponentId().compareTo(o2.getComponentId()); } } }
Source:
<code>public Blob getBlobFromJSON(ObjectNode jsonObject) { Blob blob = null; if (!jsonObject.has("upload-batch")) { return null; } final String batchId = jsonObject.get("upload-batch").textValue(); String fileId = null; if (jsonObject.has("upload-fileId")) { fileId = jsonObject.get("upload-fileId").textValue(); } if (fileId != null) { BatchManager bm = Framework.getService(BatchManager.class); Batch batch = bm.getBatch(batchId); if (batchId == null) { <START> return null; <END> } blob = batch.getBlob(fileId); if (RequestContext.getActiveContext() != null) { final boolean drop = !Boolean.parseBoolean( RequestContext.getActiveContext().getRequest().getHeader(BatchManagerConstants.NO_DROP_FLAG)); if (drop) { RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest request) { BatchManager bm = Framework.getService(BatchManager.class); bm.clean(batchId); } }); } } } return blob; }</code><technical_language>batchId == null -> batch == null</technical_language>

Target:
public Blob getBlobFromJSON(ObjectNode jsonObject) { Blob blob = null; if (!jsonObject.has("upload-batch")) { return null; } final String batchId = jsonObject.get("upload-batch").textValue(); String fileId = null; if (jsonObject.has("upload-fileId")) { fileId = jsonObject.get("upload-fileId").textValue(); } if (fileId != null) { BatchManager bm = Framework.getService(BatchManager.class); Batch batch = bm.getBatch(batchId); if (batch == null) { return null; } blob = batch.getBlob(fileId); if (RequestContext.getActiveContext() != null) { final boolean drop = !Boolean.parseBoolean( RequestContext.getActiveContext().getRequest().getHeader(BatchManagerConstants.NO_DROP_FLAG)); if (drop) { RequestContext.getActiveContext().addRequestCleanupHandler(new RequestCleanupHandler() { @Override public void cleanup(HttpServletRequest request) { BatchManager bm = Framework.getService(BatchManager.class); bm.clean(batchId); } }); } } } return blob; }
Source:
<code>Server(String id) { this.id = id; <START> EnumSet<Language> languagesDisabledByDefault = EnumSet.of(Language.TS, Language.JAVA, Language.CPP); <END> EnumSet<Language> enabledLanguages = EnumSet.complementOf(languagesDisabledByDefault); Collection<IAnalysisConfigurator> configurators = SonarLintCorePlugin.getExtensionTracker().getAnalysisConfigurators(); for (IAnalysisConfigurator configurator : configurators) { enabledLanguages.addAll(configurator.whitelistedLanguages()); } ConnectedGlobalConfiguration globalConfig = ConnectedGlobalConfiguration.builder() .setServerId(getId()) .setWorkDir(StoragePathManager.getServerWorkDir(getId())) .setStorageRoot(StoragePathManager.getServerStorageRoot()) .setLogOutput(new SonarLintAnalyzerLogOutput()) .addEnabledLanguages(enabledLanguages.toArray(new Language[0])) .build(); this.client = new ConnectedSonarLintEngineImpl(globalConfig); this.client.addStateListener(this); this.updateStatus = client.getGlobalStorageStatus(); if (client.getState().equals(State.UPDATED)) { reloadProjects(); } }</code><technical_language>I some point plan disable Cobol default. for require partner whitelist Cobol side. create a ticket forget</technical_language>

Target:
Server(String id) { this.id = id; EnumSet<Language> languagesDisabledByDefault = EnumSet.of(Language.TS, Language.JAVA, Language.CPP, Language.C, Language.OBJC, Language.SWIFT); EnumSet<Language> enabledLanguages = EnumSet.complementOf(languagesDisabledByDefault); Collection<IAnalysisConfigurator> configurators = SonarLintExtensionTracker.getInstance().getAnalysisConfigurators(); for (IAnalysisConfigurator configurator : configurators) { enabledLanguages.addAll(configurator.whitelistedLanguages()); } ConnectedGlobalConfiguration globalConfig = ConnectedGlobalConfiguration.builder() .setServerId(getId()) .setWorkDir(StoragePathManager.getServerWorkDir(getId())) .setStorageRoot(StoragePathManager.getServerStorageRoot()) .setLogOutput(new SonarLintAnalyzerLogOutput()) .addEnabledLanguages(enabledLanguages.toArray(new Language[0])) .build(); this.client = new ConnectedSonarLintEngineImpl(globalConfig); this.client.addStateListener(this); this.updateStatus = client.getGlobalStorageStatus(); if (client.getState().equals(State.UPDATED)) { reloadProjects(); } }
Source:
<code>private static final void loadIcons() { <START> vehicle_type_icons.put(ObaRoute.TYPE_BUS, createBusIcons()); <END> vehicle_type_icons.put(ObaRoute.TYPE_FERRY, createFerryIcons()); vehicle_type_icons.put(ObaRoute.TYPE_TRAM, createTramIcons()); vehicle_type_icons.put(ObaRoute.TYPE_SUBWAY, createSubwayIcons()); vehicle_type_icons.put(ObaRoute.TYPE_RAIL, createRailIcons()); final int MAX_CACHE_SIZE = 15; if (mVehicleColoredIconCache == null) { mVehicleColoredIconCache = new LruCache<>(MAX_CACHE_SIZE); } }</code><technical_language>IIRC vehicle_type_icons is static, end initialized multiple times, time VehicleOverlay is instantiated. I check for vehicle_icons[0] == null in previous code pay this initialization penalty more once. This is more important loading more vehicle icon types. add a similar IF block initialization of vehicle_type_icons, if (!vehicle_type_icons.contains(ObaRoute.TYPE_BUS)) {, do this type of check</technical_language>

Target:
private static final void loadIcons() { if (vehicle_type_icons.isEmpty()) { vehicle_type_icons.put(ObaRoute.TYPE_BUS, createBusIcons()); vehicle_type_icons.put(ObaRoute.TYPE_FERRY, createFerryIcons()); vehicle_type_icons.put(ObaRoute.TYPE_TRAM, createTramIcons()); vehicle_type_icons.put(ObaRoute.TYPE_SUBWAY, createSubwayIcons()); vehicle_type_icons.put(ObaRoute.TYPE_RAIL, createRailIcons()); } final int MAX_CACHE_SIZE = 15; if (mVehicleColoredIconCache == null) { mVehicleColoredIconCache = new LruCache<>(MAX_CACHE_SIZE); } }
Source:
<code>public static MassRepairOption parseFromXML(Node mroNode) { MassRepairOption mro = new MassRepairOption(-1); NodeList mroItemList = mroNode.getChildNodes(); for (int mroItemIdx = 0; mroItemIdx < mroItemList.getLength(); mroItemIdx++) { Node mroItemNode = mroItemList.item(mroItemIdx); if (mroItemNode.getNodeType() != Node.ELEMENT_NODE) { continue; } if (mroItemNode.getNodeName().equalsIgnoreCase("type")) { mro.setType(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("active")) { mro.setActive(Integer.parseInt(mroItemNode.getTextContent().trim()) == 1); } else if (mroItemNode.getNodeName().equalsIgnoreCase("skillMin")) { mro.setSkillMin(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("skillMax")) { mro.setSkillMax(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("btnMin")) { mro.setBthMin(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("btnMax")) { mro.setBthMax(Integer.parseInt(mroItemNode.getTextContent().trim())); } <START> MekHQ.getLogger().info(String.format("massRepairOption %d.%s\n\t%s", <END> mro.getType(), mroItemNode.getNodeName(), mroItemNode.getTextContent())); } return mro; }</code><technical_language>this instead debug</technical_language>

Target:
public static MassRepairOption parseFromXML(Node mroNode) { MassRepairOption mro = new MassRepairOption(-1); NodeList mroItemList = mroNode.getChildNodes(); for (int mroItemIdx = 0; mroItemIdx < mroItemList.getLength(); mroItemIdx++) { Node mroItemNode = mroItemList.item(mroItemIdx); if (mroItemNode.getNodeType() != Node.ELEMENT_NODE) { continue; } if (mroItemNode.getNodeName().equalsIgnoreCase("type")) { mro.setType(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("active")) { mro.setActive(Integer.parseInt(mroItemNode.getTextContent().trim()) == 1); } else if (mroItemNode.getNodeName().equalsIgnoreCase("skillMin")) { mro.setSkillMin(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("skillMax")) { mro.setSkillMax(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("btnMin")) { mro.setBthMin(Integer.parseInt(mroItemNode.getTextContent().trim())); } else if (mroItemNode.getNodeName().equalsIgnoreCase("btnMax")) { mro.setBthMax(Integer.parseInt(mroItemNode.getTextContent().trim())); } MekHQ.getLogger().debug(String.format("massRepairOption %d.%s\n\t%s", mro.getType(), mroItemNode.getNodeName(), mroItemNode.getTextContent())); } return mro; }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { <START> SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); <END> String url = ((HttpServletRequest) request).getRequestURI(); if (isBackupFinishJsonUrl(url)) { response.setContentType("application/json"); JsonObject json = new JsonObject(); json.addProperty("is_backup_finished", backupService.isBackingUp()); response.getWriter().print(json); return; } if (backupService.isBackingUp()) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); if (isAPIUrl(url) && !isMessagesJson(url)) { generateAPIResponse(request, response); } else { try { generateHTMLResponse(response); } catch (Exception e) { e.printStackTrace(); } } return; } else { chain.doFilter(request, response); } }</code><technical_language>put a condition this? injected request. a private method autoWireService Check if backupService == null call this method</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (backupService == null) { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } String url = ((HttpServletRequest) request).getRequestURI(); if (isBackupFinishJsonUrl(url)) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); generateResponseForIsBackupFinishedAPI(response); return; } if (backupService.isBackingUp()) { ((HttpServletResponse) response).setHeader("Cache-Control", "private, max-age=0, no-cache"); ((HttpServletResponse) response).setDateHeader("Expires", 0); if (isAPIUrl(url) && !isMessagesJson(url)) { generateAPIResponse(request, response); } else { generateHTMLResponse(response); } } else { chain.doFilter(request, response); } }
Source:
<code>public static SegmentLoader makeDefaultQueryableLoader( final ConfigurationObjectFactory configFactory, final Properties props ) throws S3ServiceException { SegmentLoaderConfig config = configFactory.build(SegmentLoaderConfig.class); DelegatingSegmentLoader delegateLoader = new DelegatingSegmentLoader(); final QueryableIndexFactory factory = new MMappedQueryableIndexFactory(); SingleSegmentLoader s3segmentLoader= null; try { final RestS3Service s3Client = new RestS3Service( new AWSCredentials( PropUtils.getProperty(props, "com.metamx.aws.accessKey"), PropUtils.getProperty(props, "com.metamx.aws.secretKey") ) ); final S3DataSegmentPuller segmentGetter = new S3DataSegmentPuller(s3Client); s3segmentLoader = new SingleSegmentLoader(segmentGetter, factory, config); } catch (com.metamx.common.ISE ise){ <START> log.warn("Could not create s3Client.", ise); <END> } Map<String, SegmentLoader> loaderTypes = new HashMap<String, SegmentLoader>(); loaderTypes.put("local", new SingleSegmentLoader(new LocalDataSegmentPuller(), factory, config)); loaderTypes.put("hdfs", new SingleSegmentLoader(new HdfsDataSegmentPuller(new Configuration()), factory, config)); loaderTypes.put("c*", new SingleSegmentLoader(new CassandraDataSegmentPuller(configFactory.build(CassandraDataSegmentConfig.class)), factory, config)); if (s3segmentLoader != null){ loaderTypes.put("s3", s3segmentLoader); loaderTypes.put("s3_zip", s3segmentLoader); } delegateLoader.setLoaderTypes( ImmutableMap.<String, SegmentLoader>copyOf(loaderTypes) ); return delegateLoader; }</code><technical_language>This log format is for logger. logger is a wrapper top of normal loggers, takes Throwable argument Object... arguments automatically do a String.format() for (after verified current log level is active)</technical_language>

Target:
public static SegmentLoader makeDefaultQueryableLoader( final ConfigurationObjectFactory configFactory, final Properties props ) throws S3ServiceException { SegmentLoaderConfig config = configFactory.build(SegmentLoaderConfig.class); DelegatingSegmentLoader delegateLoader = new DelegatingSegmentLoader(); final QueryableIndexFactory factory = new MMappedQueryableIndexFactory(); final RestS3Service s3Client = new RestS3Service( new AWSCredentials( props.getProperty("com.metamx.aws.accessKey", ""), props.getProperty("com.metamx.aws.secretKey", "") ) ); final S3DataSegmentPuller segmentGetter = new S3DataSegmentPuller(s3Client); final SingleSegmentLoader s3segmentLoader = new SingleSegmentLoader(segmentGetter, factory, config); delegateLoader.setLoaderTypes( ImmutableMap.<String, SegmentLoader>builder() .put("local", new SingleSegmentLoader(new LocalDataSegmentPuller(), factory, config)) .put("hdfs", new SingleSegmentLoader(new HdfsDataSegmentPuller(new Configuration()), factory, config)) .put("s3", s3segmentLoader) .put("s3_zip", s3segmentLoader) .put("c*",new SingleSegmentLoader(new CassandraDataSegmentPuller(configFactory.build(CassandraDataSegmentConfig.class)), factory, config)) .build() ); return delegateLoader; }
Source:
<code><START> public int hashCode() <END> { int result = name != null ? name.hashCode() : 0; result = 31 * result + successCount1.hashCode(); result = 31 * result + sample1Size.hashCode(); result = 31 * result + successCount2.hashCode(); result = 31 * result + sample2Size.hashCode(); return result; }</code><technical_language>Please implement equals() method either. This remove potential problem working collections</technical_language>

Target:
public int hashCode() { int result = name.hashCode(); result = 31 * result + successCount1.hashCode(); result = 31 * result + sample1Size.hashCode(); result = 31 * result + successCount2.hashCode(); result = 31 * result + sample2Size.hashCode(); return result; }
Source:
<code><START> protected void initBinder(WebDataBinder binder) { <END> binder.setValidator(appointmentValidator); }</code><technical_language>protected. In cases extends controllers</technical_language>

Target:
private void initBinder(WebDataBinder binder) { binder.setValidator(validator); }
Source:
<code>public void testCouldUseFlatGlob() throws IOException, URISyntaxException { Configuration lazyConf = new Configuration(); <START> lazyConf.set(GCS_LAZY_INITIALIZATION_ENABLE.getKey(), "true"); <END> GoogleHadoopFileSystem lazyFs = new GoogleHadoopFileSystem(); assertThat(lazyFs.couldUseFlatGlob(new Path(new URI("gs:/ test/")))).isFalse(); lazyFs.close(); }</code><technical_language>setBoolean</technical_language>

Target:
public void testCouldUseFlatGlob() throws IOException, URISyntaxException { Configuration lazyConf = new Configuration(); lazyConf.setBoolean(GCS_LAZY_INITIALIZATION_ENABLE.getKey(), true); GoogleHadoopFileSystem lazyFs = new GoogleHadoopFileSystem(); assertThat(lazyFs.couldUseFlatGlob(new Path(new URI("gs:/ test/")))).isFalse(); lazyFs.close(); }
Source:
<code>public void getLanguageId_existing_base_expected_non_negative_lang_Test() throws DotSecurityException, DotDataException, SystemException { final Language baseLanguage = new LanguageDataGen().languageCode("fr").countryCode(null).nextPersisted(); final Language frLanguage = new LanguageDataGen().languageCode("fr").countryCode("FR").nextPersisted(); final long expectedBaseId = baseLanguage.getId(); final long expectedFrId = frLanguage.getId(); Logger.info(this, "Testing fr_CR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr_CR")); Logger.info(this, "Testing fr-CR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr-CR")); Logger.info(this, "Testing fr_FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("fr_FR")); <START> Logger.info(this, "Testing FR_CR"); <END> Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("FR_FR")); Logger.info(this, "Testing fr-FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("fr-FR")); Logger.info(this, "Testing FR-FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("FR-FR")); Logger.info(this, "Testing fr"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr")); Logger.info(this, "Testing FR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("FR")); APILocator.getLanguageAPI().deleteLanguage(baseLanguage); APILocator.getLanguageAPI().deleteLanguage(frLanguage); }</code><technical_language>Is this log correct? FR_FR</technical_language>

Target:
public void getLanguageId_existing_base_expected_non_negative_lang_Test() throws DotSecurityException, DotDataException, SystemException { final Language baseLanguage = new LanguageDataGen().languageCode("fr").countryCode(null).nextPersisted(); final Language frLanguage = new LanguageDataGen().languageCode("fr").countryCode("FR").nextPersisted(); final long expectedBaseId = baseLanguage.getId(); final long expectedFrId = frLanguage.getId(); Logger.info(this, "Testing fr_CR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr_CR")); Logger.info(this, "Testing fr-CR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr-CR")); Logger.info(this, "Testing fr_FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("fr_FR")); Logger.info(this, "Testing FR_FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("FR_FR")); Logger.info(this, "Testing fr-FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("fr-FR")); Logger.info(this, "Testing FR-FR"); Assert.assertEquals(expectedFrId, LanguageUtil.getLanguageId("FR-FR")); Logger.info(this, "Testing fr"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("fr")); Logger.info(this, "Testing FR"); Assert.assertEquals(expectedBaseId, LanguageUtil.getLanguageId("FR")); APILocator.getLanguageAPI().deleteLanguage(baseLanguage); APILocator.getLanguageAPI().deleteLanguage(frLanguage); }
Source:
<code>private File getSvnPath(File workingDirectory, String label) { File svnPath = new File(workingDirectory, label); if(!svnPath.exists()) { svnPath = new File(workingDirectory, "branches" + File.separator + label); } <START> if(!svnPath.exists()) { <END> svnPath = new File(workingDirectory, "tags" + File.separator + label); } return svnPath; }</code><technical_language>this logic execute if path exist? is point of previous if</technical_language>

Target:
private File getSvnPath(File workingDirectory, String label) { File svnPath = new File(workingDirectory, label); if(!svnPath.exists()) { svnPath = new File(workingDirectory, "branches" + File.separator + label); if(!svnPath.exists()) { svnPath = new File(workingDirectory, "tags" + File.separator + label); if(!svnPath.exists()) { throw new NoSuchLabelException("No label found for: " + label); } } } return svnPath; }
Source:
<code>private Money(Currency currency, BigDecimal amount) { <START> this.currency = currency; <END> this.amount = amount; }</code><technical_language>Null checks</technical_language>

Target:
private Money(Currency currency, BigDecimal amount) { ArgChecker.notNull(currency, "currency"); ArgChecker.notNull(amount, "amount"); this.currency = currency; this.amount = amount; }
Source:
<code>public static void DELETE_SNAPSHOT(String snapshotName) throws Exception { ensureSnapshot(snapshotName, true); LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); TransactionController tc = lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); dd.startWriting(lcc); PartitionAdmin admin=SIDriver.driver().getTableFactory().getAdmin(); String sql = String.format( <START> "select conglomeratenumber from sys.syssnapshots where snapshotname='%s'", snapshotName); <END> Connection connection = getDefaultConn(); PreparedStatement ps = connection.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()) { long conglomerateNumber = rs.getLong(1); String sname = snapshotName + "_" + conglomerateNumber; admin.deleteSnapshot(sname); dd.deleteSnapshot(snapshotName, conglomerateNumber, tc); } }</code><technical_language>PreparedStatement parameters String.format()? I this exploitable I do right production code. for other places idiom is used</technical_language>

Target:
public static void DELETE_SNAPSHOT(String snapshotName) throws Exception { ensureSnapshot(snapshotName, true); LanguageConnectionContext lcc = ConnectionUtil.getCurrentLCC(); TransactionController tc = lcc.getTransactionExecute(); DataDictionary dd = lcc.getDataDictionary(); dd.startWriting(lcc); PartitionAdmin admin=SIDriver.driver().getTableFactory().getAdmin(); String sql = "select conglomeratenumber from sys.syssnapshots where snapshotname=?"; Connection connection = getDefaultConn(); PreparedStatement ps = connection.prepareStatement(sql); ps.setString(1, snapshotName); ResultSet rs = ps.executeQuery(); while (rs.next()) { long conglomerateNumber = rs.getLong(1); String sname = snapshotName + "_" + conglomerateNumber; if (LOG.isDebugEnabled()) { SpliceLogUtils.debug(LOG, "deleting snapshot %s for table %d", sname, conglomerateNumber); } admin.deleteSnapshot(sname); dd.deleteSnapshot(snapshotName, conglomerateNumber, tc); if (LOG.isDebugEnabled()) { SpliceLogUtils.debug(LOG, "deleted snapshot %s for table %d", sname, conglomerateNumber); } } }
Source:
<code>public <T> T retryTransaction(final TransactionCallback<T> callback) { final Callable<T> call = new Callable<T>() { @Override public T call() throws Exception { <START> return getDBI().inTransaction(callback); <END> } }; final Predicate<Throwable> shouldRetry = new Predicate<Throwable>() { @Override public boolean apply(Throwable e) { return isTransientException(e); } }; final int maxTries = 10; try { return RetryUtils.retry(call, shouldRetry, maxTries); } catch (Exception e) { throw Throwables.propagate(e); } }</code><technical_language>inTransaction automatically handle rollback commit</technical_language>

Target:
public <T> T retryTransaction(final TransactionCallback<T> callback) { final Callable<T> call = new Callable<T>() { @Override public T call() throws Exception { return getDBI().inTransaction(callback); } }; final int maxTries = 10; try { return RetryUtils.retry(call, shouldRetry, maxTries); } catch (Exception e) { throw Throwables.propagate(e); } }
Source:
<code>public void trigger() { final CloseableHttpClient httpclient = HttpClients.createDefault(); LOG.debug("Sending '" + event + "' event to IFTTT."); try { final HttpPost httpPost = new HttpPost(String.format(IFTTT_URL, event, key)); httpPost.setHeader("Content-type", "application/json"); final StringEntity stringEntity = new StringEntity(String.format(IFTTT_JSON, value1, value2, value3)); httpPost.setEntity(stringEntity); final CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpPost); final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { LOG.warn("Received HTTP Status for request to with body {}", statusCode, httpPost.getURI(), httpPost.getEntity()); } httpclient.close(); } catch (IOException e) { <START> e.printStackTrace(); <END> } }</code><technical_language>logger instead</technical_language>

Target:
public void trigger() { try (final CloseableHttpClient httpclient = HttpClients.createDefault()) { LOG.debug("Sending '" + event + "' event to IFTTT."); final HttpPost httpPost = new HttpPost(String.format(IFTTT_URL, event, key)); httpPost.setHeader("Content-type", "application/json"); final StringEntity stringEntity = new StringEntity(String.format(IFTTT_JSON, value1, value2, value3)); httpPost.setEntity(stringEntity); final CloseableHttpResponse closeableHttpResponse = httpclient.execute(httpPost); final int statusCode = closeableHttpResponse.getStatusLine().getStatusCode(); if (statusCode != 200) { LOG.warn("Received HTTP Status for request to with body {}", statusCode, httpPost.getURI(), httpPost.getEntity()); } } catch (IOException e) { LOG.error("Error invoking request: {}", e); } }
Source:
<code>public void testEval() throws Exception { JdbcRowDataLookupFunction lookupFunction = buildRowDataLookupFunction(); lookupFunction.open(null); ListOutputCollector collector = new ListOutputCollector(); lookupFunction.setCollector(collector); lookupFunction.eval(1, StringData.fromString("1")); List<String> result = Lists.newArrayList(collector.getOutputs()).stream() <START> .map(row -> { return String.format("%d,%s,%s,%s", row.getInt(0), row.getString(1), row.getString(2), row.getString(3)); }) <END> .sorted() .collect(Collectors.toList()); List<String> expected = new ArrayList<>(); expected.add("1,1,11-c1-v1,11-c2-v1"); expected.add("1,1,11-c1-v2,11-c2-v2"); Collections.sort(expected); assertEquals(expected, result); }</code><technical_language>map(RowData::toString)</technical_language>

Target:
public void testEval() throws Exception { JdbcRowDataLookupFunction lookupFunction = buildRowDataLookupFunction(); ListOutputCollector collector = new ListOutputCollector(); lookupFunction.setCollector(collector); lookupFunction.open(null); lookupFunction.eval(1, StringData.fromString("1")); lookupFunction.getDbConnection().close(); lookupFunction.eval(2, StringData.fromString("3")); List<String> result = Lists.newArrayList(collector.getOutputs()).stream() .map(RowData::toString) .sorted() .collect(Collectors.toList()); List<String> expected = new ArrayList<>(); expected.add("+I(1,1,11-c1-v1,11-c2-v1)"); expected.add("+I(1,1,11-c1-v2,11-c2-v2)"); expected.add("+I(2,3,null,23-c2)"); Collections.sort(expected); assertEquals(expected, result); }
Source:
<code>private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !accessModifier.equals(AccessModifier.PROTECTED)) { return; } final DetailAST typeToken = methodDefToken.findFirstToken(TokenTypes.TYPE); if (typeToken != null) { getInvalidReturnTypes(typeToken).forEach( (token, returnTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a return type.", returnTypeName))); } final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); if (parametersToken != null) { getInvalidParameterTypes(parametersToken).forEach( <START> (token, parameterTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a method argument type.", parameterTypeName))); <END> } }</code><technical_language>IMO, is private static string label for error message, strings this is good for maintenance. 3 static strings private static String EXTERNAL_DEPEPENDENCY_ERROR_TITLE = "Class ''%s'', is a class external dependency. . a"; private static String EXTERNAL_DEPEPENDENCY_ERROR_RETURN_TYPE = "return type"; private static String EXTERNAL_DEPEPENDENCY_ERROR_ARG_TYPE = "argument type"; a method getErrorMessage( EXTERNAL_DEPEPENDENCY_ERROR_ARG_TYPE) error title string need</technical_language>

Target:
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !accessModifier.equals(AccessModifier.PROTECTED)) { return; } final DetailAST typeToken = methodDefToken.findFirstToken(TokenTypes.TYPE); if (typeToken != null) { getInvalidReturnTypes(typeToken).forEach( (token, returnTypeName) -> log(token, String.format(EXTERNAL_DEPENDENCY_ERROR, returnTypeName, "return"))); } final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS); if (parametersToken != null) { getInvalidParameterTypes(parametersToken).forEach( (token, parameterTypeName) -> log(token, String.format(EXTERNAL_DEPENDENCY_ERROR, parameterTypeName, "method argument"))); } }
Source:
<code>private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws KeyStoreLoadException { InputStream inputStream = null; KeyStore ks = null; try { ks = KeyStore.getInstance("JKS"); inputStream = new FileInputStream(keyStore); ks.load(inputStream, keyStorePassword.toCharArray()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } finally { <START> if (inputStream != null) { <END> try { inputStream.close(); } catch (IOException e) { LOG.error("Failed to close an input stream: {}", e); } } } return ks; }</code><technical_language>double try block logic simplier. java try { InputStream is = new FileInputStream(keyStore); try { ... } finally { Closeables.closeQuietly(is); } } catch (...) { }</technical_language>

Target:
private static KeyStore getKeyStore(File keyStore, String keyStorePassword) throws IOException { KeyStore ks = null; InputStream is = new FileInputStream(keyStore); try { ks = KeyStore.getInstance("JKS"); ks.load(is, keyStorePassword.toCharArray()); } catch (Exception ex) { if (ex instanceof RuntimeException) { throw ((RuntimeException) ex); } throw new IOException(ex); } finally { Closeables.closeQuietly(is); } return ks; }
Source:
<code>public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry) { <START> this(manager, taskFactoryRegistry, null); <END> }</code><technical_language>mentioned below, I lazy initialize executor. reason for this change</technical_language>

Target:
public TaskStateModelFactory(HelixManager manager, Map<String, TaskFactory> taskFactoryRegistry) { this(manager, taskFactoryRegistry, Executors.newScheduledThreadPool(TaskUtil .getTargetThreadPoolSize(createZkClient(manager), manager.getClusterName(), manager.getInstanceName()), new ThreadFactory() { private AtomicInteger threadId = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { return new Thread(r, "TaskStateModelFactory-task_thread-" + threadId.getAndIncrement()); } })); }
Source:
<code>public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { <START> final HashSet<T> that = (HashSet<T>) o; <END> return this.iterator().equals(that.iterator()); } else { return false; } }</code><technical_language>I tested a bit recognized need another equals implementation. underlying HashArrayMappedTrie stored elements in arbitrary order, iterators do return elements in a specific order. This lead this implementation: java @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { final HashSet<?> = (HashSet<?>) o; return this.length() == that.length() && ((HashSet<Object>) this).containsAll(that); } else { return false; } } do cast <T> in order prevent ClassCastExceptions. Thanks for for finding!</technical_language>

Target:
public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { final HashSet<?> that = (HashSet<?>) o; return this.length() == that.length() && ((HashSet<Object>) this).containsAll(that); } else { return false; } }
Source:
<code>public void testJobOverviewHandler() throws Exception { assertTrue(getRunningJobs(CLUSTER.getClusterClient()).isEmpty()); final JobVertex sender = new JobVertex("Sender"); sender.setParallelism(2); sender.setInvokableClass(BlockingInvokable.class); final JobGraph jobGraph = new JobGraph("Stoppable streaming test job", sender); final JobID jid = jobGraph.getJobID(); ClusterClient<?> clusterClient = CLUSTER.getClusterClient(); clusterClient.submitJob(jobGraph).get(); while (getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(10); } BlockingInvokable.latch.await(); final Duration testTimeout = Duration.ofMinutes(2); <START> final LocalTime deadline = LocalTime.now().plus(testTimeout); <END> String json = TestBaseUtils.getFromHTTP("http://localhost:" + getRestPort() + "/jobs/overview"); ObjectMapper mapper = new ObjectMapper(); JsonNode parsed = mapper.readTree(json); ArrayNode jsonJobs = (ArrayNode) parsed.get("jobs"); assertEquals(1, jsonJobs.size()); assertThat("Duration must be positive", jsonJobs.get(0).get("duration").asInt() > 0); clusterClient.cancel(jobGraph.getJobID()).get(); while (!getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(20); } BlockingInvokable.reset(); }</code><technical_language>deadline variable is used. missing assert in this test is this variable obsolete</technical_language>

Target:
public void testJobOverviewHandler() throws Exception { assertTrue(getRunningJobs(CLUSTER.getClusterClient()).isEmpty()); final JobVertex sender = new JobVertex("Sender"); sender.setParallelism(2); sender.setInvokableClass(BlockingInvokable.class); final JobGraph jobGraph = new JobGraph("Stoppable streaming test job", sender); ClusterClient<?> clusterClient = CLUSTER.getClusterClient(); clusterClient.submitJob(jobGraph).get(); while (getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(10); } BlockingInvokable.latch.await(); final Duration testTimeout = Duration.ofMinutes(2); String json = TestBaseUtils.getFromHTTP("http://localhost:" + getRestPort() + "/jobs/overview"); ObjectMapper mapper = new ObjectMapper(); JsonNode parsed = mapper.readTree(json); ArrayNode jsonJobs = (ArrayNode) parsed.get("jobs"); assertEquals(1, jsonJobs.size()); assertThat("Duration must be positive", jsonJobs.get(0).get("duration").asInt() > 0); clusterClient.cancel(jobGraph.getJobID()).get(); while (!getRunningJobs(CLUSTER.getClusterClient()).isEmpty()) { Thread.sleep(20); } BlockingInvokable.reset(); }
Source:
<code>private void insert(final Long id, final Integer sortKey, final Integer firmwareVersion, final Boolean isPublic) { <START> handle.execute(String.format( <END> "Insert INTO file_info (id, sort_key, firmware_version, is_public, type, path, sha, uri, preview_uri, name)\n" + "VALUES (%s, %s, %s, %s, 'SLEEP_SOUND', '', '', '', '', '');", id, sortKey, firmwareVersion, isPublic)); }</code><technical_language>able named parameters</technical_language>

Target:
private void insert(final Long id, final Integer sortKey, final Integer firmwareVersion, final Boolean isPublic) { final String insertStatement = "Insert INTO file_info (id, sort_key, firmware_version, is_public, type, path, sha, uri, preview_uri, name)\n" + "VALUES (:id, :sort_key, :firmware_version, :is_public, 'SLEEP_SOUND', '', '', '', '', '');"; handle.createStatement(insertStatement) .bind("id", id) .bind("sort_key", sortKey) .bind("firmware_version", firmwareVersion) .bind("is_public", isPublic) .execute(); }
Source:
<code>private Object getInheritedProperty(Resource resource, String propertyName, Type declaredType, Integer maxLevel) { List<Resource> parentResources = new ArrayList<>(); int count = 0; Resource parentResource = resource.getParent(); do { if (parentResource != null && !parentResource.getResourceType().equals(NameConstants.NT_PAGE)) { parentResources.add(resource.getParent()); count++; } else { break; } parentResource = parentResource.getParent(); } while (count < maxLevel || maxLevel <= 0); <START> return new MergedValueMap(parentResources).get(propertyName, (Class<?>) declaredType); <END> }</code><technical_language>of parent valuemaps merging get a single property feels a bit heavy. loop simply call resource.getValueMap().get(propertyName, declaredType) break; if a non-null is found? dont higher resources in tree necessary property is levels, dont bother merging a bunch of maps. Thoughts</technical_language>

Target:
private Object getInheritedProperty(Resource resource, String propertyName, Type declaredType, Integer maxLevel) { int count = 0; Resource parentResource = resource.getParent(); do { if (parentResource != null && !parentResource.getResourceType().equals(NameConstants.NT_PAGE)) { Object value = parentResource.getValueMap().get(propertyName, (Class<?>)declaredType); if (ObjectUtils.anyNotNull(value)) { return value; } count++; } else { break; } parentResource = parentResource.getParent(); } while (count < maxLevel || maxLevel <= 0); return null; }
Source:
<code>public void rollbackCreateTable(Table table) throws MetaException { final Path segmentDescriptorDir = new Path(table.getSd().getLocation()); try { List<DataSegment> dataSegmentList = DruidStorageHandlerUtils .getPublishedSegments(segmentDescriptorDir, getConf()); <START> for (DataSegment dataSegment : <END> dataSegmentList) { try { deleteSegment(dataSegment); } catch (SegmentLoadingException e) { LOG.error(String.format("Error while trying to clean the segment [%s]", dataSegment), e); } } } catch (IOException e) { LOG.error("Exception while rollback", e); Throwables.propagate(e); } }</code><technical_language>*style*. line</technical_language>

Target:
public void rollbackCreateTable(Table table) throws MetaException { if (MetaStoreUtils.isExternalTable(table)) { return; } final Path segmentDescriptorDir = getSegmentDescriptorDir(); try { List<DataSegment> dataSegmentList = DruidStorageHandlerUtils .getPublishedSegments(segmentDescriptorDir, getConf()); for (DataSegment dataSegment : dataSegmentList) { try { deleteSegment(dataSegment); } catch (SegmentLoadingException e) { LOG.error(String.format("Error while trying to clean the segment [%s]", dataSegment), e); } } } catch (IOException e) { LOG.error("Exception while rollback", e); throw Throwables.propagate(e); } finally { cleanWorkingDir(); } }