auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void execute() throws MetaModelException { final ElasticSearchRestUpdateCallback updateCallback = getUpdateCallback(); final ElasticSearchRestDataContext dataContext = updateCallback.getDataContext(); final String indexName = dataContext.getIndexName(); final List<Table> tables = dataContext.getDefaultSchema().getTables(); if (!(tables.isEmpty() || tables.get(0).getName().equals(getTable().getName()))) { throw new MetaModelException("Can't add more than one table to Elasticsearch index."); } final Map<String, Object> source = new HashMap<>(); final Column[] columns = getColumns(); final Object[] values = getValues(); String id = null; for (int i = 0; i < columns.length; i++) { if (isSet(columns[i])) { final String columnName = columns[i].getName(); final Object value = values[i]; if (ElasticSearchUtils.FIELD_ID.equals(columnName)) { if (value != null) { id = value.toString(); } } else { final String fieldName = ElasticSearchUtils.getValidatedFieldName(columnName); source.put(fieldName, value); } } } if (!source.isEmpty()) { IndexRequest indexRequest = new IndexRequest(indexName).id(id); indexRequest.source(source); getUpdateCallback().execute(indexRequest); } else { logger.info("Source is empty no index request is executed."); } }

Target:
public void execute() throws MetaModelException { final ElasticSearchRestUpdateCallback updateCallback = getUpdateCallback(); final ElasticSearchRestDataContext dataContext = updateCallback.getDataContext(); final String indexName = dataContext.getIndexName(); final List<Table> tables = dataContext.getDefaultSchema().getTables(); if (!(tables.isEmpty() || tables.get(0).getName().equals(getTable().getName()))) { throw new MetaModelException("Can't add more than one table to Elasticsearch index."); } final Map<String, Object> source = new HashMap<>(); final Column[] columns = getColumns(); final Object[] values = getValues(); String id = null; for (int i = 0; i < columns.length; i++) { if (isSet(columns[i])) { final String columnName = columns[i].getName(); final Object value = values[i]; if (ElasticSearchUtils.FIELD_ID.equals(columnName)) { if (value != null) { id = value.toString(); } } else { final String fieldName = ElasticSearchUtils.getValidatedFieldName(columnName); source.put(fieldName, value); } } } if (!source.isEmpty()) { IndexRequest indexRequest = new IndexRequest(indexName).id(id); indexRequest.source(source); getUpdateCallback().execute(indexRequest); } else { logger.info("Source is empty, no index request is executed."); } }
Source:
public void onStartup(final ServletContext servletContext) throws ServletException { ServerConfiguration configuration = injectedConfig; if(configuration == null) { configuration = ConfigurationFileLoader.loadConfiguration(); } updateConfigurationBySpring(configuration); PlatformBootstrap bootstrap = new PlatformBootstrap(); bootstrap.init(servletContext, configuration); }

Target:
public void onStartup(final ServletContext servletContext) throws ServletException { final ServerConfiguration configuration = Optional.ofNullable(injectedConfig) .orElse(ConfigurationFileLoader.loadConfiguration()); updateConfigurationBySpring(configuration); final PlatformBootstrap bootstrap = new PlatformBootstrap(); bootstrap.init(servletContext, configuration); }
Source:
public void define(Context context) { ImmutableList.Builder<Object> builder = ImmutableList.builder(); Version sonarQubeVersion = context.getSonarQubeVersion(); if (!sonarQubeVersion.isGreaterThanOrEqual(SQ_6_0) || context.getRuntime().getProduct() != SonarProduct.SONARLINT) { builder.addAll(SurefireExtensions.getExtensions()); builder.addAll(JaCoCoExtensions.getExtensions(sonarQubeVersion)); builder.add(JavaSonarWayProfile.class); builder.addAll(JavaClasspathProperties.getProperties()); builder.add(JavaClasspath.class); } else { builder.addAll(JavaClasspathProperties.getProperties()); builder.add(JavaSonarLintClasspath.class); } builder.add( JavaTestClasspath.class, Java.class, PropertyDefinition.builder(Java.FILE_SUFFIXES_KEY) .defaultValue(Java.DEFAULT_FILE_SUFFIXES) .category(JavaConstants.JAVA_CATEGORY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") .subCategory("General") .onQualifiers(Qualifiers.PROJECT) .build(), new JavaRulesDefinition(context.getSonarQubeVersion()), SonarComponents.class, DefaultJavaResourceLocator.class, JavaSquidSensor.class, PostAnalysisIssueFilter.class, XmlFileSensor.class); context.addExtensions(builder.build()); }

Target:
public void define(Context context) { ImmutableList.Builder<Object> builder = ImmutableList.builder(); Version sonarQubeVersion = context.getSonarQubeVersion(); if (!sonarQubeVersion.isGreaterThanOrEqual(SQ_6_0) || context.getRuntime().getProduct() != SonarProduct.SONARLINT) { builder.addAll(SurefireExtensions.getExtensions()); builder.addAll(JaCoCoExtensions.getExtensions(sonarQubeVersion)); builder.add(JavaSonarWayProfile.class); builder.add(JavaClasspath.class); } else { builder.add(JavaSonarLintClasspath.class); } builder.addAll(JavaClasspathProperties.getProperties()); builder.add( JavaTestClasspath.class, Java.class, PropertyDefinition.builder(Java.FILE_SUFFIXES_KEY) .defaultValue(Java.DEFAULT_FILE_SUFFIXES) .category(JavaConstants.JAVA_CATEGORY) .name("File suffixes") .description("Comma-separated list of suffixes for files to analyze. To not filter, leave the list empty.") .subCategory("General") .onQualifiers(Qualifiers.PROJECT) .build(), new JavaRulesDefinition(context.getSonarQubeVersion()), SonarComponents.class, DefaultJavaResourceLocator.class, JavaSquidSensor.class, PostAnalysisIssueFilter.class, XmlFileSensor.class); context.addExtensions(builder.build()); }
Source:
public Response addCluster(@FormDataParam("clusterConfigFile") final InputStream inputStream, @FormDataParam("clusterConfigFile") final FormDataContentDisposition contentDispositionHeader, @FormDataParam("cluster") final FormDataBodyPart clusterConfig) { try { clusterConfig.setMediaType(MediaType.APPLICATION_JSON_TYPE); Cluster clusterObj = clusterConfig.getValueAs(Cluster.class); saveClusterConfig(inputStream, clusterObj); Cluster createdCluster = catalogService.addCluster(clusterObj); return WSUtils.respond(CREATED, SUCCESS, createdCluster); } catch (Exception ex) { return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); } }

Target:
public Response addCluster(@FormDataParam("clusterConfigFile") final InputStream inputStream, @FormDataParam("clusterConfigFile") final FormDataContentDisposition contentDispositionHeader, @FormDataParam("cluster") final FormDataBodyPart clusterConfig) { try { LOG.debug("Media type {}", clusterConfig.getMediaType()); if (!clusterConfig.getMediaType().equals(MediaType.APPLICATION_JSON_TYPE)) { return WSUtils.respond(UNSUPPORTED_MEDIA_TYPE, ResponseMessage.UNSUPPORTED_MEDIA_TYPE); } Cluster clusterObj = clusterConfig.getValueAs(Cluster.class); saveClusterConfig(inputStream, clusterObj); Cluster createdCluster = catalogService.addCluster(clusterObj); return WSUtils.respond(CREATED, SUCCESS, createdCluster); } catch (ProcessingException ex) { return WSUtils.respond(BAD_REQUEST, ResponseMessage.BAD_REQUEST); } catch (Exception ex) { return WSUtils.respond(INTERNAL_SERVER_ERROR, EXCEPTION, ex.getMessage()); } }
Source:
private void triggerPipeline(Pipeline pipeline, TriggerSource triggerSource) throws RejectedExecutionException { final Map<String, String> mdc = MDC.getCopyOfContextMap(); executorService.submit( () -> { if (mdc != null) { MDC.setContextMap(mdc); } triggerPipelineImpl(pipeline, triggerSource); if (mdc != null) { MDC.clear(); } }); }

Target:
private void triggerPipeline(Pipeline pipeline, TriggerSource triggerSource) throws RejectedExecutionException { Callable<Void> triggerWithCapturedContext = AuthenticatedRequest.propagate(() -> triggerPipelineImpl(pipeline, triggerSource)); executorService.submit(triggerWithCapturedContext); }
Source:
public void undo() { RunESCommand.run(new Callable<Void>() { public Void call() throws Exception { projectSpace.undoLastOperations(executedOperations.size()); return null; } }); isUndo = false; }

Target:
public void undo() { RunESCommand.run(new Callable<Void>() { public Void call() throws Exception { projectSpace.undoLastOperations(executedOperations.size()); return null; } }); canUndo = false; }
Source:
protected static void test_StartWebViewDialogActivity_LoadsUrlAndShowsTitle(String url, String title) { final WebViewActivity activity = Robolectric.buildActivity(WebViewActivity.class) .withIntent(WebViewActivity.newIntent(RuntimeEnvironment.application, url, title)).setup().get(); final View dialogView = Shadows.shadowOf(activity).getContentView(); assertNotNull(dialogView); final WebView webView = (WebView) dialogView.findViewById(R.id.eula_webView); assertNotNull(webView); final ShadowWebView shadowWebView = Shadows.shadowOf(webView); assertEquals(shadowWebView.getLastLoadedUrl(), url); android.support.v7.app.ActionBar actionBar = activity.getSupportActionBar(); assertNotNull(actionBar); if (TextUtils.isEmpty(title)) { assertTrue(!actionBar.isShowing()); } else { assertTrue(actionBar.isShowing()); assertTrue(title.equals(activity.getTitle())); } activity.onBackPressed(); assertTrue(activity.isFinishing()); }

Target:
protected static void test_StartWebViewDialogActivity_LoadsUrlAndShowsTitle(String url, String title) { final WebViewActivity activity = Robolectric.buildActivity(WebViewActivity.class) .withIntent(WebViewActivity.newIntent(RuntimeEnvironment.application, url, title)).setup().get(); final View dialogView = Shadows.shadowOf(activity).getContentView(); assertNotNull(dialogView); final WebView webView = (WebView) dialogView.findViewById(R.id.eula_webView); assertNotNull(webView); final ShadowWebView shadowWebView = Shadows.shadowOf(webView); assertEquals(shadowWebView.getLastLoadedUrl(), url); ActionBar actionBar = activity.getSupportActionBar(); assertNotNull(actionBar); if (TextUtils.isEmpty(title)) { assertTrue(!actionBar.isShowing()); } else { assertTrue(actionBar.isShowing()); assertTrue(title.equals(activity.getTitle())); } activity.onBackPressed(); assertTrue(activity.isFinishing()); }
Source:
public void getJobStatusDetailed(GetJobStatusDetailedPRequest request, StreamObserver<GetJobStatusDetailedPResponse> responseObserver) { RpcUtils.call(LOG, (RpcUtils.RpcCallableThrowsIOException<GetJobStatusDetailedPResponse>) () -> { return GetJobStatusDetailedPResponse.newBuilder() .setJobInfo(mJobMaster.getStatus(request.getJobId(), true).toProto()).build(); }, "getJobStatus", "request=%s", responseObserver, request); }

Target:
public void getJobStatusDetailed(GetJobStatusDetailedPRequest request, StreamObserver<GetJobStatusDetailedPResponse> responseObserver) { RpcUtils.call(LOG, (RpcUtils.RpcCallableThrowsIOException<GetJobStatusDetailedPResponse>) () -> { return GetJobStatusDetailedPResponse.newBuilder() .setJobInfo(mJobMaster.getStatus(request.getJobId(), true).toProto()).build(); }, "getJobStatusDetailed", "request=%s", responseObserver, request); }
Source:
public Response createDirs( @PathParam ( "pathId" ) String pathId ) { try { if ( FileUtils.isRootLevelPath( FileUtils.idToPath( pathId ) ) ) { return Response.status( Response.Status.FORBIDDEN ).entity( "couldNotCreateRootLevelFolder" ).build(); } if ( fileService.doCreateDirSafe( pathId ) ) { return Response.ok().build(); } else { return Response.status( Response.Status.CONFLICT ).entity( "couldNotCreateFolderDuplicate" ).build(); } } catch ( FileService.InvalidNameException t ) { return Response.status( Response.Status.FORBIDDEN ).entity( "containsIllegalCharacters" ).build(); } catch ( Throwable t ) { return Response.serverError().entity( "" ).build(); } }

Target:
public Response createDirs( @PathParam ( "pathId" ) String pathId ) { try { if ( FileUtils.isRootLevelPath( FileUtils.idToPath( pathId ) ) ) { return Response.status( Response.Status.FORBIDDEN ).entity( "couldNotCreateRootLevelFolder" ).build(); } if ( fileService.doCreateDirSafe( pathId ) ) { return Response.ok().build(); } else { return Response.status( Response.Status.CONFLICT ).entity( "couldNotCreateFolderDuplicate" ).build(); } } catch ( FileService.InvalidNameException e ) { return Response.status( Response.Status.FORBIDDEN ).entity( "containsIllegalCharacters" ).build(); } catch ( Throwable t ) { return Response.serverError().entity( "" ).build(); } }
Source:
public final <U> ParallelFlowable<U> compose(@NonNull ParallelTransformer<T, U> composer) { return RxJavaPlugins.onAssembly(composer.apply(this)); }

Target:
public final <U> ParallelFlowable<U> compose(@NonNull ParallelTransformer<T, U> composer) { return RxJavaPlugins.onAssembly(ObjectHelper.requireNonNull(composer, "composer is null").apply(this)); }
Source:
private void validateOutgoingMessageEnvelope(OutgoingMessageEnvelope outgoingMessageEnvelope) { MetricsSnapshot metricsSnapshot = new MetricsSnapshotSerdeV2().fromBytes((byte[]) outgoingMessageEnvelope.getMessage()); DiagnosticsStreamMessage diagnosticsStreamMessage = DiagnosticsStreamMessage.convertToDiagnosticsStreamMessage(metricsSnapshot); Assert.assertTrue(diagnosticsStreamMessage.getContainerMb().equals(containerMb)); Assert.assertTrue(diagnosticsStreamMessage.getExceptionEvents().equals(exceptionEventList)); Assert.assertTrue(diagnosticsStreamMessage.getProcessorStopEvents() .equals(Arrays.asList(new ProcessorStopEvent("0", executionEnvContainerId, hostname, 101)))); Assert.assertEquals(containerModels, diagnosticsStreamMessage.getContainerModels()); Assert.assertTrue(diagnosticsStreamMessage.getContainerNumCores().equals(containerNumCores)); Assert.assertTrue(diagnosticsStreamMessage.getNumStoresWithChangelog().equals(numStoresWithChangelog)); }

Target:
private void validateOutgoingMessageEnvelope(OutgoingMessageEnvelope outgoingMessageEnvelope) { MetricsSnapshot metricsSnapshot = new MetricsSnapshotSerdeV2().fromBytes((byte[]) outgoingMessageEnvelope.getMessage()); DiagnosticsStreamMessage diagnosticsStreamMessage = DiagnosticsStreamMessage.convertToDiagnosticsStreamMessage(metricsSnapshot); Assert.assertEquals(containerMb, diagnosticsStreamMessage.getContainerMb().intValue()); Assert.assertEquals(exceptionEventList, diagnosticsStreamMessage.getExceptionEvents()); Assert.assertEquals(diagnosticsStreamMessage.getProcessorStopEvents(), Arrays.asList(new ProcessorStopEvent("0", executionEnvContainerId, hostname, 101))); Assert.assertEquals(containerModels, diagnosticsStreamMessage.getContainerModels()); Assert.assertEquals(containerNumCores, diagnosticsStreamMessage.getContainerNumCores().intValue()); Assert.assertEquals(numStoresWithChangelog, diagnosticsStreamMessage.getNumStoresWithChangelog().intValue()); }
Source:
public SELF isEqualTo(Iterable<?> expected) { if((actual == null && expected == null) || (actual == expected)) return myself; if(actual == null || expected == null) throw new AssertionError("Iterables to compare can not be null."); if(recursiveComparisonConfiguration.isInStrictTypeCheckingOnActualMode() && !actual.getClass().isAssignableFrom(expected.getClass())) throw new AssertionError("types are not compatible."); if(sizeOf((Iterable<?>) actual) != sizeOf(expected)) throw new AssertionError("Sizes are not the same.Actual is of size " + sizeOf((Iterable<?>) actual) + ", Expected is of size " + sizeOf(expected)); boolean ignoreActualIterableOrder = recursiveComparisonConfiguration.getIgnoreActualIterableOrder(); if(!ignoreActualIterableOrder) iterableAssert.isEqualTo(expected); else { for(Object element : expected) iterableAssert.contains(element); } return myself; }

Target:
public SELF isEqualTo(Iterable<?> expected) { boolean sameReferenceOrNull = checkIfExpectedIsSameReferenceOrNull(expected); if(sameReferenceOrNull) return myself; if(recursiveComparisonConfiguration.isInStrictTypeCheckingMode() && !actual.getClass().isAssignableFrom(expected.getClass())) throw new AssertionError(format("Comparison enforces strict type checking and fields are considered different since %s is not a subtype of %s.", actual.getClass().getName(), expected.getClass().getName())); if(sizeOf(actual) != sizeOf(expected)) throw new AssertionError(format("actual and expected values are %s of different size, actual size=%s when expected size=%s%nActual: %s%nExpected: %s", "iterables", sizeOf(actual), sizeOf(expected), actual, expected)); boolean ignoreCollectionOrder = recursiveComparisonConfiguration.getIgnoreCollectionOrder(); if(!ignoreCollectionOrder) iterableAssert.isEqualTo(expected); else { for(Object element : expected) iterableAssert.contains(element); } return myself; }
Source:
private Node getPropertyNode(Document doc, String propertyId) { String docName = doc.getXMLParser().getXmlFile().getName(); if (docName.equals("custom.xml")) { NodeList nl = doc.getXMLParser().getNodesFromXPathExpression( " new DocxNamespaceContextEx(new String[] { "def", "<LINK_2>", "vt","<LINK_3>"})); if (nl.getLength() > 0) return nl.item(0); } else if (docName.equals("core.xml")) { NodeList nl = doc.getXMLParser().getNodesFromXPathExpression( "/cp:coreProperties/"+propertyId, new DocxNamespaceContextEx(new String[] { "cp", "<LINK_1>", "dc", "<LINK_0>", "dcterms", "<LINK_4>", "dcmitype","<LINK_5>"})); if (nl.getLength() > 0) return nl.item(0); } return null; }

Target:
private Node getPropertyNode(Document doc, String propertyId) { String docName = doc.getXMLParser().getXmlFile().getName(); if (docName.equals("custom.xml")) { NodeList nl = doc.getXMLParser().getNodesFromXPathExpression( " new DocxNamespaceContextEx(new String[] { "def", "<LINK_2>", "vt","<LINK_3>"})); if (nl.getLength() > 0) { return nl.item(0); } } else if (docName.equals("core.xml")) { NodeList nl = doc.getXMLParser().getNodesFromXPathExpression( "/cp:coreProperties/"+propertyId, new DocxNamespaceContextEx(new String[] { "cp", "<LINK_1>", "dc", "<LINK_0>", "dcterms", "<LINK_4>", "dcmitype","<LINK_5>"})); if (nl.getLength() > 0) return nl.item(0); } return null; }
Source:
public int getMultiplication() { return multiplication; }

Target:
@Override public int getMultiplication() { return this.mulFactor; }
Source:
protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { DocumentRef[] docRefs = ids.stream().map(IdRef::new).toArray(DocumentRef[]::new); DocumentModelList docs = session.getDocuments(docRefs); for (DocumentModel doc : docs) { for (Entry<String, Serializable> es : properties.entrySet()) { try { doc.setPropertyValue(es.getKey(), es.getValue()); } catch (PropertyException e) { log.warn("Cannot write property: " + es.getKey() + " of document: " + doc.getId(), e); } } try { session.saveDocument(doc); } catch (PropertyException e) { log.warn("Cannot save document: " + doc.getId(), e); } } }

Target:
protected void compute(CoreSession session, List<String> ids, Map<String, Serializable> properties) { DocumentRef[] docRefs = ids.stream().map(IdRef::new).toArray(DocumentRef[]::new); DocumentModelList docs = session.getDocuments(docRefs); for (DocumentModel doc : docs) { for (Entry<String, Serializable> es : properties.entrySet()) { try { doc.setPropertyValue(es.getKey(), es.getValue()); } catch (PropertyException e) { getLog().warn("Cannot write property: " + es.getKey() + " of document: " + doc.getId(), e); } } try { session.saveDocument(doc); } catch (PropertyException e) { getLog().warn("Cannot save document: " + doc.getId(), e); } } }
Source:
public void shouldThrowExceptionHttpClient() throws Exception { UUID uuid = UUID.randomUUID(); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, null)).thenThrow(new RapidProClientException("Exception")); Contact fromWebservice = contactWebService.getContactByUUID(uuid); }

Target:
public void shouldThrowExceptionHttpClient() throws Exception { UUID uuid = UUID.randomUUID(); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, null)).thenThrow(new RapidProClientException("Exception")); contactWebService.getContactByUUID(uuid); }
Source:
private void initializeHeaderOutLong() throws IOException { headerOut.close(); headerOutLong = new CountingOutputStream(ioPeon.makeOutputStream(makeFilename("headerLong"))); File f = ioPeon.getFile(makeFilename("header")); try (RandomAccessFile headerFile = new RandomAccessFile(f, "r")) { for (int i = 0; i < numWritten; i++) { headerFile.seek(i * Ints.BYTES); int count = headerFile.readInt(); headerOutLong.write(Longs.toByteArray(count)); } } }

Target:
private void initializeHeaderOutLong() throws IOException { headerOut.close(); headerOutLong = new CountingOutputStream(ioPeon.makeOutputStream(makeFilename("headerLong"))); try (RandomAccessFile headerFile = new RandomAccessFile(ioPeon.getFile(makeFilename("header")), "r")) { ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES).order(ByteOrder.nativeOrder()); for (int i = 0; i < numWritten; i++) { int count = headerFile.readInt(); writeLongValueToOutputStream(buf, count, headerOutLong); } } }
Source:
public void setOnBehalfOf(String onBehalfOfID) { this.onBehalfOf = APIResource.setExpandableFieldID(onBehalfOfID, this.destination); }

Target:
public void setOnBehalfOf(String onBehalfOfID) { this.onBehalfOf = APIResource.setExpandableFieldID(onBehalfOfID, this.onBehalfOf); }
Source:
public void showAllSurvey(final List<Survey> surveys) { if (surveys.size() == 0) { surveySelectText.setText(R.string.no_survey); } SurveyListAdapter surveyListAdapter = new SurveyListAdapter(getActivity(), surveys); lv_surveys_list.setAdapter(surveyListAdapter); lv_surveys_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mListener.loadSurveyQuestion(surveys.get(position), clientId); } }); }

Target:
public void showAllSurvey(final List<Survey> surveys) { if (surveys.size() == 0) { surveySelectText.setText(getResources(). getString(R.string.no_survey_available_for_client)); } else { SurveyListAdapter surveyListAdapter = new SurveyListAdapter(getActivity(), surveys); lv_surveys_list.setAdapter(surveyListAdapter); lv_surveys_list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { mListener.loadSurveyQuestion(surveys.get(position), clientId); } }); } }
Source:
public void shutdown() { cancelScheduledTasks(); if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } DiscoveryManager.getInstance().setDiscoveryClient(null); DiscoveryManager.getInstance().setEurekaClientConfig(null); }

Target:
public void shutdown() { cancelScheduledTasks(); if (instanceInfo != null && shouldRegister(instanceInfo)) { instanceInfo.setStatus(InstanceStatus.DOWN); unregister(); } }
Source:
public void write(JsonWriter out, T value) throws IOException { TypeAdapter chosen = delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type && !Primitives.areEquivalentTypes(runtimeType, type)) { TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType)); if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { chosen = runtimeTypeAdapter; } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) { chosen = delegate; } else { chosen = runtimeTypeAdapter; } } chosen.write(out, value); }

Target:
public void write(JsonWriter out, T value) throws IOException { TypeAdapter chosen = delegate; Type runtimeType = getRuntimeTypeIfMoreSpecific(type, value); if (runtimeType != type) { TypeAdapter runtimeTypeAdapter = context.getAdapter(TypeToken.get(runtimeType)); if (!(runtimeTypeAdapter instanceof ReflectiveTypeAdapterFactory.Adapter)) { chosen = runtimeTypeAdapter; } else if (!(delegate instanceof ReflectiveTypeAdapterFactory.Adapter)) { chosen = delegate; } else { chosen = runtimeTypeAdapter; } } chosen.write(out, value); }
Source:
private boolean loadBooleanParam(String name, FilterConfig filterConfig, boolean defaultValue) { boolean result = defaultValue; String fParam = filterConfig.getInitParameter(name); if (fParam != null) { result = parseBoolean(fParam); } String sParam = System.getProperty("blazegraph." + filterConfig.getFilterName() + "." + name); if (sParam != null) { result = parseBoolean(sParam); } return result; }

Target:
private boolean loadBooleanParam(String name, FilterConfig filterConfig, boolean defaultValue) { String result = loadStringParam(name, filterConfig); return result != null ? parseBoolean(result) : defaultValue; }
Source:
public void theEnableDebugRequestIsReceived(final Map<String, String> requestData) throws Throwable { final EnableDebuggingRequest request = EnableDebuggingRequestFactory.fromParameterMap(requestData); final EnableDebuggingAsyncResponse asyncResponse = this.requestClientEnableDebugging.doRequest(request); assertNotNull("asyncResponse should not be null", asyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, asyncResponse.getCorrelationUid()); }

Target:
public void theEnableDebugRequestIsReceived(final Map<String, String> requestData) throws Throwable { final EnableDebuggingRequest enableDebuggingRequest = EnableDebuggingRequestFactory .fromParameterMap(requestData); final EnableDebuggingAsyncResponse enableDebuggingAsyncResponse = this.smartMeteringManagementRequestClientEnableDebugging .doRequest(enableDebuggingRequest); assertNotNull("AsyncResponse should not be null", enableDebuggingAsyncResponse); ScenarioContext.current().put(PlatformSmartmeteringKeys.KEY_CORRELATION_UID, enableDebuggingAsyncResponse.getCorrelationUid()); }
Source:
private void sendCancelCommand(IntSet cancelledSegments) { Address origin = rpcManager.getAddress(); CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }

Target:
private void sendCancelCommand(IntSet cancelledSegments) { CacheRpcCommand cmd = commandsFactory.buildStateTransferCancelCommand(topologyId, cancelledSegments); try { rpcManager.sendTo(source, cmd, DeliverOrder.NONE); } catch (Exception e) { log.debugf("Caught an exception while cancelling state transfer from node %s for segments %s", source, cancelledSegments); } }
Source:
public void testWebView() { WelcomePageBase welcomePage = initPage(getDriver(), WelcomePageBase.class); LoginPageBase loginPage = welcomePage.clickNextBtn(); loginPage.login(); WebViewPageBase webViewPageBase = initPage(getDriver(), WebViewPageBase.class); MobileContextUtils contextHelper = new MobileContextUtils(); contextHelper.switchMobileContext(MobileContextUtils.View.WEB, getDriver()); ContactUsPageBase contactUsPage = webViewPageBase.goToContactUsPage(); contactUsPage.typeName("John Doe"); contactUsPage.typeEmail("some@email.com"); contactUsPage.typeQuestion("This is a message"); MobileUtils.hideKeyboard(); contactUsPage.submit(); Assert.assertTrue(contactUsPage.isSuccessMessagePresent() || contactUsPage.isRecaptchaPresent(), "message was not sent or captcha was not displayed"); }

Target:
public void testWebView() { WelcomePageBase welcomePage = initPage(getDriver(), WelcomePageBase.class); LoginPageBase loginPage = welcomePage.clickNextBtn(); loginPage.login(); WebViewPageBase webViewPageBase = initPage(getDriver(), WebViewPageBase.class); MobileContextUtils contextHelper = new MobileContextUtils(); contextHelper.switchMobileContext(View.WEB); ContactUsPageBase contactUsPage = webViewPageBase.goToContactUsPage(); contactUsPage.typeName("John Doe"); contactUsPage.typeEmail("some@email.com"); contactUsPage.typeQuestion("This is a message"); MobileUtils.hideKeyboard(); contactUsPage.submit(); Assert.assertTrue(contactUsPage.isSuccessMessagePresent() || contactUsPage.isRecaptchaPresent(), "message was not sent or captcha was not displayed"); }
Source:
private void fireStack(@Nonnull ItemStack stack) { final ITriggerable rpc = createServerRpcProxy(ITriggerable.class); rpc.trigger(); double yawr = Math.toRadians(currentYaw); double pitchr = Math.toRadians(currentPitch); double barrel_length = 0.5; double barrel_base_height = 0.3; double x = pos.getX() + 0.5 - Math.sin(yawr) * Math.cos(pitchr) * barrel_length; double y = pos.getY() + barrel_base_height + Math.sin(pitchr) * barrel_length; double z = pos.getZ() + 0.5 + Math.cos(yawr) * Math.cos(pitchr) * barrel_length; EntityItem item = new EntityItemProjectile(world, x, y, z, stack); item.setDefaultPickupDelay(); Vec3d motion = getMotion(); item.motionX = motion.x; item.motionY = motion.y; item.motionZ = motion.z; world.spawnEntity(item); playSoundAtBlock(OpenBlocks.Sounds.BLOCK_CANNON_ACTIVATE, 0.2f, 1.0f); }

Target:
private void fireStack(@Nonnull ItemStack stack) { final ITriggerable rpc = createServerRpcProxy(ITriggerable.class); rpc.trigger(); double yawr = Math.toRadians(currentYaw); double pitchr = Math.toRadians(currentPitch); double barrelLength = 0.5; double barrelBaseHeight = 0.3; double x = pos.getX() + 0.5 - Math.sin(yawr) * Math.cos(pitchr) * barrelLength; double y = pos.getY() + barrelBaseHeight + Math.sin(pitchr) * barrelLength; double z = pos.getZ() + 0.5 + Math.cos(yawr) * Math.cos(pitchr) * barrelLength; EntityItem item = new EntityItemProjectile(world, x, y, z, stack); item.setDefaultPickupDelay(); Vec3d motion = getMotion(); item.motionX = motion.x; item.motionY = motion.y; item.motionZ = motion.z; world.spawnEntity(item); playSoundAtBlock(OpenBlocks.Sounds.BLOCK_CANNON_ACTIVATE, 0.2f, 1.0f); }
Source:
public void onCreateButtonClicked() { ObservableList<Mod> selectedMods = modListView.getSelectionModel().getSelectedItems(); try { modService.overrideActivatedMods(modListView.getSelectionModel().getSelectedItems()); } catch (IOException e) { logger.warn("Activated Mods could not be updated", e); } Set<String> simMods = selectedMods.stream() .map(Mod::getUid) .collect(Collectors.toSet()); NewGameInfo newGameInfo = new NewGameInfo( titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModListView.getSelectionModel().getSelectedItem(), mapListView.getSelectionModel().getSelectedItem().getFolderName(), simMods); gameService.hostGame(newGameInfo).exceptionally(throwable -> { logger.warn("Game could not be hosted", throwable); notificationService.addNotification( new ImmediateNotification( i18n.get("errorTitle"), i18n.get("game.create.failed"), Severity.WARN, throwable, Collections.singletonList(new ReportAction(i18n, reportingService, throwable)))); return null; }); onCloseButtonClicked(); }

Target:
public void onCreateButtonClicked() { ObservableList<Mod> selectedMods = modListView.getSelectionModel().getSelectedItems(); try { modService.overrideActivatedMods(modListView.getSelectionModel().getSelectedItems()); } catch (IOException e) { logger.warn("Activated mods could not be updated", e); } Set<String> simMods = selectedMods.stream() .map(Mod::getUid) .collect(Collectors.toSet()); NewGameInfo newGameInfo = new NewGameInfo( titleTextField.getText(), Strings.emptyToNull(passwordTextField.getText()), featuredModListView.getSelectionModel().getSelectedItem(), mapListView.getSelectionModel().getSelectedItem().getFolderName(), simMods); gameService.hostGame(newGameInfo).exceptionally(throwable -> { logger.warn("Game could not be hosted", throwable); notificationService.addNotification( new ImmediateNotification( i18n.get("errorTitle"), i18n.get("game.create.failed"), Severity.WARN, throwable, Collections.singletonList(new ReportAction(i18n, reportingService, throwable)))); return null; }); onCloseButtonClicked(); }
Source:
private List<String> asList(String allValues) { String tempAllValues = allValues; List<String> valuesList = Collections.emptyList(); if (!StringUtils.isBlank(tempAllValues)) { tempAllValues = tempAllValues.trim().substring(1, tempAllValues.length() - 1); valuesList = Arrays.asList(tempAllValues.split("\\s*,\\s*")); } return valuesList; }

Target:
private List<String> asList(String allValues) { List<String> valuesList = Collections.emptyList(); if (!StringUtils.isBlank(allValues)) { String tempAllValues = allValues.trim().substring(1, allValues.length() - 1); valuesList = Arrays.asList(tempAllValues.split("\\s*,\\s*")); } return valuesList; }
Source:
public void onPageLoadError(Throwable caught) { if (!isAdded()) { return; } tocDrawer.closeDrawers(); updateProgressBar(false, true, 0); refreshView.setRefreshing(false); if (pageRefreshed) { pageRefreshed = false; FeedbackUtil.showError(getActivity(), caught); } hidePageContent(); errorView.setError(caught); errorView.setVisibility(View.VISIBLE); if (getActivity() != null) { refreshView.setEnabled(ThrowableUtil.isRetryable(getActivity(), caught)); } errorState = true; if (getActivity() != null && getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadError(caught); } }

Target:
public void onPageLoadError(Throwable caught) { if (!isAdded()) { return; } tocDrawer.closeDrawers(); updateProgressBar(false, true, 0); refreshView.setRefreshing(false); if (pageRefreshed) { pageRefreshed = false; FeedbackUtil.showError(getActivity(), caught); } hidePageContent(); errorView.setError(caught); errorView.setVisibility(View.VISIBLE); if (getActivity() != null) { refreshView.setEnabled(ThrowableUtil.isRetryable(getActivity(), caught)); } errorState = true; if (getPageLoadCallbacks() != null) { getPageLoadCallbacks().onLoadError(caught); } }
Source:
public StubSearchWorkAssert matches(StubSearchWork expected) { StringBuilder builder = new StringBuilder( messageBase ); boolean hasAnyMismatch; boolean mismatch = checkForMismatch( builder, "resultType", expected.getResultType(), actual.getResultType() ); hasAnyMismatch = mismatch; mismatch = checkForMismatch( builder, "routingKeys", expected.getRoutingKeys(), actual.getRoutingKeys() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "timeout", expected.getTimeout(), actual.getTimeout() ); hasAnyMismatch = hasAnyMismatch || mismatch; if ( expected.getTimeout() != null ) { mismatch = checkForMismatch( builder, "timeUnit", expected.getTimeUnit(), actual.getTimeUnit() ); hasAnyMismatch = hasAnyMismatch || mismatch; } mismatch = checkForMismatch( builder, "offset", expected.getOffset(), actual.getOffset() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "limit", expected.getLimit(), actual.getLimit() ); hasAnyMismatch = hasAnyMismatch || mismatch; if ( hasAnyMismatch ) { Assert.fail( builder.toString() ); } return this; }

Target:
public StubSearchWorkAssert matches(StubSearchWork expected) { StringBuilder builder = new StringBuilder( messageBase ); boolean hasAnyMismatch; boolean mismatch = checkForMismatch( builder, "resultType", expected.getResultType(), actual.getResultType() ); hasAnyMismatch = mismatch; mismatch = checkForMismatch( builder, "routingKeys", expected.getRoutingKeys(), actual.getRoutingKeys() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "truncateAfterTimeout", expected.getTruncateAfterTimeout(), actual.getTruncateAfterTimeout() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "truncateAfterTimeUnit", expected.getTruncateAfterTimeUnit(), actual.getTruncateAfterTimeUnit() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "failAfterTimeout", expected.getFailAfterTimeout(), actual.getFailAfterTimeout() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "failAfterTimeUnit", expected.getFailAfterTimeUnit(), actual.getFailAfterTimeUnit() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "offset", expected.getOffset(), actual.getOffset() ); hasAnyMismatch = hasAnyMismatch || mismatch; mismatch = checkForMismatch( builder, "limit", expected.getLimit(), actual.getLimit() ); hasAnyMismatch = hasAnyMismatch || mismatch; if ( hasAnyMismatch ) { Assert.fail( builder.toString() ); } return this; }
Source:
public String toString() { return "[" + stream().map(Constraint::toString).sorted().collect(Collectors.joining(",")) + "]"; }

Target:
public String toString() { return stream().map(Constraint::toString).sorted().collect(Collectors.joining(",", "[", "]")); }
Source:
HttpSolrServer getAutosuggestCore() { return new HttpSolrServer("http:// localhost:8090/solr" + "/autosuggest"); }

Target:
HttpSolrServer getAutosuggestCore() { return new HttpSolrServer(solrBaseUrl + "/autosuggest"); }
Source:
public void verifyOnHistoryPage() { String url = driver.getCurrentUrl(); String[] urlParts = url.split("/"); Assertion.assertEquals(urlParts[urlParts.length - 1], "History"); PageObjectLogging.log("verifyOnHistoryPage", "verify that the url is the correct one for history page", true); }

Target:
public void verifyOnHistoryPage() { String url = driver.getCurrentUrl(); Assertion.assertTrue(url.contains("/History")); PageObjectLogging.log("verifyOnHistoryPage", "the url is the correct one for history page", true); }
Source:
private <K2, V2> Multimap<K2, V2> createFromEntries(Iterable<? extends Tuple2<? extends K2, ? extends V2>> entries) { Map<K2, Traversable<V2>> back = emptyMapSupplier(); for (Tuple2<? extends K2, ? extends V2> entry : entries) { if (back.containsKey(entry._1)) { back = back.put(entry._1, (Traversable<V2>) containerType.add.apply(back.get(entry._1).get(), entry._2)); } else { back = back.put(entry._1, (Traversable<V2>) containerType.add.apply(emptyContainer.get(), entry._2)); } } return createFromMap(back); }

Target:
private <K2, V2> Multimap<K2, V2> createFromEntries(Iterable<? extends Tuple2<? extends K2, ? extends V2>> entries) { Map<K2, Traversable<V2>> back = emptyMapSupplier(); for (Tuple2<? extends K2, ? extends V2> entry : entries) { if (back.containsKey(entry._1)) { back = back.put(entry._1, containerType.add(back.get(entry._1).get(), entry._2)); } else { back = back.put(entry._1, containerType.add(emptyContainer.get(), entry._2)); } } return createFromMap(back); }
Source:
public boolean accept(Path path) { String filePathName = path.toString(); try { FileSystem fileSystem = path.getFileSystem(new Configuration()); if (fileSystem.exists(path) && fileSystem.isDirectory(path)) { return true; } } catch (IOException e) { throw new IllegalArgumentException(String.format("Error accessing path: %s.", path), e); } if (!useTimeFilter) { String fileName = path.getName(); Matcher matcher = regex.matcher(fileName); return matcher.matches(); } if (lastRead.equals("-1")) { String currentTime = sdf.format(prevHour); return filePathName.contains(currentTime); } Date fileDate; String filename = path.getName(); try { fileDate = sdf.parse(filename.substring(0, DATE_LENGTH)); } catch (Exception pe) { try { int startIndex = filename.indexOf(".") + 1; fileDate = sdf.parse(filename.substring(startIndex, startIndex + DATE_LENGTH)); } catch (Exception e) { LOG.warn("Couldn't parse file: " + filename); return false; } } return isWithinRange(fileDate); }

Target:
public boolean accept(Path path) { String filePathName = path.toString(); try { FileSystem fileSystem = path.getFileSystem(new Configuration()); FileStatus[] fileStatus = fileSystem.globStatus(path); if (fileSystem.isDirectory(path) && !filePathName.endsWith("/")) { filePathName += "/"; } if (fileStatus != null && fileSystem.isDirectory(path) && (fileSystem.getContentSummary(path).getDirectoryCount() > 1 || pattern.matcher(filePathName).find())) { return true; } } catch (IOException e) { throw new IllegalArgumentException(String.format("Input path %s does not exists. %s.", path.toString(), e.getMessage()), e); } if (!useTimeFilter) { Matcher matcher = regex.matcher(filePathName); return matcher.matches(); } if (lastRead.equals("-1")) { String currentTime = sdf.format(prevHour); return filePathName.contains(currentTime); } Date fileDate; String filename = path.getName(); try { fileDate = sdf.parse(filename.substring(0, DATE_LENGTH)); } catch (Exception pe) { try { int startIndex = filename.indexOf(".") + 1; fileDate = sdf.parse(filename.substring(startIndex, startIndex + DATE_LENGTH)); } catch (Exception e) { LOG.warn("Couldn't parse file: " + filename); return false; } } return isWithinRange(fileDate); }
Source:
protected Predicate<DetailedS3Object> getDatePredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } String newer = this.filterParams.get(NEWERTHAN); String older = this.filterParams.get(OLDERTHAN); if (Guard.isStringNullOrEmpty(newer) && Guard.isStringNullOrEmpty(older)) { return Predicates.notNull(); } final long newerThan = Guard.isStringNullOrEmpty(newer) ? 0L : new Date().getTime() - Utils.dateDiffToSeconds(newer) * 1000; final long olderThan = Guard.isStringNullOrEmpty(older) ? Long.MAX_VALUE : new Date().getTime() - Utils.dateDiffToSeconds(older) * 1000; return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getCreationDate().after(new Date(newerThan)) && input.getCreationDate().before(new Date(olderThan)); } }; }

Target:
private Predicate<DetailedS3Object> getDatePredicate() throws CommandException { if (Guard.isMapNullOrEmpty(this.filterParams)) { return Predicates.notNull(); } final String newer = this.filterParams.get(NEWERTHAN); final String older = this.filterParams.get(OLDERTHAN); if (Guard.isStringNullOrEmpty(newer) && Guard.isStringNullOrEmpty(older)) { return Predicates.notNull(); } final long newerThan = Guard.isStringNullOrEmpty(newer) ? 0L : new Date().getTime() - Utils.dateDiffToSeconds(newer) * MILLIS_PER_SECOND; final long olderThan = Guard.isStringNullOrEmpty(older) ? Long.MAX_VALUE : new Date().getTime() - Utils.dateDiffToSeconds(older) * MILLIS_PER_SECOND; return new Predicate<DetailedS3Object>() { @Override public boolean apply(@Nullable final DetailedS3Object input) { return input.getCreationDate().after(new Date(newerThan)) && input.getCreationDate().before(new Date(olderThan)); } }; }
Source:
public ValidationResult validateNetworkInterfaces(VM vm) { Map<String, VmNetworkInterface> interfaceNetworkMap = Entities.vmInterfacesByNetworkName(vm.getInterfaces()); Set<String> interfaceNetworkNames = interfaceNetworkMap.keySet(); List<Network> clusterNetworks = getNetworkDAO().getAllForCluster(vm.getVdsGroupId()); Set<String> clusterNetworksNames = Entities.objectNames(clusterNetworks); ValidationResult validationResult = isVmInterfacesConfigured(vm); if (!validationResult.isValid()) { return validationResult; } validationResult = isVmInterfacesAttachedToClusterNetworks(vm, clusterNetworksNames, interfaceNetworkNames); if (!validationResult.isValid()) { return validationResult; } validationResult = isVmInterfacesAttachedToVmNetworks(clusterNetworks, interfaceNetworkNames); if (!validationResult.isValid()) { return validationResult; } return ValidationResult.VALID; }

Target:
public ValidationResult validateNetworkInterfaces(VM vm) { Map<String, VmNetworkInterface> interfaceNetworkMap = Entities.vmInterfacesByNetworkName(vm.getInterfaces()); Set<String> interfaceNetworkNames = interfaceNetworkMap.keySet(); List<Network> clusterNetworks = getNetworkDao().getAllForCluster(vm.getVdsGroupId()); Set<String> clusterNetworksNames = Entities.objectNames(clusterNetworks); ValidationResult validationResult = isVmInterfacesConfigured(vm); if (!validationResult.isValid()) { return validationResult; } validationResult = isVmInterfacesAttachedToClusterNetworks(vm, clusterNetworksNames, interfaceNetworkNames); if (!validationResult.isValid()) { return validationResult; } validationResult = isVmInterfacesAttachedToVmNetworks(clusterNetworks, interfaceNetworkNames); if (!validationResult.isValid()) { return validationResult; } return ValidationResult.VALID; }
Source:
private void doSeekCol(Cell cell) throws IOException { if (this.matcher.isUserScan() && !get && !useRowColBloom && seekToSameBlock && bytesRead > switchToNextOnlyBytes) { this.heap.next(); } else { seekOrSkipToNextColumn(cell); } }

Target:
private void doSeekCol(Cell cell) throws IOException { if (switchToNextOnlyBytes > 0 && this.matcher.isUserScan() && !get && !useRowColBloom && seekToSameBlock && bytesRead > switchToNextOnlyBytes) { this.heap.next(); } else { seekOrSkipToNextColumn(cell); } }
Source:
private void initToolbar(Toolbar toolbar) { if (DEBUG) Log.d(TAG, "initToolbar() called with: toolbar = [" + toolbar + "]"); boolean isLight = ThemeHelper.isLightThemeSelected(getActivity()); toolbar.setTitle(R.string.download_dialog_title); toolbar.setNavigationIcon(isLight ? R.drawable.ic_arrow_back_black_24dp : R.drawable.ic_arrow_back_white_24dp); toolbar.inflateMenu(R.menu.dialog_url); toolbar.setNavigationOnClickListener(v -> getDialog().dismiss()); okButton = toolbar.findViewById(R.id.okay); okButton.setEnabled(false); if (playlistDownloadCallback != null) { toolbar.setTitle(getResources().getString(R.string.download) + " (" + getResources().getString(R.string.playlist) + ")"); MenuItem menuItem = toolbar.getMenu().findItem(R.id.skip); menuItem.setVisible(true); } else toolbar.setTitle(R.string.download_dialog_title); toolbar.setOnMenuItemClickListener(item -> { if (item.getItemId() == R.id.okay) { prepareSelectedDownload(); if (playlistDownloadCallback != null) { if (smartDownloadCheckbox.isChecked() && downloadSetting != null) { playlistDownloadCallback.accept(downloadSetting); } else { playlistDownloadCallback.accept(null); } } } else if (item.getItemId() == R.id.skip) { if (playlistDownloadCallback != null) { playlistDownloadCallback.accept(null); } } getDialog().dismiss(); return true; }); }

Target:
private void initToolbar(Toolbar toolbar) { if (DEBUG) Log.d(TAG, "initToolbar() called with: toolbar = [" + toolbar + "]"); boolean isLight = ThemeHelper.isLightThemeSelected(getActivity()); toolbar.setTitle(R.string.download_dialog_title); toolbar.setNavigationIcon(isLight ? R.drawable.ic_arrow_back_black_24dp : R.drawable.ic_arrow_back_white_24dp); toolbar.inflateMenu(R.menu.dialog_url); toolbar.setNavigationOnClickListener(v -> getDialog().dismiss()); toolbar.setNavigationContentDescription(R.string.cancel); okButton = toolbar.findViewById(R.id.okay); okButton.setEnabled(false); if (playlistDownloadCallback != null) { toolbar.setTitle(getResources().getString(R.string.download) + " (" + getResources().getString(R.string.playlist) + ")"); MenuItem menuItem = toolbar.getMenu().findItem(R.id.skip); menuItem.setVisible(true); } else { toolbar.setTitle(R.string.download_dialog_title); } toolbar.setOnMenuItemClickListener(item -> { if (item.getItemId() == R.id.okay) { prepareSelectedDownload(); } else if (item.getItemId() == R.id.skip) { if (playlistDownloadCallback != null) { playlistDownloadCallback.accept(null); } } getDialog().dismiss(); return true; }); }
Source:
public ResponseEntity<Map<String, Object>> encryptionTooWeak() { Map<String, Object> body = new HashMap<String, Object>(); body.put("status", "INVALID"); body.put("description", "Encryption method provided too weak"); return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); }

Target:
public ResponseEntity<Map<String, Object>> encryptionTooWeak() { Map<String, Object> body = new HashMap<String, Object>(); body.put("status", "INVALID"); body.put("description", "The encryption algorithm is not strong enough"); return new ResponseEntity<>(body, HttpStatus.NOT_FOUND); }
Source:
private Optional<URL> getUrlForFile( File possibleFileInSrc) { try { return Optional.fromNullable( possibleFileInSrc.toURI().toURL() ); } catch(MalformedURLException malformedURLException) { logger.error("Error in dev mode while streaming files from src dir. ", malformedURLException); } return null; }

Target:
private Optional<URL> getUrlForFile( File possibleFileInSrc) { try { return Optional.fromNullable( possibleFileInSrc.toURI().toURL() ); } catch(MalformedURLException malformedURLException) { logger.error("Error in dev mode while streaming files from src dir. ", malformedURLException); } return Optional.absent(); }
Source:
private void skipIfImageNotPresent() { Image image = view.getComputeService().getImage(getImageId()); if (image == null) { throw new SkipException("Image " + getImageId() + " not available. Skipping windows tests."); } }

Target:
private void skipIfImageNotPresent() { Image image = client.getImage(getImageId()); if (image == null) { throw new SkipException("Image " + getImageId() + " not available. Skipping windows tests."); } }
Source:
public void run() { jobs.forEach(Job::run); }

Target:
public void run() { jobs.forEach(j -> { try { j.run(); } catch (RuntimeException ex) { logger.warn("Job execution failed.", ex); } }); }