auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static ViewAssertion matchesVisually(final Bitmap expectedBitmap) { return new ViewAssertion() { @Override public void check(View view, NoMatchingViewException noViewFoundException) { if(noViewFoundException!=null) { throw noViewFoundException; } Bitmap viewBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); view.draw(new Canvas(viewBitmap)); assertTrue("View matches the given bitmap " + HumanReadables.describe(view), BitmapUtil.compareBitmaps(viewBitmap, expectedBitmap)); } }; }

Target:
public static ViewAssertion matchesVisually(final Bitmap expectedBitmap) { return new ViewAssertion() { @Override public void check(View view, NoMatchingViewException noViewFoundException) { if(noViewFoundException != null) { throw noViewFoundException; } Bitmap viewBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), expectedBitmap.getConfig()); view.draw(new Canvas(viewBitmap)); assertTrue("View matches the given bitmap " + HumanReadables.describe(view), BitmapUtil.compareBitmaps(viewBitmap, expectedBitmap)); } }; }
Source:
private PrometheusClient getPrometheusClient() { if (prometheusClient == null) { Provider provider = providerDao.get(vdsManager.getClusterId()); prometheusClient = PrometheusClient.create(provider); } return prometheusClient; }

Target:
private PrometheusClient getPrometheusClient() { if (prometheusClient == null) { Provider<?> provider = providerDao.get(vdsManager.getClusterId()); prometheusClient = KubevirtUtils.create(provider); } return prometheusClient; }
Source:
public void doChange(ScoreDirector<TaskAssigningSolution> scoreDirector) { final TaskAssigningSolution workingSolution = scoreDirector.getWorkingSolution(); final User workingUser = scoreDirector.lookUpWorkingObjectOrReturnNull(user); if (workingUser != null) { if (workingUser.isEnabled()) { scoreDirector.beforeProblemPropertyChanged(workingUser); workingUser.setEnabled(false); scoreDirector.afterProblemPropertyChanged(workingUser); } releaseAllTasks(workingUser, scoreDirector); workingSolution.setUserList(new ArrayList<>(workingSolution.getUserList())); scoreDirector.beforeProblemFactRemoved(workingUser); workingSolution.getUserList().remove(workingUser); scoreDirector.afterProblemFactRemoved(workingUser); scoreDirector.triggerVariableListeners(); } }

Target:
public void doChange(ScoreDirector<TaskAssigningSolution> scoreDirector) { final TaskAssigningSolution workingSolution = scoreDirector.getWorkingSolution(); final User workingUser = scoreDirector.lookUpWorkingObjectOrReturnNull(user); if (workingUser == null) { return; } if (workingUser.isEnabled()) { scoreDirector.beforeProblemPropertyChanged(workingUser); workingUser.setEnabled(false); scoreDirector.afterProblemPropertyChanged(workingUser); } releaseAllTasks(workingUser, scoreDirector); workingSolution.setUserList(new ArrayList<>(workingSolution.getUserList())); scoreDirector.beforeProblemFactRemoved(workingUser); workingSolution.getUserList().remove(workingUser); scoreDirector.afterProblemFactRemoved(workingUser); scoreDirector.triggerVariableListeners(); }
Source:
private void setInitialState() { for (PlexBindingProvider provider : providers) setInitialState(provider); }

Target:
private void setInitialState() { for (PlexBindingProvider provider : providers) { setInitialState(provider); } }
Source:
public void ensureEmptyGuestIdsAreIgnored() throws Exception { Owner owner = new Owner("admin"); Map<String, ArrayList<GuestId>> hostGuestMap = new HashMap<String, ArrayList<GuestId>>(); hostGuestMap.put("HYPERVISOR_A", new ArrayList(Arrays.asList(new GuestId("GUEST_A"), new GuestId("")))); when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner); when(consumerCurator.getHostConsumersMap(any(Owner.class), any(Set.class))). thenReturn(new VirtConsumerMap()); when(consumerCurator.getGuestConsumersMap(any(Owner.class), any(Set.class))). thenReturn(new VirtConsumerMap()); when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner); when(principal.canAccess(eq(owner), eq(SubResource.CONSUMERS), eq(Access.CREATE))). thenReturn(true); when(consumerTypeCurator.lookupByLabel( eq(ConsumerTypeEnum.HYPERVISOR.getLabel()))).thenReturn(hypervisorType); when(idCertService.generateIdentityCert(any(Consumer.class))) .thenReturn(new IdentityCertificate()); HypervisorCheckInResult result = null; try { result = hypervisorResource.hypervisorUpdate(hostGuestMap, principal, owner.getKey(), true); } catch (PersistenceException e) { fail("Expected no exception"); } assertTrue(result != null); assertTrue(result.getCreated() != null); Consumer[] created = result.getCreated().toArray(new Consumer[1]); assertTrue(created.length == 1); List<GuestId> gids = created[0].getGuestIds(); assertTrue(gids.size() == 1); }

Target:
public void ensureEmptyGuestIdsAreIgnored() throws Exception { Owner owner = new Owner("admin"); Map<String, List<GuestId>> hostGuestMap = new HashMap<String, List<GuestId>>(); hostGuestMap.put("HYPERVISOR_A", new ArrayList( Arrays.asList(new GuestId("GUEST_A"), new GuestId("")))); when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner); when(consumerCurator.getHostConsumersMap(any(Owner.class), any(Set.class))) .thenReturn(new VirtConsumerMap()); when(consumerCurator.getGuestConsumersMap(any(Owner.class), any(Set.class))) .thenReturn(new VirtConsumerMap()); when(ownerCurator.lookupByKey(eq(owner.getKey()))).thenReturn(owner); when(principal.canAccess(eq(owner), eq(SubResource.CONSUMERS), eq(Access.CREATE))) .thenReturn(true); when(consumerTypeCurator.lookupByLabel(eq(ConsumerTypeEnum.HYPERVISOR.getLabel()))) .thenReturn(hypervisorType); when(idCertService.generateIdentityCert(any(Consumer.class))) .thenReturn(new IdentityCertificate()); HypervisorCheckInResult result = hypervisorResource.hypervisorUpdate( hostGuestMap, principal, owner.getKey(), true); assertNotNull(result); assertNotNull(result.getCreated()); List<Consumer> created = new ArrayList<Consumer>(result.getCreated()); assertEquals(1, created.size()); List<GuestId> gids = created.get(0).getGuestIds(); assertEquals(1, gids.size()); }
Source:
public TopologySummary getTopologySummaryByName(String name) throws AuthorizationException, TException { try { getTopologySummaryByNameCalls.mark(); checkAuthorization(null, null, "getTopologySummaries"); IStormClusterState state = stormClusterState; String topoId = state.getTopoId(name).orElseThrow(() -> new WrappedNotAliveException(name + " is not alive")); return getTopologySummary(topoId, state.topologyBases().get(topoId)); } catch (Exception e) { LOG.warn("Get TopologySummaryByName info exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }

Target:
public TopologySummary getTopologySummaryByName(String name) throws NotAliveException, AuthorizationException, TException { try { getTopologySummaryByNameCalls.mark(); checkAuthorization(name, null, "getTopologySummaryByName"); IStormClusterState state = stormClusterState; String topoId = state.getTopoId(name).orElseThrow(() -> new WrappedNotAliveException(name + " is not alive")); return getTopologySummaryImpl(topoId, state.topologyBases().get(topoId)); } catch (Exception e) { LOG.warn("Get TopologySummaryByName info exception.", e); if (e instanceof TException) { throw (TException) e; } throw new RuntimeException(e); } }
Source:
private Player getRandomPlayer(boolean allowDevs) { final Collection<? extends Player> players = Bukkit.getOnlinePlayers(); if (players.isEmpty()) { return null; } if (!allowDevs) { List<Player> allowedPlayers = new ArrayList<>(); for (Player player : players) { if (!FUtil.DEVELOPERS.contains(player.getName())) { allowedPlayers.add(player); } if (!FUtil.FOUNDER.contains(player.getName())) { allowedPlayers.add(player); } } return allowedPlayers.get(random.nextInt(allowedPlayers.size())); } return (Player) players.toArray()[random.nextInt(players.size())]; }

Target:
private Player getRandomPlayer(boolean allowDevs) { final Collection<? extends Player> players = Bukkit.getOnlinePlayers(); if (players.isEmpty()) { return null; } if (!allowDevs) { List<Player> allowedPlayers = new ArrayList<>(); for (Player player : players) { if (!FUtil.DEVELOPERS.contains(player.getName())) { allowedPlayers.add(player); } } return allowedPlayers.get(random.nextInt(allowedPlayers.size())); } return (Player) players.toArray()[random.nextInt(players.size())]; }
Source:
protected Optional<CoverageReportView> getCoverageReportView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity != null) { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); } else { return Optional.empty(); } }

Target:
protected Optional<CoverageReportView> getCoverageReportView(PlaceRequest placeRequest) { final Activity activity = placeManager.getActivity(placeRequest); if (activity == null) { return Optional.empty(); } else { final AbstractWorkbenchActivity coverageActivity = (AbstractWorkbenchActivity) activity; return Optional.of((CoverageReportView) coverageActivity.getWidget()); } }
Source:
public ResourceLocation getShaderType() { return new ResourceLocation("immersiveengineering", "drill"); }

Target:
public ResourceLocation getShaderType() { return new ResourceLocation(ImmersiveEngineering.MODID, "drill"); }
Source:
protected static GoExpression findExpressionAtOffset(GoIntroduceOperation operation) { PsiFile file = operation.getFile(); int offset = operation.getEditor().getCaretModel().getOffset(); PsiElement element = file.findElementAt(offset); GoParenthesesExpr parenthesesParent = PsiTreeUtil.getParentOfType(element, GoParenthesesExpr.class); if (element instanceof PsiWhiteSpace || (parenthesesParent != null && parenthesesParent.getRparen() == element)) { element = file.findElementAt(offset - 1); } return element instanceof GoExpression ? (GoExpression)element : PsiTreeUtil.getParentOfType(element, GoExpression.class); }

Target:
private static GoExpression findExpressionAtOffset(GoIntroduceOperation operation) { PsiFile file = operation.getFile(); int offset = operation.getEditor().getCaretModel().getOffset(); GoExpression expr = PsiTreeUtil.getNonStrictParentOfType(file.findElementAt(offset), GoExpression.class); GoExpression preExpr = PsiTreeUtil.getNonStrictParentOfType(file.findElementAt(offset - 1), GoExpression.class); if (expr == null || preExpr != null && PsiTreeUtil.isAncestor(expr, preExpr, false)) return preExpr; return expr; }
Source:
public List<SqlFunction> listFunctions(Session session) { Set<String> managerIds = isListBuiltInFunctionsOnly(session) ? ImmutableSet.of(BuiltInFunctionNamespaceManager.ID) : functionNamespaceManagers.keySet(); ImmutableList.Builder<SqlFunction> functions = ImmutableList.builder(); for (String managerId : managerIds) { FunctionNamespaceManager<? extends SqlFunction> manager = functionNamespaceManagers.get(managerId); Set<CatalogSchemaPrefix> servingNamespaces = this.servingNamespaces.get().get(managerId); for (SqlFunction function : manager.listFunctions()) { CatalogSchemaName functionNamespace = function.getSignature().getName().getFunctionNamespace(); if (!servingNamespaces.contains(functionNamespace.asCatalogSchemaPrefix()) && !servingNamespaces.contains(new CatalogSchemaPrefix(functionNamespace.getCatalogName(), Optional.empty()))) { throw new PrestoException( GENERIC_INTERNAL_ERROR, format("Invalid function [%s] found in function namespace manager [%s]", function.getSignature().getName(), managerId)); } if (function.getVisibility() == PUBLIC || (function.getVisibility() == EXPERIMENTAL && isExperimentalFunctionsEnabled(session))) { functions.add(function); } } } return functions.build(); }

Target:
public List<SqlFunction> listFunctions(Session session) { Collection<FunctionNamespaceManager<?>> managers = isListBuiltInFunctionsOnly(session) ? ImmutableSet.of(builtInFunctionNamespaceManager) : functionNamespaceManagers.values(); return managers.stream() .flatMap(manager -> manager.listFunctions().stream()) .filter(function -> function.getVisibility() == PUBLIC || (function.getVisibility() == EXPERIMENTAL && SystemSessionProperties.isExperimentalFunctionsEnabled(session))) .collect(toImmutableList()); }
Source:
public void setUp() throws Exception { if (!hasCleared) { clearTestRegistries(); hasCleared = true; } bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout, true, StandardCharsets.UTF_8)); }

Target:
public void setUp() throws Exception { if (!hasCleared) { clearTestRegistries(); hasCleared = true; } bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout, true, StandardCharsets.UTF_8.name())); }
Source:
public int updateUploading(String filePath, boolean uploading) { ContentValues cv = new ContentValues(); cv.put(ProviderTableMeta.FILE_UPLOADING, uploading); int result = getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, ProviderTableMeta.FILE_PATH + "=? AND "+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { filePath, mAccount.name }); Log_OC.d(TAG, "updateUploading, result=" + String.valueOf(result)); return result; }

Target:
public int updateUploading(String filePath, boolean uploading) { ContentValues cv = new ContentValues(); cv.put(ProviderTableMeta.FILE_UPLOADING, uploading); int result = -1; if (getContentResolver() != null) { result = getContentResolver().update(ProviderTableMeta.CONTENT_URI, cv, ProviderTableMeta.FILE_PATH + "=? AND "+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { filePath, mAccount.name }); } else { try { result = getContentProvider().update(ProviderTableMeta.CONTENT_URI, cv, ProviderTableMeta.FILE_PATH + "=? AND "+ ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { filePath, mAccount.name }); } catch (RemoteException e) { Log_OC.e(TAG, "Fail to update 'uploading' of " + filePath + " in database", e); } } return result; }
Source:
public synchronized void notifyManager() { _logger.debug(String.format("Notifying Manager for %s", this.getClass().getName())); try { _metricManager.reportMetric( (IMetric<?>) this.clone()); } catch (NullPointerException ex) { _logger.error(String.format("Metric Manager is not set for %s metric %s", this.getClass().getName(), ex.toString())); } catch (CloneNotSupportedException ex) { _logger.error(String.format("Failed to take snapshot for %s metric %s", this.getClass().getName(), ex.toString())); } }

Target:
public void notifyManager() { logger.debug(String.format("Notifying Manager for %s", this.getClass().getName())); try { metricManager.reportMetric(this); } catch (Throwable ex) { logger.error(String.format("Metric Manager is not set for %s metric", this.getClass().getName()), ex); } }
Source:
protected boolean parseHeader(ParsableByteArray data) throws UnsupportedFormatException { if (!hasParsedAudioDataHeader) { int header = data.readUnsignedByte(); audioFormat = (header >> 4) & 0x0F; if (audioFormat == AUDIO_FORMAT_MP3) { int sampleRateIndex = (header >> 2) & 0x03; if (sampleRateIndex < 0 || sampleRateIndex >= AUDIO_SAMPLING_RATE_TABLE.length) { Log.d(TAG, "Invalid sample rate, attempting to read at 44.1k"); sampleRateIndex = 3; } int sampleRate = AUDIO_SAMPLING_RATE_TABLE[sampleRateIndex]; Format format = Format.createAudioSampleFormat(null, MimeTypes.AUDIO_MPEG, null, Format.NO_VALUE, Format.NO_VALUE, 1, sampleRate, null, null, 0, null); output.format(format); hasOutputFormat = true; } else if (audioFormat == AUDIO_FORMAT_ALAW || audioFormat == AUDIO_FORMAT_ULAW) { String type = audioFormat == AUDIO_FORMAT_ALAW ? MimeTypes.AUDIO_ALAW : MimeTypes.AUDIO_ULAW; int pcmEncoding = (header & 0x01) == 1 ? C.ENCODING_PCM_16BIT : C.ENCODING_PCM_8BIT; Format format = Format.createAudioSampleFormat(null, type, null, Format.NO_VALUE, Format.NO_VALUE, 1, 8000, pcmEncoding, null, null, 0, null); output.format(format); hasOutputFormat = true; } else if (audioFormat != AUDIO_FORMAT_AAC) { throw new UnsupportedFormatException("Audio format not supported: " + audioFormat); } hasParsedAudioDataHeader = true; } else { data.skipBytes(1); } return true; }

Target:
protected boolean parseHeader(ParsableByteArray data) throws UnsupportedFormatException { if (!hasParsedAudioDataHeader) { int header = data.readUnsignedByte(); audioFormat = (header >> 4) & 0x0F; if (audioFormat == AUDIO_FORMAT_MP3) { int sampleRateIndex = (header >> 2) & 0x03; int sampleRate = AUDIO_SAMPLING_RATE_TABLE[sampleRateIndex]; Format format = Format.createAudioSampleFormat(null, MimeTypes.AUDIO_MPEG, null, Format.NO_VALUE, Format.NO_VALUE, 1, sampleRate, null, null, 0, null); output.format(format); hasOutputFormat = true; } else if (audioFormat == AUDIO_FORMAT_ALAW || audioFormat == AUDIO_FORMAT_ULAW) { String type = audioFormat == AUDIO_FORMAT_ALAW ? MimeTypes.AUDIO_ALAW : MimeTypes.AUDIO_ULAW; int pcmEncoding = (header & 0x01) == 1 ? C.ENCODING_PCM_16BIT : C.ENCODING_PCM_8BIT; Format format = Format.createAudioSampleFormat(null, type, null, Format.NO_VALUE, Format.NO_VALUE, 1, 8000, pcmEncoding, null, null, 0, null); output.format(format); hasOutputFormat = true; } else if (audioFormat != AUDIO_FORMAT_AAC) { throw new UnsupportedFormatException("Audio format not supported: " + audioFormat); } hasParsedAudioDataHeader = true; } else { data.skipBytes(1); } return true; }
Source:
public static boolean isInformationSchema(Schema schema) { String name = schema.getName(); if (name == null) { return false; } return MetaModelHelper.isInformationSchema(schema); }

Target:
public static boolean isInformationSchema(Schema schema) { return MetaModelHelper.isInformationSchema(schema); }
Source:
private void createIndex() { lastFoundElementPosition = 0; filteredPlan.clear(); for (PlanElement element : plan.getList()) { if (!element.isComment()) { filteredPlan.add(element); } } }

Target:
private void createIndex() { lastFoundElementPosition = 0; filteredPlan.clear(); for (PlanElement element : plan.getList()) { if (!element.isComment()) filteredPlan.add(element); } }
Source:
public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { if (!ta.isFinished()) { earliestUnfinishedAttempt = ta; } } NodeId nodeId = earliestUnfinishedAttempt.getNodeId(); task.unhealthyNodesHistory.add(nodeId); LOG.info("A long-tailed attempt was running on node {}, adding it to the task's unhealthy node history.", nodeId, earliestUnfinishedAttempt.getID()); task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }

Target:
public void transition(TaskImpl task, TaskEvent event) { LOG.info("Scheduling a redundant attempt for task " + task.taskId); task.counters.findCounter(TaskCounter.NUM_SPECULATIONS).increment(1); TaskAttempt earliestUnfinishedAttempt = null; for (TaskAttempt ta : task.attempts.values()) { if (!ta.isFinished()) { earliestUnfinishedAttempt = ta; task.nodesWithRunningAttempts.add(ta.getNodeId()); } } task.addAndScheduleAttempt(earliestUnfinishedAttempt.getID()); }
Source:
private void validateOATag(final File testSam, final File truthSam) { final ArrayList<String> truthOAValues = new ArrayList<>(); final ArrayList<String> testOAValues = new ArrayList<>(); SAMRecordIterator iterator = SamReaderFactory.makeDefault().open(truthSam).iterator(); while (iterator.hasNext()){ SAMRecord rec = iterator.next(); truthOAValues.add(rec.getStringAttribute(AddOATag.OA)); } iterator = SamReaderFactory.makeDefault().open(testSam).iterator(); while (iterator.hasNext()){ SAMRecord rec = iterator.next(); testOAValues.add(rec.getStringAttribute(AddOATag.OA)); } Assert.assertEquals(testOAValues, truthOAValues); }

Target:
private static void validateOATag(final File testSam, final File truthSam) { final ArrayList<String> truthOAValues = new ArrayList<>(); final ArrayList<String> testOAValues = new ArrayList<>(); SAMRecordIterator iterator = SamReaderFactory.makeDefault().open(truthSam).iterator(); while (iterator.hasNext()) { SAMRecord rec = iterator.next(); truthOAValues.add(rec.getStringAttribute(AddOATag.OA)); } iterator = SamReaderFactory.makeDefault().open(testSam).iterator(); while (iterator.hasNext()) { SAMRecord rec = iterator.next(); testOAValues.add(rec.getStringAttribute(AddOATag.OA)); } Assert.assertEquals(testOAValues, truthOAValues); }
Source:
private static Guid getEntityId(String fileName) { return Guid.createGuidFromString(fileName.substring(0, fileName.indexOf(".ovf"))); }

Target:
private static Guid getEntityId(String fileName) { return Guid.createGuidFromString(fileName.substring(0, fileName.length() - OVF_FILE_EXT.length())); }
Source:
public static ExternalIdBundle parse(Iterable<String> strs) { ArgChecker.noNulls(strs, "strs"); List<ExternalId> externalIds = StreamSupport.stream(strs.spliterator(), false) .map(ExternalId::parse) .collect(Collectors.toList()); return create(externalIds); }

Target:
public static ExternalIdBundle parse(Iterable<String> strs) { ArgChecker.noNulls(strs, "strs"); Set<ExternalId> ids = StreamSupport.stream(strs.spliterator(), false) .map(ExternalId::parse) .collect(Collectors.toSet()); return create(ids); }
Source:
public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } this.encoder = CharsetUtil.encoder(charset); }

Target:
public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } this.charset = charset; }
Source:
public Gff3Writer(final Path path) throws IOException { if (!FileExtensions.GFF3.stream().anyMatch(e -> path.toString().endsWith(e))) { throw new TribbleException("File " + path + " does not have extension consistent with gff3"); } final OutputStream outputStream = IOUtil.hasGzipFileExtension(path)? new GZIPOutputStream(Files.newOutputStream(path)) : Files.newOutputStream(path); out = new PrintStream(outputStream); initialize(); }

Target:
public Gff3Writer(final Path path) throws IOException { if (FileExtensions.GFF3.stream().noneMatch(e -> path.toString().endsWith(e))) { throw new TribbleException("File " + path + " does not have extension consistent with gff3"); } final OutputStream outputStream = IOUtil.hasGzipFileExtension(path)? new BlockCompressedOutputStream(path.toFile()) : Files.newOutputStream(path); out = new BufferedOutputStream(outputStream); initialize(); }
Source:
public void createCSR() { if (StringUtils.isBlank(getAlias())) { HelperUtil.addMessageError(null, "Required fields cannot be empty when creating CSR."); return; } csrFile = null; SimpleCertificateResponseMessageType response = service.createCSR(getAlias()); if (null != response && response.isStatus()) { HelperUtil.addMessageInfo(null, MessageFormat.format("Successfully created CSR for: {0}", getAlias())); if(null != response.getCsrData()){ DataHandler data = response.getCsrData(); String filename = MessageFormat.format("{0}-{1}.csr", getAlias(), CoreHelpUtils.formatDate("yyyyMMdd", new Date())); try { csrFile = new DefaultStreamedContent(data.getInputStream(), data.getContentType(), filename); } catch (IOException e) { LOG.error("unable to open input-stream from response", e.getLocalizedMessage(), e); } } } else { HelperUtil.addMessageError(null, MessageFormat.format("Failed to create CSR for: {0}", getAlias())); } }

Target:
public void createCSR() { if (StringUtils.isBlank(getAlias())) { HelperUtil.addMessageError(null, "Required fields cannot be empty when creating CSR."); return; } csrFile = null; SimpleCertificateResponseMessageType response = service.createCSR(getAlias()); if (null != response && response.isStatus()) { HelperUtil.addMessageInfo(null, MessageFormat.format("Successfully created CSR for: {0}", getAlias())); if(null != response.getCsrData()){ DataHandler data = response.getCsrData(); String filename = MessageFormat.format("{0}-{1}.csr", getAlias(), CoreHelpUtils.formatDate("yyyyMMdd", new Date())); try { csrFile = new DefaultStreamedContent(data.getInputStream(), data.getContentType(), filename); } catch (IOException e) { LOG.error(ERROR_INPUTSTREAM, e.getLocalizedMessage(), e); HelperUtil.addMessageError(null, ERROR_INPUTSTREAM); } } } else { HelperUtil.addMessageError(null, MessageFormat.format("Failed to create CSR for: {0}", getAlias())); } }
Source:
public static Vector num2Vec(int num, int vecSize) { return new DenseLocalOnHeapVector(vecSize).setX(num, 1); }

Target:
public static Vector num2Vec(int num, int vecSize) { return num2Vec(num, vecSize, false); }
Source:
public CharSequence apply(final String context, final Options options) throws IOException { final List<String> languageTags = getLocales(options); final String language = languageTags.get(0); final String[] parts = StringUtils.split(context, ':'); final boolean usingDefaultBundle = parts.length == 1; final String bundle = usingDefaultBundle ? "translations" : parts[0]; final boolean containsPlural = containsPlural(options); final String key = usingDefaultBundle ? context : parts[1]; final String resolvedValue = containsPlural ? Optional.ofNullable(resolve(language, bundle, key + "_plural")).orElseGet(() -> resolve(language, bundle, key)) : resolve(language, bundle, key); String parametersReplaced = StringUtils.defaultString(resolvedValue); for (final Map.Entry<String, Object> entry : options.hash.entrySet()) { parametersReplaced = parametersReplaced.replace("__" + entry.getKey() + "__", entry.getValue().toString()); } return parametersReplaced; }

Target:
public CharSequence apply(final String context, final Options options) throws IOException { final List<String> languageTags = getLocales(options); final String language = languageTags.get(0); final TranslationIdentifier translationIdentifier = obtainTranslationIdentifier(context); final String bundle = translationIdentifier.bundle; final String key = translationIdentifier.key; final String resolvedValue = pluralize(options, language, bundle, key); return replaceParameters(options, resolvedValue); }
Source:
public RetryPolicyOptions(RetryStrategy retryStrategy, String retryAfterHeader, ChronoUnit retryAfterTimeUnit) { this.retryStrategy = Objects.requireNonNull(retryStrategy, "'retryStrategy' cannot be null."); this.retryAfterHeader = retryAfterHeader; this.retryAfterTimeUnit = retryAfterTimeUnit; if (!isNullOrEmpty(retryAfterHeader)) { Objects.requireNonNull(retryAfterTimeUnit, "'retryAfterTimeUnit' cannot be null."); } }

Target:
public RetryPolicyOptions(RetryStrategy retryStrategy, String retryAfterHeader, ChronoUnit retryAfterTimeUnit) { if (Objects.isNull(retryStrategy)) { this.retryStrategy = new ExponentialBackoff(); } else { this.retryStrategy = retryStrategy; } this.retryAfterHeader = retryAfterHeader; this.retryAfterTimeUnit = retryAfterTimeUnit; if (!isNullOrEmpty(retryAfterHeader)) { Objects.requireNonNull(retryAfterTimeUnit, "'retryAfterTimeUnit' cannot be null."); } }
Source:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { LOGGER.error("Failed to call killAllJobs on listener={} error={}", t, killAllListener); } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }

Target:
public CompletableFuture<Integer> killAll() { for (KillAllListener killAllListener : killAllListeners) { try { killAllListener.killAllJobs(); } catch (Throwable t) { LOGGER.error("Failed to call killAllJobs on listener={} error={}", killAllListener, t); } } Collection<UUID> toKill = ImmutableList.copyOf(activeTasks.keySet()); if (toKill.isEmpty()) { return CompletableFuture.completedFuture(0); } return killTasks(toKill, null); }
Source:
public static void main(String[] args) throws InterruptedException { Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices.builder() .discovery(serviceEndpoint -> serviceDiscovery(serviceEndpoint, seed)) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); ServiceCall service = seed.call(); ServiceMessage request = ServiceMessage.builder().qualifier(SERVICE_QUALIFIER).data("joe").build(); Publisher<ServiceMessage> publisher = service.requestOne(request, Greeting.class); Mono.from(publisher) .subscribe( consumer -> { Greeting greeting = consumer.data(); System.out.println(greeting.message()); }); Thread.currentThread().join(); }

Target:
public static void main(String[] args) { Microservices seed = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .startAwait(); Microservices ms = Microservices.builder() .discovery(serviceEndpoint -> serviceDiscovery(serviceEndpoint, seed)) .transport(ServiceTransports::rsocketServiceTransport) .services(new GreetingServiceImpl()) .startAwait(); ServiceCall service = seed.call(); ServiceMessage request = ServiceMessage.builder().qualifier(SERVICE_QUALIFIER).data("joe").build(); Publisher<ServiceMessage> publisher = service.requestOne(request, Greeting.class); Mono.from(publisher) .subscribe( consumer -> { Greeting greeting = consumer.data(); System.out.println(greeting.message()); }); seed.onShutdown().block(); ms.onShutdown().block(); }
Source:
public static Optional<List<Parameter>> getParametersList(io.swagger.oas.annotations.Parameter[] parameters) { if (parameters == null) { return Optional.empty(); } List<Parameter> parametersObject = new ArrayList<>(); for (io.swagger.oas.annotations.Parameter parameter : parameters) { Parameter parameterObject = new Parameter(); parameterObject.setDescription(parameter.description()); parameterObject.setDeprecated(parameter.deprecated()); parameterObject.setName(parameter.name()); parameterObject.setRequired(parameter.required()); parameterObject.setStyle(StringUtils.isNoneBlank(parameter.style()) ? Parameter.StyleEnum.valueOf(parameter.style()) : null); parameterObject.setAllowEmptyValue(parameter.allowEmptyValue()); parameterObject.setAllowReserved(parameter.allowReserved()); parameterObject.setExplode(parameter.explode()); parameterObject.setIn(parameter.in()); parameterObject.setContent(getContents(parameter.content()).get()); parametersObject.add(parameterObject); } return Optional.of(parametersObject); }

Target:
public static Optional<List<Parameter>> getParametersList(io.swagger.oas.annotations.Parameter[] parameters) { if (parameters == null) { return Optional.empty(); } List<Parameter> parametersObject = new ArrayList<>(); for (io.swagger.oas.annotations.Parameter parameter : parameters) { getParameter(parameter).ifPresent(parametersObject::add); } return Optional.of(parametersObject); }
Source:
public Optional<List<String>> getProjectDependencies(){ return Optional.ofNullable(projectDependencies); }

Target:
public List<String> getProjectDependencies(){ return projectDependencies != null ? projectDependencies : Collections.emptyList(); }
Source:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); if (tempFile != null && tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }

Target:
private void validateFolderName(String folderName) throws IOException { File tempFile = new File(folderName); if (tempFile.getParent() != null) { String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator." + " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders"; throw new IOException(errorMsg); } }
Source:
public void onProjectileLaunch(ProjectileLaunchEvent event) { ConfigurationManager cfg = plugin.getGlobalStateManager(); WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld()); if (event.getEntityType() == EntityType.ARROW && wcfg.disableArrowShooting) { event.setCancelled(true); } }

Target:
public void onProjectileLaunch(ProjectileLaunchEvent event) { ConfigurationManager cfg = plugin.getGlobalStateManager(); WorldConfiguration wcfg = cfg.get(event.getEntity().getWorld()); if (wcfg.disableArrowShooting && event.getEntityType() == EntityType.ARROW) { event.setCancelled(true); } }
Source:
public ValueMatcher makeValueMatcher(String[] dimensions, final Predicate<Object[]> predicate) { final int[] dimIndices = new int[dimensions.length]; for (int i = 0; i < dimensions.length; i++) { Integer dimIndexObject = index.getDimensionIndex(dimensions[i]); if (dimIndexObject == null) { return BooleanValueMatcher.FALSE; } dimIndices[i] = dimIndexObject; } final Object[] current = new String[dimIndices.length]; return new ValueMatcher() { @Override public boolean matches() { String[][] selected = new String[dimIndices.length][]; int[] currentIdx = new int[dimIndices.length]; String[][] dims = holder.getKey().getDims(); for (int idx = 0; idx < dimIndices.length; idx++) { if (dimIndices[idx] >= dims.length) { return predicate.apply(null); } selected[idx] = dims[dimIndices[idx]]; if (selected[idx] == null) { current[idx] = null; selected[idx] = new String[0]; } else { current[idx] = selected[idx][0]; } currentIdx[idx] = 0; } if (predicate.apply(current)) { return true; } int currentIteratorIdx = 0; while (true) { currentIdx[currentIteratorIdx]++; if (currentIdx[currentIteratorIdx] < selected[currentIteratorIdx].length) { current[currentIteratorIdx] = selected[currentIteratorIdx][currentIdx[currentIteratorIdx]]; if (currentIteratorIdx > 0) { for (int idx = 0; idx < currentIteratorIdx; idx++) { currentIdx[idx] = 0; current[idx] = selected[idx][0]; } currentIteratorIdx = 0; } if (predicate.apply(current)) { return true; } } else { currentIteratorIdx++; if (currentIteratorIdx == dimIndices.length) { break; } } } return false; } }; }

Target:
public ValueMatcher makeValueMatcher(String[] dimensions, final Predicate<Object[]> predicate) { final int[] dimIndices = new int[dimensions.length]; final IncrementalIndex.DimDim[] dimValues = new IncrementalIndex.DimDim[dimensions.length]; Arrays.fill(dimIndices, -1); for (int i = 0; i < dimensions.length; i++) { IncrementalIndex.DimensionDesc dimensionDesc = index.getDimension(dimensions[i]); if (dimensionDesc != null) { dimIndices[i] = dimensionDesc.getIndex(); dimValues[i] = dimensionDesc.getValues(); } } return new ValueMatcher() { private final List<Object>[] dimValuesList = new List[dimIndices.length]; @Override public boolean matches() { int[][] dims = holder.getKey().getDims(); for (int i = 0; i < dimIndices.length; i++) { if (dimIndices[i] < 0 || dimIndices[i] >= dims.length) { dimValuesList[i] = EMPTY_PARAM; continue; } int[] dimIdx = dims[dimIndices[i]]; if (dimIdx == null || dimIdx.length == 0) { dimValuesList[i] = EMPTY_PARAM; } else { dimValuesList[i] = Lists.newArrayListWithCapacity(dimIdx.length); for (int j = 0; j < dimIdx.length; j++) { dimValuesList[i].add(dimValues[i].getValue(dimIdx[j])); } } } for (Object[] param : IterableUtils.cartesian(Object.class, dimValuesList)) { if (predicate.apply(param)) { return true; } } return false; } }; }
Source:
public boolean setBlueprintProvisioningState(BlueprintProvisioningState blueprintProvisioningState) { boolean updated = false; for (Service s : getServices().values()) { for (ServiceComponent sc : s.getServiceComponents().values()) { if (!sc.isClientComponent()) { for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) { HostComponentDesiredStateEntity desiredStateEntity = sch.getDesiredStateEntity(); if (desiredStateEntity.getBlueprintProvisioningState() != blueprintProvisioningState) { desiredStateEntity.setBlueprintProvisioningState(blueprintProvisioningState); hostComponentDesiredStateDAO.merge(desiredStateEntity); updated = true; } } } } } return updated; }

Target:
private boolean setBlueprintProvisioningState(BlueprintProvisioningState blueprintProvisioningState) { boolean updated = false; for (Service s : getServices().values()) { for (ServiceComponent sc : s.getServiceComponents().values()) { if (!sc.isClientComponent()) { for (ServiceComponentHost sch : sc.getServiceComponentHosts().values()) { HostComponentDesiredStateEntity desiredStateEntity = sch.getDesiredStateEntity(); if (desiredStateEntity.getBlueprintProvisioningState() != blueprintProvisioningState) { desiredStateEntity.setBlueprintProvisioningState(blueprintProvisioningState); hostComponentDesiredStateDAO.merge(desiredStateEntity); updated = true; } } } } } return updated; }
Source:
public void setUp () { senseiServiceProxy = new SenseiServiceProxy("localhost", 9000); }

Target:
public void setUp () { senseiServiceProxy = new SenseiServiceProxy("localhost", 8080); }
Source:
private void addDevicesToEntity(UserDto userDto, User userEntity) { userDto.getOwnPrivateData().getDevices().stream().map(d -> (UserDeviceDto) d).map(d -> createUserDeviceEntity(d, 0)) .forEach(d -> userEntity.addDevice(d)); }

Target:
private void addDevicesToEntity(UserDto userDto, User userEntity) { userDto.getOwnPrivateData().getDevices().orElse(Collections.emptySet()).stream().map(d -> (UserDeviceDto) d) .map(d -> createUserDeviceEntity(d, 0)).forEach(d -> userEntity.addDevice(d)); }
Source:
public static Block slice( @TypeParameter("E") Type type, @SqlType("array(E)") Block array, @SqlType(StandardTypes.BIGINT) long fromIndex, @SqlType(StandardTypes.BIGINT) long length) { checkCondition(length >= 0, INVALID_FUNCTION_ARGUMENT, "length must be greater than or equal to 0"); checkCondition(fromIndex != 0, INVALID_FUNCTION_ARGUMENT, "SQL array indices start at 1"); int size = array.getPositionCount(); if (size == 0) { return array; } if (fromIndex < 0) { fromIndex = size + fromIndex + 1; } long toIndex = Math.min(fromIndex + length, size + 1); if (fromIndex >= toIndex || fromIndex < 1 || toIndex < 0) { return type.createBlockBuilder(new BlockBuilderStatus(), 0).build(); } return array.getRegion((int) (fromIndex - 1), (int) (toIndex - fromIndex)); }

Target:
public static Block slice( @TypeParameter("E") Type type, @SqlType("array(E)") Block array, @SqlType(StandardTypes.BIGINT) long fromIndex, @SqlType(StandardTypes.BIGINT) long length) { checkCondition(length >= 0, INVALID_FUNCTION_ARGUMENT, "length must be greater than or equal to 0"); checkCondition(fromIndex != 0, INVALID_FUNCTION_ARGUMENT, "SQL array indices start at 1"); int size = array.getPositionCount(); if (size == 0) { return array; } if (fromIndex < 0) { fromIndex = size + fromIndex + 1; } long toIndex = Math.min(fromIndex + length, size + 1); if (fromIndex >= toIndex || fromIndex < 1) { return type.createBlockBuilder(new BlockBuilderStatus(), 0).build(); } return array.getRegion((int) (fromIndex - 1), (int) (toIndex - fromIndex)); }
Source:
public List<Runnable> shutdownNow() { shutdown = true; List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); controllerThread.interrupt(); return runnableList; }

Target:
public List<Runnable> shutdownNow() { shutdown = true; controllerThread.interrupt(); List<Runnable> runnableList = new LinkedList<>(); runnableList.addAll(executorService.shutdownNow()); runnableList.addAll(blockedTasks); return runnableList; }
Source:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return tokens[4].substring(0, tokens[4].length() - 4); }

Target:
private String getRepositoryName(String location) { final String[] tokens = location.split(SEPARATOR); return (location.endsWith(GIT_EXTENSION)) ? tokens[4].substring(0, tokens[4].length() - 4) : tokens[4].substring(0); }
Source:
NamedTableNode(String alias, TableName name) { super(alias, name); this.dyn_columns = new ArrayList<ColumnDef>(); }

Target:
NamedTableNode(String alias, TableName name) { super(alias, name); dyncolumns = Collections.<ColumnDef>emptyList(); }
Source:
public AuditContext(final ConnectionProvider connectionProvider, final DialectName dialect, final String schema) { final JaversSqlRepository repository = SqlRepositoryBuilder.sqlRepository() .withConnectionProvider(connectionProvider) .withDialect(dialect) .withSchema(schema) .build(); this.javers = JaversBuilder.javers() .registerJaversRepository(repository) .build(); PersistenceListenerManager.getInstance().addListener(new PersistenceListener() { @Override public void onEntityPersisted(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } @Override public void onEntityRemoved(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commitShallowDelete(getAuthor(), entity); } } @Override public void onEntityUpdated(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } }); }

Target:
public AuditContext(final ConnectionProvider connectionProvider, final DialectName dialect, final String schema) { Assert.requireNonNull(connectionProvider , "connectionProvider"); Assert.requireNonNull(dialect , "dialect"); Assert.requireNonNull(schema , "schema"); final JaversSqlRepository repository = SqlRepositoryBuilder.sqlRepository() .withConnectionProvider(connectionProvider) .withDialect(dialect) .withSchema(schema) .build(); this.javers = JaversBuilder.javers() .registerJaversRepository(repository) .build(); PersistenceListenerManager.getInstance().addListener(new PersistenceListener() { @Override public void onEntityPersisted(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } @Override public void onEntityRemoved(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commitShallowDelete(getAuthor(), entity); } } @Override public void onEntityUpdated(final AbstractEntity entity) { if(isAuditable(entity)) { javers.commit(getAuthor(), entity); } } }); }
Source:
public void run() { ObjectInputStream br = null; try { br = new ObjectInputStream(client.getInputStream()); while (br != null) { Object streamObject = br.readObject(); if(streamObject instanceof Contact) { Contact ct = (Contact) streamObject; System.out.println("Got contact first=" + ct.getFirstName() + " last=" + ct.getLastName() + " number=" + ct.getPhoneNumber()); } else if(streamObject instanceof TextMessage) { TextMessage txtMessage = (TextMessage) streamObject; txtMessage.setReceiver(new Contact("Jonathan", "Mielke", "6185204620", "")); System.out.println("Client: " + txtMessage.getContent()); System.out.println("TEXT ADDED TO ARRAY"); TaskBar.myTextArray.add(txtMessage); synchronized(TaskBar.textManager){ TaskBar.textManager.notify(); } } else{ System.out.println("Unknown object sent through stream"); } } } catch (Exception e) { System.out.println(e.getMessage() + " inside run()"); } }

Target:
public void run() { Contact user = new Contact("Jonathan", "Mielke", "6185204620", ""); ObjectInputStream br = null; try { br = new ObjectInputStream(client.getInputStream()); while (br != null) { Object streamObject = br.readObject(); if(streamObject instanceof Contact) { Contact ct = (Contact) streamObject; System.out.println("Got contact first=" + ct.getFirstName() + " last=" + ct.getLastName() + " number=" + ct.getPhoneNumber()); } else if(streamObject instanceof TextMessage) { TextMessage txtMessage = (TextMessage) streamObject; txtMessage.setReceiver(user); System.out.println("Client: " + txtMessage.getContent()); System.out.println("TEXT ADDED TO ARRAY"); TaskBar.myTextArray.add(txtMessage); synchronized(TaskBar.textManager){ TaskBar.textManager.notify(); } } else{ System.out.println("Unknown object sent through stream"); } } } catch (Exception e) { System.out.println(e.getMessage() + " inside run()"); } }
Source:
public void sendStringTest() throws Exception { String garbageString = "This string is garbage that needs to be cleared."; String searchString = "sugarcrm"; iface.go(elementsPage); WebDriverElement textField = iface.getWebDriverElement(Strategy.ID, "textfield"); textField.sendString(garbageString); textField.sendString(searchString + Keys.TAB); Assert.assertEquals(searchString, textField.getText()); String searchString1 = "sugar"; String searchString2 = "con"; textField.sendString(searchString1); textField.sendString(searchString2, true); Assert.assertEquals(searchString1 + searchString2, textField.getText()); }

Target:
public void sendStringTest() throws Exception { String garbageString = "This string is garbage that needs to be cleared."; String searchString = "sugarcrm"; iface.go(elementsPage); WebDriverElement textField = iface.getWebDriverElement(Strategy.ID, "textfield"); textField.sendString(garbageString); textField.sendString(searchString); Assert.assertEquals(searchString, textField.getText()); String searchString1 = "sugar"; String searchString2 = "con"; textField.sendString(searchString1); textField.sendString(searchString2, true); Assert.assertEquals(searchString1 + searchString2, textField.getText()); }
Source:
private void doProvisionSshKeys( List<SshPairImpl> sshPairs, KubernetesEnvironment k8sEnv, String wsId) { Map<String, String> data = sshPairs .stream() .filter( sshPair -> !isNullOrEmpty(sshPair.getName()) && !isNullOrEmpty(sshPair.getPrivateKey())) .collect( toMap( SshPairImpl::getName, sshPair -> Base64.getEncoder().encodeToString(sshPair.getPrivateKey().getBytes()))); Secret secret = new SecretBuilder() .addToData(data) .withType(SSH_SECRET_TYPE) .withNewMetadata() .withName(wsId + SSH_SECRET_NAME_SUFFIX) .endMetadata() .build(); k8sEnv.getSecrets().put(secret.getMetadata().getName(), secret); k8sEnv .getPodsData() .values() .forEach(p -> mountSshKeySecret(secret.getMetadata().getName(), p.getSpec())); }

Target:
private void doProvisionSshKeys( List<SshPairImpl> sshPairs, KubernetesEnvironment k8sEnv, String wsId) { Map<String, String> data = sshPairs .stream() .filter(sshPair -> !isNullOrEmpty(sshPair.getPrivateKey())) .collect( toMap( SshPairImpl::getName, sshPair -> Base64.getEncoder().encodeToString(sshPair.getPrivateKey().getBytes()))); Secret secret = new SecretBuilder() .addToData(data) .withType(SSH_SECRET_TYPE) .withNewMetadata() .withName(wsId + SSH_SECRET_NAME_SUFFIX) .endMetadata() .build(); k8sEnv.getSecrets().put(secret.getMetadata().getName(), secret); k8sEnv .getPodsData() .values() .forEach(p -> mountSshKeySecret(secret.getMetadata().getName(), p.getSpec())); }
Source:
private static void checkDBConnectivity() { boolean dbUp = false; long expectedTimeout = System.currentTimeMillis() + DbFacade.getInstance().getOnStartConnectionTimeout(); long waitBetweenInterval = DbFacade.getInstance().getConnectionCheckInterval(); while (!dbUp && System.currentTimeMillis() < expectedTimeout) { try { dbUp = DbFacade.getInstance().checkDBConnection(); } catch (RuntimeException ex) { log.error("Error in getting DB connection. The database is inaccessible. " + "Original exception is: {}", ExceptionUtils.getMessage(ex)); try { Thread.sleep(waitBetweenInterval); } catch (InterruptedException e) { log.warn("Failed to wait between connection polling attempts. " + "Original exception is: {}", ExceptionUtils.getMessage(e)); } } } if (!dbUp) { throw new IllegalStateException("Could not obtain connection to the database." + " Please make sure that DB is up and accepting connections, and " + "restart the application."); } }

Target:
private static void checkDBConnectivity() { boolean dbUp = false; long expectedTimeout = System.currentTimeMillis() + DbFacade.getInstance().getOnStartConnectionTimeout(); long waitBetweenInterval = DbFacade.getInstance().getConnectionCheckInterval(); while (!dbUp && System.currentTimeMillis() < expectedTimeout) { try { dbUp = DbFacade.getInstance().checkDBConnection(); } catch (RuntimeException ex) { log.error("Error in getting DB connection, database is inaccessible: {}", ex.getMessage()); log.debug("Exception", ex); try { Thread.sleep(waitBetweenInterval); } catch (InterruptedException e) { log.warn("Failed to wait between connection polling attempts. " + "Original exception is: {}", ExceptionUtils.getMessage(e)); } } } if (!dbUp) { throw new IllegalStateException("Could not obtain connection to the database." + " Please make sure that DB is up and accepting connections, and " + "restart the application."); } }