auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Label findByLabelValue(String labelValue) { <END> return uniqueResult(namedQuery("io.dockstore.webservice.core.Label.findFileFormatByValue").setParameter("labelValue", labelValue)); }</code><technical_language>awry</technical_language>

Target:
public Label findByLabelValue(String labelValue) { return uniqueResult(namedQuery("io.dockstore.webservice.core.Label.findByLabelValue").setParameter("labelValue", labelValue)); }
Source:
<code>protected void executeMethod(String name) { try { Method method = target.getClass().getDeclaredMethod(name); method.setAccessible(true); ReflectionUtils.invokeMethod(method, target); } catch (NoSuchMethodException | SecurityException exception) { <START> LOG.warning(exception.getMessage()); <END> } }</code><technical_language>I this throw exception instead of logging it. Otherwise, visible in a log silently ignored</technical_language>

Target:
protected Object executeMethod(String name) { return executeMethod(name, new Class<?>[0]); }
Source:
<code>public void populateBroadleafValidatorMap() { String[] beanNames = applicationContext.getBeanNamesForType(BroadleafEntityValidator.class); <START> broadLeafValidatorMap = new HashMap<>(beanNames.length); <END> for (String beanName : beanNames) { BroadleafEntityValidator<?> formFoxValidator = applicationContext.getBean(beanName, BroadleafEntityValidator.class); Class<?> entityType = GenericTypeResolver.resolveTypeArgument(formFoxValidator.getClass(), BroadleafEntityValidator.class); if (entityType != null) { String entityClassName = entityType.getName(); LOG.info(String.format("Registering validator %s for entity type %s", formFoxValidator.getClass().getName(), entityClassName)); List<BroadleafEntityValidator<?>> registeredValidatorsForType = broadLeafValidatorMap .get(entityClassName); if (registeredValidatorsForType == null) { registeredValidatorsForType = new ArrayList<>(); broadLeafValidatorMap.put(entityClassName, registeredValidatorsForType); } registeredValidatorsForType.add(formFoxValidator); } else { LOG.warn("Could not determine entity type for " + formFoxValidator.getClass().getName()); } } }</code><technical_language>suggestion broadleafValidatorMap = new HashMap<>(beanNames.length);</technical_language>

Target:
public void populateBroadleafValidatorMap() { String[] beanNames = applicationContext.getBeanNamesForType(BroadleafEntityValidator.class); broadleafValidatorMap = new HashMap<>(beanNames.length); for (String beanName : beanNames) { BroadleafEntityValidator<?> broadleafValidator = applicationContext.getBean(beanName, BroadleafEntityValidator.class); Class<?> entityType = GenericTypeResolver.resolveTypeArgument(broadleafValidator.getClass(), BroadleafEntityValidator.class); if (entityType != null) { String entityClassName = entityType.getName(); LOG.info(String.format("Registering validator %s for entity type %s", broadleafValidator.getClass().getName(), entityClassName)); List<BroadleafEntityValidator<?>> registeredValidatorsForType = broadleafValidatorMap .get(entityClassName); if (registeredValidatorsForType == null) { registeredValidatorsForType = new ArrayList<>(); broadleafValidatorMap.put(entityClassName, registeredValidatorsForType); } registeredValidatorsForType.add(broadleafValidator); } else { LOG.warn("Could not determine entity type for " + broadleafValidator.getClass().getName()); } } }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } TargetCard target = new TargetDiscard(0, Integer.MAX_VALUE, StaticFilters.FILTER_CARD, controller.getId()); <START> controller.choose(outcome, controller.getHand(), target, game); <END> int numDiscarded = controller.discard(new CardsImpl(target.getTargets()), source, game).size(); return numDiscarded > 0 && new SearchLibraryPutInHandEffect(new TargetCardInLibrary( 0, numDiscarded, StaticFilters.FILTER_CARD_BASIC_LAND ), true, true).apply(game, source); }</code><technical_language>AIDontUseIt (otherwise AI discards hand for lands)</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } TargetCard target = new TargetDiscard(0, Integer.MAX_VALUE, StaticFilters.FILTER_CARD, controller.getId()); controller.choose(Outcome.AIDontUseIt, controller.getHand(), target, game); int numDiscarded = controller.discard(new CardsImpl(target.getTargets()), source, game).size(); new SearchLibraryPutInHandEffect(new TargetCardInLibrary( 0, numDiscarded, StaticFilters.FILTER_CARD_BASIC_LAND ), true, true).apply(game, source); return true; }
Source:
<code>private long getMemberRecord(int memberIndex) throws CoreException { <START> if (memberIndex >= MAX_MEMBER_COUNT) { <END> return 0; } return getDB().getRecPtr(getMemberOffset(memberIndex)); }</code><technical_language>preferable sacrifice code reuse for readability check memberIndex < MAX_MEMBER_COUNT calling getMemberRecord</technical_language>

Target:
private long getMemberRecord(int memberIndex) throws CoreException { return getDB().getRecPtr(getMemberOffset(memberIndex)); }
Source:
<code>public void testTransparentTile() throws IOException, FactoryException { Layer layer = new AsyncTileLayer(service); MapContent map = new SingleLayerMapContent(layer); GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); ReferencedEnvelope mapBounds = service.getBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); int imageWidth = 600; Rectangle imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); map.getViewport().setScreenArea(imageBounds); map.getViewport().setBounds(mapBounds); BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); Graphics2D gr = image.createGraphics(); gr.setPaint(Color.RED); gr.fill(imageBounds); renderer.paint(gr, imageBounds, mapBounds); int argb = image.getRGB(0, 0); boolean hasAlphaChannel = image.getAlphaRaster() != null; Color c = new Color(argb, hasAlphaChannel); <START> System.out.println(String.format("First pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); <END> Assert.assertEquals("Color should be RED (background)", Color.RED, c); argb = image.getRGB(69, 49); c = new Color(argb, hasAlphaChannel); System.out.println(String.format("Rendered pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); Assert.assertEquals("Color should be black", Color.BLACK, c); argb = image.getRGB(154, 64); c = new Color(argb, hasAlphaChannel); System.out.println(String.format("Rendered pixel : alpha=%s red=%s green=%s blue=%s", c.getAlpha(), c.getRed(), c.getGreen(), c.getBlue())); Assert.assertEquals("Color should be very dark red", new Color(44, 0, 0), c); }</code><technical_language>Please System.out in tests. three. a logger builds control output. builds fail log files large</technical_language>

Target:
public void testTransparentTile() { Layer layer = new AsyncTileLayer(service); MapContent map = new SingleLayerMapContent(layer); GTRenderer renderer = new StreamingRenderer(); renderer.setMapContent(map); ReferencedEnvelope mapBounds = service.getBounds(); double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0); int imageWidth = 600; Rectangle imageBounds = new Rectangle(0, 0, imageWidth, (int) Math.round(imageWidth * heightToWidth)); map.getViewport().setScreenArea(imageBounds); map.getViewport().setBounds(mapBounds); BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB); Graphics2D gr = image.createGraphics(); gr.setPaint(Color.RED); gr.fill(imageBounds); renderer.paint(gr, imageBounds, mapBounds); int argb = image.getRGB(0, 0); boolean hasAlphaChannel = image.getAlphaRaster() != null; Color c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be RED (background)", Color.RED, c); argb = image.getRGB(69, 49); c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be black", Color.BLACK, c); argb = image.getRGB(154, 64); c = new Color(argb, hasAlphaChannel); Assert.assertEquals("Color should be very dark red", new Color(44, 0, 0), c); }
Source:
<code>public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = lastScenarioId + 1; lastScenarioId = id; s.setId(id); } else { <START> id = s.getId(); <END> } m.addScenario(s); scenarios.put(id, s); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }</code><technical_language>this happen</technical_language>

Target:
public void addScenario(Scenario s, Mission m) { int id; if (s.getId() == Scenario.S_DEFAULT_ID) { id = ++lastScenarioId; s.setId(id); } else { id = s.getId(); } m.addScenario(s); scenarios.put(id, s); MekHQ.triggerEvent(new ScenarioNewEvent(s)); }
Source:
<code>public <T> boolean put(final String dataType, final long id, final T value) { <START> final String operationId = Long.toString(operationIdCounter.getAndIncrement()); <END> final DataOperation operation = new DataOperation(null, operationId, DataOpType.PUT, dataType, id, value); executeOperation(operation); return operation.getResult(); }</code><technical_language>operationId a String</technical_language>

Target:
public <T> boolean put(final String dataType, final long id, final T value) { final String operationId = Long.toString(operationIdCounter.getAndIncrement()); final DataOperation<T> operation = new DataOperation<>(Optional.<String>empty(), operationId, DataOpType.PUT, dataType, id, Optional.of(value)); executeOperation(operation); return operation.isSuccess(); }
Source:
<code>protected AccessTokenAuthenticationRequestFactory createInstance(ServletContext sc) throws Exception { <START> return new DefaultAccessTokenAuthenticationRequestFactory(); <END> }</code><technical_language>public class AccessTokenAuthenticationRequestFactoryFactory extends ConfigSingletonFactory<AccessTokenAuthenticationRequestFactory> { @Override protected AccessTokenAuthenticationRequestFactory createInstance(ServletContext sc) throws Exception { AccountStoreResolver resolver = getConfig().getInstance("stormpath.web.accountStoreResolver"); return new DefaultAccessTokenAuthenticationRequestFactory(resolver); } }</technical_language>

Target:
protected AccessTokenAuthenticationRequestFactory createInstance(ServletContext sc) throws Exception { AccountStoreResolver resolver = getConfig().getInstance("stormpath.web.accountStoreResolver"); return new DefaultAccessTokenAuthenticationRequestFactory(resolver); }
Source:
<code>protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; try { Date fromExtension = <START> new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); <END> if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }</code><technical_language>if extension return VALID_TO? I guess null pointer exception</technical_language>

Target:
protected boolean attachUserToSession() { if (!StringUtils.isEmpty(getParameters().getSessionId())) { SessionDataContainer.getInstance().setUser(getParameters().getSessionId(), getCurrentUser()); } else { if (!SessionDataContainer.getInstance().setUser(getCurrentUser())) { return failCanDoAction(VdcBllMessages.USER_CANNOT_LOGIN_SESSION_MISSING); } SessionDataContainer.getInstance().refresh(); int userSessionHardLimit = Config.<Integer> getValue(ConfigValues.UserSessionHardLimit); Date validTo = userSessionHardLimit != 0 ? DateUtils.addMinutes(new Date(), userSessionHardLimit) : null; if (authRecord.<String> get(AuthRecord.VALID_TO) != null) { try { Date fromExtension = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ").parse(authRecord.<String> get(AuthRecord.VALID_TO)); if (validTo != null) { validTo = validTo.compareTo(fromExtension) < 0 ? validTo : fromExtension; } else { validTo = fromExtension; } } catch (ParseException e) { log.warn("Error parsing AuthRecord.VALID_TO . Default VALID_TO value will be set on session"); log.debug("Exception is ", e); } } SessionDataContainer.getInstance().setHardLimit(validTo); } return true; }
Source:
<code>private static Pattern extractPathFromFmt(String pathTransformFmt) { int refIdx = pathTransformFmt.indexOf(PATH_TRANSFORM_PATH_CATCH); String pathMatchingFragment = "(.*)"; String transformed; if (refIdx < 0) { transformed = Pattern.quote(pathTransformFmt); } else { if (refIdx == 0) { if (pathTransformFmt.length() > 2) { transformed = pathMatchingFragment + Pattern.quote(pathTransformFmt.substring(2)); } else { transformed = pathMatchingFragment; } } else { String prefix = Pattern.quote(pathTransformFmt.substring(0, refIdx)); String suffix = refIdx < pathTransformFmt.length() - 2 ? Pattern.quote(pathTransformFmt.substring(refIdx + 2)) : ""; transformed = prefix + pathMatchingFragment + suffix; } <START> } <END> return Pattern.compile("^" + transformed + "$"); }</code><technical_language>takes a significant amount of time figure out this code block does, I block merging it</technical_language>

Target:
private static Pattern extractPathFromFmt(String pathTransformFmt) { Matcher m = PATH_FORMAT_DECONSTRUCTION_REGEX.matcher(pathTransformFmt); if (m.matches() && m.groupCount() == 2) { String prefix = Pattern.quote(m.group(1)); String suffix = Pattern.quote(m.group(2)); return Pattern.compile("^" + prefix + "(.*)" + suffix + "$"); } else { LOGGER.warn( format( "Invalid path transformation format '%s' could not be successfully matched by the" + " deconstruction regex '%s'. Using the path transformation as is which can result in malfunctioning" + " ingresses.", pathTransformFmt, PATH_FORMAT_DECONSTRUCTION_REGEX)); return Pattern.compile(Pattern.quote(pathTransformFmt)); } }
Source:
<code>public void nullArrayToUnmodifiableNonNullList() { Object[] array = null; <START> assertThat(InternalQueries.unmodifiableNonNullList(array)).isEqualTo(emptyList()); <END> }</code><technical_language>isEqualTo -> isEmpty</technical_language>

Target:
public void nullArrayToUnmodifiableNonNullList() { Object[] array = null; assertThat(InternalQueries.unmodifiableNonNullList(array)).isSameAs(emptyList()); }
Source:
<code>public void refreshModel() { modifiedSeveritySinceLastRun.clear(); Set<IResource> currentDirty = null; if (dirty != null) { currentDirty = new HashSet<>(); currentDirty.addAll(this.dirty); this.dirty.removeAll(currentDirty); removeFromCache(currentDirty); modifiedSeveritySinceLastRun.addAll(currentDirty); } try { for (IMarker marker : WorkbenchNavigatorPlugin.getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) { IResource <START> resource = <END> marker.getResource(); if (neverRan || currentDirty.contains(resource)) { int severity = marker.getAttribute(IMarker.SEVERITY, 0); if (severity >= 0) { propagateSeverityToCache(resource, severity); } } } neverRan = false; } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); throw new RuntimeException(e); } catch (CancellationException e) { } }</code><technical_language>this null deleted marker</technical_language>

Target:
public void refreshModel() { modifiedSeveritySinceLastRun.clear(); Set<IResource> localDirty = new HashSet<>(dirty); synchronized (this.dirty) { this.dirty.removeAll(localDirty); } removeFromCache(localDirty); modifiedSeveritySinceLastRun.addAll(localDirty); try { for (IMarker marker : WorkbenchNavigatorPlugin.getWorkspace().getRoot().findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE)) { IResource resource = marker.getResource(); if (resource != null && (neverRan || localDirty.contains(resource))) { int severity = marker.getAttribute(IMarker.SEVERITY, 0); if (severity >= 0) { propagateSeverityToCache(resource, severity); } } } neverRan = false; } catch (CoreException e) { WorkbenchNavigatorPlugin.log(e.getMessage(), new Status(IStatus.ERROR, WorkbenchNavigatorPlugin.PLUGIN_ID, e.getMessage(), e)); throw new RuntimeException(e); } catch (CancellationException e) { } }
Source:
<code>public void analyzeSentimentWithLanguageWithOpinionMining() { textAnalyticsAsyncClient.analyzeSentiment("The hotel was dark and unclean.", "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true)) .subscribe(documentSentiment -> { List<MinedOpinion> positiveMinedOpinions = new ArrayList<>(); List<MinedOpinion> mixedMinedOpinions = new ArrayList<>(); List<MinedOpinion> negativeMinedOpinions = new ArrayList<>(); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { sentenceSentiment.getMinedOpinions().forEach(minedOpinion -> { TextSentiment aspectTextSentiment = minedOpinion.getAspect().getSentiment(); <START> if (NEGATIVE.equals(aspectTextSentiment)) { negativeMinedOpinions.add(minedOpinion); } else if (POSITIVE.equals(aspectTextSentiment)) { positiveMinedOpinions.add(minedOpinion); } else if (MIXED.equals(aspectTextSentiment)) { mixedMinedOpinions.add(minedOpinion); <END> } }); } System.out.printf("Negative aspects count: %d%n", negativeMinedOpinions.size()); for (MinedOpinion negativeMinedOpinion : negativeMinedOpinions) { System.out.printf("\tAspect: %s%n", negativeMinedOpinion.getAspect().getText()); for (OpinionSentiment opinionSentiment : negativeMinedOpinion.getOpinions()) { System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the aspect negated: %s.%n", opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated()); } } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment#String-String-AnalyzeSentimentOptions }</code><technical_language>a good idea making lists, add content L508-l513 here? Applicable for examples below</technical_language>

Target:
public void analyzeSentimentWithLanguageWithOpinionMining() { textAnalyticsAsyncClient.analyzeSentiment("The hotel was dark and unclean.", "en", new AnalyzeSentimentOptions().setIncludeOpinionMining(true)) .subscribe(documentSentiment -> { for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("\tSentence sentiment: %s%n", sentenceSentiment.getSentiment()); sentenceSentiment.getMinedOpinions().forEach(minedOpinions -> { AspectSentiment aspectSentiment = minedOpinions.getAspect(); System.out.printf("\tAspect sentiment: %s, aspect text: %s%n", aspectSentiment.getSentiment(), aspectSentiment.getText()); for (OpinionSentiment opinionSentiment : minedOpinions.getOpinions()) { System.out.printf("\t\t'%s' sentiment because of \"%s\". Is the opinion negated: %s.%n", opinionSentiment.getSentiment(), opinionSentiment.getText(), opinionSentiment.isNegated()); } }); } }); END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.analyzeSentiment#String-String-AnalyzeSentimentOptions }
Source:
<code>public int size() { int size = cleared ? 0 : snapshot.size(); for ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) { switch ( op.getValue().getType() ) { case PUT: case PUT_NULL: if ( cleared || snapshot.get( op.getKey() ) == null ) { <START> size++; <END> } break; case REMOVE: if ( !cleared && snapshot.get( op.getKey() ) != null ) { size--; } break; } } return size; }</code><technical_language>consider a cleared state, in subsequently added a null. is size == 1 ? asking size is evaluated if association object removed</technical_language>

Target:
public int size() { int size = cleared ? 0 : snapshot.size(); for ( Map.Entry<RowKey,AssociationOperation> op : currentState.entrySet() ) { switch ( op.getValue().getType() ) { case PUT: case PUT_NULL: if ( cleared || !snapshot.containsKey( op.getKey() ) ) { size++; } break; case REMOVE: if ( !cleared && snapshot.containsKey( op.getKey() ) ) { size--; } break; } } return size; }
Source:
<code>public void initialize(FlowletContext context) throws Exception { super.initialize(context); Map<String, String> args = context.getRuntimeArguments(); boolean pullDisabled = false; if (args.containsKey(ARG_TWITTER4J_DISABLED)) { <START> if (Boolean.parseBoolean(args.get(ARG_TWITTER4J_DISABLED))) { <END> LOG.warn("Pulling tweets is disabled via '" + ARG_TWITTER4J_DISABLED + "' runtime argument."); pullDisabled = true; } } String srcFile = null; if (args.containsKey(ARG_SOURCE_FILE)) { srcFile = args.get(ARG_SOURCE_FILE); LOG.info("Will read tweets from file: " + srcFile); } if (!pullDisabled || srcFile != null) { queue = new LinkedBlockingQueue<Tweet>(internalQueueSize); } if (!pullDisabled) { ConfigurationBuilder cb = new ConfigurationBuilder(); if (args.containsKey(ARG_TWITTER4J_OAUTH_CONSUMER_KEY)) { cb.setOAuthConsumerKey(args.get(ARG_TWITTER4J_OAUTH_CONSUMER_KEY)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_CONSUMER_SECRET)) { cb.setOAuthConsumerSecret(args.get(ARG_TWITTER4J_OAUTH_CONSUMER_SECRET)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN)) { cb.setOAuthAccessToken(args.get(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN)); } if (args.containsKey(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN_SECRET)) { cb.setOAuthAccessTokenSecret(args.get(ARG_TWITTER4J_OAUTH_ACCESS_TOKEN_SECRET)); } Configuration conf = cb.build(); twitterStreamPuller = new CollectingThread(conf); twitterStreamPuller.start(); } if (srcFile != null) { fileReader = new FileReaderThread(srcFile); fileReader.start(); } }</code><technical_language>java if (args.get(ARG_TWITTER4J_DISABLED) != null && Boolean.parseBoolean(args.get(ARG_TWITTER4J_DISABLED))) { avoid potential null pointer exception (contains return true, get return null, meaning is null)</technical_language>

Target:
public void initialize(FlowletContext context) throws Exception { super.initialize(context); Map<String, String> args = context.getRuntimeArguments(); boolean pullDisabled = false; if (args.containsKey(ARG_TWITTER4J_DISABLED)) { if (Boolean.parseBoolean(args.get(ARG_TWITTER4J_DISABLED))) { LOG.warn("Pulling tweets is disabled via '" + ARG_TWITTER4J_DISABLED + "' runtime argument."); pullDisabled = true; } } String srcFile = null; if (args.containsKey(ARG_SOURCE_FILE)) { srcFile = args.get(ARG_SOURCE_FILE); LOG.info("Will read tweets from file: " + srcFile); } if (!pullDisabled || srcFile != null) { queue = new LinkedBlockingQueue<Tweet>(internalQueueSize); } if (!pullDisabled) { twitterStreamPuller = createTwitterStreamPuller(args); twitterStreamPuller.start(); } if (srcFile != null) { fileReader = new FileReaderThread(srcFile); fileReader.start(); } }
Source:
<code>private void updateDirectoryFileSelection() { directoryFileSelector.setDirectorySelected(true); if (currentResourceSelection != null) { <START> String text; <END> if (currentResourceSelection.size() > 1) { directoryFileSelector.setDirectorySelected(false); StringBuilder sb = new StringBuilder(); for (IResource resource : currentResourceSelection) { sb.append(resource.getLocation().toString()); sb.append(DirectoryOrFileSelector.FILE_SEPARATOR); } sb.setLength(sb.length() - DirectoryOrFileSelector.FILE_SEPARATOR.length()); text = sb.toString(); } else { IResource selected = currentResourceSelection.iterator().next(); directoryFileSelector.setDirectorySelected(selected.getType() != IResource.FILE); text = selected.getLocation().toString(); } directoryFileSelector.setText(text); } }</code><technical_language>!currentResourceSelection.isEmpty(). consider switching if ! if (isEmtpy()) IResource... else directoryFileSelector..</technical_language>

Target:
private void updateDirectoryFileSelection() { directoryFileSelector.setDirectorySelected(true); if (currentResourceSelection != null) { String text; if (currentResourceSelection.isEmpty()) { IResource selected = currentResourceSelection.iterator().next(); directoryFileSelector.setDirectorySelected(selected.getType() != IResource.FILE); text = selected.getLocation().toString(); } else { directoryFileSelector.setDirectorySelected(false); StringBuilder sb = new StringBuilder(); for (IResource resource : currentResourceSelection) { sb.append(resource.getLocation().toString()); sb.append(DirectoryOrFileSelector.FILE_SEPARATOR); } sb.setLength(sb.length() - DirectoryOrFileSelector.FILE_SEPARATOR.length()); text = sb.toString(); } directoryFileSelector.setText(text); } }
Source:
<code>public ResizeRecommendationV4Response(Set<String> scaleUpHostGroups, Set<String> scaleDownHostGroups) { <START> this.scaleUpHostGroups = scaleUpHostGroups; <END> this.scaleDownHostGroups = scaleDownHostGroups; }</code><technical_language>Set.copyOf, line please</technical_language>

Target:
public ResizeRecommendationV4Response(Set<String> scaleUpHostGroups, Set<String> scaleDownHostGroups) { this.scaleUpHostGroups = Set.copyOf(scaleUpHostGroups); this.scaleDownHostGroups = Set.copyOf(scaleDownHostGroups); }
Source:
<code>public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { <START> if (fis != null) { <END> IOUtils.closeQuietly(fis); } } }</code><technical_language>IOUtils checks for null..</technical_language>

Target:
public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { IOUtils.closeQuietly(fis); } }
Source:
<code>public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailTempDirectory = new File(props.getString("reportal.mail.temp.directory", "/tmp/reportal")); reportalMailTempDirectory.mkdirs(); ReportalMailCreator.reportalMailTempDirectory = reportalMailTempDirectory; List<String> allowedDomains = props.getStringList("reportal.allowed.email.domains", (List<String>) null); if (allowedDomains != null) { allowedEmailDomains = new HashSet<String>(); for (String domain : allowedDomains) { allowedEmailDomains.add(domain); <START> } <END> } ReportalMailCreator.outputLocation = props.getString("reportal.output.location", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); }</code><technical_language>List addAll? Edit: I meant allowedEmailDomains takes a collection, allowedDomains</technical_language>

Target:
public ReportalServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); reportalStorageUser = props.getString("reportal.storage.user", "reportal"); itemsPerPage = props.getInt("reportal.items_per_page", 20); showNav = props.getBoolean("reportal.show.navigation", false); reportalMailTempDirectory = new File(props.getString("reportal.mail.temp.dir", "/tmp/reportal")); reportalMailTempDirectory.mkdirs(); ReportalMailCreator.reportalMailTempDirectory = reportalMailTempDirectory; List<String> allowedDomains = props.getStringList("reportal.allowed.email.domains", (List<String>) null); if (allowedDomains != null) { allowedEmailDomains = new HashSet<String>(allowedDomains); } ReportalMailCreator.outputLocation = props.getString("reportal.output.dir", "/tmp/reportal"); ReportalMailCreator.outputFileSystem = props.getString("reportal.output.filesystem", "local"); ReportalMailCreator.reportalStorageUser = reportalStorageUser; webResourcesFolder = new File(new File(props.getSource()).getParentFile().getParentFile(), "web"); webResourcesFolder.mkdirs(); setResourceDirectory(webResourcesFolder); System.out.println("Reportal web resources: " + webResourcesFolder.getAbsolutePath()); }
Source:
<code>public void testEquality() { Exception exception = new UnsupportedQueryException("We do not support this query"); ProcessingDetails processingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); ProcessingDetails identicalProcessingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); <START> assertThat(processingDetails.equals(identicalProcessingDetails), is(true)); <END> }</code><technical_language>more expressive matchers instead of assertThat(<expression results in a boolean>, is(true)). If this assertion fails printed message "expected true false", helpful tells tested. In this case, is() matcher print a more useful message failure: java assertThat(processingDetails, is(identicalProcessingDetails))</technical_language>

Target:
public void testEquality() { Exception exception = new UnsupportedQueryException("We do not support this query"); ProcessingDetails processingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); ProcessingDetails identicalProcessingDetails = new ProcessingDetailsImpl("test source", exception, "warning"); assertThat(processingDetails, is(identicalProcessingDetails)); }
Source:
<code>private String findWsdlCommand() throws MojoExecutionException { if (!windowsModus) { return wsdlCommand; } if (wsdlExeFolderLocation != null) { return wsdlExeFolderLocation.getAbsolutePath(); } for (File sdk : findAllInstalledSDKs(DEFAULT_WSDL_PATHS)) { File bindir = new File(sdk, "bin"); File wsdlFile = new File(bindir, wsdlCommand); if (wsdlFile.exists()) { wsdlExeFolderLocation = wsdlFile; return wsdlFile.getAbsolutePath(); } } throw new MojoExecutionException("unable to find " + wsdlCommand + " in paths " + Arrays.toString(DEFAULT_WSDL_PATHS) + "\n " + "You can specify the path manually by adding the argument \n" <START> + " -DwsdlExeFolderLocation=\"C:\\path\\to\\wsdl.exe\""); <END> }</code><technical_language>wouldnt allowing configure this a param for execution. I this solution is more platform agnostic, I of some reasons want this in development environments streamlined</technical_language>

Target:
private String findWsdlCommand() throws MojoExecutionException { if (isLinux()) { if (isMonoCommandInstalled(wsdlCommand)) { return wsdlCommand; } throw new MojoExecutionException("The program '" + wsdlCommand + "' is currently not installed. You can install it by typing: " + "sudo apt-get install mono-devel"); } if (wsdlExeFolderLocation != null) { return wsdlExeFolderLocation.getAbsolutePath(); } for (File sdk : findAllInstalledSDKs(DEFAULT_WSDL_PATHS)) { File bindir = new File(sdk, "bin"); File wsdlFile = new File(bindir, wsdlCommand); if (wsdlFile.exists()) { wsdlExeFolderLocation = wsdlFile; return wsdlFile.getAbsolutePath(); } } throw new MojoExecutionException("unable to find " + wsdlCommand + " in paths " + Arrays.toString(DEFAULT_WSDL_PATHS) + "\n " + "You can specify the path manually by adding the argument \n" + " -DwsdlExeFolderLocation=\"C:\\path\\to\\wsdl.exe\""); }
Source:
<code>public List<String> getWailaBody( final IPart part, final List<String> currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) { if( part instanceof PartP2PTunnel ) { NBTTagCompound nbtData = accessor.getNBTData(); if( nbtData.hasKey( TAG_P2P_STATE ) ) { int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); if( stateArr.length == 2 ) { int state = stateArr[0]; int outputs = stateArr[1]; <START> switch( state ) <END> { case STATE_UNLINKED: currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); break; case STATE_OUTPUT: currentToolTip.add( WailaText.P2POutput.getLocal() ); break; case STATE_INPUT: if( outputs <= 1 ) { currentToolTip.add( WailaText.P2PInputOneOutput.getLocal() ); } else { currentToolTip.add( String.format( WailaText.P2PInputManyOutputs.getLocal(), outputs ) ); } break; } } } } return currentToolTip; }</code><technical_language>![CRITICAL](<LINK_0> Add a default case this switch. [![rule](<LINK_1>](<LINK_2> ![CRITICAL](<LINK_0> Refactor this code nest more 3 if/for/while/switch/try statements. [![rule](<LINK_1>](<LINK_3></technical_language>

Target:
public List<String> getWailaBody( final IPart part, final List<String> currentToolTip, final IWailaDataAccessor accessor, final IWailaConfigHandler config ) { if( part instanceof PartP2PTunnel ) { NBTTagCompound nbtData = accessor.getNBTData(); if( nbtData.hasKey( TAG_P2P_STATE ) ) { int[] stateArr = nbtData.getIntArray( TAG_P2P_STATE ); if( stateArr.length == 2 ) { int state = stateArr[0]; int outputs = stateArr[1]; switch( state ) { case STATE_UNLINKED: currentToolTip.add( WailaText.P2PUnlinked.getLocal() ); break; case STATE_OUTPUT: currentToolTip.add( WailaText.P2POutput.getLocal() ); break; case STATE_INPUT: currentToolTip.add( getOutputText( outputs ) ); break; } } } } return currentToolTip; }
Source:
<code>public void applyEnrichmentTag_JsonParseEx() throws Exception { <START> when(jsonStringParser.parseAndValidate(Mockito.anyString())).thenThrow(new IllegalArgumentException()); <END> defaultEnrichmentTagApplier.applyEnrichmentTag(judgment, enrichmentTag); verifyNoMoreInteractions(jsonStringParser); verifyZeroInteractions(enrichmentTagValueConverter, judgmentUpdater); }</code><technical_language>throw JsonParseException here</technical_language>

Target:
public void applyEnrichmentTag_JsonParseEx() throws Exception { when(jsonStringParser.parseAndValidate(Mockito.anyString())).thenThrow(new IllegalArgumentException()); catchException(defaultEnrichmentTagApplier).applyEnrichmentTag(judgment, enrichmentTag); assertTrue(caughtException() instanceof IllegalArgumentException); verify(jsonStringParser).parseAndValidate(enrichmentTag.getValue()); verifyZeroInteractions(enrichmentTagValueConverter, judgmentUpdater); }
Source:
<code>@Get("/fortunes") public HttpResponse fortunes() { List<Fortune> fortunes = getFortunes(); fortunes.add(new Fortune(0, "Additional fortune added at request time.")); fortunes.sort(Comparator.comparing(Fortune::getMessage)); try { HttpHeaders headers = HttpHeaders.of(HttpStatus.OK).add( <START> HttpHeaderNames.SERVER, "armeria").add(HttpHeaderNames.DATE, <END> DATE_FORMATTER.format(new Date())).contentType( MediaType.HTML_UTF_8); return HttpResponse.of(headers, HttpData.ofUtf8(buildMustacheTemplate(fortunes))); } catch (Exception e) { return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR); } }</code><technical_language>settings wiki wrong. familiar them. send code style settings I use</technical_language>

Target:
public HttpResponse fortunes() throws SQLException, IOException { List<Fortune> fortunes = getFortunes(); fortunes.add( new Fortune(0, "Additional fortune added at request time.")); fortunes.sort(Comparator.comparing(Fortune::getMessage)); return HttpResponse.of( HttpHeadersHelper.getHttpHeader(MediaType.HTML_UTF_8), HttpData.ofUtf8(buildMustacheTemplate(fortunes))); }
Source:
<code>protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); ((GridData) this.getText().getLayoutData()).heightHint = 100; createMessageArea(composite); if (labelsInfo != null) { createMiddleRadioSection(composite); } <START> Point size = parent.getParent().computeSize(650, SWT.DEFAULT); <END> parent.getShell().setMinimumSize(size); return parent; }</code><technical_language>hardcoded replaced a constant</technical_language>

Target:
protected Control createDialogArea(Composite parent) { Composite composite = (Composite) super.createDialogArea(parent); ((GridData) this.getText().getLayoutData()).heightHint = 100; ((GridData) this.getText().getLayoutData()).grabExcessVerticalSpace = true; ((GridData) this.getText().getLayoutData()).verticalAlignment = SWT.FILL; createMessageArea(composite); if (labelsInfo != null) { createMiddleRadioSection(composite); } parent.getShell().addControlListener(new ControlListener() { @Override public void controlResized(ControlEvent e) { Point size = parent.getShell().computeSize(WIDTH, SWT.DEFAULT); parent.getShell().setMinimumSize(size); parent.getShell().setSize(size); if (hasDrafts(fRevisionInfo)) { scrolledDraftArea.layout(); } parent.getShell().removeControlListener(this); } @Override public void controlMoved(ControlEvent e) { } }); return parent; }
Source:
<code>private void addInformationPanelAboutDisable() { if (_descriptor instanceof Allowable && !((Allowable) _descriptor).isAllowed()) { final ImageIcon icon = imageManager.getImageIcon(IconUtils.STATUS_INFO, IconUtils.ICON_SIZE_TASK_PANE); DCPanel panel = new DCPanel(); DCHtmlBox dcHtmlBox = new DCHtmlBox( "<p>This service is not currently available for your DataCloud account.</p>" + "<p> Please contact 'support@datacleaner.org' to obtain access.</p>"); panel.add(dcHtmlBox); <START> addTaskPane(icon, "Component is disabled", panel, true); <END> } }</code><technical_language>a standard for panels. Please HTML boxes</technical_language>

Target:
private void addInformationPanelAboutDisable() { if (_descriptor instanceof Allowable && !((Allowable) _descriptor).isAllowed()) { final ImageIcon icon = imageManager.getImageIcon(IconUtils.STATUS_INFO, IconUtils.ICON_SIZE_TASK_PANE); DCPanel panel = new DCPanel(); DCHtmlBox dcHtmlBox = new DCHtmlBox( "<p>This service is not currently available for your DataCloud account.</p>" + "<p> More information on your " + "<a href='" + RemoteDescriptorProvider.DATACLEANER_BASE_URL + "/userprofile" + "'>DataCleaner profile</a>" + ".</p>"); panel.add(dcHtmlBox); addTaskPane(icon, "Component is disabled", panel, true); } }
Source:
<code>public void start() { if (properties == null) { <START> return; <END> } ExecutorService executorService = Executors.newFixedThreadPool(properties.getSubscriptions().size()); List<PubsubSubscriber> subscribers = new ArrayList<>(); properties .getSubscriptions() .forEach( (AmazonPubsubProperties.AmazonPubsubSubscription subscription) -> { log.info("Bootstrapping SQS for SNS topic: {}", subscription.getTopicARN()); ARN queueArn = new ARN(subscription.getQueueARN()); ARN topicArn = new ARN(subscription.getTopicARN()); SQSSubscriber worker = new SQSSubscriber( subscription, pubsubMessageHandlerFactory.create(subscription), AmazonSNSClientBuilder.standard() .withCredentials(awsCredentialsProvider) .withClientConfiguration(new ClientConfiguration()) .withRegion(topicArn.getRegion()) .build(), AmazonSQSClientBuilder.standard() .withCredentials(awsCredentialsProvider) .withClientConfiguration(new ClientConfiguration()) .withRegion(queueArn.getRegion()) .build(), enabled::get, registry); try { executorService.submit(worker); subscribers.add(worker); log.debug( "Created worker for subscription: {}", worker.getWorkerName(), subscription.getName()); } catch (RejectedExecutionException e) { log.error("Could not start {}", worker.getWorkerName(), e); } }); pubsubSubscribers.putAll(subscribers); }</code><technical_language>I feel this throw exception, minimum log error. If distance of setting configuration point @ConditionalOnExpression("${pubsub.enabled:false} && ${pubsub.amazon.enabled:false}") evaluates true, I application is misconfigured silently fail do supposedly enabled do</technical_language>

Target:
public void start() { Preconditions.checkNotNull( properties, "Can't initialize SQSSubscriberProvider with null properties"); ExecutorService executorService = Executors.newFixedThreadPool(properties.getSubscriptions().size()); List<PubsubSubscriber> subscribers = new ArrayList<>(); properties .getSubscriptions() .forEach( (AmazonPubsubProperties.AmazonPubsubSubscription subscription) -> { log.info("Bootstrapping SQS for SNS topic: {}", subscription.getTopicARN()); ARN queueArn = new ARN(subscription.getQueueARN()); ARN topicArn = new ARN(subscription.getTopicARN()); SQSSubscriber worker = new SQSSubscriber( subscription, pubsubMessageHandlerFactory.create(subscription), messageAcknowledger, AmazonSNSClientBuilder.standard() .withCredentials(awsCredentialsProvider) .withClientConfiguration(new ClientConfiguration()) .withRegion(topicArn.getRegion()) .build(), AmazonSQSClientBuilder.standard() .withCredentials(awsCredentialsProvider) .withClientConfiguration(new ClientConfiguration()) .withRegion(queueArn.getRegion()) .build(), PubSubUtils.getEnabledSupplier(dynamicConfig, subscription, eurekaStatus), registry); try { executorService.submit(worker); subscribers.add(worker); log.debug( "Created worker for subscription: {}", worker.getWorkerName(), subscription.getName()); } catch (RejectedExecutionException e) { log.error("Could not start {}", worker.getWorkerName(), e); } }); pubsubSubscribers.putAll(subscribers); }
Source:
<code>public void shouldNotifyEventWhenUpdateAnnotation() { Annotation annotation = createAnnotation(annotatedDocumentModel); try (CapturingEventListener listener = new CapturingEventListener(COMMENT_UPDATED)) { annotation.setText("I update the annotation"); annotationService.updateAnnotation(session, annotation.getId(), annotation); DocumentModel annotationDocumentModel = session.getDocument(new IdRef(annotation.getId())); DocumentModel annotationParentDocumentModel = session.getDocument( new IdRef((String) annotationDocumentModel.getPropertyValue(COMMENT_PARENT_ID))); <START> transactionalFeature.nextTransaction(); <END> Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, annotationDocumentModel, annotationParentDocumentModel, annotatedDocumentModel); } }</code><technical_language>Put updateAnnotation</technical_language>

Target:
public void shouldNotifyEventWhenUpdateAnnotation() { Annotation annotation = createAnnotation(annotatedDocumentModel); try (CapturingEventListener listener = new CapturingEventListener(COMMENT_UPDATED)) { annotation.setText("I update the annotation"); annotationService.updateAnnotation(session, annotation.getId(), annotation); transactionalFeature.nextTransaction(); DocumentModel annotationDocumentModel = session.getDocument(new IdRef(annotation.getId())); DocumentModel annotationParentDocumentModel = session.getDocument( new IdRef((String) annotationDocumentModel.getPropertyValue(COMMENT_PARENT_ID))); Event expectedEvent = listener.streamCapturedEvents() .findFirst() .orElseThrow(() -> new AssertionError("Event wasn't fired")); checkDocumentEventContext(expectedEvent, annotationDocumentModel, annotationParentDocumentModel, annotatedDocumentModel); } }
Source:
<code>private void setSenderCopyMessage(ActivityCommentMessage senderCopyMessage) { <START> if (this.senderCopyMessageList == null) <END> { this.senderCopyMessageList = Arrays.asList(senderCopyMessage); } else { this.senderCopyMessageList.set(0, senderCopyMessage); } }</code><technical_language>Suggestion: extract a util method this.senderCopyMessageSingleton = SingletonUtil.setValue(this.senderCopyMessageList, senderCopyMessage)</technical_language>

Target:
private void setSenderCopyMessage(ActivityCommentMessage senderCopyMessage) { this.senderCopyMessageHolder = setToHolder(this.senderCopyMessageHolder, senderCopyMessage); }
Source:
<code>public InputStream readFrom(long offset) throws IOException { final GetObjectRequest request = new GetObjectRequest(object.getBucket(), object.getPath()); request.setRange(offset); try { final S3Object s3Object = s3Client.getObject(request); if (s3Object == null) { throw new ISE( "Failed to get an s3 object for bucket[%s], key[%s], and start[%d]", object.getBucket(), object.getPath(), offset ); } <START> return s3Object.getObjectContent(); <END> } catch (AmazonS3Exception e) { throw new IOException(e); } }</code><technical_language>this decompress stream before</technical_language>

Target:
protected InputStream readFrom(long offset) throws IOException { final GetObjectRequest request = new GetObjectRequest(object.getBucket(), object.getPath()); request.setRange(offset); try { final S3Object s3Object = s3Client.getObject(request); if (s3Object == null) { throw new ISE( "Failed to get an s3 object for bucket[%s], key[%s], and start[%d]", object.getBucket(), object.getPath(), offset ); } return s3Object.getObjectContent(); } catch (AmazonS3Exception e) { throw new IOException(e); } }
Source:
<code>private WebElement getInviteInstructorLink(int instrNum) { String id = "instrRemindLink" + instrNum; <START> return browser.driver.findElement(By.id(id)); <END> }</code><technical_language>above: I is clear enough id variable for</technical_language>

Target:
private WebElement getInviteInstructorLink(int instrNum) { return browser.driver.findElement(By.id("instrRemindLink" + instrNum)); }
Source:
<code>public Map<String, List<String>> getRoutingData() throws InvalidRoutingDataException { Map<String, List<String>> routingData = new HashMap<>(); List<String> children; try { children = _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNoNodeException e) { throw new InvalidRoutingDataException( "Routing data directory ZNode " + MetadataStoreRoutingConstants.ROUTING_DATA_PATH + " does not exist. Routing ZooKeeper address: " + _zkAddress); } <START> for (String child : children) { <END> ZNRecord record = _zkClient.readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + child); List<String> shardingKeys = record.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY); if (shardingKeys != null && !shardingKeys.isEmpty()) { routingData.put(child, shardingKeys); } } return routingData; }</code><technical_language>Nit: name variables better. for (String realmName : allRealmNames) { a pick</technical_language>

Target:
public Map<String, List<String>> getRoutingData() throws InvalidRoutingDataException { Map<String, List<String>> routingData = new HashMap<>(); List<String> allRealmAddresses; try { allRealmAddresses = _zkClient.getChildren(MetadataStoreRoutingConstants.ROUTING_DATA_PATH); } catch (ZkNoNodeException e) { throw new InvalidRoutingDataException( "Routing data directory ZNode " + MetadataStoreRoutingConstants.ROUTING_DATA_PATH + " does not exist. Routing ZooKeeper address: " + _zkAddress); } for (String realmAddress : allRealmAddresses) { ZNRecord record = _zkClient.readData(MetadataStoreRoutingConstants.ROUTING_DATA_PATH + "/" + realmAddress); List<String> shardingKeys = record.getListField(MetadataStoreRoutingConstants.ZNRECORD_LIST_FIELD_KEY); if (shardingKeys != null) { routingData.put(realmAddress, shardingKeys); } } return routingData; }