auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static boolean isJobServiceWithSameParamsPending(Context context, ComponentName componentName, PersistableBundle bundleCompare, String exceptKey) { JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); boolean jobAlreadyScheduled = false; <START> for (JobInfo jobInfo : scheduler.getAllPendingJobs()) { <END> if (jobInfo.getService().getClassName().compareTo(componentName.getClassName()) == 0) { PersistableBundle extras = jobInfo.getExtras(); if (extras != null) { Set<String> keySetOne = extras.keySet(); Set<String> keySetTwo = bundleCompare.keySet(); if ((exceptKey == null && (keySetOne.size() == keySetTwo.size())) || ((exceptKey != null && (keySetOne.size() - 1 == keySetTwo.size())) && extras.keySet().containsAll(bundleCompare.keySet()))) { jobAlreadyScheduled = true; for (String key : bundleCompare.keySet()) { Object one = extras.get(key); Object two = bundleCompare.get(key); if (!one.equals(two)) { jobAlreadyScheduled = false; break; } } if (jobAlreadyScheduled) { AppLog.i(AppLog.T.STATS, "Job was already scheduled"); break; } } } } } return jobAlreadyScheduled; }</code><technical_language>check getAllPendingJobs is returning null. In API21 is notNull annotation for method</technical_language>

Target:
public static boolean isJobServiceWithSameParamsPending(Context context, ComponentName componentName, PersistableBundle bundleCompare, String exceptKey) { JobScheduler scheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE); boolean jobAlreadyScheduled = false; List<JobInfo> jobs = scheduler.getAllPendingJobs(); if (jobs == null) { return jobAlreadyScheduled; } for (JobInfo jobInfo : jobs) { if (jobInfo.getService().getClassName().compareTo(componentName.getClassName()) == 0) { PersistableBundle extras = jobInfo.getExtras(); if (extras != null) { Set<String> keySetOne = extras.keySet(); Set<String> keySetTwo = bundleCompare.keySet(); if ((exceptKey == null && (keySetOne.size() == keySetTwo.size())) || ((exceptKey != null && (keySetOne.size() - 1 == keySetTwo.size())) && extras.keySet().containsAll(bundleCompare.keySet()))) { jobAlreadyScheduled = true; for (String key : bundleCompare.keySet()) { Object one = extras.get(key); Object two = bundleCompare.get(key); if ((one != null && two == null) || (one == null && two != null)) { jobAlreadyScheduled = false; break; } if (one == two) { continue; } if (one instanceof int[] && two instanceof int[]) { if (Arrays.equals((int[]) one, (int[]) two)) { continue; } else { jobAlreadyScheduled = false; break; } } else { if (!one.equals(two)) { jobAlreadyScheduled = false; break; } } } if (jobAlreadyScheduled) { AppLog.i(AppLog.T.STATS, "Job was already scheduled"); return jobAlreadyScheduled; } } } } } return jobAlreadyScheduled; }
Source:
<code>private Collection<ConditionalStreamListenerHandler> findMatchingHandlers(Message<?> message) { ArrayList<ConditionalStreamListenerHandler> matchingMethods = new ArrayList<>(); for (ConditionalStreamListenerHandler conditionalStreamListenerHandlerMethod : this.handlerMethods) { if (conditionalStreamListenerHandlerMethod.getCondition() == null) { matchingMethods.add(conditionalStreamListenerHandlerMethod); } else { Object value = conditionalStreamListenerHandlerMethod.getCondition().getValue(this.evaluationContext, message); if (Boolean.class.isAssignableFrom(value.getClass())) { if ((Boolean) value) { matchingMethods.add(conditionalStreamListenerHandlerMethod); } } else if (Boolean.valueOf(String.valueOf(value))) { matchingMethods.add(conditionalStreamListenerHandlerMethod); <START> } <END> } } return matchingMethods; }</code><technical_language>I Expression.getValue() return type variant Boolean.class trick for us. conversion service is in charge in SpEL</technical_language>

Target:
private Collection<ConditionalStreamListenerHandler> findMatchingHandlers(Message<?> message) { ArrayList<ConditionalStreamListenerHandler> matchingMethods = new ArrayList<>(); for (ConditionalStreamListenerHandler conditionalStreamListenerHandlerMethod : this.handlerMethods) { if (conditionalStreamListenerHandlerMethod.getCondition() == null) { matchingMethods.add(conditionalStreamListenerHandlerMethod); } else { boolean conditionMetOnMessage = conditionalStreamListenerHandlerMethod.getCondition().getValue( this.evaluationContext, message, Boolean.class); if (conditionMetOnMessage) { matchingMethods.add(conditionalStreamListenerHandlerMethod); } } } return matchingMethods; }
Source:
<code>public static void main(String[] args) throws Exception { MainDc mainInstance = new MainDc(); Properties nuroDCProp = new Properties(); mainInstance.loadDefaultValues(); mainInstance.loadFromEnrivonmentVariables(); try { <START> nuroDCProp.load(new FileInputStream(mainInstance.configFilePath)); <END> } catch (FileNotFoundException ex) { logger.error("Properties file not found"); throw new RuntimeException("Properties file not found"); } catch (IOException ex) { logger.error("Error while parsing properties file"); throw new RuntimeException("Error while parsing properties file"); } int port; try { port = Integer.parseInt(mainInstance.managerPort); } catch (NumberFormatException ex) { logger.error("Error while converting manager port - must be an integer"); throw new RuntimeException("Error while parsing properties file"); } Registry.initialize(mainInstance.managerIp, port, nuroDCProp); Registry.startMonitoring(); }</code><technical_language>is semantic of config strategies? environment variables a config file. mechanism? I this simplify bootstrap of DC runtime management. Wdyt</technical_language>

Target:
public static void main(String[] args) throws Exception { MainDc mainInstance = new MainDc(); if (args.length > 0) { mainInstance.configFilePath = args[0]; } else { mainInstance.configFilePath = CONFIG_FILE_PATH; } Properties nuroDCProp = new Properties(); try { nuroDCProp.load(new FileInputStream(mainInstance.configFilePath)); } catch (FileNotFoundException ex) { logger.error("Properties file not found"); throw new RuntimeException("Properties file not found"); } catch (IOException ex) { logger.error("Error while parsing properties file"); throw new RuntimeException("Error while parsing properties file"); } Registry.initialize(nuroDCProp); Registry.startMonitoring(); }
Source:
<code>public FontManager(String preferredFont, AssetManager assets) { <START> fonts.clear(); <END> fonts.put("default", Typeface.defaultFromStyle(Typeface.NORMAL)); String[] files = null; try { files = assets.list(FONT_PATH); } catch (IOException | RuntimeException e) { e.printStackTrace(); } if (files == null) { Timber.w("Couldn't load font assets from %s", FONT_PATH); return; } for (String file : files) { String fileName = String.format("%s/%s", FONT_PATH, file); fonts.put(fileName, Typeface.createFromAsset(assets, fileName)); Timber.i("Processed Font: %s", fileName); } setCurrentFont(preferredFont); }</code><technical_language>revert this, put call buildFontList getFontList? removed a behaviour change I notice, means if adds new fonts show app is restarted - user realise that</technical_language>

Target:
private FontManager(String preferredFont, AssetManager assets) { buildFontList(preferredFont, assets); }
Source:
<code>public MarkupFormatter getMarkupFormatter() { <START> return getJenkins().getMarkupFormatter(); <END> }</code><technical_language>loads of findbugs for potential NPE this style getInstance() return null</technical_language>

Target:
public MarkupFormatter getMarkupFormatter() { return Jenkins.getInstance().getMarkupFormatter(); }
Source:
<code>public void onSaveDefaultActiveFilter(@Observes final SavedFilterAsDefaultActiveEvent event) { filterSettingsManager.saveDefaultActiveFilter(event.getSavedFilter().getKey(), () -> { <START> view.removeAllSavedFilters(); <END> loadSavedFilters(); }); }</code><technical_language>reloading filters a bit unnecessary, update icon maybe</technical_language>

Target:
public void onSaveDefaultActiveFilter(@Observes final SavedFilterAsDefaultActiveEvent event) { filterSettingsManager.saveDefaultActiveFilter(event.getSavedFilter().getKey(), () -> view.updateSavedFiltersDefault(event.getSavedFilter().getKey()) ); }
Source:
<code>public void stop() { IoUtils.safeClose(normalServer); IoUtils.safeClose(secureServer); <START> httpAuthenticationFactory.shutdownAuthenticationMechanismFactoryExecutory(); <END> }</code><technical_language>This method name a typo (final 'y')</technical_language>

Target:
public void stop() { IoUtils.safeClose(normalServer); IoUtils.safeClose(secureServer); }
Source:
<code>private ObjectReader configureObjReader() { this.count=0; CsvSchema firstLineSchema = getCsvSchema()!=null? getCsvSchema():CsvSchema.emptySchema().withHeader(); <START> ObjectReader objectReader = configureCsvMapper().readerFor(JsonNode.class); <END> return objectReader.with(firstLineSchema); }</code><technical_language>Similar CsvSchema, users override default? in: CsvMapper csvMapper = getCsvMapper()!=null ? CsvMapper() : configureCsvMapper(); ObjectReader objectReader = csvMapper.readerFor(JsonNode.class);</technical_language>

Target:
private ObjectReader configureObjReader() { this.count=0; CsvSchema firstLineSchema = getCsvSchema()!=null? getCsvSchema():CsvSchema.emptySchema().withHeader(); CsvMapper csvMapper = getCsvMapper()!=null ? getCsvMapper() : configureCsvMapper(); ObjectReader objectReader = csvMapper.readerFor(JsonNode.class); return objectReader.with(firstLineSchema); }
Source:
<code>public void perform(Value value) { <START> String effectiveValue = value.asString(); <END> if (trim) { effectiveValue = effectiveValue.trim(); } if (Strings.isEmpty(effectiveValue)) { throw new IllegalArgumentException(NLS.get("RequiredCheck.errorMsg")); } }</code><technical_language>fetch raw</technical_language>

Target:
public void perform(Value value) { String effectiveValue = trim ? value.getString() : value.getRawString(); if (Strings.isEmpty(effectiveValue)) { throw new IllegalArgumentException(NLS.get("RequiredCheck.errorMsg")); } }
Source:
<code>public static void assertOperatorIsBlocked(Operator operator, Duration timeout) { try { operator.isBlocked().get(timeout.toMillis(), TimeUnit.MILLISECONDS); fail("Operator is expected to be blocked for at least " + timeout.toString()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } catch (ExecutionException e) { throw new RuntimeException(e.getCause()); } <START> catch (TimeoutException ignored) { <END> } }</code><technical_language>s/ignored/expected</technical_language>

Target:
public static void assertOperatorIsBlocked(Operator operator, Duration timeout) { if (waitForOperatorToUnblock(operator, timeout)) { fail("Operator is expected to be blocked for at least " + timeout.toString()); } }
Source:
<code>public Emailer(final Props props, final CommonMetrics commonMetrics) { super(props); this.commonMetrics = requireNonNull(commonMetrics, "commonMetrics is null."); this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); this.mailPort = props.getInt("mail.port", DEFAULT_SMTP_PORT); this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); this.mailSender = props.getString("mail.sender", ""); this.tls = props.getString("mail.tls", "false"); final int mailTimeout = props.getInt("mail.timeout.millis", 30000); EmailMessage.setTimeout(mailTimeout); final int connectionTimeout = props.getInt("mail.connection.timeout.millis", 30000); EmailMessage.setConnectionTimeout(connectionTimeout); EmailMessage.setTotalAttachmentMaxSize(getAttachmentMaxSize()); this.clientHostname = props.getString("jetty.hostname", "localhost"); if (props.getBoolean("jetty.use.ssl", true)) { this.scheme = HTTPS; <START> this.clientPortNumber = Integer.toString(props.getInt("mail.jetty.ssl.port", props.getInt("jetty.ssl.port", <END> Constants.DEFAULT_SSL_PORT_NUMBER))); } else { this.scheme = HTTP; this.clientPortNumber = Integer.toString(props.getInt("mail.jetty.port", props.getInt("jetty.port", Constants.DEFAULT_PORT_NUMBER))); } this.testMode = props.getBoolean("test.mode", false); }</code><technical_language>Please define new key names in Constant class. This easier discover</technical_language>

Target:
public Emailer(final Props props, final CommonMetrics commonMetrics) { super(props); this.commonMetrics = requireNonNull(commonMetrics, "commonMetrics is null."); this.azkabanName = props.getString("azkaban.name", "azkaban"); this.mailHost = props.getString("mail.host", "localhost"); this.mailPort = props.getInt("mail.port", DEFAULT_SMTP_PORT); this.mailUser = props.getString("mail.user", ""); this.mailPassword = props.getString("mail.password", ""); this.mailSender = props.getString("mail.sender", ""); this.tls = props.getString("mail.tls", "false"); final int mailTimeout = props.getInt("mail.timeout.millis", 30000); EmailMessage.setTimeout(mailTimeout); final int connectionTimeout = props.getInt("mail.connection.timeout.millis", 30000); EmailMessage.setConnectionTimeout(connectionTimeout); EmailMessage.setTotalAttachmentMaxSize(getAttachmentMaxSize()); this.clientHostname = props.getString(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_HOSTNAME, props.getString("jetty.hostname", "localhost")); if (props.getBoolean("jetty.use.ssl", true)) { this.scheme = HTTPS; this.clientPortNumber = Integer.toString(props.getInt(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_SSL_PORT, props.getInt("jetty.ssl.port", Constants.DEFAULT_SSL_PORT_NUMBER))); } else { this.scheme = HTTP; this.clientPortNumber = Integer.toString(props.getInt(ConfigurationKeys.AZKABAN_WEBSERVER_EXTERNAL_PORT, props.getInt("jetty.port", Constants.DEFAULT_PORT_NUMBER))); } this.testMode = props.getBoolean("test.mode", false); }
Source:
<code>private void disableSystemAudioIfExist() { assertRunOnServiceThread(); if (getAvrDeviceInfo() == null) { return; } removeAction(SystemAudioActionFromAvr.class); removeAction(SystemAudioActionFromTv.class); removeAction(SystemAudioAutoInitiationAction.class); removeAction(SystemAudioStatusAction.class); removeAction(VolumeControlAction.class); <START> setSystemAudioMode(false); <END> }</code><technical_language>do if(!mService.isControlEnabled()) { setSystemAudioMode(false); }</technical_language>

Target:
private void disableSystemAudioIfExist() { assertRunOnServiceThread(); if (getAvrDeviceInfo() == null) { return; } removeAction(SystemAudioActionFromAvr.class); removeAction(SystemAudioActionFromTv.class); removeAction(SystemAudioAutoInitiationAction.class); removeAction(SystemAudioStatusAction.class); removeAction(VolumeControlAction.class); if (!mService.isControlEnabled()) { setSystemAudioMode(false); } }
Source:
<code>public int getClassLoadingCount() throws IOException, InterruptedException { if (getChannel() == null) { <START> return -1; <END> } return channel.call(new LoadingCount(false)); }</code><technical_language>main difference i PRs is this PR leverages of getChannel() returns a channel object. a lines function channel object directly. a readability standpoint this is pretty confusing a reader misinterpret getChannel() scenes in actual fact doesn't</technical_language>

Target:
public int getClassLoadingCount() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingCount(false)); }
Source:
<code>private void loadContainers(final IDockerConnection connection) { final Job loadContainersJob = new Job(DVMessages .getFormattedString("ContainersLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getContainers(true); Display.getDefault().asyncExec(() -> { viewer.refresh(); }); return Status.OK_STATUS; } }; loadContainersJob.addJobChangeListener(new JobChangeAdapter() { @Override public void <START> done(IJobChangeEvent <END> event) { } }); loadContainersJob.schedule(); }</code><technical_language>here, I entire addJobChangeListener removed others</technical_language>

Target:
private void loadContainers(final IDockerConnection connection) { final Job loadContainersJob = new Job(DVMessages .getFormattedString("ContainersLoadJob.msg", connection.getUri())) { @Override protected IStatus run(final IProgressMonitor monitor) { connection.getContainers(true); Display.getDefault().asyncExec(() -> { viewer.refresh(); }); return Status.OK_STATUS; } }; loadContainersJob.schedule(); }
Source:
<code>private void readToLogEnd() { log.trace("Reading to end of offset log"); Set<TopicPartition> assignment = consumer.assignment(); Map<TopicPartition, Long> endOffsets = consumer.endOffsets(assignment); log.trace("Reading to end of log offsets {}", endOffsets); while (!endOffsets.isEmpty()) { Iterator<Map.Entry<TopicPartition, Long>> it = endOffsets.entrySet().iterator(); while (it.hasNext()) { Map.Entry<TopicPartition, Long> entry = it.next(); TopicPartition topicPartition = entry.getKey(); <START> Long endOffset = entry.getValue(); <END> long lastConsumedOffset = consumer.position(topicPartition); if (lastConsumedOffset >= endOffset) { log.trace("Reached end offset for {}", endOffset, topicPartition); it.remove(); } else { log.trace( "Behind end offset for {}; last-consumed offset is {}", endOffset, topicPartition, lastConsumedOffset); poll(Integer.MAX_VALUE); break; } } } }</code><technical_language>unboxing happen in comparison in if branch anyways, do early declaring type long here</technical_language>

Target:
private void readToLogEnd() { log.trace("Reading to end of offset log"); Set<TopicPartition> assignment = consumer.assignment(); Map<TopicPartition, Long> endOffsets = consumer.endOffsets(assignment); log.trace("Reading to end of log offsets {}", endOffsets); while (!endOffsets.isEmpty()) { Iterator<Map.Entry<TopicPartition, Long>> it = endOffsets.entrySet().iterator(); while (it.hasNext()) { Map.Entry<TopicPartition, Long> entry = it.next(); TopicPartition topicPartition = entry.getKey(); long endOffset = entry.getValue(); long lastConsumedOffset = consumer.position(topicPartition); if (lastConsumedOffset >= endOffset) { log.trace("Read to end offset for {}", endOffset, topicPartition); it.remove(); } else { log.trace("Behind end offset for {}; last-read offset is {}", endOffset, topicPartition, lastConsumedOffset); poll(Integer.MAX_VALUE); break; } } } }
Source:
<code>public BinaryMemcacheClient<V> connectBinary() { <START> final Authenticator authenticator = firstNonNull( <END> this.authenticator, BinaryAuthenticationValidator.INSTANCE); authenticator.validate(true); return new DefaultBinaryMemcacheClient<>( connectRaw(true, authenticator), metrics, valueTranscoder, charset, maxKeyLength); }</code><technical_language>a potentially null field unnecessary. initializing BinaryAuthenticationValidator.INSTANCE</technical_language>

Target:
public BinaryMemcacheClient<V> connectBinary() { final Authenticator authenticator = this.authenticator.orElse(BinaryAuthenticationValidator.getInstance()); authenticator.validate(true); return new DefaultBinaryMemcacheClient<>( connectRaw(true, authenticator), metrics, valueTranscoder, charset, maxKeyLength); }
Source:
<code>private void getAllMembersHelper(IResource res, ArrayList<IResource> ret) { if (res instanceof IContainer) { IContainer cont = (IContainer) res; try { for (IResource r : cont.members()) { if (r.getLocation().toFile().isFile()) { ret.add(r); } else { getAllMembersHelper(r, ret); } } <START> } catch (CoreException e) { <END> } } }</code><technical_language>CoreException is wider ResourceException, is want ignore. explicitlyt checking resource exists more precise</technical_language>

Target:
private void getAllMembersHelper(IResource res, ArrayList<IResource> ret) { ArrayList<IResource> tmp = new ArrayList<IResource> (); if (res instanceof IContainer) { IContainer cont = (IContainer) res; try { for (IResource r : cont.members()) { if (r.getLocation().toFile().isFile()) { tmp.add(r); } else { getAllMembersHelper(r, tmp); } } } catch (CoreException e) { return; } ret.addAll(tmp); } }
Source:
<code>private synchronized void checkFile(File file) { if (!processedFiles.contains(file.getAbsolutePath())) { processedFiles.add(file.getAbsolutePath()); <START> listener.onFileCreate(file); <END> } else { LOG.info("File already processed {}.", file); } }</code><technical_language>onFileCreate fail, is exception, in case, file in processedFiles list retry setting pipe</technical_language>

Target:
private synchronized void checkFile(File file) { if (!processedFiles.contains(file.getAbsolutePath())) { try { LOG.debug("Start processing file {}", file); listener.onFileCreate(file); processedFiles.add(file.getAbsolutePath()); } catch (IOException e) { LOG.error("File has been processed with error {}", e); } } else { LOG.info("File already processed {}.", file); } }
Source:
<code>public int wordCount(DataStore<String, WebPage> inStore, DataStore<String, TokenDatum> outStore) throws IOException { GoraSparkEngine<String, WebPage> goraSparkEngine = new GoraSparkEngine<>(String.class, WebPage.class); SparkConf sparkConf = new SparkConf().setAppName("Gora Spark Word Count Application").setMaster("local"); Class[] c = new Class[1]; c[0] = inStore.getPersistentClass(); sparkConf.registerKryoClasses(c); JavaSparkContext sc = new JavaSparkContext(sparkConf); JavaPairRDD<String, WebPage> goraRDD = goraSparkEngine.initialize(sc, inStore); JavaPairRDD<String, String> goraRDDFlatenned = goraRDD.flatMapValues(flatMapFun); long count = goraRDD.count(); log.info("Total Web page count: {}", count); JavaRDD<Tuple2<String, Long>> mappedGoraRdd = goraRDDFlatenned.values().map(mapFunc); System.out.println(mappedGoraRdd.collect()); JavaPairRDD<String, TokenDatum> reducedGoraRdd = JavaPairRDD.fromJavaRDD(mappedGoraRdd).reduceByKey(redFunc) .mapToPair(metricFunc); log.info("SparkWordCount debug purpose TokenDatum print starts:"); Map<String, TokenDatum> tokenDatumMap = reducedGoraRdd.collectAsMap(); for (String key : tokenDatumMap.keySet()) { log.info(key); log.info(tokenDatumMap.get(key).toString()); } log.info("SparkWordCount debug purpose TokenDatum print ends:"); System.out.println(reducedGoraRdd.collect()); Configuration sparkHadoopConf = goraSparkEngine.generateOutputConf(outStore); reducedGoraRdd.saveAsNewAPIHadoopDataset(sparkHadoopConf); <START> System.out.println(outStore.get("d")); <END> return 1; }</code><technical_language>remove these, test println()</technical_language>

Target:
public int wordCount(DataStore<String, WebPage> inStore, DataStore<String, TokenDatum> outStore) throws IOException { GoraSparkEngine<String, WebPage> goraSparkEngine = new GoraSparkEngine<>(String.class, WebPage.class); SparkConf sparkConf = new SparkConf().setAppName("Gora Spark Word Count Application").setMaster("local"); Class[] c = new Class[1]; c[0] = inStore.getPersistentClass(); sparkConf.registerKryoClasses(c); JavaSparkContext sc = new JavaSparkContext(sparkConf); JavaPairRDD<String, WebPage> goraRDD = goraSparkEngine.initialize(sc, inStore); JavaPairRDD<String, String> goraRDDFlatenned = goraRDD.flatMapValues(flatMapFun); long count = goraRDD.count(); log.info("Total Web page count: {}", count); JavaRDD<Tuple2<String, Long>> mappedGoraRdd = goraRDDFlatenned.values().map(mapFunc); JavaPairRDD<String, TokenDatum> reducedGoraRdd = JavaPairRDD.fromJavaRDD(mappedGoraRdd).reduceByKey(redFunc) .mapToPair(metricFunc); log.info("SparkWordCount debug purpose TokenDatum print starts:"); Map<String, TokenDatum> tokenDatumMap = reducedGoraRdd.collectAsMap(); for (String key : tokenDatumMap.keySet()) { log.info(key); log.info(tokenDatumMap.get(key).toString()); } log.info("SparkWordCount debug purpose TokenDatum print ends:"); log.info(reducedGoraRdd.collect().toString()); Configuration sparkHadoopConf = goraSparkEngine.generateOutputConf(outStore); reducedGoraRdd.saveAsNewAPIHadoopDataset(sparkHadoopConf); return 1; }
Source:
<code>public static int getCategoryOfFilterMatch(String documentFilter, String completionFilter) { if (documentFilter == null || documentFilter.isEmpty()) { return 5; <START> } else if (completionFilter.matches("^(|.*\\W)" + documentFilter + "(|\\W.*)$")) { END> return 1; } else if (completionFilter.matches("^(|.*\\W)" + documentFilter + ".*$")) { return 2; } else if (completionFilter.contains(documentFilter)) { return 3; } else if (isSubstringFoundOrderedInString(documentFilter, completionFilter)) { return 4; } return 5; }</code><technical_language>This a heavy operation, if called for items, a serious performance hog. I avoid relying regexp possible, if do rely them, need Pattern invoke Pattern.compile once. IIRC, matches Pattern.compile() time</technical_language>

Target:
public static int getCategoryOfFilterMatch(String documentFilter, String completionFilter) { if (documentFilter.isEmpty()) { return 5; } documentFilter = documentFilter.toLowerCase(); completionFilter = completionFilter.toLowerCase(); int subIndex = completionFilter.indexOf(documentFilter); int topCategory = 5; if (subIndex == -1) { return isSubstringFoundOrderedInString(documentFilter, completionFilter) ? 4 : 5; } while (subIndex != -1) { if (subIndex > 0 && Character.isLetterOrDigit(completionFilter.charAt(subIndex - 1))) { topCategory = Math.min(topCategory, 3); } else if (subIndex + documentFilter.length() < completionFilter.length() - 1 && Character.isLetterOrDigit(completionFilter.charAt(subIndex + documentFilter.length() + 1))) { topCategory = Math.min(topCategory, 2); } else { topCategory = 1; } if (topCategory == 1) { break; } subIndex = completionFilter.indexOf(documentFilter, subIndex + 1); } return topCategory; }
Source:
<code>public Builder(final WebDriver driver, final URL script) { this.driver = driver; this.script = script; <START> AXE.inject(this.driver, this.script, this.skipFrames); <END> }</code><technical_language>This line move analyze function in order for skipFrames builder function effect</technical_language>

Target:
public Builder(final WebDriver driver, final URL script) { this.driver = driver; this.script = script; }
Source:
<code>private void parse(InputStream in, boolean recurse) throws IOException, MessagingException { mHeader.clear(); mFrom = null; mTo = null; mCc = null; mBcc = null; mReplyTo = null; xOriginalTo = null; deliveredTo = null; xEnvelopeTo = null; mMessageId = null; mReferences = null; mInReplyTo = null; mSentDate = null; mBody = null; <START> MimeConfig.Builder configBuilder = new MimeConfig.Builder(); <END> configBuilder.setMaxHeaderLen(-1); configBuilder.setMaxLineLen(-1); configBuilder.setMaxHeaderCount(-1); MimeStreamParser parser = new MimeStreamParser(configBuilder.build()); parser.setContentHandler(new MimeMessageBuilder(new DefaultBodyFactory())); if (recurse) { parser.setRecurse(); } try { parser.parse(new EOLConvertingInputStream(in)); } catch (MimeException me) { throw new MessagingException(me.getMessage(), me); } }</code><technical_language>setter calls builder chained? nicer way</technical_language>

Target:
private void parse(InputStream in, boolean recurse) throws IOException, MessagingException { mHeader.clear(); mFrom = null; mTo = null; mCc = null; mBcc = null; mReplyTo = null; xOriginalTo = null; deliveredTo = null; xEnvelopeTo = null; mMessageId = null; mReferences = null; mInReplyTo = null; mSentDate = null; mBody = null; MimeConfig parserConfig = new MimeConfig.Builder() .setMaxHeaderLen(-1) .setMaxLineLen(-1) .setMaxHeaderCount(-1) .build(); MimeStreamParser parser = new MimeStreamParser(parserConfig); parser.setContentHandler(new MimeMessageBuilder(new DefaultBodyFactory())); if (recurse) { parser.setRecurse(); } try { parser.parse(new EOLConvertingInputStream(in)); } catch (MimeException me) { throw new MessagingException(me.getMessage(), me); } }
Source:
<code>public void testStorageTypeStatsJMX() throws Exception { URL baseUrl = new URL (cluster.getHttpUri(0)); String result = readOutput(new URL(baseUrl, "/jmx")); Map<String, Object> stat = (Map<String, Object>) JSON.parse(result); Object[] beans =(Object[]) stat.get("beans"); Map<String, Object> blockStats = null; for (Object bean : beans) { Map<String, Object> map = (Map<String, Object>) bean; if (map.get("name").equals("Hadoop:service=NameNode,name=BlockStats")) { blockStats = map; } } assertNotNull(blockStats); Object[] storageTypeStatsList = (Object[])blockStats.get("StorageTypeStats"); assertNotNull(storageTypeStatsList); assertEquals(4, storageTypeStatsList.length); Set<String> typesPresent = new HashSet<> (); for (Object obj : storageTypeStatsList) { Map<String, Object> entry = (Map<String, Object>)obj; String storageType = (String)entry.get("key"); Map<String,Object> storageTypeStats = (Map<String,Object>)entry.get("value"); typesPresent.add(storageType); if (storageType.equals("ARCHIVE") || storageType.equals("DISK") ) { assertEquals(3L, storageTypeStats.get("nodesInService")); } else if (storageType.equals("RAM_DISK")) { <START> assertEquals(7L, storageTypeStats.get("nodesInService")); <END> } else if (storageType.equals("NVDIMM")) { assertEquals(1L, storageTypeStats.get("nodesInService")); } else { fail(); } } assertTrue(typesPresent.contains("ARCHIVE")); assertTrue(typesPresent.contains("DISK")); assertTrue(typesPresent.contains("RAM_DISK")); assertTrue(typesPresent.contains("NVDIMM")); }</code><technical_language>this if-else if-else if-else longer, switch case</technical_language>

Target:
public void testStorageTypeStatsJMX() throws Exception { URL baseUrl = new URL (cluster.getHttpUri(0)); String result = readOutput(new URL(baseUrl, "/jmx")); Map<String, Object> stat = (Map<String, Object>) JSON.parse(result); Object[] beans =(Object[]) stat.get("beans"); Map<String, Object> blockStats = null; for (Object bean : beans) { Map<String, Object> map = (Map<String, Object>) bean; if (map.get("name").equals("Hadoop:service=NameNode,name=BlockStats")) { blockStats = map; } } assertNotNull(blockStats); Object[] storageTypeStatsList = (Object[])blockStats.get("StorageTypeStats"); assertNotNull(storageTypeStatsList); assertEquals(4, storageTypeStatsList.length); Set<String> typesPresent = new HashSet<> (); for (Object obj : storageTypeStatsList) { Map<String, Object> entry = (Map<String, Object>)obj; String storageType = (String)entry.get("key"); Map<String,Object> storageTypeStats = (Map<String,Object>)entry.get("value"); typesPresent.add(storageType); switch (storageType) { case "ARCHIVE": case "DISK": assertEquals(3L, storageTypeStats.get("nodesInService")); break; case "RAM_DISK": assertEquals(7L, storageTypeStats.get("nodesInService")); break; case "NVDIMM": assertEquals(1L, storageTypeStats.get("nodesInService")); break; default: fail(); } } assertTrue(typesPresent.contains("ARCHIVE")); assertTrue(typesPresent.contains("DISK")); assertTrue(typesPresent.contains("RAM_DISK")); assertTrue(typesPresent.contains("NVDIMM")); }
Source:
<code>public void testExpandedImageUsingInvalidUrl() throws ImageStore.CantGetImageException{ final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_imgurl", ""); <START> when(mpPushSpy.getBitmapFromUrl(VALID_URL)).thenReturn(null); <END> mpPushSpy.createNotification(intent); verify(mpPushSpy).getBitmapFromUrl(VALID_URL); verify(builderSpy).setStyle(new Notification.BigTextStyle().setSummaryText("MESSAGE")); }</code><technical_language>mpPushSpy.getBitmapFromUrl(VALID_URL) called sending empty string mp_imgurl. I need mock this method called all</technical_language>

Target:
public void testExpandedImageUsingInvalidUrl() { final Intent intent = new Intent(); intent.putExtra("mp_message", "MESSAGE"); intent.putExtra("mp_img", INVALID_IMAGE_URL); when(mpPushSpy.getBitmapFromUrl(INVALID_IMAGE_URL)).thenReturn(null); mpPushSpy.createNotification(intent); verify(mpPushSpy).getBitmapFromUrl(INVALID_IMAGE_URL); verify(mpPushSpy).setBigTextStyle("MESSAGE"); }
Source:
<code>@Test public void testWindowOnWindowDoesNotCombineProjects() { final String query = "SELECT ROW_NUMBER() OVER (ORDER BY rn)\n" + "FROM (SELECT *,\n" <START> + " ROW_NUMBER() OVER (ORDER BY \"product_id\") as rn\n" <END> + " FROM \"foodmart\".\"product\")"; final String expected = "SELECT ROW_NUMBER() OVER (ORDER BY \"RN\")\n" + "FROM (SELECT \"product_class_id\", \"product_id\", \"brand_name\"," + " \"product_name\", \"SKU\", \"SRP\", \"gross_weight\"," + " \"net_weight\", \"recyclable_package\", \"low_fat\"," + " \"units_per_case\", \"cases_per_pallet\", \"shelf_width\"," + " \"shelf_height\", \"shelf_depth\"," + " ROW_NUMBER() OVER (ORDER BY \"product_id\") AS \"RN\"\n" + "FROM \"foodmart\".\"product\") AS \"t\""; sql(query) .withPostgresql() .ok(expected); }</code><technical_language>do options for , reference for underlying inputs</technical_language>

Target:
@Test void testWindowOnWindowDoesNotCombineProjects() { final String query = "SELECT ROW_NUMBER() OVER (ORDER BY rn)\n" + "FROM (SELECT *,\n" + " ROW_NUMBER() OVER (ORDER BY \"product_id\") as rn\n" + " FROM \"foodmart\".\"product\")"; final String expected = "SELECT ROW_NUMBER() OVER (ORDER BY \"RN\")\n" + "FROM (SELECT \"product_class_id\", \"product_id\", \"brand_name\"," + " \"product_name\", \"SKU\", \"SRP\", \"gross_weight\"," + " \"net_weight\", \"recyclable_package\", \"low_fat\"," + " \"units_per_case\", \"cases_per_pallet\", \"shelf_width\"," + " \"shelf_height\", \"shelf_depth\"," + " ROW_NUMBER() OVER (ORDER BY \"product_id\") AS \"RN\"\n" + "FROM \"foodmart\".\"product\") AS \"t\""; sql(query) .withPostgresql() .ok(expected); }
Source:
<code>public void addDistinctLocationByPartOfDay(Point point) { boolean distinct = true; for (ExplorationStatisticsEntry location : distinctLocations.values()) { if (location.getLocationId() == entries.get(point).getLocationId() && <START> PartOfDay.getCorrespondingConstant( <END> entries.get(point).getDiscoveredDate()).getName().getSingular().equalsIgnoreCase( PartOfDay.getCorrespondingConstant(location.getDiscoveredDate()).toString())) { distinct = false; break; } } if (distinct) { distinctLocations.put(point, entries.get(point)); } }</code><technical_language>this more readable introducing local variables. a multi-line expression is ideal</technical_language>

Target:
public void addDistinctLocationByPartOfDay(Point point) { boolean distinct = true; for (ExplorationStatisticsEntry location : distinctLocations.values()) { PartOfDay day = PartOfDay.getCorrespondingConstant(entries.get(point).getDiscoveredDate()); String entryName = day.getName().getSingular(); String distinctName = PartOfDay.getCorrespondingConstant(location.getDiscoveredDate()).toString(); if (location.getLocationId() == entries.get(point).getLocationId() && entryName.equalsIgnoreCase(distinctName)) { distinct = false; break; } } if (distinct) { distinctLocations.put(point, entries.get(point)); } }
Source:
<code>protected Configuration getConfiguration() throws IOException { conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, tmpFolder.newFolder().getAbsolutePath()); <START> conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, SnapshotCodecV2.class.getName()); <END> return conf; }</code><technical_language>remove this line, latest codec, right</technical_language>

Target:
private Configuration getConfiguration() throws IOException { conf.unset(TxConstants.Manager.CFG_TX_HDFS_USER); conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_DIR, TMP_FOLDER.newFolder().getAbsolutePath()); return conf; }
Source:
<code>public boolean isAuthorized() { if (session.isVoAdmin(voId)) { return true; } else { <START> return group != null && session.isGroupAdmin(groupId); <END> } }</code><technical_language>Hi, existing object ids start 1 define voId/groupId=0 default, safely like: session.isVoAdmin(voId) || session.isGroupAdmin(groupId) in IF</technical_language>

Target:
public boolean isAuthorized() { return (session.isVoAdmin(voId) || session.isGroupAdmin(groupId)); }
Source:
<code>private void addStoredKnowledge(String testID) { logger.info("addStoredKnowledge with testID: " + testID); AddStoredKnowledgeTask task = new AddStoredKnowledgeTask(testID); <START> Future<Boolean> future = taskExecutorService.submit(task); <END> testTasks.put(testID, future); try { boolean hasRegressionModel = future.get(); TestRunningState nextState = hasRegressionModel ? DETERMINE_EXECUTE_VALIDATION_SET : DETERMINE_EXECUTE_EXPERIMENTS; testModelDAO.setTestRunningState(testID, nextState); handleTestState(testID); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }</code><technical_language>Determining if require a prediction model happen in scheduler</technical_language>

Target:
private void addStoredKnowledge(String testID) { logger.info("addStoredKnowledge with testID: " + testID); AddStoredKnowledgeTask task = new AddStoredKnowledgeTask(testID); Future<?> future = taskExecutorService.submit(task); testTasks.put(testID, future); try { future.get(); boolean hasRegressionModel = explorationModelDAO.hasRegressionModel(testID); TestRunningState nextState = hasRegressionModel ? DETERMINE_EXECUTE_VALIDATION_SET : DETERMINE_EXECUTE_EXPERIMENTS; testModelDAO.setTestRunningState(testID, nextState); handleTestState(testID); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } catch (BenchFlowTestIDDoesNotExistException e) { logger.error("test ID does not exist - should not happen"); } }
Source:
<code><START> public InvocationContext createRemoteInvocationContextForCommand( <END> VisitableCommand cacheCommand, Address origin) { if (cacheCommand instanceof FlagAffectedCommand) { InvocationContext context = createRemoteInvocationContext(origin); return context; } else { return this.createRemoteInvocationContext(origin); } }</code><technical_language>hmmm... if branches do thing... I missing something</technical_language>

Target:
public InvocationContext createRemoteInvocationContextForCommand( VisitableCommand cacheCommand, Address origin) { return createRemoteInvocationContext(origin); }
Source:
<code>public void activate() { super.activate(); if (!(semanticElement instanceof Transition) <START> && !(((Transition) semanticElement).eContainer() instanceof Vertex)) { <END> return; } Vertex owningElement = (Vertex) ((Transition) semanticElement).eContainer(); DiagramEventBroker.getInstance(gep.getEditingDomain()).addNotificationListener(owningElement, transitionPriorityChangeListener); }</code><technical_language>This || instead of a &&</technical_language>

Target:
public void activate() { super.activate(); if (!(semanticElement instanceof Transition) || !(((Transition) semanticElement).eContainer() instanceof Vertex)) { return; } Vertex owningElement = (Vertex) ((Transition) semanticElement).eContainer(); DiagramEventBroker.getInstance(gep.getEditingDomain()).addNotificationListener(owningElement, transitionPriorityChangeListener); }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(BigtableTable.class) .add("hashCode", "0x" + Integer.toHexString(hashCode())) .add("project", options.getProjectId()) .add("zone", options.getZone()) .add("cluster", options.getCluster()) .add("table", tableName.getNameAsString()) <START> .toString(); <END> }</code><technical_language>nice connection is prod endpoint</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(BigtableTable.class) .add("hashCode", "0x" + Integer.toHexString(hashCode())) .add("project", options.getProjectId()) .add("zone", options.getZone()) .add("cluster", options.getCluster()) .add("table", tableName.getNameAsString()) .add("host", options.getDataHost()) .toString(); }
Source:
<code>public synchronized void stop() { if (container != null) { LOGGER.info("Shutting down container " + container.toString() + " from StreamProcessor"); <START> container.shutdown(false); <END> } else { LOGGER.info("Shutting down JobCoordinator from StreamProcessor"); jobCoordinator.stop(); } }</code><technical_language>besides container.shutdown, do jobcoordinator stop well</technical_language>

Target:
public synchronized void stop() { boolean containerShutdownInvoked = false; if (container != null) { try { LOGGER.info("Shutting down container " + container.toString() + " from StreamProcessor"); container.shutdown(); containerShutdownInvoked = true; } catch (IllegalContainerStateException icse) { LOGGER.info("Container was not running", icse); } } if (!containerShutdownInvoked) { LOGGER.info("Shutting down JobCoordinator from StreamProcessor"); jobCoordinator.stop(); } }
Source:
<code><START> public void shutdown() { <END> for (EventListenerWrapper listenerWrapper : aSyncListenersList) { removeWrapperFromList(listenerWrapper, aSyncListenersList); } for (EventListenerWrapper listenerWrapper : syncListenersList) { removeWrapperFromList(listenerWrapper, syncListenersList); } orderedExecutor.shutdown(); }</code><technical_language>This synchronized... call "clear" etc</technical_language>

Target:
public synchronized void shutdown() { storeEventSource.removeEventListener(eventListener); storeEventSource.setEventOrdering(false); syncListenersList.clear(); aSyncListenersList.clear(); orderedExecutor.shutdown(); }
Source:
<code>private Constraint oneAssignmentPerDatePerTeam(ConstraintFactory constraintFactory) { return constraintFactory.from(TeamAssignment.class) .ifExistsOther(TeamAssignment.class, Joiners.equal(TeamAssignment::getTeam), Joiners.equal(TeamAssignment::getDay), Joiners.lessThan(TeamAssignment::getId), Joiners.filtering((teamAssignment, otherTeamAssignment) -> teamAssignment.getTeam() != null)) .penalize("oneAssignmentPerDatePerTeam", HardMediumSoftScore.ONE_HARD); <START> } <END></code><technical_language>This a "score trap" (see docs). Edit: really, 2 aassignments, yield -1, 3 yield -2 4 yield -3. a 100% score trap. Still, I find penalities work better: If 2 assignments conflict, penality -1hard (AB) If 3 assignements conflict, penality -3hard (AB, BC, AC) If 4 conflict, -6hard (AB, AC, AD, BC, BD, CD)</technical_language>

Target:
private Constraint oneAssignmentPerDatePerTeam(ConstraintFactory constraintFactory) { return constraintFactory.from(TeamAssignment.class) .join(TeamAssignment.class, Joiners.equal(TeamAssignment::getTeam), Joiners.equal(TeamAssignment::getDay), Joiners.lessThan(TeamAssignment::getId)) .penalize("oneAssignmentPerDatePerTeam", HardMediumSoftScore.ONE_HARD); }
Source:
<code>public void testBug503035_1() { IGraph<String> graph = new Graph<String>(); graph.addChildren("A", ImmutableSet.of("B", "C")); graph.addChildren("B", ImmutableSet.of("C")); graph.addChildren("C", ImmutableSet.of("B")); Iterator<String> it = graph.breadthFirstIterator(); assertEquals("A", it.next()); <START> assertTrue(it.hasNext()); <END> assertEquals("B", it.next()); assertEquals("C", it.next()); assertFalse(it.hasNext()); }</code><technical_language>test hasNext time (before calling 1st next calling next</technical_language>

Target:
public void testBug503035_1() { IGraph<String> graph = new Graph<String>(); graph.addChildren("A", ImmutableSet.of("B", "C")); graph.addChildren("B", ImmutableSet.of("C")); graph.addChildren("C", ImmutableSet.of("B")); Iterator<String> it = graph.breadthFirstIterator(); assertTrue(it.hasNext()); assertEquals("A", it.next()); assertTrue(it.hasNext()); assertEquals("B", it.next()); assertTrue(it.hasNext()); assertEquals("C", it.next()); assertFalse(it.hasNext()); }
Source:
<code>ByteBuf slice() { <START> return slice != null ? slice : (slice = srcBuf.slice(srcIdx(offset), length())); <END> }</code><technical_language>please this more readable... compact hard read</technical_language>

Target:
ByteBuf slice() { ByteBuf s = slice; if (s == null) { slice = s = srcBuf.slice(srcIdx(offset), length()); } return s; }
Source:
<code>public void onCreate() { super.onCreate(); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE); String currentAppId = getOneSignalAppId(this); <START> setOneSignalAppId(this, "380dc082-5231-4cc2-ab51-a03da5a0e4c2"); <END> OneSignal.init( this, "1234567", getOneSignalAppId(this), new ExampleNotificationOpenedHandler(), new ExampleNotificationReceivedHandler() ); }</code><technical_language>pointing this out in case dont want commit this app id</technical_language>

Target:
public void onCreate() { super.onCreate(); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectAll() .penaltyLog() .build()); OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE); String currentAppId = getOneSignalAppId(this); if (currentAppId == null) setOneSignalAppId(this, "0ba9731b-33bd-43f4-8b59-61172e27447d"); OneSignal.init( this, "1234567", getOneSignalAppId(this), new ExampleNotificationOpenedHandler(), new ExampleNotificationReceivedHandler() ); }
Source:
<code>public void postRun() throws Exception { Config cfg = allProjectsConfig.load(); if (installVerified) { cfg.setString(KEY_LABEL, LABEL_VERIFIED, KEY_FUNCTION, "MaxWithBlock"); cfg.setStringList(KEY_LABEL, LABEL_VERIFIED, KEY_VALUE, Arrays.asList(new String[] {"-1 Fails", " 0 No score", "+1 Verified"})); <START> allProjectsConfig.save("Review Label Initialization"); <END> } }</code><technical_language>"Configure 'Verified' label"</technical_language>

Target:
public void postRun() throws Exception { Config cfg = allProjectsConfig.load(); if (installVerified) { cfg.setString(KEY_LABEL, LABEL_VERIFIED, KEY_FUNCTION, "MaxWithBlock"); cfg.setStringList(KEY_LABEL, LABEL_VERIFIED, KEY_VALUE, Arrays.asList(new String[] {"-1 Fails", " 0 No score", "+1 Verified"})); allProjectsConfig.save("Configure 'Verified' label"); } }
Source:
<code>protected NamingEnumeration<SearchResult> searchLdap(String query, String scope) { SearchControls controls = new SearchControls(); LdapContext context = null; controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> results; try { context = getServiceContext(); results = context.search(getConstantsConfig().getDomain(), query, controls); <START> if (scope == getConstantsConfig().getGroupScope()) { <END> String groupSearchDomain = getConstantsConfig().getGroupSearchDomain(); if (StringUtils.isNotEmpty(groupSearchDomain) && StringUtils.isNotBlank(groupSearchDomain)) { results = context.search(getConstantsConfig().getGroupSearchDomain(), query, controls); } } } catch (NamingException e) { getLogger().error("When searching ldap from /v1/identity Failed to search: " + query + " scope:" + getConstantsConfig().getDomain(), e); throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, getConstantsConfig().getConfig(), "Organizational Unit not found.", null); } finally { if (context != null){ getContextPool().returnObject(context); } } return results; }</code><technical_language>getConstantsConfig().getGroupScope().equalsIgnoreCase(scope) avoid NPE's</technical_language>

Target:
protected NamingEnumeration<SearchResult> searchLdap(String query, String scope) { SearchControls controls = new SearchControls(); LdapContext context = null; controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> results; try { context = getServiceContext(); if (getConstantsConfig().getGroupScope().equalsIgnoreCase(scope) && StringUtils.isNotBlank(getConstantsConfig().getGroupSearchDomain())) { results = context.search(getConstantsConfig().getGroupSearchDomain(), query, controls); } else { results = context.search(getConstantsConfig().getDomain(), query, controls); } } catch (NamingException e) { getLogger().error("When searching ldap from /v1/identity Failed to search: " + query + " scope:" + getConstantsConfig().getDomain(), e); throw new ClientVisibleException(ResponseCodes.INTERNAL_SERVER_ERROR, getConstantsConfig().getConfig(), "Organizational Unit not found.", null); } finally { if (context != null){ getContextPool().returnObject(context); } } return results; }