auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void createDocumentVersions(DocumentModel doc, VersioningOption vo, int nrVersions) { // create a document with major versions for (int i = 1; i <= nrVersions; i++) { doc.setPropertyValue("dc:description", "" + i); doc.putContextData(VersioningService.VERSIONING_OPTION, vo); session.saveDocument(doc); } session.save(); }

Target:
protected DocumentModel createDocumentVersions(DocumentModel doc, VersioningOption vo, int nrVersions) { for (int i = 1; i <= nrVersions; i++) { doc.setPropertyValue("dc:description", String.valueOf(i)); doc.putContextData(VersioningService.VERSIONING_OPTION, vo); doc = session.saveDocument(doc); } session.save(); return doc; }
Source:
private static boolean responseOk(final int status) { switch (status) { case HttpStatus.SC_CREATED: case HttpStatus.SC_OK: return true; default: return false; } }

Target:
private static boolean responseOk(final int status) { return status / 100 == 2; //all 2xx is ok }
Source:
@Override public void onClose(Status status, Metadata trailers) { Throwable error = null; try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onClose(status, trailers); } catch (Throwable e) { error = e; throw e; } finally { GrpcClientResponse response = new GrpcClientResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } }

Target:
@Override public void onClose(Status status, Metadata trailers) { // See /instrumentation/grpc/RATIONALE.md for why we don't catch exceptions from the delegate GrpcClientResponse response = new GrpcClientResponse(request, status, trailers, null); finish(response, spanRef.getAndSet(null)); try (Scope scope = currentTraceContext.maybeScope(invocationContext)) { delegate().onClose(status, trailers); } }
Source:
@Override public void close(Status status, Metadata trailers) { Throwable error = null; try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } catch (Throwable e) { error = e; throw e; } finally { GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } }

Target:
@Override public void close(Status status, Metadata trailers) { // See /instrumentation/grpc/RATIONALE.md for why we don't catch exceptions from the delegate GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, null); finish(response, spanRef.getAndSet(null)); try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } }
Source:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); // remove propagation headers from the record tracing.propagation().keys().forEach(key -> record.headers().remove(key)); // Inject new propagation headers tracing.propagation().injector(injector) .inject(span.context(), record); }

Target:
private void handleConsumed(ConsumerRecord record) { Span span = startAndFinishConsumerSpan(record); // remove propagation headers from the record tracing.propagation().keys().forEach(key -> record.headers().remove(key)); // Inject new propagation headers injector.inject(span.context(), record); }
Source:
private void decodeRowType4() throws IOException { if(optionByteAligned) resetBuffer(); eof: while (true) { // read till next EOL code Node n = eolOnlyTree.root; while (true) { n = n.walk(readBit()); if (n == null) { continue eof; } if (n.isLeaf) { break eof; } } } if (!optionG32D || readBit()) { decode1D(); } else { decode2D(); } }

Target:
private void decodeRowType4() throws IOException { if (optionByteAligned) { resetBuffer(); } eof: while (true) { // read till next EOL code Node n = eolOnlyTree.root; while (true) { n = n.walk(readBit()); if (n == null) { continue eof; } if (n.isLeaf) { break eof; } } } if (!optionG32D || readBit()) { decode1D(); } else { decode2D(); } }
Source:
private void doMain() throws Exception { // Start the process start(); while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } unregisterMBeans(); }

Target:
private void doMain() throws Exception { // Start the process this.start(); while (true) { // look for some terminator // attempt to read off queue // process message // TODO : Make something here, maybe watch for files? try { Thread.sleep(5); } catch (Exception e) { log.info("shutting down", e); break; } } this.unregisterMBeans(); }
Source:
protected void after() { System.setOut(originalOut); System.setErr(originalErr); // I guess it's useful to print this after completion System.out.println("What was captured:"); System.out.println(out); }

Target:
protected void after() { System.setOut(originalOut); System.setErr(originalErr); // I guess it's useful to print this after completion //System.out.println("What was captured:"); //System.out.println(out); }
Source:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); return dBuilder.parse(inputStream); }

Target:
public static Document getDocument(String xml) throws ParserConfigurationException, IOException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = factory.newDocumentBuilder(); try (InputStream inputStream = new ByteArrayInputStream(xml.getBytes())) { return dBuilder.parse(inputStream); } }
Source:
protected List<ExternalBeanDefinition> getExternalMiningClasses() { List<ExternalBeanDefinition> list = null; if (externalMiningFields != null && !externalMiningFields.isEmpty()) { list = externalMiningFields.stream() .map(ref -> ref.getBeanDefinition()) .distinct() .collect(Collectors.toList()); } return list != null ? list : new ArrayList<>(); }

Target:
protected List<ExternalBeanDefinition> getExternalMiningClasses() { List<ExternalBeanDefinition> list = null; if (externalMiningFields != null && !externalMiningFields.isEmpty()) { list = externalMiningFields.stream() .map(ref -> ref.getBeanDefinition()) .distinct() .collect(Collectors.toList()); } // DO NOT USE Collections.emptyList() here!!! emptyList() returns an EmptyList instance // which is an internal class from Collections class, therefore not accessible // by reflection - when mvel parses a RuleUnit template and there is // a size call, it tries to invoke the method using reflection return list != null ? list : new ArrayList<>(0); }
Source:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { // override tccl so persistence unit can be found from within given class loader - e.g. kjar Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; this.name += ":" + persistenceUnit; }

Target:
public JPAPlaceholderResolverStrategy(String persistenceUnit, ClassLoader cl) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); try { // override tccl so persistence unit can be found from within given class loader - e.g. kjar Thread.currentThread().setContextClassLoader(cl); this.emf = Persistence.createEntityManagerFactory(persistenceUnit); initializeManagedClasses(); this.closeEmf = true; } finally { Thread.currentThread().setContextClassLoader(tccl); } this.classLoader = cl; }
Source:
private static void attachShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { LOGGER.info("JMXFetch is closing"); // Properly close log handlers LogManager.shutdown(); } } ); }

Target:
private static void attachShutdownHook() { Runtime.getRuntime().addShutdownHook( new Thread() { @Override public void run() { log.info("JMXFetch is closing"); // Properly close log handlers LogManager.shutdown(); } } ); }
Source:
private String getCassandraAlias() { if (renameCassandraMetrics()) { Map<String, String> beanParameters = getBeanParameters(); String type = beanParameters.get("type"); String metricName = beanParameters.get("name"); String attributeName = getAttributeName(); if (attributeName.equals("Value")) { return "cassandra." + metricName; } return "cassandra." + metricName + "." + attributeName; } //Deprecated Cassandra metric. Remove domain prefix. return getDomain().replace("org.apache.", "") + "." + getAttributeName(); }

Target:
private String getCassandraAlias() { if (renameCassandraMetrics()) { Map<String, String> beanParameters = getBeanParameters(); String metricName = beanParameters.get("name"); String attributeName = getAttributeName(); if (attributeName.equals("Value")) { return "cassandra." + metricName; } return "cassandra." + metricName + "." + attributeName; } //Deprecated Cassandra metric. Remove domain prefix. return getDomain().replace("org.apache.", "") + "." + getAttributeName(); }
Source:
protected BaseCommand(SelectedOptions selectedOptions) { this.options = selectedOptions; this.paths = selectedOptions.getPaths(); if (options.isQuiet()) { this.printStream = new PrintStream(new OutputStream() { @Override public void write(int b) throws IOException { // throw away output } }); } }

Target:
protected BaseCommand(SelectedOptions selectedOptions) { this.options = selectedOptions; this.paths = selectedOptions.getPaths(); if (options.isQuiet()) { this.printStream = new PrintStream(new OutputStream() { @Override public void write(int b) { // throw away output } }); } }
Source:
public Set<Class<?>> getProviderClasses() { if (providerClasses == null && parent != null) return parent.getProviderClasses(); if(initialized) { return providerClasses; } Set<Class<?>> set = new HashSet<Class<?>>(); if (parent != null) set.addAll(parent.getProviderClasses()); set.addAll(providerClasses); return set; }

Target:
public Set<Class<?>> getProviderClasses() { if(initialized) { return providerClasses; } Set<Class<?>> set = new HashSet<Class<?>>(); if (parent != null) set.addAll(parent.getProviderClasses()); set.addAll(providerClasses); return set; }
Source:
public boolean close(final long timeout, final TimeUnit unit) { internalClose(); try { // mimic executor.awaitTermination giving time for tasks to complete long duration = TimeUnit.MILLISECONDS.convert(timeout, unit); Thread.sleep(duration); } catch (InterruptedException e) { onErrorConsumers.forEach(consumer -> { consumer.accept(e); }); Thread.currentThread().interrupt(); return false; } return true; }

Target:
public boolean close(final long timeout, final TimeUnit unit) { // Ignoring timeout because we are canceling tasks on a local list. // This is not a shutdown of an executor which may be running // other unrelated tasks. internalClose(); return true; }
Source:
public boolean configure(FeatureContext context) { // this is tied to the deployment, which is what we want for the reactive context if(context.getConfiguration().getRuntimeType() == RuntimeType.CLIENT) return false; Dispatcher dispatcher = ResteasyProviderFactory.getContextData(Dispatcher.class); if(dispatcher == null) { System.err.println("Creating new context for "+context.getConfiguration().getRuntimeType()+" deployment because it looks like we're in a special thread"); return false; } dispatcher.getDefaultContextObjects().put(Context.class, new Context()); return true; }

Target:
public boolean configure(FeatureContext context) { // this is tied to the deployment, which is what we want for the reactive context if(context.getConfiguration().getRuntimeType() == RuntimeType.CLIENT) return false; Dispatcher dispatcher = ResteasyProviderFactory.getContextData(Dispatcher.class); if(dispatcher == null) { // this can happen, but it means we're not able to find a deployment return false; } dispatcher.getDefaultContextObjects().put(Context.class, new Context()); return true; }
Source:
public void subscribe(@Context SseEventSink sink) throws IOException { synchronized (outputLock) { if (sink == null) { throw new IllegalStateException("No client connected."); } } eventSink = sink; //subscribe if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }

Target:
public void subscribe(@Context SseEventSink sink) throws IOException { if (sink == null) { throw new IllegalStateException("No client connected."); } eventSink = sink; //subscribe if (sseBroadcaster == null) { sseBroadcaster = sse.newBroadcaster(); } sseBroadcaster.register(sink); }
Source:
public void addExecutedTest(Class<?> testClass) { System.out.println("Adding class with a run: " + testClass.getName()); addTest(testClass); executedTestClasses.add(testClass); }

Target:
public void addExecutedTest(Class<?> testClass) { addTest(testClass); executedTestClasses.add(testClass); }
Source:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } // do not exceed max value of Long if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round(seconds * FACTOR); } }

Target:
public long getSeconds() { if (seconds == Long.MAX_VALUE || seconds == 0) { return seconds; } if (FACTOR == 1) { return seconds; } // do not exceed max value of Long if (seconds >= Long.MAX_VALUE / FACTOR) { return Long.MAX_VALUE; } else { return Math.round((double) seconds * FACTOR); } }
Source:
public void setNewHighScoreMode(boolean mode) { if (mode) { this.clearTouchAreas(); this.registerTouchArea(inputText); inputText.setVisible(true); inTopText.setVisible(true); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); } else { this.clearTouchAreas(); inputText.setVisible(false); inTopText.setVisible(false); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); } }

Target:
public void setNewHighScoreMode(boolean mode) { this.clearTouchAreas(); this.registerTouchArea(restartButtonSprite); this.registerTouchArea(exitButtonSprite); if (mode) { this.registerTouchArea(inputText); inputText.setVisible(true); inTopText.setVisible(true); } else { inputText.setVisible(false); inTopText.setVisible(false); } }
Source:
private void fire() { Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); activity.getSceneSwitcher().getGameScene().createTorpedo( gun.getShootStartPoint() , gun.getGunAngle()); }

Target:
private void fire() { getGun().fire(); }
Source:
private void stopGun() { Gun gun = activity.getSceneSwitcher().getGameScene().getGun(); gun.stopRotate(); }

Target:
private void stopGun() { getGun().stopRotate(); }
Source:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain; try { // pre-condition domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); // operation domain.destroy(); // verification fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { // verification } }

Target:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain = null; try { // pre-condition domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); // operation domain.destroy(); // verification fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { // verification } }
Source:
public List<String> getLines(Channel channel) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(channel))); List<String> lines = new ArrayList<String>(); String line; // Read File Line By Line while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }

Target:
public List<String> getLines(Channel channel) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(getInputStream(channel))); List<String> lines = new ArrayList<String>(); String line = null; // Read File Line By Line while ((line = reader.readLine()) != null) { lines.add(line); } return lines; }
Source:
public boolean isBiometricEnabled() { SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.Companion.getAppContext()); return (appPrefs.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false)); }

Target:
protected boolean isBiometricEnabled() { SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(MainApp.Companion.getAppContext()); return (appPrefs.getBoolean(BiometricActivity.PREFERENCE_SET_BIOMETRIC, false)); }
Source:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); // check if its a oauth SALS callback intent if(intent.getAction().equals(ACTION_VIEW) && intent.getData().getHost().equals("android.owncloud.com")) { getOAuth2AccessTokenFromCapturedRedirection(intent.getData()); } }

Target:
public void onNewIntent(Intent intent) { super.onNewIntent(intent); if(intent.getAction().equals(ACTION_VIEW)) { getOAuth2AccessTokenFromCapturedRedirection(intent.getData()); } }
Source:
public static boolean isNetworkActive(Context context) { boolean isNetworkActive = true; ConnectivityManager cm = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); // Check network availabality (no info object implies no connectivity) if (activeNetwork == null || (activeNetwork!= null && !activeNetwork.isConnectedOrConnecting())) { isNetworkActive = false; } return isNetworkActive; }

Target:
public static boolean isNetworkActive(Context context) { ConnectivityManager cm = (ConnectivityManager)context. getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.isConnectedOrConnecting()); }
Source:
public void onCheckedChanged(CompoundButton switchView, boolean isChecked) { if (!isResumed()) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return; } boolean permission; if (isChecked) { permission = true; } else { permission = false; } ((FileActivity) getActivity()).getFileOperationsHelper(). setUploadPermissionsToShare( mFile, permission ); ; // undo the toggle to grant the view will be correct if the dialog is cancelled switchView.setOnCheckedChangeListener(null); switchView.toggle(); switchView.setOnCheckedChangeListener(mOnEditPermissionInteractionListener); }

Target:
public void onCheckedChanged(CompoundButton switchView, boolean isChecked) { if (!isResumed()) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return; } ((FileActivity) getActivity()).getFileOperationsHelper(). setUploadPermissionsToShare( mFile, isChecked ); ; // undo the toggle to grant the view will be correct if the dialog is cancelled switchView.setOnCheckedChangeListener(null); switchView.toggle(); switchView.setOnCheckedChangeListener(mOnEditPermissionInteractionListener); }
Source:
protected RemoteOperationResult run(OwnCloudClient client) { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); if (result.isSuccess()){ // Read data from the result OCCapability capability = (OCCapability) result.getData().get(0); // Save the capabilities into database getStorageManager().saveCapabilities(capability); } return result; }

Target:
protected RemoteOperationResult run(OwnCloudClient client) { GetRemoteCapabilitiesOperation getCapabilities = new GetRemoteCapabilitiesOperation(); RemoteOperationResult result = getCapabilities.execute(client); if (result.isSuccess()){ // Read data from the result if( result.getData()!= null && result.getData().size() > 0) { OCCapability capability = (OCCapability) result.getData().get(0); // Save the capabilities into database getStorageManager().saveCapabilities(capability); } } return result; }
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); if (DisplayUtils.isGridView(directory, getStorageManager())){ switchToGridView(); } else { switchToListView(); } }

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); }
Source:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); switchLayout(directory); }

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); // Sync Folder startSyncFolderOperation(directory, false); }
Source:
private void syncContents(OwnCloudClient client) { startDirectDownloads(); startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client); startContentSynchronizations(mFavouriteFilesToSyncContents, client); walkSubfolders(mFoldersToWalkDown, client); // this must be the last! }

Target:
private void syncContents(OwnCloudClient client) { startDirectDownloads(); startContentSynchronizations(mFilesToSyncContentsWithoutUpload, client); startContentSynchronizations(mFavouriteFilesToSyncContents, client); walkSubfolders(client); // this must be the last! }
Source:
public void handle(FailureContext context) { // <1> try { String failingOperationDescription = context.getFailingOperation().toString(); // <2> Throwable throwable = context.getThrowable(); // <3> // ... report the failure ... // <4> } catch (Throwable t) { // ... handle the failure and do *not* propagate the throwable ... // <5> } }

Target:
public void handle(FailureContext context) { // <1> String failingOperationDescription = context.getFailingOperation().toString(); // <2> Throwable throwable = context.getThrowable(); // <3> // ... report the failure ... // <4> }
Source:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } // java.sql.Date does not support toInstant(). See HSEARCH-3670. // We're using here the same strategy applied on DefaultJavaSqlDateValueBridge to handle them. return value instanceof java.sql.Date ? Instant.ofEpochMilli( value.getTime() ) : value.toInstant(); }

Target:
public Instant toIndexedValue(Date value, ValueBridgeToIndexedValueContext context) { if ( value == null ) { return null; } // java.sql.* types do not support toInstant(). See HSEARCH-3670 return Instant.ofEpochMilli( value.getTime() ); }
Source:
public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); //Needs to have a timeout higher than zero to prevent race conditions over (network) RPCs //for distributed indexes (Infinispan but probably also NFS and similar) SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString() ); } }

Target:
public static void initializeIndexIfNeeded(Directory directory, EventContext eventContext) throws IOException { if ( DirectoryReader.indexExists( directory ) ) { return; } try { IndexWriterConfig iwriterConfig = new IndexWriterConfig( AnalyzerConstants.KEYWORD_ANALYZER ) .setOpenMode( OpenMode.CREATE_OR_APPEND ); //Needs to have a timeout higher than zero to prevent race conditions over (network) RPCs //for distributed indexes (Infinispan but probably also NFS and similar) SleepingLockWrapper delayedDirectory = new SleepingLockWrapper( directory, 2000, 20 ); IndexWriter iw = new IndexWriter( delayedDirectory, iwriterConfig ); iw.close(); } catch (LockObtainFailedException lofe) { log.lockingFailureDuringInitialization( directory.toString(), eventContext ); } }
Source:
public static Instant parseInstant(String value) { // Using the default ISO format DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT; try { return Instant.parse( value ); } catch (DateTimeParseException e) { throw log.unableToParseTemporal( Instant.class, value, formatter, e ); } }

Target:
public static Instant parseInstant(String value) { try { // Using the default ISO format return Instant.parse( value ); } catch (DateTimeParseException e) { throw log.unableToParseTemporal( Instant.class, value, DateTimeFormatter.ISO_INSTANT, e ); } }
Source:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { if ( status != ServiceStatus.RUNNING ) { stateExpectedFailure(); } stopReal(); } else if ( status != ServiceStatus.RUNNING ) { //Could happen on circular dependencies stateExpectedFailure(); } }

Target:
synchronized void stopVirtual() { userCounter--; if ( userCounter == 0 ) { //Do not check for the expected status in this case: we don't want a previous service start failure to //prevent us to further attempt to stop services. stopReal(); } }
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { field.mappedOn( Elasticsearch.class ) .dynamic( DynamicType.TRUE ); } }

Target:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { field.mappedOn( Elasticsearch.class ) .dynamic( dynamicType ); } }
Source:
static String getDocumentId(LuceneWork work) { return work.getTenantId() == null ? work.getIdInString() : work.getTenantId() + "_" + work.getIdInString(); }

Target:
private String getDocumentId(LuceneWork work) { return work.getTenantId() == null ? work.getIdInString() : work.getTenantId() + "_" + work.getIdInString(); }
Source:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SUPPORTED_TYPES == null ) { // LAZY init, but don't to it more than once SUPPORTED_TYPES_LOCK.lock(); try { if ( SUPPORTED_TYPES == null ) { Set<Class<? extends DeletionQuery>> set = new HashSet<>(); set.add( SingularTermDeletionQuery.class ); SUPPORTED_TYPES = Collections.unmodifiableSet( set ); } } finally { SUPPORTED_TYPES_LOCK.unlock(); } } return SUPPORTED_TYPES.contains( type ); }

Target:
public static boolean isSupported(Class<? extends DeletionQuery> type) { if ( SingularTermDeletionQuery.class == type ) { return true; } return false; }
Source:
public boolean filter(String fromUrl, String toUrl) { //this implementation doesnt do anything with fromUrl if (exemptions != null) { for (Pattern pattern : exemptions) { if (pattern.matcher(toUrl).matches()) { return true; //If a regex matches, then exempted } } } //not exempted return false; }

Target:
public boolean filter(String fromUrl, String toUrl) { //this implementation does not consider fromUrl param. //the regex rules are applied to toUrl. return this.filter(toUrl) != null; }
Source:
public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); System.out.println("actual = " + actual); assertThat(replaceNewLine(actual)).isEqualTo(replaceNewLine(Resources.toString( Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8))); }

Target:
public void should_generate_yaml() throws Exception { RestxSpec testCase = restxSpecLoader.load( "restx/tests/restx_test_case_example_1.yaml"); String actual = testCase.toString(); // System.out.println("actual = " + actual); assertThat(actual).isEqualTo(Resources.toString( Resources.getResource("restx/tests/expected_restx_case_example_1.yaml"), Charsets.UTF_8)); }
Source:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { // not an URL return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return url.toString(); } }

Target:
public static String redactUrl(String path) { URL url; try { url = new URL(path); } catch (MalformedURLException e) { // not an URL return path; } if (url.getUserInfo() != null) { return url.toString().replace(url.getUserInfo(), REDACTED_USER_INFO); } else { return path; } }
Source:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = "http://www.myserver.org/viewProfile.jspa?username="; assertNull(instance.getUserPage()); // default value is null instance.setUserPage(page.substring(5)); assertEquals(page.substring(5), instance.getUserPage()); }

Target:
public void testUserPage() { RuntimeEnvironment instance = RuntimeEnvironment.getInstance(); String page = "http://www.myserver.org/viewProfile.jspa?username="; assertNull(instance.getUserPage()); // default value is null instance.setUserPage(page); assertEquals(page, instance.getUserPage()); }
Source:
public static boolean isLocal(Project project, String path) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); String srcRoot = env.getSourceRootPath(); if (path.startsWith(srcRoot)) { if (env.hasProjects()) { String relPath = path.substring(srcRoot.length()); if (project != null && project.equals(Project.getProject(relPath))) { // File is under the current project, so it's local. return true; } } else { // File is under source root, and we don't have projects, so // consider it local. return true; } } return false; }

Target:
public static boolean isLocal(Project project, String path) { RuntimeEnvironment env = RuntimeEnvironment.getInstance(); String srcRoot = env.getSourceRootPath(); if (path.startsWith(srcRoot)) { if (env.hasProjects()) { if (project != null && project.equals(Project.getProject(path.substring(srcRoot.length())))) { // File is under the current project, so it's local. return true; } } else { // File is under source root, and we don't have projects, so // consider it local. return true; } } return false; }
Source:
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setHttpRequestInitializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(300 * 60000); // 300 minutes connect timeout httpRequest.setReadTimeout(300 * 60000); // 300 minutes read timeout } }) .setApplicationName(SERVICE_APP_NAME).build(); }

Target:
static public Drive getDriveService(String token) { GoogleCredential credential = new GoogleCredential().setAccessToken(token); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setHttpRequestInitializer(new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { credential.initialize(httpRequest); httpRequest.setConnectTimeout(3 * 60000); // 3 minutes connect timeout httpRequest.setReadTimeout(3 * 60000); // 3 minutes read timeout } }) .setApplicationName(SERVICE_APP_NAME).build(); }
Source:
static public LocalDateTime stringToLocalDate(String s) { if (s.endsWith("Z")) { // UTC time Instant instant = Instant.parse(s); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } else return LocalDateTime.parse(s, DateTimeFormatter.ISO_LOCAL_DATE_TIME); }

Target:
static public LocalDateTime stringToLocalDate(String s) { if (s.endsWith("Z")) { // UTC time Instant instant = Instant.parse(s); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } else { return LocalDateTime.parse(s, DateTimeFormatter.ISO_LOCAL_DATE_TIME); } }
Source:
private static JSITDMNElement.JSIExtensionElements getOrCreateExtensionElements(final JSITDRGElement target) { // TODO {gcardosi} add because present in original json JSITDMNElement.JSIExtensionElements toReturn = target.getExtensionElements() == null ? new JSITDMNElement.JSIExtensionElements() : target.getExtensionElements(); if (!Objects.isNull(toReturn) && Objects.isNull(toReturn.getAny())) { toReturn.setAny(new ArrayList<>()); } return toReturn; }

Target:
private static JSITDMNElement.JSIExtensionElements getOrCreateExtensionElements(final JSITDRGElement target) { // Add because it is present in the original JSON when unmarshalling JSITDMNElement.JSIExtensionElements toReturn = Objects.isNull(target.getExtensionElements()) ? new JSITDMNElement.JSIExtensionElements() : target.getExtensionElements(); if (!Objects.isNull(toReturn) && Objects.isNull(toReturn.getAny())) { toReturn.setAny(new ArrayList<>()); } return toReturn; }
Source:
private Object[] toArray(List<?> messageArguments) { return messageArguments.stream().toArray(Object[]::new); }

Target:
private Object[] toArray(List<?> messageArguments) { return messageArguments.toArray(new Object[0]); }
Source:
String toDisplay(final String rawValue) { if (StringUtils.isEmpty(rawValue)) { return ""; } final String dateString = removePrefixAndSuffix(rawValue); try { final java.util.Date date = RAW_FORMAT.parse(dateString); return DISPLAY_FORMAT.format(date); } catch (final IllegalArgumentException exception) { return ""; } }

Target:
String toDisplay(final String rawValue) { if (StringUtils.isEmpty(rawValue)) { return ""; } final String dateString = removePrefixAndSuffix(rawValue); try { final Date date = RAW_FORMAT.parse(dateString); return DISPLAY_FORMAT.format(date); } catch (final IllegalArgumentException exception) { return ""; } }
Source:
public UpdateCanvasControlPointPositionCommand(final Edge edge, final ControlPoint[] controlPoints) { this.edge = edge; this.controlPoints = controlPoints; // Actual control points must be cloned at this point, before execution. oldControlPoints = Stream.of(getControlPoints(edge)) .map(ControlPoint::copy) .toArray(ControlPoint[]::new); ; }

Target:
public UpdateCanvasControlPointPositionCommand(final Edge edge, final ControlPoint[] controlPoints) { this.edge = edge; this.controlPoints = controlPoints; // Actual control points must be cloned at this point, before execution. oldControlPoints = Stream.of(getControlPoints(edge)) .map(ControlPoint::copy) .toArray(ControlPoint[]::new); }
Source:
public void setup() { final QName key = new QName(DMNModelInstrumentedBase.Namespace.KIE.getUri(), ConstraintType.CONSTRAINT_KEY, DMNModelInstrumentedBase.Namespace.KIE.getPrefix()); when(dmnUnary.getId()).thenReturn(ID); when(dmnUnary.getAdditionalAttributes()).thenReturn(additionalAttributes); when(dmnUnary.getText()).thenReturn(TEXT); when(additionalAttributes.getOrDefault(key, "")).thenReturn(CONSTRAINT_TYPE_TEXT); }

Target:
public void setup() { when(dmnUnary.getId()).thenReturn(ID); when(dmnUnary.getAdditionalAttributes()).thenReturn(additionalAttributes); when(dmnUnary.getText()).thenReturn(TEXT); }
Source:
public void save(String id) { context.saveStyle(); HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph Optional.ofNullable(id).ifPresent(node -> map.put(DEFAULT_NODE_ID, id)); context.addAttributes(map); }

Target:
public void save(String id) { context.saveStyle(); HashMap<String, String> map = new HashMap<>(); //setting the node id in case it exists on graph if (id != null) { map.put(DEFAULT_NODE_ID, id); } context.addAttributes(map); }
Source:
public static String getCaseFileVariableName(Property p) { String name = p.getName(); // legacy uses ID instead of name return name == null ? p.getId() : name; }

Target:
private static String getCaseFileVariableName(Property p) { String name = p.getName(); // legacy uses ID instead of name return name == null ? p.getId() : name; }
Source:
private boolean jsonExists(String path) { File test = new File(path + File.separator + JSON_POM_FILE); return test.exists() && test.isFile(); }

Target:
private boolean jsonExists(String path) { File test = new File(path, JSON_POM_FILE); return test.exists() && test.isFile(); }
Source:
public boolean isSupported(String feature) { throwException(); return true; }

Target:
public boolean isSupported(String feature) { throwException(); return false; }
Source:
static <T, U> Function<T, Result<U>> ignored(Class<?> expectedClass) { return t -> Result.ignored( "Ignored: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); }

Target:
private static <T, U> Function<T, Result<U>> ignored(Class<?> expectedClass) { return t -> Result.ignored( "Ignored: " + Optional.ofNullable(t) .map(o -> o.getClass().getCanonicalName()) .orElse("null -- expected " + expectedClass.getCanonicalName())); }
Source:
void setStringValue(String value) { if (value == null || value.isEmpty()) { return; } DataInputAssociation input = input(value); getIoSpecification(element).getDataInputs().add((DataInput) input.getTargetRef()); element.getDataInputAssociations().add(input); }

Target:
private void setStringValue(String value) { if (value == null || value.isEmpty()) { return; } DataInputAssociation input = input(value); getIoSpecification(element).getDataInputs().add((DataInput) input.getTargetRef()); element.getDataInputAssociations().add(input); }
Source:
private void onSaveError(final ClientRuntimeError error) { showError(error.getThrowable() instanceof DefinitionNotFoundException ? "somps" : error.getMessage()); }

Target:
private void onSaveError(final ClientRuntimeError error) { showError(error); }
Source:
private void onSafeRename() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to rename a .java file that could be parsed without errors, and we can calculate the //className we can check for class usages prior to renaming and we can also suggest to perform an automatic // class renaming. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_renaming_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> rename(), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file renaming procedure. rename(); } }

Target:
public void onSafeRename() { if (context.getEditorModelContent().getOriginalClassName() != null) { //if we are about to rename a .java file that could be parsed without errors, and we can calculate the //className we can check for class usages prior to renaming and we can also suggest to perform an automatic // class renaming. final String className = context.getEditorModelContent().getOriginalClassName(); showAssetUsagesDisplayer.showAssetUsages(Constants.INSTANCE.modelEditor_confirm_renaming_of_used_class(className), versionRecordManager.getCurrentPath(), className, ResourceType.JAVA, () -> rename(), () -> { }); } else { //we couldn't parse the class, so no check can be done. Just proceed with the standard //file renaming procedure. rename(); } }
Source:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { if (title.trim().length() > 0) { // Apply title's value. viewHandler.applyTitle(title, mutationContext); // Apply title's font styles. applyFont(element, mutationContext); } }

Target:
public void applyTitle(final String title, final W element, final MutationContext mutationContext) { // Apply title's value. viewHandler.applyTitle(title, mutationContext); // Apply title's font styles. applyFont(element, mutationContext); }
Source:
public void init() { // Initialize caches. super.initialize(); // Initialize the application's VFS. initFileSystem(); // Register packaged diagrams into VFS. registerAppDefinitions(); // Load vfs diagrams and put into the parent registry. final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams && !diagrams.isEmpty() ) { for ( Diagram diagram : diagrams ) { getRegistry().register( diagram ); } } }

Target:
public void init() { // Initialize caches. super.initialize(); // Initialize the application's VFS. initFileSystem(); // Register packaged diagrams into VFS. registerAppDefinitions(); // Load vfs diagrams and put into the parent registry. final Collection<Diagram> diagrams = getAllDiagrams(); if ( null != diagrams ) { diagrams.forEach( diagram -> getRegistry().register( diagram ) ); } }
Source:
public static OkHttpClient getInstance() { if (sOkHttpClient == null) { sOkHttpClient = new OkHttpClient(); sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString())); } return sOkHttpClient; }

Target:
public static synchronized OkHttpClient getInstance() { if (sOkHttpClient == null) { sOkHttpClient = new OkHttpClient(); sOkHttpClient.setConnectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setReadTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.setWriteTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS); sOkHttpClient.networkInterceptors().add(new UserAgentInterceptor(getUserAgentString())); } return sOkHttpClient; }
Source:
public InternetDataConnection.OutputStreamProvider forOutput() throws IOException { if (output != null) throw new RuntimeException("Output has already been enabled"); if (connected) throw new RuntimeException("Cannot enable output after having already connected"); connection.setDoOutput(true); output = new InternetDataConnection.OutputStreamProvider(); return output; }

Target:
public InternetDataConnection.OutputStreamProvider forOutput() throws IOException { if (output != null) { throw new RuntimeException("Output has already been enabled"); } if (connected) { throw new RuntimeException("Cannot enable output after having already connected"); } connection.setDoOutput(true); output = new InternetDataConnection.OutputStreamProvider(); return output; }
Source:
public InternetDataConnection.BothStreams andInput() throws IOException { if (connected) throw new RuntimeException("Cannot enable output after having already connected"); return new InternetDataConnection.BothStreams(new InternetDataConnection.InputStreamProvider(), this); }

Target:
public InternetDataConnection.BothStreams andInput() throws IOException { if (connected) { throw new RuntimeException("Cannot enable output after having already connected"); } return new InternetDataConnection.BothStreams( new InternetDataConnection.InputStreamProvider(), this); }
Source:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { if (successMessage != null && !successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { if (failMessage != null && !failMessage.isEmpty()) { printError(failMessage); } } return success; }); }

Target:
public void teleport(Location location, String successMessage, String failMessage) { PaperLib.teleportAsync(getPlayer(), BukkitAdapter.adapt(location)) .thenApply(success -> { if (success) { // The success message can be cleared via flag if (!successMessage.isEmpty()) { MessagingUtil.sendStringToChat(this, successMessage); } } else { printError(failMessage); } return success; }); }
Source:
public void init() { // Check things are going to work. try { log.info("Search using solr on: "+ getSolrUrl()); } catch (IllegalStateException e) { log.error(e.getMessage()); } }

Target:
public void init() { // Check things are going to work. try { String url = getSolrUrl(); log.info("Search using solr on: "+ url); } catch (IllegalStateException e) { log.error(e.getMessage()); } }
Source:
public boolean isNewWallThreadActivityDisplayed(String title, String threadAuthor, String threadContent) { return activities.stream() .filter(activity -> activity.getType() == ActivityType.WALL_POST) .filter(activity -> activity.getTitleLink().getText().contains(title)) .filter(activity -> activity.getWallThreadAuthor().contains(threadAuthor)) .anyMatch(activity -> activity.getWallThreadContent().contains(threadContent)); }

Target:
public boolean isNewWallThreadActivityDisplayed(String title, String threadAuthor, String threadContent) { return activities.stream() .filter(activity -> activity.getType() == ActivityType.WALL_POST) .filter(activity -> activity.getTitleLink().getText().contains(title)) .filter(activity -> activity.getWallThreadAuthor().equals(threadAuthor)) .anyMatch(activity -> activity.getWallThreadContent().contains(threadContent)); }
Source:
private WebElement getActiveDialog() { WebElement dialog = null; List<WebElement> elements = driver.findElements(By.cssSelector(".discussion-dialog.is-visible")); if (elements.isEmpty()) { // allow selenium to throw exception dialog = driver.findElement(By.cssSelector(".discussion-dialog.is-visible.modal-dialog-approve")); } else if (1 < elements.size()) { // only one modal dialog should be visible throw new IllegalStateException("Only one modal dialog should be visible!"); } else { dialog = elements.get(0); } return dialog; }

Target:
private WebElement getActiveDialog() { List<WebElement> elements = driver.findElements(By.cssSelector(".discussion-dialog.is-visible")); if (elements.isEmpty()) { // allow selenium to throw exception return driver.findElement(By.cssSelector(".discussion-dialog.is-visible.modal-dialog-approve")); } else if (1 < elements.size()) { // only one modal dialog should be visible throw new IllegalStateException("Only one modal dialog should be visible!"); } else { return elements.get(0); } }
Source:
public RecentWikiActivityPage open(){ editArticle("RWA Tests"); getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }

Target:
public RecentWikiActivityPage open() { getUrl(String.format("%s%s", urlBuilder.getUrlForWiki(), URLsContent.RECENT_WIKI_ACTIVITY)); return this; }
Source:
public static Object[][] fliteTagOasis() { return new Object[][]{ {"adtest", "SyntheticTests/FliteTag", ".flite-tag-extension"}, {"adtest", "SyntheticTests/FliteTagModifiedTag", ".flite-tag-extension"}}; }

Target:
public static Object[][] fliteTagOasis() { return new Object[][]{ {"SyntheticTests/FliteTag"}, {"SyntheticTests/FliteTagModifiedTag"}}; }
Source:
public boolean isTestElementVisible() { boolean isVisible = false; try { wait.forElementVisible(testElement, 3, 1); isVisible = true; } catch (TimeoutException exception) { isVisible = false; } return isVisible; }

Target:
public boolean isTestElementVisible() { boolean isVisible = false; try { wait.forElementVisible(testElement, 3, 1); isVisible = true; } catch (TimeoutException e) { isVisible = false; } return isVisible; }
Source:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); //we must wait some seconds to make sure button is activated Thread.sleep(1000); Assertion.assertTrue(loginPage.isSubmitButtonDisabled()); }

Target:
public void notPossibleToLogInWhenPasswordFieldBlank() throws InterruptedException { LoginPage loginPage = new LoginPage(driver).get(); loginPage.logUserIn(Configuration.getCredentials().userName10, ""); Assertion.assertTrue(loginPage.isSubmitButtonDisabled(2)); }