auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private List<Entity> generateEntities(String extensionName, HttpServletRequest request) throws FalconException, IOException { Properties properties = new Properties(); properties.load(request.getInputStream()); List<Entity> entities = extension.getEntities(extensionName, properties); for (Entity entity : entities) { String tags = entity.getTags(); if (!StringUtils.isEmpty(tags)) { if (tags.contains(TAG_PREFIX_EXTENSION_NAME)) { throw new FalconException("Generated extention entity " + entity.getName() + " should not contain tag prefix " + TAG_PREFIX_EXTENSION_NAME); } if (tags.contains(TAG_PREFIX_EXTENSION_JOB)) { throw new FalconException("Generated extention entity " + entity.getName() + " should not contain tag prefix " + TAG_PREFIX_EXTENSION_JOB); } setEntityTags(entity, tags + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_NAME + extensionName + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_JOB + properties.getProperty(ExtensionProperties.JOB_NAME.getName())); } else { setEntityTags(entity, TAG_PREFIX_EXTENSION_NAME + extensionName + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_JOB + properties.getProperty(ExtensionProperties.JOB_NAME.getName())); } } return entities; }

Target:
private List<Entity> generateEntities(String extensionName, HttpServletRequest request) throws FalconException, IOException { Properties properties = new Properties(); properties.load(request.getInputStream()); List<Entity> entities = extension.getEntities(extensionName, properties); for (Entity entity : entities) { String tags = entity.getTags(); if (StringUtils.isNotEmpty(tags)) { if (tags.contains(TAG_PREFIX_EXTENSION_NAME)) { throw new FalconException("Generated extention entity " + entity.getName() + " should not contain tag prefix " + TAG_PREFIX_EXTENSION_NAME); } if (tags.contains(TAG_PREFIX_EXTENSION_JOB)) { throw new FalconException("Generated extention entity " + entity.getName() + " should not contain tag prefix " + TAG_PREFIX_EXTENSION_JOB); } setEntityTags(entity, tags + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_NAME + extensionName + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_JOB + properties.getProperty(ExtensionProperties.JOB_NAME.getName())); } else { setEntityTags(entity, TAG_PREFIX_EXTENSION_NAME + extensionName + TAG_SEPARATOR + TAG_PREFIX_EXTENSION_JOB + properties.getProperty(ExtensionProperties.JOB_NAME.getName())); } } return entities; }
Source:
protected void accept(Diff diff, boolean rightToLeft) { final Optional<OpaqueElementBodyChange> possibleBodyChange = getOpaqueElementBodyChange(diff); if (possibleBodyChange.isPresent()) { final OpaqueElementBodyChange bodyChange = getOpaqueElementBodyChange(diff).get(); if (LOGGER.isDebugEnabled()) { int refinedElementCount = bodyChange.getRefinedBy().size(); LOGGER.debug("accept(Diff, boolean) - " + refinedElementCount + " refined diffs merged for diff " + diff.hashCode()); } switch (bodyChange.getKind()) { case ADD: acceptRefiningDiffs(bodyChange, rightToLeft); break; case DELETE: acceptRefiningDiffs(bodyChange, rightToLeft); break; case CHANGE: changeElement(bodyChange, rightToLeft); break; case MOVE: moveElement(bodyChange, rightToLeft); break; default: break; } } }

Target:
protected void accept(Diff diff, boolean rightToLeft) { final Optional<OpaqueElementBodyChange> possibleBodyChange = getOpaqueElementBodyChange(diff); if (possibleBodyChange.isPresent()) { final OpaqueElementBodyChange bodyChange = getOpaqueElementBodyChange(diff).get(); if (LOGGER.isDebugEnabled()) { int refinedElementCount = bodyChange.getRefinedBy().size(); LOGGER.debug("accept(Diff, boolean) - " + refinedElementCount + " refined diffs to merge for diff " + diff.hashCode()); } switch (bodyChange.getKind()) { case ADD: acceptRefiningDiffs(bodyChange, rightToLeft); break; case DELETE: acceptRefiningDiffs(bodyChange, rightToLeft); break; case CHANGE: changeElement(bodyChange, rightToLeft); break; case MOVE: moveElement(bodyChange, rightToLeft); break; default: break; } } }
Source:
public Set<ScheduledTime> getScheduledTimes(ScheduledTime start, ScheduledTime end) { DateTime startDT = start.getDateTime(); DateTime endDT = end.getDateTime(); DateTime hour; if (isFullHour(startDT)) { hour = startDT; } else { hour = startDT.plusHours(1).withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0); } Set<ScheduledTime> hours = new HashSet<ScheduledTime>(); while(hour.isBefore(endDT)) { hours.add(new ScheduledTime(hour)); hour = hour.plusHours(1); } return hours; }

Target:
public SortedSet<ScheduledTime> getScheduledTimes(ScheduledTime start, ScheduledTime end) { DateTime startDT = start.getDateTime(); DateTime endDT = end.getDateTime(); DateTime hour; if (isFullHour(startDT)) { hour = startDT; } else { hour = startDT.plusHours(1).withMillisOfSecond(0).withSecondOfMinute(0).withMinuteOfHour(0); } SortedSet<ScheduledTime> hours = new TreeSet<ScheduledTime>(); while(hour.isBefore(endDT)) { hours.add(new ScheduledTime(hour)); hour = hour.plusHours(1); } return hours; }
Source:
default Option<T> reduceRightOption(BiFunction<? super T, ? super T, ? extends T> op) { return reduceLeftOption(op); }

Target:
default Option<T> reduceRightOption(BiFunction<? super T, ? super T, ? extends T> op) { Objects.requireNonNull(op, "op is null"); return getOption(); }
Source:
public static AttestationValue getValueFromCache(String key){ AttestationValue value = attestationValues.get(key); return value; }

Target:
public AttestationValue getValueFromCache(String key) { return attestationValues.get(key); }
Source:
public static MessageNumberSet[] createMessageNumberSets(@Nonnull final long[] msgs) { final List<MessageNumberSet> v = new ArrayList<MessageNumberSet>(); int i = 0; while (i < msgs.length) { long start = msgs[i]; int j = i + 1; while (j < msgs.length && msgs[j] == msgs[j - 1] + 1) { j++; } long end = msgs[j - 1]; v.add(new MessageNumberSet(start, end)); i = j; } return v.toArray(new MessageNumberSet[0]); }

Target:
public static MessageNumberSet[] createMessageNumberSets(@Nonnull final long[] msgs) { final List<MessageNumberSet> v = new ArrayList<MessageNumberSet>(); int i = 0; while (i < msgs.length) { long start = msgs[i]; int j = i + 1; while (j < msgs.length && msgs[j] == msgs[j - 1] + 1) { j++; } long end = msgs[j - 1]; v.add(new MessageNumberSet(start, end)); i = j; } return v.toArray(new MessageNumberSet[v.size()]); }
Source:
public boolean maybePunctuateStreamTime() { final long timestamp = partitionGroup.streamTime(); if (timestamp == RecordQueue.UNKNOWN) { return false; } else { final boolean punctuated = streamTimePunctuationQueue.mayPunctuate(timestamp, PunctuationType.STREAM_TIME, this); if (punctuated) { commitNeeded = true; } return punctuated; } }

Target:
public boolean maybePunctuateStreamTime() { final long streamTime = partitionGroup.streamTime(); if (streamTime == RecordQueue.UNKNOWN) { return false; } else { final boolean punctuated = streamTimePunctuationQueue.mayPunctuate(streamTime, PunctuationType.STREAM_TIME, this); if (punctuated) { commitNeeded = true; } return punctuated; } }
Source:
public T get() { if ((value == null) && (supplier != null)) { synchronized (this) { if (supplier != null) { value = supplier.get(); supplier = null; } } } return value; }

Target:
public T get() { return (supplier == null) ? value : computeValue(); }
Source:
public static void setUpClass() throws Exception { service1 = ignite(); service1.port(1122); service1.init(); service1.awaitInitialization(); service2 = ignite(); service2.port(70000); service2.initExceptionHandler((e) -> errorMessage = "Custom init error"); service2.init(); service2.awaitInitialization(); }

Target:
public static void setUpClass() throws Exception { service = ignite(); service.port(NON_VALID_PORT); service.initExceptionHandler((e) -> errorMessage = "Custom init error"); service.init(); service.awaitInitialization(); }
Source:
public static boolean isElementVisible(WebElement element, WebDriver webDriver) { webDriver.manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS); try { return element.isDisplayed(); } catch (NoSuchElementException e) { return false; } finally { webDriver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS); } }

Target:
public static boolean isElementVisible(WebElement element, WebDriver webDriver) { webDriver.manage().timeouts().implicitlyWait(500, TimeUnit.MILLISECONDS); try { return element.isDisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { return false; } finally { webDriver.manage().timeouts().implicitlyWait(TIMEOUT, TimeUnit.SECONDS); } }
Source:
private void importPlugin(IPluginModelBase model, int importType, IProgressMonitor monitor) throws CoreException { try { SubMonitor subMonitor = SubMonitor.convert(monitor, "", 5); IProject project = createProject(model, subMonitor.newChild(1)); if (project == null) { return; } if (Platform.inDevelopmentMode()) { File location = new File(model.getInstallLocation()); if (location.isDirectory()) { File classpathFile = new File(location, ".classpath"); File projectFile = new File(location, ".project"); if (classpathFile.exists() && classpathFile.isFile() && projectFile.exists() && projectFile.isFile()) { PluginImportHelper.importContent(location, project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, subMonitor.newChild(4)); return; } } } Map<String, IPath> sourceMap = null; if (importType == IMPORT_BINARY || (importType == IMPORT_WITH_SOURCE && !canFindSource(model))) { sourceMap = importAsBinary(project, model, subMonitor.newChild(4)); } else if (importType == IMPORT_BINARY_WITH_LINKS) { sourceMap = importAsBinaryWithLinks(project, model, subMonitor.newChild(4)); } else if (importType == IMPORT_WITH_SOURCE) { importAsSource(project, model, subMonitor.newChild(4)); } setProjectNatures(project, model); if (project.hasNature(JavaCore.NATURE_ID) && project.findMember(".classpath") == null) fProjectClasspaths.put(project, ClasspathComputer.getClasspath(project, model, sourceMap, true, false)); } finally { monitor.done(); } }

Target:
private void importPlugin(IPluginModelBase model, int importType, IProgressMonitor monitor) throws CoreException { SubMonitor subMonitor = SubMonitor.convert(monitor, 5); IProject project = createProject(model, subMonitor.newChild(1)); if (project == null) { return; } if (Platform.inDevelopmentMode()) { File location = new File(model.getInstallLocation()); if (location.isDirectory()) { File classpathFile = new File(location, ".classpath"); File projectFile = new File(location, ".project"); if (classpathFile.exists() && classpathFile.isFile() && projectFile.exists() && projectFile.isFile()) { PluginImportHelper.importContent(location, project.getFullPath(), FileSystemStructureProvider.INSTANCE, null, subMonitor.newChild(4)); return; } } } Map<String, IPath> sourceMap = null; if (importType == IMPORT_BINARY || (importType == IMPORT_WITH_SOURCE && !canFindSource(model))) { sourceMap = importAsBinary(project, model, subMonitor.newChild(4)); } else if (importType == IMPORT_BINARY_WITH_LINKS) { sourceMap = importAsBinaryWithLinks(project, model, subMonitor.newChild(4)); } else if (importType == IMPORT_WITH_SOURCE) { importAsSource(project, model, subMonitor.newChild(4)); } setProjectNatures(project, model); if (project.hasNature(JavaCore.NATURE_ID) && project.findMember(".classpath") == null) fProjectClasspaths.put(project, ClasspathComputer.getClasspath(project, model, sourceMap, true, false)); }
Source:
public void request(@NonNull Context context, @NonNull WikiSite wiki, int age, @NonNull Callback cb) { cancel(); disposables.add(ServiceFactory.getRest(wiki).getAnnouncements() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(list -> { List<Card> cards = new ArrayList<>(); if (list != null) { cards.addAll(buildCards(list.items())); } FeedCoordinator.postCardsToCallback(cb, cards); }, throwable -> { L.v(throwable); cb.error(throwable); })); }

Target:
public void request(@NonNull Context context, @NonNull WikiSite wiki, int age, @NonNull Callback cb) { cancel(); disposables.add(ServiceFactory.getRest(wiki).getAnnouncements() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(list -> FeedCoordinator.postCardsToCallback(cb, new ArrayList<>(buildCards(list.items()))), throwable -> { L.v(throwable); cb.error(throwable); })); }
Source:
public long getCountQueryTimeout() { return (getConnection().getConfig().getCountQueryTimeout()==0)?DEFAULT_TIMEOUT:getConnection().getConfig().getCountQueryTimeout(); }

Target:
public long getCountQueryTimeout() { return (getConnection().getConfig().getCountQueryTimeout()); }
Source:
public Double getPrediction(DiseaseOccurrence occurrence) throws JsonProcessingException, WebServiceClientException, NumberFormatException { Integer diseaseGroupId = getDiseaseGroupId(occurrence); if (diseaseGroupId != null) { String url = rootUrl + diseaseGroupId + "/predict"; JsonDiseaseOccurrenceDataPoint data = new JsonDiseaseOccurrenceDataPoint(occurrence); String bodyAsJson = writeRequestBodyAsJson(data); String response = webServiceClient.makePostRequestWithJSON(url, bodyAsJson); if (response.equals(EXPECTED_PREDICTION_FAILURE_RESPONSE)) { return null; } else { return parseDouble(response); } } else { throw new MachineWeightingPredictorException("No disease group"); } }

Target:
public Double getPrediction(DiseaseOccurrence occurrence) throws JsonProcessingException, WebServiceClientException, NumberFormatException { Integer diseaseGroupId = getDiseaseGroupId(occurrence); if (diseaseGroupId != null) { String url = buildUrl(diseaseGroupId, PREDICT_METHOD); JsonDiseaseOccurrenceDataPoint data = new JsonDiseaseOccurrenceDataPoint(occurrence); String bodyAsJson = writeRequestBodyAsJson(data); String response = webServiceClient.makePostRequestWithJSON(url, bodyAsJson); if (response.equals(EXPECTED_PREDICTION_FAILURE_RESPONSE)) { return null; } else { return parseDouble(response); } } else { throw new MachineWeightingPredictorException("No disease group"); } }
Source:
public static String encodeString(String strToEncode) throws APIException { String algorithm = "SHA-512"; MessageDigest md; byte[] input; try { md = MessageDigest.getInstance(algorithm); input = strToEncode.getBytes(encoding); } catch (NoSuchAlgorithmException e) { log.error(getPasswordEncodeFailMessage(algorithm), e); throw new APIException("system.cannot.find.password.encryption.algorithm", null, e); } catch (UnsupportedEncodingException e) { throw new APIException("system.cannot.find.encoding", new Object[] { encoding }, e); } return hexString(md.digest(input)); }

Target:
public static String encodeString(String strToEncode) throws APIException { String algorithm = "SHA-512"; MessageDigest md; byte[] input; try { md = MessageDigest.getInstance(algorithm); input = strToEncode.getBytes(StandardCharsets.UTF_8); } catch (NoSuchAlgorithmException e) { log.error(getPasswordEncodeFailMessage(algorithm), e); throw new APIException("system.cannot.find.password.encryption.algorithm", null, e); } return hexString(md.digest(input)); }
Source:
public void updateColumn( final AttributeCol52 originalColumn, final AttributeCol52 editedColumn ) { assertNotReadOnly(); try { final List<BaseColumnFieldDiff> diffs = synchronizer.updateColumn( originalColumn, editedColumn ); if ( !( diffs == null || diffs.isEmpty() ) ) { view.getLayer().draw(); model.getAuditLog().add( new UpdateColumnAuditLogEntry( identity.getIdentifier(), originalColumn, editedColumn, diffs ) ); refreshAttributesPanelEvent.fire( new RefreshAttributesPanelEvent( this, model.getAttributeCols() ) ); } } catch ( ModelSynchronizer.MoveColumnVetoException e ) { } }

Target:
public void updateColumn( final AttributeCol52 originalColumn, final AttributeCol52 editedColumn ) { doUpdateColumn( originalColumn, editedColumn, () -> synchronizer.updateColumn( originalColumn, editedColumn ), () -> refreshAttributesPanelEvent.fire( new RefreshAttributesPanelEvent( this, model.getAttributeCols() ) ) ); }
Source:
private A loadAndDispatch(I aggregateId, CommandId commandId, Message command, CommandContext context) { final AggregateStorage<I> aggregateStorage = aggregateStorage(); A aggregate; Integer eventCountBeforeSave = null; int eventCountBeforeDispatch; do { if (eventCountBeforeSave != null) { log().warn("New events detected during the dispatch of the command " + "Possible concurrent modification of {}" + "Repeating the command dispatching.", command, getAggregateClass(), aggregateId); } eventCountBeforeDispatch = aggregateStorage.readEventCountAfterLastSnapshot(aggregateId); aggregate = load(aggregateId); try { aggregate.dispatch(command, context); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof Exception) { final Exception exception = (Exception) cause; commandStatusService.setToError(commandId, exception); } else if (cause instanceof FailureThrowable) { final FailureThrowable failure = (FailureThrowable) cause; commandStatusService.setToFailure(commandId, failure); } else { commandStatusService.setToError(commandId, Errors.fromThrowable(cause)); } } eventCountBeforeSave = aggregateStorage.readEventCountAfterLastSnapshot(aggregateId); } while (eventCountBeforeDispatch != eventCountBeforeSave); checkNotNull(aggregate); return aggregate; }

Target:
private A loadAndDispatch(I aggregateId, CommandId commandId, Message command, CommandContext context) { final AggregateStorage<I> aggregateStorage = aggregateStorage(); A aggregate; Integer eventCountBeforeSave = null; int eventCountBeforeDispatch = 0; do { if (eventCountBeforeSave != null) { final int newEventCount = eventCountBeforeSave - eventCountBeforeDispatch; log().warn("Detected the concurrent modification of {}" + "New events detected while dispatching the command " + "The number of new events is {}. " + "Restarting the command dispatching.", getAggregateClass(), aggregateId, command, newEventCount); } eventCountBeforeDispatch = aggregateStorage.readEventCountAfterLastSnapshot(aggregateId); aggregate = load(aggregateId); try { aggregate.dispatch(command, context); } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof Exception) { final Exception exception = (Exception) cause; commandStatusService.setToError(commandId, exception); } else if (cause instanceof FailureThrowable) { final FailureThrowable failure = (FailureThrowable) cause; commandStatusService.setToFailure(commandId, failure); } else { commandStatusService.setToError(commandId, Errors.fromThrowable(cause)); } } eventCountBeforeSave = aggregateStorage.readEventCountAfterLastSnapshot(aggregateId); } while (eventCountBeforeDispatch != eventCountBeforeSave); return aggregate; }
Source:
private String attachFooterToHTML(String content) throws MessagingException, IOException { Matcher matcher = BODY_CLOSING_TAG.matcher(content); if (!matcher.find()) { return content + getFooterHTML(); } int insertionIndex = matcher.start(matcher.groupCount() - 1); return new StringBuilder() .append(content, 0, insertionIndex) .append(getFooterHTML()) .append(content.substring(insertionIndex)) .toString(); }

Target:
private String attachFooterToHTML(String content) throws MessagingException, IOException { Matcher matcher = BODY_CLOSING_TAG.matcher(content); if (!matcher.find()) { return content + getFooterHTML(); } int insertionIndex = matcher.start(matcher.groupCount() - 1); return new StringBuilder() .append(content.substring(0, insertionIndex)) .append(getFooterHTML()) .append(content.substring(insertionIndex)) .toString(); }
Source:
public static byte[] encode(Chain chain) { ByteBuffer msg = null; boolean firstIteration = true ; for (Element element : chain) { if (firstIteration) { firstIteration = false; ByteBuffer buffer = ByteBuffer.allocate(1); if (element instanceof SequencedElement) { buffer.put(SEQUENCED_CHAIN); } else { buffer.put(NON_SEQUNCED_CHAIN); } buffer.flip(); msg = combine(buffer, encodeElement(element)); continue; } if (msg == null) { throw new IllegalArgumentException("Message cannot be null"); } msg = combine(msg, encodeElement(element)); } return msg != null ? msg.array() : new byte[0]; }

Target:
public static byte[] encode(Chain chain) { ByteBuffer msg = null; boolean firstIteration = true ; for (Element element : chain) { if (firstIteration) { firstIteration = false; ByteBuffer buffer = ByteBuffer.allocate(1); if (element instanceof SequencedElement) { buffer.put(SEQUENCED_CHAIN); } else { buffer.put(NON_SEQUENCED_CHAIN); } buffer.flip(); msg = combine(buffer, encodeElement(element)); continue; } if (msg == null) { throw new IllegalArgumentException("Message cannot be null"); } msg = combine(msg, encodeElement(element)); } return msg != null ? msg.array() : new byte[0]; }
Source:
private void sendMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double processingUnit = getProcessingUnit(); if (processingUnit != Double.POSITIVE_INFINITY) { final int numPartitionBlocks = memoryStore.getNumBlocks(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumPartitionBlocks(numPartitionBlocks) .setMetricWindowMs(metricsWindowMs) .setAvgProcessingTime(processingUnit) .build(); LOG.log(Level.INFO, "ServerMetrics {0}", metricsMessage); metricsMsgSender.send(metricsMessage); } windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }

Target:
private void sendMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double avgPullTime = getAvgProcTimePerReq(pullStats); final double avgPushTime = getAvgProcTimePerReq(pushStats); final double avgReqProcTime = getAvgProcTimePerReq(requestStats); resetStats(); if (avgPullTime != Double.POSITIVE_INFINITY && avgPushTime != Double.POSITIVE_INFINITY) { final int numPartitionBlocks = memoryStore.getNumBlocks(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumPartitionBlocks(numPartitionBlocks) .setMetricWindowMs(metricsWindowMs) .setAvgPullProcessingTime(avgPullTime) .setAvgPushProcessingTime(avgPushTime) .setAvgReqProcessingTime(avgReqProcTime) .build(); LOG.log(Level.FINE, "Sending ServerMetrics {0}", metricsMessage); metricsMsgSender.send(metricsMessage); } windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }
Source:
private void validateQualityGate(DbSession dbSession, OrganizationDto organizationDto, String name) { List<String> errors = new ArrayList<>(); checkQualityGateDoesNotAlreadyExist(dbSession, organizationDto, name, errors); checkRequest(errors.isEmpty(), errors); }

Target:
private void validateQualityGate(DbSession dbSession, OrganizationDto organizationDto, String name) { checkQualityGateDoesNotAlreadyExist(dbSession, organizationDto, name); }
Source:
public void snapshotNotExistsWhenSnapshotsNotAllowed() throws Exception { final String fname = "/commons-codec/commons-codec/11-SNAPSHOT/maven-metadata.xml.md5"; final String content = "kljsjdlfkjsdlkj123j13=20=s0dfjklxjkj"; fixture.getServer().expect( "GET", fixture.formatUrl( fname ), new ExpectationHandler() { @Override public void handle( final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse ) throws ServletException, IOException { httpServletResponse.setStatus( 200 ); httpServletResponse.setHeader( "Content-Length", Integer.toString( content.length() ) ); PrintWriter writer = httpServletResponse.getWriter(); writer.write( content ); } } ); final String baseUri = fixture.getBaseUri(); final SimpleHttpLocation location = new SimpleHttpLocation( "test", baseUri, false, true, true, true, null ); final Transfer transfer = fixture.getTransfer( new ConcreteResource( location, fname ) ); final String url = fixture.formatUrl( fname ); assertThat( transfer.exists(), equalTo( false ) ); HttpDownload dl = new HttpDownload( url, location, transfer, new HashMap<Transfer, Long>(), new EventMetadata(), fixture.getHttp(), new ObjectMapper(), metricRegistry, metricConfig ); DownloadJob resultJob = dl.call(); assertThat( resultJob, notNullValue() ); Transfer result = resultJob.getTransfer(); ContentsFilteringTransferDecorator decorator = new ContentsFilteringTransferDecorator(); OverriddenBooleanValue value = decorator.decorateExists( result, new EventMetadata() ); assertThat( value.overrides(), equalTo( true ) ); assertThat( value.getResult(), equalTo( false ) ); }

Target:
public void snapshotNotExistsWhenSnapshotsNotAllowed() throws Exception { final String fname = "/commons-codec/commons-codec/11-SNAPSHOT/maven-metadata.xml.md5"; final String content = "kljsjdlfkjsdlkj123j13=20=s0dfjklxjkj"; fixture.getServer().expect( "GET", fixture.formatUrl( fname ), 200, content ); final String baseUri = fixture.getBaseUri(); final SimpleHttpLocation location = new SimpleHttpLocation( "test", baseUri, false, true, true, true, null ); final Transfer transfer = fixture.getTransfer( new ConcreteResource( location, fname ) ); final String url = fixture.formatUrl( fname ); assertThat( transfer.exists(), equalTo( false ) ); HttpDownload dl = new HttpDownload( url, location, transfer, new HashMap<Transfer, Long>(), new EventMetadata(), fixture.getHttp(), new ObjectMapper(), metricRegistry, metricConfig ); DownloadJob resultJob = dl.call(); assertThat( resultJob, notNullValue() ); Transfer result = resultJob.getTransfer(); ContentsFilteringTransferDecorator decorator = new ContentsFilteringTransferDecorator(); OverriddenBooleanValue value = decorator.decorateExists( result, new EventMetadata() ); assertThat( value.overrides(), equalTo( true ) ); assertThat( value.getResult(), equalTo( false ) ); }
Source:
public static <T> Collection<EnhancedAnnotatedMethod<?, ? super T>> filterMethods(final Collection<EnhancedAnnotatedMethod<?, ? super T>> methods) { List<EnhancedAnnotatedMethod<?, ? super T>> filteredMethods = new ArrayList<>(); for (EnhancedAnnotatedMethod<?, ? super T> method : methods) { if (!method.getJavaMember().isBridge() && !method.getJavaMember().isSynthetic()) { filteredMethods.add(method); } } return ImmutableList.copyOf(filteredMethods); }

Target:
public static <T> Collection<EnhancedAnnotatedMethod<?, ? super T>> filterMethods(final Collection<EnhancedAnnotatedMethod<?, ? super T>> methods) { List<EnhancedAnnotatedMethod<?, ? super T>> filteredMethods = new ArrayList<>(); for (EnhancedAnnotatedMethod<?, ? super T> method : methods) { if (!method.getJavaMember().isBridge() && !method.getJavaMember().isSynthetic()) { filteredMethods.add(method); } } return Collections.unmodifiableList(filteredMethods); }
Source:
public ImmutableList<DeviceData> getBetweenHourDateByTS(final Long accountId, final String externalDeviceId, final DateTime startUTCTime, final DateTime endUTCTime, final DateTime startLocalTime, final DateTime endLocalTime, final int startHour, final int endHour) { final List<DeviceData> results = getBetweenLocalTime(accountId, externalDeviceId, startUTCTime, endUTCTime, startLocalTime, endLocalTime, ALL_ATTRIBUTES); final List<DeviceData> filteredResults = Lists.newArrayList(); for (final DeviceData data: results) { final int hourOfDay = data.localTime().getHourOfDay(); if (hourOfDay >= startHour || hourOfDay < endHour) { filteredResults.add(data); } } return ImmutableList.copyOf(filteredResults); }

Target:
public ImmutableList<DeviceData> getBetweenHourDateByTS(final Long accountId, final String externalDeviceId, final DateTime startUTCTime, final DateTime endUTCTime, final DateTime startLocalTime, final DateTime endLocalTime, final int startHour, final int endHour) { return getBetweenHourDateByTS(accountId, externalDeviceId, startUTCTime, endUTCTime, startLocalTime, endLocalTime, startHour, endHour, false); }
Source:
private String getThemePrefixedPath(String path) { String prefix = themeProperties != null ? themeProperties.get(IntroTheme.ATT_ID) : null; prefix = prefix == null ? "" : prefix.trim(); if (prefix.length() == 0) { return null; } return prefix.charAt(prefix.length() - 1) == Path.SEPARATOR ? prefix + path : prefix + Path.SEPARATOR + path; }

Target:
private String getThemePrefixedPath(String path) { String prefix = themeProperties != null ? themeProperties.get(IntroTheme.ATT_ID) : null; prefix = prefix == null ? "" : prefix.trim(); if (prefix.length() == 0) { return null; } return prefix + Path.SEPARATOR + path; }
Source:
public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() { @Override public void run() { Shell shell = new Shell(display); shell.setText("Data Binding Snippet 004"); shell.setLayout(new GridLayout(2, false)); new Label(shell, SWT.NONE).setText("Enter '5' to be valid:"); Text text = new Text(shell, SWT.BORDER); WritableValue value = WritableValue.withValueType(String.class); new Label(shell, SWT.NONE).setText("Error:"); Label errorLabel = new Label(shell, SWT.BORDER); errorLabel.setForeground(display.getSystemColor(SWT.COLOR_RED)); GridDataFactory.swtDefaults().hint(200, SWT.DEFAULT) .applyTo(errorLabel); DataBindingContext dbc = new DataBindingContext(); dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(text), value, new UpdateValueStrategy() .setAfterConvertValidator(new FiveValidator()), null); dbc.bindValue(SWTObservables.observeText(errorLabel), new AggregateValidationStatus(dbc.getBindings(), AggregateValidationStatus.MAX_SEVERITY)); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } }); display.dispose(); }

Target:
public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() { @Override public void run() { Shell shell = new Shell(display); shell.setText("Data Binding Snippet 004"); shell.setLayout(new GridLayout(2, false)); new Label(shell, SWT.NONE).setText("Enter '5' to be valid:"); Text text = new Text(shell, SWT.BORDER); WritableValue value = WritableValue.withValueType(String.class); new Label(shell, SWT.NONE).setText("Error:"); Label errorLabel = new Label(shell, SWT.BORDER); errorLabel.setForeground(display.getSystemColor(SWT.COLOR_RED)); GridDataFactory.swtDefaults().hint(200, SWT.DEFAULT) .applyTo(errorLabel); DataBindingContext dbc = new DataBindingContext(); dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(text), value, new UpdateValueStrategy() .setAfterConvertValidator(new FiveValidator()), null); dbc.bindValue( WidgetProperties.text(SWT.Modify).observe(errorLabel), new AggregateValidationStatus(dbc.getBindings(), AggregateValidationStatus.MAX_SEVERITY)); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } } }); display.dispose(); }
Source:
public String toString() { return String.format( "DlmsDevice[deviceId=%s, hls3=%b, hls4=%b, hls5=%b, ipAddress=%s, port=%s, logicalId=%s, clientId=%s]", this.deviceIdentification, this.hls3Active, this.hls4Active, this.hls5Active, this.ipAddress, this.port, this.logicalId, this.clientId); }

Target:
public String toString() { return String.format( "DlmsDevice[deviceId=%s, lls1=%b, hls3=%b, hls4=%b, hls5=%b, ipAddress=%s, port=%s, logicalId=%s, clientId=%s]", this.deviceIdentification, this.lls1Active, this.hls3Active, this.hls4Active, this.hls5Active, this.ipAddress, this.port, this.logicalId, this.clientId); }
Source:
public static DataCenter create(String id, String name, int version, ProvisioningState state, Location location, List<Server> servers, List<Storage> storages) { return new AutoValue_DataCenter(id, name, version, state, location, servers, storages); }

Target:
public static DataCenter create(String id, String name, int version, ProvisioningState state, Location location, List<Server> servers, List<Storage> storages) { return new AutoValue_DataCenter(id, name, version, state, location, servers != null ? ImmutableList.copyOf(servers) : Lists.<Server>newArrayList(), storages != null ? ImmutableList.copyOf(storages) : Lists.<Storage>newArrayList()); }
Source:
public FormValidation doCheckIsRunUnmetered(@QueryParameter Boolean isRunUnmetered, @QueryParameter String appArtifact) { if (isRunUnmetered) { AWSDeviceFarm adf = getAWSDeviceFarm(); String os = adf.getOs(appArtifact); if (adf.getUnmeteredDevices(os) <= 0) { return FormValidation.error(String.format("Your Account does not have unmetered %s devices.", os)); } } return FormValidation.ok(); }

Target:
public FormValidation doCheckIsRunUnmetered(@QueryParameter Boolean isRunUnmetered, @QueryParameter String appArtifact) { if (isRunUnmetered) { AWSDeviceFarm adf = getAWSDeviceFarm(); String os = adf.getOs(appArtifact); if (adf.getUnmeteredDevices(os) <= 0) { return FormValidation.error(String.format("Your account does not have unmetered %s devices.", os)); } } return FormValidation.ok(); }
Source:
public Response<?> apply(ChangeResource rsrc, Publish.Input in) throws AuthException, ResourceConflictException, NoSuchChangeException, IOException, InvalidChangeOperationException, OrmException { Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange()); if (!edit.isPresent()) { throw new ResourceConflictException(String.format( "no edit exists for change %s", rsrc.getChange().getChangeId())); } PatchSet current = db.get().patchSets().get( rsrc.getChange().currentPatchSetId()); if (current.getId().equals(edit.get().getBasePatchSet().getId())) { throw new ResourceConflictException(String.format( "edit for change %s is already on latest ps: %s", rsrc.getChange().getChangeId(), current.getId())); } editModifier.rebaseEdit(edit.get(), current); return Response.none(); }

Target:
public Response<?> apply(ChangeResource rsrc, Publish.Input in) throws AuthException, ResourceConflictException, NoSuchChangeException, IOException, InvalidChangeOperationException, OrmException { Optional<ChangeEdit> edit = editUtil.byChange(rsrc.getChange()); if (!edit.isPresent()) { throw new ResourceConflictException(String.format( "no edit exists for change %s", rsrc.getChange().getChangeId())); } PatchSet current = db.get().patchSets().get( rsrc.getChange().currentPatchSetId()); if (current.getId().equals(edit.get().getBasePatchSet().getId())) { throw new ResourceConflictException(String.format( "edit for change %s is already on latest patch set: %s", rsrc.getChange().getChangeId(), current.getId())); } editModifier.rebaseEdit(edit.get(), current); return Response.none(); }
Source:
boolean awaitBlobCreations() throws InterruptedException { return creationHelper.await(11, TimeUnit.SECONDS); }

Target:
boolean awaitBlobCreations() throws InterruptedException { return creationHelper.await(10, TimeUnit.SECONDS); }
Source:
private EnumSet<XMPPContact.Feature> runDiscovery(String fullJid) { EnumSet<XMPPContact.Feature> features = EnumSet.noneOf(XMPPContact.Feature.class); if (discoveryManager == null) return features; try { DiscoverInfo discoverInfo = discoveryManager.discoverInfo(fullJid); for (Iterator<DiscoverInfo.Feature> it = discoverInfo.getFeatures(); it.hasNext(); ) { String feature = it.next().getVar(); if (SarosConstants.XMPP_FEATURE_NAMESPACE.equals(feature)) { features.add(XMPPContact.Feature.SAROS); } else if (SarosConstants.NAMESPACE_SERVER.equals(feature)) { features.add(XMPPContact.Feature.SAROS_SERVER); } } } catch (XMPPException e) { log.debug("Feature discovery for " + fullJid + " failed", e); } return features; }

Target:
private EnumSet<ResourceFeature> runDiscovery(String fullJid) { EnumSet<ResourceFeature> features = EnumSet.noneOf(ResourceFeature.class); if (discoveryManager == null) return features; try { DiscoverInfo discoverInfo = discoveryManager.discoverInfo(fullJid); for (Iterator<DiscoverInfo.Feature> it = discoverInfo.getFeatures(); it.hasNext(); ) { ResourceFeature.getFeature(it.next().getVar()).ifPresent(features::add); } } catch (XMPPException e) { log.debug("Feature discovery for " + fullJid + " failed", e); } return features; }
Source:
private void finish() { int bufferLen = (int) (length & 63); if (bufferLen > 55) { buffer[bufferLen++] = (byte) 0x80; Arrays.fill(buffer, bufferLen, 64, (byte) 0); compress(buffer, 0); Arrays.fill(buffer, 0, 56, (byte) 0); } else { buffer[bufferLen++] = (byte) 0x80; Arrays.fill(buffer, bufferLen, 56, (byte) 0); } NB.encodeInt32(buffer, 56, (int) (length >>> (32 - 3))); NB.encodeInt32(buffer, 60, (int) (length << 3)); compress(buffer, 0); if (foundCollision) { if (!safeHash) { throw new Sha1CollisionException(); } LOG.warn("possible SHA-1 collision; safeHash" + (safeHash ? "" : " disabled,") + ' ' + h.toObjectId().name()); } }

Target:
private void finish() { int bufferLen = (int) (length & 63); if (bufferLen > 55) { buffer[bufferLen++] = (byte) 0x80; Arrays.fill(buffer, bufferLen, 64, (byte) 0); compress(buffer, 0); Arrays.fill(buffer, 0, 56, (byte) 0); } else { buffer[bufferLen++] = (byte) 0x80; Arrays.fill(buffer, bufferLen, 56, (byte) 0); } NB.encodeInt32(buffer, 56, (int) (length >>> (32 - 3))); NB.encodeInt32(buffer, 60, (int) (length << 3)); compress(buffer, 0); if (foundCollision) { ObjectId id = h.toObjectId(); LOG.warn("possible SHA-1 collision; safeHash " + (safeHash ? "is" : "disabled,") + ' ' + id.name()); if (!safeHash) { throw new Sha1CollisionException(id); } } }
Source:
public void is_false_value() throws Exception { List<Boolean> falseValues = createLiterals(Tree.Kind.BOOLEAN_LITERAL, "false", "False", "FALSE") .map(CheckUtils::isFalseValue).collect(Collectors.toList()); assertThat(falseValues).containsOnly(true); falseValues = createLiterals(Tree.Kind.NUMERIC_LITERAL, "0", "0.0") .map(CheckUtils::isFalseValue).collect(Collectors.toList()); assertThat(falseValues).containsOnly(true); falseValues = createLiterals(Tree.Kind.REGULAR_STRING_LITERAL, "\"0\"", "'0'", "''") .map(CheckUtils::isFalseValue).collect(Collectors.toList()); assertThat(falseValues).containsOnly(true); }

Target:
public void is_false_value() throws Exception { assertThat(createLiterals(Tree.Kind.BOOLEAN_LITERAL, "false", "False", "FALSE") .allMatch(CheckUtils::isFalseValue)).isTrue(); assertThat(createLiterals(Tree.Kind.NUMERIC_LITERAL, "0", "0.0") .allMatch(CheckUtils::isFalseValue)).isTrue(); assertThat(createLiterals(Tree.Kind.REGULAR_STRING_LITERAL, "\"0\"", "'0'", "''") .allMatch(CheckUtils::isFalseValue)).isTrue(); }
Source:
protected boolean evaluateFilter(JsonBuilderContext context) { if (filter == null) return true; int i = 0; JsonBuilderContext evaluationContenxt = context; while (i < filterContextPos) { evaluationContenxt = evaluationContenxt.getParent(); i++; } return filter.evaluate(evaluationContenxt.getCurrentObj()); }

Target:
protected boolean evaluateFilter(JsonBuilderContext context) { if (filter == null) return true; JsonBuilderContext evaluationContenxt = context; for (int i = 0; i < filterContextPos; i++) { evaluationContenxt = evaluationContenxt.getParent(); } return filter.evaluate(evaluationContenxt.getCurrentObj()); }
Source:
public static MultifactorAuthenticationProviderBypass newMultifactorAuthenticationProviderBypass( final MultifactorAuthenticationProviderBypassProperties props) { val bypass = new ChainingMultifactorAuthenticationBypassProvider(); bypass.addBypass(new DefaultMultifactorAuthenticationProviderBypass(props)); if (props.getGroovy().getLocation() != null) { bypass.addBypass(new GroovyMultifactorAuthenticationProviderBypass(props)); } if (StringUtils.isNotBlank(props.getRest().getUrl())) { bypass.addBypass(new RestMultifactorAuthenticationProviderBypass(props)); } return bypass; }

Target:
public static MultifactorAuthenticationProviderBypass newMultifactorAuthenticationProviderBypass( final MultifactorAuthenticationProviderBypassProperties props) { val bypass = new ChainingMultifactorAuthenticationBypassProvider(); bypass.addBypass(new DefaultMultifactorAuthenticationProviderBypass(props)); if (props.getType() == MultifactorAuthenticationProviderBypassProperties.MultifactorProviderBypassTypes.GROOVY) { bypass.addBypass(new GroovyMultifactorAuthenticationProviderBypass(props)); } if (props.getType() == MultifactorAuthenticationProviderBypassProperties.MultifactorProviderBypassTypes.REST) { bypass.addBypass(new RestMultifactorAuthenticationProviderBypass(props)); } return bypass; }
Source:
protected void onShowPage(boolean firstShow) { try { loadConfiguration(); if (!isEnable) { disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText( "Restricting the tables to load from specific database schemas, is not " + "supported for this database driver. All database tables will be loaded."); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setMessage(""); setPageComplete(true); return; } Connection conn = getConnection(); if (conn == null) { disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText( "Could not established connection with database. Please check the settings."); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setErrorMessage("Connection error!"); setPageComplete(false); return; } else { setErrorMessage(null); } if (firstShow) { createComponent(); } else { disposeControl(); schemas.clear(); createComponent(); } getSchemas(conn); schemaTable.setInput(schemas); if (multipleSelection) { schemaTable.setAllChecked(true); setPageComplete(true); setMessage("Please select one or multiple schemas."); } else { setMessage("Please select one schema."); } } catch (SQLException e) { log.error(e.getMessage(), e); } }

Target:
protected void onShowPage(boolean firstShow) { loadConfiguration(); if (!isEnable) { disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText("Restricting the tables to load from specific database schemas, is not " + "supported for this database driver. All database tables will be loaded."); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setMessage(""); setPageComplete(true); return; } Connection conn = null; try { conn = getConnection(); } catch (SQLException e) { log.error(e.getMessage(), e); disposeControl(); Label label = new Label(page, SWT.WRAP); label.setText("Could not establish connection with database: " + e.getMessage()); label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1)); page.layout(true, true); setErrorMessage("Connection error!"); setPageComplete(false); return; } setErrorMessage(null); if (firstShow) { createComponent(); } else { disposeControl(); schemas.clear(); createComponent(); } try { getSchemas(conn); schemaTable.setInput(schemas); if (multipleSelection) { schemaTable.setAllChecked(true); setPageComplete(true); setMessage("Please select one or multiple schemas."); } else { setMessage("Please select one schema."); } } catch (SQLException e) { log.error(e.getMessage(), e); } }
Source:
public JSONObject toJson() { JSONObject json = super.toJson(); json.put("format", MainJsonObjectFactory.get().createJsonObject(((INumberColumn) getColumn()).getFormat()).toJson()); json.put("aggregationFunction", ((INumberColumn) getColumn()).getAggregationFunction()); json.put("backgroundEffect", ((INumberColumn) getColumn()).getBackgroundEffect()); return json; }

Target:
public JSONObject toJson() { JSONObject json = super.toJson(); json.put("format", MainJsonObjectFactory.get().createJsonObject(getColumn().getFormat()).toJson()); json.put("aggregationFunction", getColumn().getAggregationFunction()); json.put("backgroundEffect", getColumn().getBackgroundEffect()); return json; }
Source:
private void executeFailoverTest(Runnable failureInjector) throws Exception { EurekaRegistrationClient registrationClient = eurekaDeploymentResource.getEurekaDeployment().registrationClientToWriteCluster(); EurekaInterestClient interestClient = eurekaDeploymentResource.getEurekaDeployment().cannonicalInterestClient(); try { ExtTestSubscriber<ChangeNotification<InstanceInfo>> interestSubscriber = subscribeTo(interestClient, INSTANCE_UP); PublishSubject<InstanceInfo> registrationSubject = PublishSubject.create(); Subscription registrationSubscription = registrationClient.register(registrationSubject).subscribe(); registrationSubject.onNext(INSTANCE_UP); assertThat(interestSubscriber.takeNext(60, TimeUnit.SECONDS), is(addChangeNotificationOf(INSTANCE_UP))); failureInjector.run(); registrationSubject.onNext(INSTANCE_DOWN); assertThat(registrationSubscription.isUnsubscribed(), is(false)); assertThat(interestSubscriber.takeNext(60, TimeUnit.SECONDS), is(modifyChangeNotificationOf(INSTANCE_DOWN))); } finally { registrationClient.shutdown(); interestClient.shutdown(); } }

Target:
private void executeFailoverTest(Runnable failureInjector) throws Exception { EurekaRegistrationClient registrationClient = eurekaDeploymentResource.getEurekaDeployment().registrationClientToWriteCluster(); EurekaInterestClient interestClient = eurekaDeploymentResource.getEurekaDeployment().cannonicalInterestClient(); ExtTestSubscriber<ChangeNotification<InstanceInfo>> interestSubscriber = subscribeTo(interestClient, INSTANCE_UP); PublishSubject<InstanceInfo> registrationSubject = PublishSubject.create(); Subscription registrationSubscription = registrationClient.register(registrationSubject).subscribe(); registrationSubject.onNext(INSTANCE_UP); assertThat(interestSubscriber.takeNext(60, TimeUnit.SECONDS), is(addChangeNotificationOf(INSTANCE_UP))); failureInjector.run(); registrationSubject.onNext(INSTANCE_DOWN); assertThat(registrationSubscription.isUnsubscribed(), is(false)); assertThat(interestSubscriber.takeNext(60, TimeUnit.SECONDS), is(modifyChangeNotificationOf(INSTANCE_DOWN))); }
Source:
private void testDurability(boolean disableWAL) throws Exception { Connection conn = DriverManager.getConnection(getUrl()); try { Durability expectedDurability = disableWAL ? Durability.SKIP_WAL : Durability.USE_DEFAULT; conn.setAutoCommit(false); conn.createStatement().execute("CREATE TABLE t1 (k integer not null primary key, a.k varchar, b.k varchar) " + (disableWAL ? "DISABLE_WAL=true" : "")); conn.createStatement().execute("UPSERT INTO t1 VALUES(1,'a','b')"); conn.createStatement().execute("DELETE FROM t1 WHERE k=2"); assertDurability(conn,expectedDurability); conn.createStatement().execute("DELETE FROM t1 WHERE k=1"); assertDurability(conn,expectedDurability); } finally { try { conn.rollback(); conn.createStatement().execute("DROP TABLE t1"); } finally { conn.close(); } } }

Target:
private void testDurability(boolean disableWAL) throws Exception { try(Connection conn = DriverManager.getConnection(getUrl())) { Durability expectedDurability = disableWAL ? Durability.SKIP_WAL : Durability.USE_DEFAULT; conn.setAutoCommit(false); conn.createStatement().execute("CREATE TABLE t1 (k integer not null primary key, a.k varchar, b.k varchar) " + (disableWAL ? "DISABLE_WAL=true" : "")); conn.createStatement().execute("UPSERT INTO t1 VALUES(1,'a','b')"); conn.createStatement().execute("DELETE FROM t1 WHERE k=2"); assertDurability(conn,expectedDurability); conn.createStatement().execute("DELETE FROM t1 WHERE k=1"); assertDurability(conn,expectedDurability); conn.rollback(); conn.createStatement().execute("DROP TABLE t1"); } }
Source:
static boolean isVcardFile(Content content) { try { byte[] t = new byte[VCARD_HEADER.length()]; if (content.getSize() > MIN_FILE_SIZE) { int byteRead = content.read(t, 0, VCARD_HEADER.length()); if (byteRead > 0) { String header = new String(t); return header.equalsIgnoreCase(VCARD_HEADER); } } } catch (TskException ex) { logger.log(Level.WARNING, String.format("Exception while detecting if the file '%s' (id=%d) is a vCard file.", content.getName(), content.getId())); return false; } return false; }

Target:
static boolean isVcardFile(Content content) { try { if (content.getSize() > MIN_FILE_SIZE) { byte[] buffer = new byte[VCARD_HEADER.length()]; int byteRead = content.read(buffer, 0, VCARD_HEADER.length()); if (byteRead > 0) { String header = new String(buffer); return header.equalsIgnoreCase(VCARD_HEADER); } } } catch (TskException ex) { logger.log(Level.WARNING, String.format("Exception while detecting if the file '%s' (id=%d) is a vCard file.", content.getName(), content.getId())); return false; } return false; }