auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void shouldUpdatePerson() throws Exception { Person person = preparePerson(); URI url = config.toInstancePathWithParams("/person/{uuid}", person.getUuid()); when(restOperations.exchange(eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) .thenReturn(getResponse(PERSON_RESPONSE_JSON)); Person updated = personResource.updatePerson(config, person); verify(restOperations).exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class)); assertThat(updated, equalTo(preparePerson())); assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config))); assertThat(JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class), equalTo(readFromFile(CREATE_PERSON_JSON, JsonObject.class))); }

Target:
public void shouldUpdatePerson() throws Exception { Person person = preparePerson(); URI url = config.toInstancePathWithParams("/person/{uuid}?v=full", person.getUuid()); when(restOperations.exchange(eq(url), eq(HttpMethod.POST), any(HttpEntity.class), eq(String.class))) .thenReturn(getResponse(PERSON_RESPONSE_JSON)); Person updated = personResource.updatePerson(config, person); verify(restOperations).exchange(eq(url), eq(HttpMethod.POST), requestCaptor.capture(), eq(String.class)); assertThat(updated, equalTo(preparePerson())); assertThat(requestCaptor.getValue().getHeaders(), equalTo(getHeadersForPost(config))); assertThat(JsonUtils.readJson(requestCaptor.getValue().getBody(), JsonObject.class), equalTo(readFromFile(CREATE_PERSON_JSON, JsonObject.class))); }
Source:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { log.error(String.format("An error has occurred while session validation. Message is %1$s", ex.getMessage())); if (log.isDebugEnabled()) { log.debug("", ex); } ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpSession httpSession = ((HttpServletRequest) request).getSession(false); if (httpSession != null) { String engineSession = (String) httpSession.getAttribute(SessionConstants.HTTP_SESSION_ENGINE_SESSION_ID_KEY); InitialContext ctx = null; if (engineSession != null) { ctx = new InitialContext(); try { VdcQueryReturnValue returnValue = FiltersHelper.getBackend(ctx) .runPublicQuery(VdcQueryType.ValidateSession, new VdcQueryParametersBase(engineSession)); if (!returnValue.getSucceeded()) { httpSession.invalidate(); } } finally { ctx.close(); } } } doFilter = true; } catch (Exception ex) { log.error("An error has occurred while session validation.", ex); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { boolean validRequest = !StringUtils.isEmpty(repositoryUrl); if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); LOGGER.info(String.format(LOG_TRYING_TO_SYNC_REPOSITORY, repositoryUrl)); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryUrl(repositoryUrl); } try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_CLEARING_MODEL_VERSION); configurationService.setModelRepositoryVersion(""); } LOGGER.info(LOG_SYNC_REPO_SUCCESSFUL); return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { LOGGER.warn(LOG_SYNC_REPO_FAILED); LOGGER.error(e); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_REVERTING_MODEL_REPOSITORY_URL); configurationService.setModelRepositoryUrl(oldUrl); } } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }

Target:
public ResponseEntity<List<String>> syncRepository(String repositoryUrl) { boolean validRequest = !StringUtils.isEmpty(repositoryUrl); if (validRequest) { String oldUrl = configurationService.getModelRepositoryUrl(); LOGGER.info(String.format(LOG_TRYING_TO_SYNC_REPOSITORY, repositoryUrl)); if (!repositoryUrl.equals(oldUrl)) { configurationService.setModelRepositoryUrl(repositoryUrl); } try { sourceCodeManager.updateRepository(); List<String> versions = sourceCodeManager.getAvailableVersions(); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_CLEARING_MODEL_VERSION); configurationService.setModelRepositoryVersion(""); } LOGGER.info(LOG_SYNC_REPO_SUCCESSFUL); return new ResponseEntity<List<String>>(versions, HttpStatus.OK); } catch (Exception e) { LOGGER.error(LOG_SYNC_REPO_FAILED, e); if (!repositoryUrl.equals(oldUrl)) { LOGGER.info(LOG_REVERTING_MODEL_REPOSITORY_URL); configurationService.setModelRepositoryUrl(oldUrl); } } } return new ResponseEntity<List<String>>(HttpStatus.BAD_REQUEST); }
Source:
public void testAsyncTasks() throws Exception { LimitedExecutor limitedExecutor = new LimitedExecutor(NAME, executor, 1); CompletableFuture<Void> blockingFuture = new CompletableFuture<>(); CompletableFuture<String> cf1 = new CompletableFuture<>(); limitedExecutor.executeAsync(() -> blockingFuture.thenRunAsync(() -> cf1.complete("bla"))); CompletableFuture<String> cf2 = new CompletableFuture<>(); limitedExecutor.execute(() -> cf2.complete("bla")); Thread.sleep(100); assertFalse(cf2.isDone()); blockingFuture.complete(null); assertEquals("bla", cf1.get(10, SECONDS)); assertEquals("bla", cf2.get(10, SECONDS)); }

Target:
public void testAsyncTasks() throws Exception { LimitedExecutor limitedExecutor = new LimitedExecutor(NAME, executor, 1); CompletableFuture<Void> blockingFuture = new CompletableFuture<>(); CompletableFuture<String> cf1 = new CompletableFuture<>(); limitedExecutor.executeAsync(() -> blockingFuture.thenRunAsync(() -> cf1.complete("bla"))); CompletableFuture<String> cf2 = new CompletableFuture<>(); limitedExecutor.execute(() -> cf2.complete("bla")); Thread.sleep(10); assertFalse(cf2.isDone()); blockingFuture.complete(null); assertEquals("bla", cf1.get(10, SECONDS)); assertEquals("bla", cf2.get(10, SECONDS)); }
Source:
private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); image.setVolumeType(VolumeType.Preallocated); }); } }

Target:
private void adjustKVMDataForBlockSD() { if (getVm().getOrigin() == OriginType.KVM && getActionState() == CommandActionState.EXECUTE && getStorageDomain() != null && getStorageDomain().getStorageType().isBlockDomain()) { getVm().getImages().forEach(image -> { image.setActualSizeInBytes(image.getSize()); image.setVolumeType(VolumeType.Preallocated); }); log.info("Block Storage Domains do not support Sparseness. The Import is defaulting to Preallocated."); } }
Source:
public final boolean waitForLockRelease(long lockAcquisitionTimeout) throws InterruptedException { notifier.await(lockAcquisitionTimeout, TimeUnit.MILLISECONDS); return txComplete; }

Target:
public final boolean waitForLockRelease(long lockAcquisitionTimeout) throws InterruptedException { try { notifier.get(lockAcquisitionTimeout, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw new IllegalStateException("Should never happen", e); } catch (TimeoutException e) { } return txComplete; }
Source:
public UnionCondition(final ConditionType conditionType, final List<AbstractCondition> conditions) { super(conditionType); this.conditions = conditions; }

Target:
private UnionCondition(final ConditionType conditionType, final List<AbstractCondition> conditions) { super(conditionType); this.conditions = conditions; }
Source:
public void testTransformMetacardFromUpstreamResponse() throws CatalogTransformerException, IOException, XpathException, SAXException { MetacardImpl metacard = createMockMetacard(); metacard.setLocation(POINT_WKT); Result result = mock(Result.class); doReturn(metacard).when(result).getMetacard(); SourceResponseImpl sourceResponse = new SourceResponseImpl(null, singletonList(result)); BinaryContent content = kmlTransformer.transform(sourceResponse, emptyMap()); assertThat(content.getMimeTypeValue(), is(KMLTransformerImpl.KML_MIMETYPE.toString())); final String kmlString = IOUtils.toString(content.getInputStream(), StandardCharsets.UTF_8); assertXpathEvaluatesTo("Results (1)", "/m:kml/m:Document/m:name", kmlString); assertXpathExists(" assertXpathEvaluatesTo("myTitle", " }

Target:
public void testTransformMetacardFromUpstreamResponse() throws CatalogTransformerException, IOException, XpathException, SAXException { MetacardImpl metacard = createMockMetacard(); metacard.setLocation(POINT_WKT); Result result = new ResultImpl(metacard); SourceResponseImpl sourceResponse = new SourceResponseImpl(null, singletonList(result)); BinaryContent content = kmlTransformer.transform(sourceResponse, emptyMap()); assertThat(content.getMimeTypeValue(), is(KMLTransformerImpl.KML_MIMETYPE.toString())); final String kmlString = IOUtils.toString(content.getInputStream(), StandardCharsets.UTF_8); assertXpathEvaluatesTo("Results (1)", "/m:kml/m:Document/m:name", kmlString); assertXpathExists(" assertXpathEvaluatesTo("myTitle", " }
Source:
public PingCommand getCurrentStatus(long id) { if ((_relativePath == null) || (_relativePath.isEmpty()) || (_cmsUserInfo == null) || (_cmsUserInfo.length == 0)) { s_logger.error("Failed to ping to Nuage VSD"); _shouldAudit = true; return null; } try { login(); } catch (Exception e) { s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserInfo[1] + " Exception " + e.getMessage()); _shouldAudit = true; return null; } PingNuageVspCommand pingNuageVspCommand = new PingNuageVspCommand(Host.Type.L2Networking, id, _shouldAudit); _shouldAudit = false; return pingNuageVspCommand; }

Target:
public PingCommand getCurrentStatus(long id) { if (_relativePath == null || _relativePath.isEmpty()) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the relative path information"); _shouldAudit = true; return null; } if (_cmsUserInfo == null || _cmsUserInfo.length < 2) { s_logger.error("Refusing to ping Nuage VSD because the resource configuration is missing the CMS user information"); _shouldAudit = true; return null; } try { login(); } catch (ExecutionException | ConfigurationException e) { s_logger.error("Failed to ping to Nuage VSD on " + _name + " as user " + _cmsUserInfo[1], e); _shouldAudit = true; return null; } PingNuageVspCommand pingNuageVspCommand = new PingNuageVspCommand(Host.Type.L2Networking, id, _shouldAudit); _shouldAudit = false; return pingNuageVspCommand; }
Source:
public DataRadioStation getNextById(String id) { if (listStations.size() == 0) return null; for (int i = 0; i < listStations.size() - 1; i++) { if (listStations.get(i).ID.equals(id)) { return listStations.get(i + 1); } } return listStations.get(0); }

Target:
public DataRadioStation getNextById(String id) { if (listStations.isEmpty()) return null; for (int i = 0; i < listStations.size() - 1; i++) { if (listStations.get(i).ID.equals(id)) { return listStations.get(i + 1); } } return listStations.get(0); }
Source:
public void should_format_failed_future() { CompletableFuture<Object> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException("some random error")); assertThat(STANDARD_REPRESENTATION.toStringOf(future)).matches("CompletableFuture\\[Failed: java.lang.RuntimeException: some random error\\]\n" + StackTraceUtils.getStackTraceRegex()); }

Target:
public void should_format_failed_future() { CompletableFuture<Object> future = new CompletableFuture<>(); future.completeExceptionally(new RuntimeException("some random error")); assertThat(STANDARD_REPRESENTATION.toStringOf(future)).startsWith(String.format("CompletableFuture[Failed: java.lang.RuntimeException: some random error]%n")) .contains("Caused by: java.lang.RuntimeException: some random error"); }
Source:
public List<ComponentConfiguration> getSnapshot(long sid) throws KuraException { List<ComponentConfiguration> returnConfigs = new ArrayList<ComponentConfiguration>(); XmlComponentConfigurations xmlConfigs = loadEncryptedSnapshotFileContent(sid); if (xmlConfigs == null) { return returnConfigs; } List<ComponentConfigurationImpl> configs = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configs) { if (config != null) { try { Map<String, Object> decryptedProperties = decryptPasswords(config); config.setProperties(decryptedProperties); } catch (Throwable t) { s_logger.warn("Error during snapshot password decryption"); } } } returnConfigs.addAll(xmlConfigs.getConfigurations()); return returnConfigs; }

Target:
public List<ComponentConfiguration> getSnapshot(long sid) throws KuraException { List<ComponentConfiguration> returnConfigs = new ArrayList<ComponentConfiguration>(); XmlComponentConfigurations xmlConfigs = loadEncryptedSnapshotFileContent(sid); if (xmlConfigs != null) { List<ComponentConfigurationImpl> configs = xmlConfigs.getConfigurations(); for (ComponentConfigurationImpl config : configs) { if (config != null) { try { Map<String, Object> decryptedProperties = decryptPasswords(config); config.setProperties(decryptedProperties); } catch (Throwable t) { logger.warn("Error during snapshot password decryption"); } } } returnConfigs.addAll(xmlConfigs.getConfigurations()); } return returnConfigs; }
Source:
public void stopWithoutFailureLogging() throws LifeCycleStopException { final class CollectForSuppressedExceptionsHandler implements LifeCycleStopFailureHandler { private final List<Exception> failures = new ArrayList<>(); @Override public void handlePreDestroyException(Class<?> klass, Method method, Exception exception) { log.debug(exception, "Exception in PreDestroy method %s::%s()", klass.getName(), method.getName()); failures.add(exception); } } CollectForSuppressedExceptionsHandler handler = stop(new CollectForSuppressedExceptionsHandler()); if (!handler.failures.isEmpty()) { LifeCycleStopException stopException = new LifeCycleStopException(); for (Exception e : handler.failures) { stopException.addSuppressed(e); } throw stopException; } }

Target:
public void stopWithoutFailureLogging() throws LifeCycleStopException { List<Exception> failures = new ArrayList<>(); stop((klass, method, exception) -> failures.add(exception)); if (!failures.isEmpty()) { LifeCycleStopException stopException = new LifeCycleStopException(); for (Exception e : failures) { stopException.addSuppressed(e); } throw stopException; } }
Source:
private void moveGap(int newGapStart, int minGapLength) { char[] target; int newGapLength; if (gapLength >= minGapLength) { target = content; newGapLength = gapLength; } else { int textLength = content.length - gapLength; target = new char[Math.max(textLength*2, textLength + minGapLength)]; newGapLength = target.length - textLength; } int gapEnd = gapStart + gapLength; int newGapEnd = newGapStart + newGapLength; if (newGapStart < gapStart) { System.arraycopy(content, 0, target, 0, newGapStart); System.arraycopy(content, newGapStart, target, newGapEnd, gapStart - newGapStart); System.arraycopy(content, gapEnd, target, newGapEnd + (gapStart - newGapStart), content.length-gapEnd); } else { System.arraycopy(content, 0, target, 0, gapStart); System.arraycopy(content, gapEnd, target, gapStart, newGapStart - gapStart); System.arraycopy(content, gapEnd + (newGapStart - gapStart), target, newGapEnd, target.length-newGapEnd); } content = target; gapStart = newGapStart; gapLength = newGapLength; }

Target:
private void moveGap(int newGapStart, int minGapLength) { char[] target; int newGapLength; if (newGapStart == gapStart && minGapLength <= gapLength) { return; } if (gapLength >= minGapLength) { target = content; newGapLength = gapLength; } else { int textLength = content.length - gapLength; target = new char[Math.max(textLength*2, textLength + minGapLength)]; newGapLength = target.length - textLength; } int gapEnd = gapStart + gapLength; int newGapEnd = newGapStart + newGapLength; if (newGapStart < gapStart) { System.arraycopy(content, 0, target, 0, newGapStart); System.arraycopy(content, newGapStart, target, newGapEnd, gapStart - newGapStart); System.arraycopy(content, gapEnd, target, newGapEnd + (gapStart - newGapStart), content.length-gapEnd); } else { System.arraycopy(content, 0, target, 0, gapStart); System.arraycopy(content, gapEnd, target, gapStart, newGapStart - gapStart); System.arraycopy(content, gapEnd + (newGapStart - gapStart), target, newGapEnd, target.length-newGapEnd); } content = target; gapStart = newGapStart; gapLength = newGapLength; }
Source:
public InetAddress getInterface() { throw new UnsupportedOperationException("Retrieval of network interface address not supported"); }

Target:
public InetAddress getInterface() { return null; }
Source:
private void processNewPut(ScanResults results, IndexValue putValue) { if (!isExpired(putValue.getExpiresAtMs(), results.containerForecastStartTimeMs)) { results.updateContainerBaseBucket(String.valueOf(putValue.getServiceId()), String.valueOf(putValue.getContainerId()), putValue.getSize()); handleContainerBucketUpdate(results, putValue, putValue.getExpiresAtMs(), SUBTRACT); } if (!isExpired(putValue.getExpiresAtMs(), results.logSegmentForecastStartTimeMs)) { results.updateLogSegmentBaseBucket(putValue.getOffset().getName(), putValue.getSize()); handleLogSegmentBucketUpdate(results, putValue, putValue.getExpiresAtMs(), SUBTRACT); } }

Target:
private void processNewPut(ScanResults results, IndexValue putValue) { long expiresAtMs = putValue.getExpiresAtMs(); if (!isExpired(expiresAtMs, results.containerForecastStartTimeMs)) { results.updateContainerBaseBucket(String.valueOf(putValue.getServiceId()), String.valueOf(putValue.getContainerId()), putValue.getSize()); if (expiresAtMs != Utils.Infinite_Time) { handleContainerBucketUpdate(results, putValue, expiresAtMs, SUBTRACT); } } if (!isExpired(expiresAtMs, results.logSegmentForecastStartTimeMs)) { results.updateLogSegmentBaseBucket(putValue.getOffset().getName(), putValue.getSize()); if (expiresAtMs != Utils.Infinite_Time) { handleLogSegmentBucketUpdate(results, putValue, expiresAtMs, SUBTRACT); } } }
Source:
public static String abbreviateName(Class<?> cls, int pkgNameDepth) { if (pkgNameDepth == 0) return cls.getSimpleName(); if (pkgNameDepth < 0 || pkgNameDepth > 2) return cls.getName(); String[] pkgNameParts = cls.getName().split("\\."); if (pkgNameParts.length == 1) return pkgNameParts[0]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < pkgNameParts.length - 1; ++i) { sb.append(pkgNameParts[i].charAt(0)); if (pkgNameDepth > 1 && pkgNameParts[i].length() > 1) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() - 1)); sb.append("."); } sb.append(pkgNameParts[pkgNameParts.length - 1]); return sb.toString(); }

Target:
public static String abbreviateName(Class<?> cls, int pkgNameDepth) { if (pkgNameDepth < 1) return cls.getSimpleName(); if (pkgNameDepth >= MAX_ABBREVIATE_NAME_LVL) return cls.getName(); String[] pkgNameParts = cls.getName().split("\\."); if (pkgNameParts.length == 1) return pkgNameParts[0]; StringBuilder sb = new StringBuilder(); for (int i = 0; i < pkgNameParts.length - 1; ++i) { if( pkgNameParts[i].length() == 3 ) sb.append(pkgNameParts[i]); else { sb.append(pkgNameParts[i].charAt(0)); if (pkgNameParts[i].length() > 3) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() / 2)); if (pkgNameParts[i].length() > 1) sb.append(pkgNameParts[i].charAt(pkgNameParts[i].length() - 1)); } sb.append("."); } sb.append(pkgNameParts[pkgNameParts.length - 1]); return sb.toString(); }
Source:
public ResponseEntity<?> create(@Valid @RequestBody final EventTypeBase eventType, final Errors errors, final NativeWebRequest request) throws TopicCreationException, InternalNakadiException, NoSuchPartitionStrategyException, DuplicatedEventTypeNameException, InvalidEventTypeException, ValidationException { if (featureToggleService.isFeatureEnabled(DISABLE_EVENT_TYPE_CREATION)) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } if (errors.hasErrors()) { throw new ValidationException(errors); } eventTypeService.create(eventType); return ResponseEntity.status(HttpStatus.CREATED).headers(generateWarningHeaders(eventType)).build(); }

Target:
public ResponseEntity<?> create(@Valid @RequestBody final EventTypeBase eventType, final Errors errors, final NativeWebRequest request) throws TopicCreationException, InternalNakadiException, NoSuchPartitionStrategyException, DuplicatedEventTypeNameException, InvalidEventTypeException, ValidationException, FeatureNotAvailableException { if (featureToggleService.isFeatureEnabled(DISABLE_EVENT_TYPE_CREATION)) { throw new FeatureNotAvailableException("Event Type creation is disabled", DISABLE_EVENT_TYPE_CREATION); } if (errors.hasErrors()) { throw new ValidationException(errors); } eventTypeService.create(eventType); return ResponseEntity.status(HttpStatus.CREATED).headers(generateWarningHeaders(eventType)).build(); }
Source:
public T parseFile(String absoluteFilename, Map<String, Object> additionalParams) throws FileParsingException { try { this.workbook = this.fileService.retrieveWorkbook(absoluteFilename); return this.parseWorkbook(this.workbook, additionalParams); } catch (InvalidFormatException | IOException e) { AbstractExcelFileParser.LOG.debug(e.getMessage(), e); throw new FileParsingException(this.messageSource.getMessage("common.error.invalid.file", null, Locale.ENGLISH)); } }

Target:
public T parseFile(String absoluteFilename, Map<String, Object> additionalParams) throws FileParsingException { try { this.workbook = this.fileService.retrieveWorkbook(absoluteFilename); return this.parseWorkbook(this.workbook, additionalParams); } catch (InvalidFormatException e) { AbstractExcelFileParser.LOG.debug(e.getMessage(), e); throw new FileParsingException(this.messageSource.getMessage(FILE_INVALID, null, Locale.ENGLISH)); } catch (IOException e) { AbstractExcelFileParser.LOG.debug(e.getMessage(), e); throw new FileParsingException(this.messageSource.getMessage(FILE_READ_ERROR, null, Locale.ENGLISH)); } }
Source:
private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); Instant now = Instant.now(); Files.setLastModifiedTime(probe, FileTime.from(now)); FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant t1i = t1.toInstant(); for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 200) { Files.setLastModifiedTime(probe, FileTime.from(t1i.plusNanos(i * 1000))); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); fsResolution = fsResolution.plus(clockResolution); saveFileTimeResolution(s, fsResolution); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }

Target:
private static Optional<Duration> measureFsTimestampResolution( FileStore s, Path dir) { Duration configured = readFileTimeResolution(s); if (!UNDEFINED_RESOLUTION.equals(configured)) { return Optional.of(configured); } Path probe = dir.resolve(".probe-" + UUID.randomUUID()); try { Files.createFile(probe); FileTime t1 = Files.getLastModifiedTime(probe); FileTime t2 = t1; Instant t1i = t1.toInstant(); for (long i = 1; t2.compareTo(t1) <= 0; i += 1 + i / 200) { Files.setLastModifiedTime(probe, FileTime.from(t1i.plusNanos(i * 1000))); t2 = Files.getLastModifiedTime(probe); } Duration fsResolution = Duration.between(t1.toInstant(), t2.toInstant()); Duration clockResolution = measureClockResolution(); fsResolution = fsResolution.plus(clockResolution); saveFileTimeResolution(s, fsResolution); return Optional.of(fsResolution); } catch (AccessDeniedException e) { LOG.warn(e.getLocalizedMessage(), e); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } finally { deleteProbe(probe); } return Optional.empty(); }
Source:
public void testCreatePatch() { SourcesFileCreateHyperlink patchTest = new SourcesFileCreateHyperlink(testFile, specfile.getPatch(0).getFileName(), null); assertNotNull(patchTest); patchTest.open(); assertNotNull(testFile.getProject().findMember("test.patch")); }

Target:
public void testCreatePatch() { SourcesFileCreateHyperlink patchTest = new SourcesFileCreateHyperlink(testFile, specfile.getPatch(0).getFileName(), null); assertNotNull(patchTest); patchTest.open(); assertNotNull(testFile.getProject().findMember("test")); }
Source:
public synchronized FinalT next() { return createNext.apply(currentIterator.next()); }

Target:
public FinalT next() { if (hasNext()) { return createNext.apply(currentIterator.next()); } throw new NoSuchElementException(); }
Source:
public long getWrittenRows() { return logicalWrittenRows; }

Target:
public long getWrittenRows() { return writtenRows; }
Source:
protected PartialList<String> doQuery(String query, String queryType, QueryFilter queryFilter, int countUpTo) { final Timer.Context timerContext = queryTimer.time(); int match = 0; try { Mutable<String> idKeyHolder = new MutableObject<>(); PartialList<Map<String, Serializable>> pl = doQueryAndFetch(query, queryType, queryFilter, false, countUpTo, idKeyHolder); String idKey = idKeyHolder.getValue(); List<String> ids = new ArrayList<>(pl.size()); for (Map<String, Serializable> map : pl) { String id = (String) map.get(idKey); ids.add(id); } match = ids.size(); return new PartialList<>(ids, pl.totalSize()); } finally { long duration = timerContext.stop(); if (LOG_MIN_DURATION_NS >= 0 && duration > LOG_MIN_DURATION_NS) { String msg = String.format("duration_ms:\t%.2f\t%s %s\tquery\t%s", duration / 1000000.0, queryFilter, countUpToAsString(countUpTo), query); if (log.isTraceEnabled()) { log.info(msg, new Throwable("Slow query stack trace")); } else { log.info(msg); } } } }

Target:
protected PartialList<String> doQuery(String query, String queryType, QueryFilter queryFilter, int countUpTo) { final Timer.Context timerContext = queryTimer.time(); try { Mutable<String> idKeyHolder = new MutableObject<>(); PartialList<Map<String, Serializable>> pl = doQueryAndFetch(query, queryType, queryFilter, false, countUpTo, idKeyHolder); String idKey = idKeyHolder.getValue(); List<String> ids = new ArrayList<>(pl.size()); for (Map<String, Serializable> map : pl) { String id = (String) map.get(idKey); ids.add(id); } return new PartialList<>(ids, pl.totalSize()); } finally { long duration = timerContext.stop(); if (LOG_MIN_DURATION_NS >= 0 && duration > LOG_MIN_DURATION_NS) { String msg = String.format("duration_ms:\t%.2f\t%s %s\tquery\t%s", duration / 1000000.0, queryFilter, countUpToAsString(countUpTo), query); if (log.isTraceEnabled()) { log.info(msg, new Throwable("Slow query stack trace")); } else { log.info(msg); } } } }
Source:
public void switchChunk(String chunkType) { if (chunk_ != null) { DocDisplay docDisplay = target_.getDocDisplay(); Position start = chunk_.getPreamble(); Position end = chunk_.getEnd(); String chunkText = docDisplay.getTextForRange(Range.fromPoints(start, end)); JsArrayString chunkLines = StringUtil.split(chunkText, "\n"); if (chunkLines.length() > 0) { String firstLine = chunkLines.get(0); Position linedEnd = Position.create(start.getRow(),firstLine.length()); String newFirstLine = firstLine.replaceFirst("{[a-zA-Z]+", "{" + chunkType); docDisplay.replaceRange(Range.fromPoints(start, linedEnd), newFirstLine); target_.getNotebook().clearChunkOutput(chunk_); } } }

Target:
public void switchChunk(String chunkType) { if (chunk_ != null) { DocDisplay docDisplay = target_.getDocDisplay(); Position start = chunk_.getPreamble(); Position end = chunk_.getEnd(); String chunkText = docDisplay.getTextForRange(Range.fromPoints(start, end)); JsArrayString chunkLines = StringUtil.split(chunkText, "\n"); if (chunkLines.length() > 0) { String firstLine = chunkLines.get(0); Position linedEnd = Position.create(start.getRow(),firstLine.length()); String newFirstLine = firstLine.replaceFirst("[, ]*engine='[a-zA-Z]+'", ""); newFirstLine = newFirstLine.replaceFirst("{[a-zA-Z]+", "{" + chunkType); docDisplay.replaceRange(Range.fromPoints(start, linedEnd), newFirstLine); target_.getNotebook().clearChunkOutput(chunk_); } } }
Source:
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params) { final TaskStatusPlus taskStatusPlus = indexingServiceClient.getLastCompleteTask(); if (taskStatusPlus != null) { for (ImmutableDruidDataSource dataSource : params.getDataSources()) { if (!params.getCoordinatorDynamicConfig().getKillPendingSegmentsSkipList().contains(dataSource.getName())) { log.info( "Kill pendingSegments created until [%s] for dataSource[%s]", dataSource, taskStatusPlus.getCreatedTime() ); indexingServiceClient.killPendingSegments(dataSource.getName(), taskStatusPlus.getCreatedTime()); } } } return params; }

Target:
public DruidCoordinatorRuntimeParams run(DruidCoordinatorRuntimeParams params) { final List<DateTime> createdTimes = new ArrayList<>(); createdTimes.add( indexingServiceClient .getRunningTasks() .stream() .map(TaskStatusPlus::getCreatedTime) .min(Comparators.naturalNullsFirst()) .orElse(DateTimes.nowUtc()) ); createdTimes.add( indexingServiceClient .getPendingTasks() .stream() .map(TaskStatusPlus::getCreatedTime) .min(Comparators.naturalNullsFirst()) .orElse(DateTimes.nowUtc()) ); createdTimes.add( indexingServiceClient .getWaitingTasks() .stream() .map(TaskStatusPlus::getCreatedTime) .min(Comparators.naturalNullsFirst()) .orElse(DateTimes.nowUtc()) ); final TaskStatusPlus completeTaskStatus = indexingServiceClient.getLastCompleteTask(); if (completeTaskStatus != null) { createdTimes.add(completeTaskStatus.getCreatedTime()); } createdTimes.sort(Comparators.naturalNullsFirst()); Preconditions.checkState(!createdTimes.isEmpty(), "Failed to gather createdTimes of tasks"); ENDING_SEGMENTS_OFFSET). final DateTime pendingSegmentsCleanupEndTime = createdTimes.get(0).minus(KEEP_PENDING_SEGMENTS_OFFSET); for (ImmutableDruidDataSource dataSource : params.getDataSources()) { if (!params.getCoordinatorDynamicConfig().getKillPendingSegmentsSkipList().contains(dataSource.getName())) { log.info( "Killed [%d] pendingSegments created until [%s] for dataSource[%s]", indexingServiceClient.killPendingSegments(dataSource.getName(), pendingSegmentsCleanupEndTime), pendingSegmentsCleanupEndTime, dataSource ); } } return params; }
Source:
public void scanNow(final ContainerSpecKey containerSpecKey) { ServerTemplate serverTemplate = templateStorage.load(containerSpecKey.getServerTemplateKey().getId()); if (serverTemplate == null) { throw new KieServerControllerNotFoundException("No server template found for id " + containerSpecKey.getServerTemplateKey().getId()); } ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerSpecKey.getId()); if (containerSpec == null) { throw new KieServerControllerNotFoundException("No container spec found for id " + containerSpecKey.getId()); } List<Container> containers = kieServerInstanceManager.scanNow(serverTemplate, containerSpec); notificationService.notify(serverTemplate, containerSpec, containers); }

Target:
public void scanNow(final ContainerSpecKey containerSpecKey) { ServerTemplate serverTemplate = templateStorage.load(containerSpecKey.getServerTemplateKey().getId()); if (serverTemplate == null) { throw new KieServerControllerIllegalArgumentException("No server template found for id " + containerSpecKey.getServerTemplateKey().getId()); } ContainerSpec containerSpec = serverTemplate.getContainerSpec(containerSpecKey.getId()); if (containerSpec == null) { throw new KieServerControllerIllegalArgumentException("No container spec found for id " + containerSpecKey.getId()); } List<Container> containers = kieServerInstanceManager.scanNow(serverTemplate, containerSpec); notificationService.notify(serverTemplate, containerSpec, containers); }
Source:
public Object[][] dataBiasCorrection() { LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final AllelicCountCollection sampleNormal = new AllelicCountCollection(SAMPLE_NORMAL_FILE); final AllelicCountCollection sampleWithBadSNPs = new AllelicCountCollection(SAMPLE_WITH_BAD_SNPS_FILE); final AllelicCountCollection sampleWithEvent = new AllelicCountCollection(SAMPLE_WITH_EVENT_FILE); final AllelicPanelOfNormals allelicPoNNormal = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_NORMAL_COUNTS_FILE)); final AllelicPanelOfNormals allelicPoNWithBadSNPs = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_WITH_BAD_SNPS_COUNTS_FILE)); final double minorFractionExpectedInMiddleSegmentNormal = 0.5; final double minorFractionExpectedInMiddleSegmentWithBadSNPsAndNormalPON = 0.4; final double minorFractionExpectedInMiddleSegmentWithEvent = 0.33; return new Object[][]{ {sampleNormal, allelicPoNNormal, minorFractionExpectedInMiddleSegmentNormal}, {sampleWithBadSNPs, allelicPoNNormal, minorFractionExpectedInMiddleSegmentWithBadSNPsAndNormalPON}, {sampleWithEvent, allelicPoNNormal, minorFractionExpectedInMiddleSegmentWithEvent}, {sampleWithBadSNPs, allelicPoNWithBadSNPs, minorFractionExpectedInMiddleSegmentNormal} }; }

Target:
public Object[][] dataBiasCorrection() { LoggingUtils.setLoggingLevel(Log.LogLevel.INFO); final AllelicCountCollection sampleNormal = new AllelicCountCollection(SAMPLE_NORMAL_FILE); final AllelicCountCollection sampleWithBadSNPs = new AllelicCountCollection(SAMPLE_WITH_BAD_SNPS_FILE); final AllelicCountCollection sampleWithEvent = new AllelicCountCollection(SAMPLE_WITH_EVENT_FILE); final AllelicPanelOfNormals allelicPoNNormal = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_NORMAL_COUNTS_FILE)); final AllelicPanelOfNormals allelicPoNWithBadSNPs = new AllelicPanelOfNormals(new AllelicCountCollection(ALLELIC_PON_WITH_BAD_SNPS_COUNTS_FILE)); final double minorFractionExpectedInMiddleSegmentNormal = 0.5; final double minorFractionExpectedInMiddleSegmentWithBadSNPsAndNormalPoN = 0.4; final double minorFractionExpectedInMiddleSegmentWithEvent = 0.33; return new Object[][]{ {sampleNormal, allelicPoNNormal, minorFractionExpectedInMiddleSegmentNormal}, {sampleWithBadSNPs, allelicPoNNormal, minorFractionExpectedInMiddleSegmentWithBadSNPsAndNormalPoN}, {sampleWithEvent, allelicPoNNormal, minorFractionExpectedInMiddleSegmentWithEvent}, {sampleWithBadSNPs, allelicPoNWithBadSNPs, minorFractionExpectedInMiddleSegmentNormal} }; }
Source:
public String getStashRootUrl() { if ((stashRootUrl == null) || (stashRootUrl.trim().isEmpty())) { return null; } else { return stashRootUrl; } }

Target:
public String getStashRootUrl() { return stashRootUrl; }
Source:
public URI getProcessBaseUriForExistingProcess(Process process) { if ( Objects.nonNull(process.getId())) { process.setProcessBaseUri(fileManagementModule.createUriForExistingProcess(process.getId().toString())); } return process.getProcessBaseUri(); }

Target:
public URI getProcessBaseUriForExistingProcess(Process process) { URI processBaseUri = process.getProcessBaseUri(); if (Objects.isNull(processBaseUri) && Objects.nonNull(process.getId())) { process.setProcessBaseUri(fileManagementModule.createUriForExistingProcess(process.getId().toString())); } return process.getProcessBaseUri(); }
Source:
protected void addSLAComplianceFilter() { Map<String, String> aliasMap = new HashMap<String, String>(); aliasMap.put("0", constants.SlaNA()); aliasMap.put("1", constants.SlaPending()); aliasMap.put("2", constants.SlaMet()); aliasMap.put("3", constants.SlaAborted()); aliasMap.put("4", constants.SlaViolated()); view.addSelectFilter(constants.SlaCompliance(), aliasMap, f -> addSearchFilter(f, equalsTo(COLUMN_SLA_COMPLIANCE, f.getValue()))); }

Target:
protected void addSLAComplianceFilter() { Map<String, String> aliasMap = new HashMap<String, String>(); aliasMap.put(String.valueOf(ProcessInstance.SLA_ABORTED), constants.SlaAborted()); aliasMap.put(String.valueOf(ProcessInstance.SLA_MET), constants.SlaMet()); aliasMap.put(String.valueOf(ProcessInstance.SLA_NA), constants.SlaNA()); aliasMap.put(String.valueOf(ProcessInstance.SLA_PENDING), constants.SlaPending()); aliasMap.put(String.valueOf(ProcessInstance.SLA_VIOLATED), constants.SlaViolated()); view.addSelectFilter(constants.SlaCompliance(), aliasMap, f -> addSearchFilter(f, equalsTo(COLUMN_SLA_COMPLIANCE, f.getValue()))); }
Source:
protected void setupKeyEvents() { setOnKeyPressed(e -> { if (e.isControlDown()) { return; } if (e.getCode() == KeyCode.ENTER) { e.consume(); if (selectedIndex.isPresent()) { logger.info("Enter key selection on item " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN || KeyboardShortcuts.upIssue.match(e) || KeyboardShortcuts.downIssue.match(e)) { e.consume(); handleUpDownKeys(e.getCode() == KeyCode.DOWN || KeyboardShortcuts.downIssue.match(e)); assert selectedIndex.isPresent() : "handleUpDownKeys doesn't set selectedIndex!"; if (!e.isShiftDown()) { logger.info("Enter key selection on item index " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (FIRST_ISSUE.match(e)) { e.consume(); selectnthItem(1); } if (LAST_ISSUE.match(e)) { e.consume(); selectnthItem(getItems().size() - 1); } }); }

Target:
protected void setupKeyEvents() { setOnKeyPressed(e -> { if (e.isControlDown()) { return; } if (e.getCode() == KeyCode.ENTER) { e.consume(); if (selectedIndex.isPresent()) { logger.info("Enter key selection on item " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (e.getCode() == KeyCode.UP || e.getCode() == KeyCode.DOWN || KeyboardShortcuts.upIssue.match(e) || KeyboardShortcuts.downIssue.match(e)) { e.consume(); handleUpDownKeys(e.getCode() == KeyCode.DOWN || KeyboardShortcuts.downIssue.match(e)); assert selectedIndex.isPresent() : "handleUpDownKeys doesn't set selectedIndex!"; if (!e.isShiftDown()) { logger.info("Enter key selection on item index " + selectedIndex.get()); onItemSelected.accept(selectedIndex.get()); } } if (FIRST_ISSUE.match(e)) { e.consume(); selectNthItem(1); } if (LAST_ISSUE.match(e)) { e.consume(); selectNthItem(getItems().size()); } }); }
Source:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); DataStorageConfiguration dsCfg = new DataStorageConfiguration() .setDefaultDataRegionConfiguration(new DataRegionConfiguration() .setMaxSize(100 * 1024 * 1024) .setPersistenceEnabled(true)) .setWalMode(NONE); cfg.setDataStorageConfiguration(dsCfg) .setAuthenticationEnabled(true) .setPluginProviders(new TestSecurityPluginProvider("server", "server", ALLOW_ALL, false, new TestSecurityData("client", "client", SecurityPermissionSetBuilder.create() .defaultAllowAll(false) .appendTaskPermissions("org.apache.ignite.internal.visor.query.VisorQueryTask", TASK_EXECUTE) .appendTaskPermissions("org.apache.ignite.internal.visor.compute.VisorGatewayTask", TASK_EXECUTE) .build() ))); return cfg; }

Target:
@Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); DataStorageConfiguration dsCfg = new DataStorageConfiguration() .setDefaultDataRegionConfiguration(new DataRegionConfiguration().setPersistenceEnabled(true)); SecurityPermissionSet sysTaskAllow = SecurityPermissionSetBuilder.create() .defaultAllowAll(false) .appendCachePermissions("*", CACHE_READ) .appendTaskPermissions("org.apache.ignite.internal.visor.query.VisorQueryTask", TASK_EXECUTE) .appendTaskPermissions("org.apache.ignite.internal.visor.compute.VisorGatewayTask", TASK_EXECUTE) .build(); cfg.setDataStorageConfiguration(dsCfg) .setAuthenticationEnabled(true) .setPluginProviders(new TestSecurityPluginProvider("server", "server", ALLOW_ALL, false, new TestSecurityData("client", "client", sysTaskAllow))); return cfg; }
Source:
public JComponent getPreferredFocusedComponent() { String name = myNameField.getText(); if (name.length() == 0 || name.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return myNameField; } else if (myValueField.isVisible()) { return myValueField; } else if (myModuleCombo.isVisible()) { return myModuleCombo; } else { return myFileNameCombo; } }

Target:
public JComponent getPreferredFocusedComponent() { String name = myNameField.getText(); if (name.isEmpty() || name.equals(ResourceHelper.prependResourcePrefix(myModule, null))) { return myNameField; } else if (myValueField.isVisible()) { return myValueField; } else if (myModuleCombo.isVisible()) { return myModuleCombo; } else { return myFileNameCombo; } }
Source:
private void logErrorsWithOriginalAccountingDetails(ConcurStandardAccountingExtractDetailLine line) { ConcurAccountInfo accountingInformation = buildConcurAccountingInformation( line, line.getJournalAccountCode(), line.getSubObjectCode()); buildValidationResult(accountingInformation, false); }

Target:
private void logErrorsWithOriginalAccountingDetails(ConcurStandardAccountingExtractDetailLine line) { ConcurAccountInfo accountingInformation = buildConcurAccountingInformation(line); buildValidationResult(accountingInformation, false); }
Source:
public String getProperty(String key) { if (properties != null) { if (properties.containsKey(key)) { return properties.get(key); } } return null; }

Target:
public String getProperty(String key) { if (properties != null) { return properties.get(key); } return null; }
Source:
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { throw new NotEnoughArgumentsException(); } if (!sender.isAuthorized("essentials.warpinfo")) { throw new Exception(tl("noPerm", "essentials.warpinfo")); } final String name = args[0]; final Location loc = ess.getWarps().getWarp(args[0]); sender.sendMessage(tl("warpInfo", name)); sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); }

Target:
public void run(final Server server, final CommandSource sender, final String commandLabel, final String[] args) throws Exception { if (args.length == 0) { throw new NotEnoughArgumentsException(); } final String name = args[0]; final Location loc = ess.getWarps().getWarp(name); sender.sendMessage(tl("warpInfo", name)); sender.sendMessage(tl("whoisLocation", loc.getWorld().getName(), loc.getBlockX(), loc.getBlockY(), loc.getBlockZ())); }
Source:
static String requestPayloadIfStringOrFormIfNotReturnEmptyString(HttpRequest request) { if (request.getPayload() != null && ("application/x-www-form-urlencoded".equals(request.getPayload().getContentMetadata().getContentType()) || request .getPayload() instanceof StringPayload) && request.getPayload().getContentMetadata().getContentLength() != null && request.getPayload().getContentMetadata().getContentLength() < 1024) { try { String logStatement; if (request.getPayload() instanceof StringPayload) { logStatement = request.getPayload().isSensitive() ? "---- SENSITIVE INFORMATION ----" : request.getPayload().getRawContent().toString(); } else { logStatement = Strings2.toStringAndClose(request.getPayload().openStream()); } return String.format(" [%s] ", logStatement); } catch (IOException e) { } } return ""; }

Target:
static String requestPayloadIfStringOrFormIfNotReturnEmptyString(HttpRequest request) { return requestPayloadIfStringOrFormIfNotReturnEmptyString(request, false); }
Source:
private void loadSystemLogLevel() { if (rootLogLevel != null) { return; } final StaticLoggerBinder binder = StaticLoggerBinder.getSingleton(); if (binder.getLoggerFactory() != null) { if (logger.isDebugEnabled()) { rootLogLevel = LogLevel.VERBOSE; } if (logger.isInfoEnabled()) { rootLogLevel = LogLevel.INFORMATIONAL; } if (logger.isWarnEnabled()) { rootLogLevel = LogLevel.WARNING; } if (logger.isErrorEnabled()) { rootLogLevel = LogLevel.ERROR; } } rootLogLevel = getEnvironmentLoggingLevel(); }

Target:
private LogLevel loadSystemLogLevel() { if (isLogFromEnv()) { return getEnvironmentLoggingLevel(); } if (logger.isDebugEnabled()) { return LogLevel.VERBOSE; } if (logger.isInfoEnabled()) { return LogLevel.INFORMATIONAL; } if (logger.isWarnEnabled()) { return LogLevel.WARNING; } if (logger.isErrorEnabled()) { return LogLevel.ERROR; } return LogLevel.NOT_SET; }
Source:
public void sleeping_if_timeout() throws InterruptedException { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); ReadResponse response = queueModeHelper.server.send(queueModeHelper.getCurrentRegistration(), new ReadRequest(3, 0, 1), 1); queueModeHelper.ensureTimeoutException(response); queueModeHelper.ensureClientSleeping(); }

Target:
public void sleeping_if_timeout() throws InterruptedException { queueModeHelper.assertClientNotRegisterered(); queueModeHelper.client.start(); queueModeHelper.waitForRegistration(1); queueModeHelper.assertClientRegisterered(); queueModeHelper.ensureClientAwake(); queueModeHelper.client.stop(false); ReadResponse response = queueModeHelper.server.send(queueModeHelper.getCurrentRegistration(), new ReadRequest(3, 0, 1), 1); queueModeHelper.ensureTimeoutException(response); queueModeHelper.ensureClientSleeping(); }
Source:
public ImageLicense processPage(int pageId, PageTitle pageTitle, JSONObject result) { try { JSONObject imageInfo = (JSONObject) result.optJSONArray("imageinfo").get(0); ImageLicense license = imageInfo != null ? parseImageLicenseMetadata(imageInfo.getJSONObject("extmetadata")) : null; return license; } catch (Exception e) { Log.d(TAG, "Caught exception: " + e.getMessage()); return null; } }

Target:
public ImageLicense processPage(int pageId, PageTitle pageTitle, JSONObject result) { try { if (result.optJSONArray("imageinfo") != null) { JSONObject imageInfo = (JSONObject) result.optJSONArray("imageinfo").get(0); ImageLicense license = parseImageLicenseMetadata(imageInfo.getJSONObject("extmetadata")); return license; } return null; } catch (JSONException e) { Log.d(TAG, "Caught exception: " + e.getMessage(), e); return null; } }
Source:
public void test_descriptor() throws Exception { init(false); SensorDescriptor sensorDescriptor = mock(SensorDescriptor.class); when(sensorDescriptor.onlyOnLanguage(any(String.class))).thenReturn(sensorDescriptor); sensor.describe(sensorDescriptor); verify(sensorDescriptor).name("XML Sensor"); verify(sensorDescriptor).onlyOnLanguage("xml"); }

Target:
public void test_descriptor() throws Exception { init(false); DefaultSensorDescriptor sensorDescriptor = new DefaultSensorDescriptor(); sensor.describe(sensorDescriptor); assertThat(sensorDescriptor.name()).isEqualTo("XML Sensor"); assertThat(sensorDescriptor.languages()).containsOnly(Xml.KEY); }