auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public QueryControlResult create(final Tuple<String, AvroDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroDag(tuple); final String queryId = tuple.getKey(); final String appId = tuple.getValue().getAppId(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Create Query [aid: {0}, qid: {2}]", new Object[]{appId, queryId}); } if (!applicationMap.containsKey(appId)) { createApplication(appId, tuple.getValue().getJarPaths()); } final ApplicationInfo applicationInfo = applicationMap.get(appId); final DAG<ConfigVertex, MISTEdge> configDag = configDagGenerator.generate(tuple.getValue()); final Query query = createAndStartQuery(queryId, applicationInfo, configDag); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { e.printStackTrace(); LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.toString()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }

Target:
public QueryControlResult create(final Tuple<String, AvroDag> tuple) { final QueryControlResult queryControlResult = new QueryControlResult(); queryControlResult.setQueryId(tuple.getKey()); try { planStore.saveAvroDag(tuple); final String queryId = tuple.getKey(); final String appId = tuple.getValue().getAppId(); if (LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Create Query [aid: {0}, qid: {2}]", new Object[]{appId, queryId}); } if (!applicationMap.containsKey(appId)) { createApplication(appId, tuple.getValue().getJarPaths()); } final ApplicationInfo applicationInfo = applicationMap.get(appId); final DAG<ConfigVertex, MISTEdge> configDag = configDagGenerator.generate(tuple.getValue()); while (applicationInfo.getGroups().isEmpty()) { Thread.sleep(100); } final Query query = createAndStartQuery(queryId, applicationInfo, configDag); queryControlResult.setIsSuccess(true); queryControlResult.setMsg(ResultMessage.submitSuccess(tuple.getKey())); return queryControlResult; } catch (final Exception e) { e.printStackTrace(); LOG.log(Level.SEVERE, "An exception occurred while starting {0} query: {1}", new Object[] {tuple.getKey(), e.toString()}); queryControlResult.setIsSuccess(false); queryControlResult.setMsg(e.getMessage()); return queryControlResult; } }
Source:
public void addPage(BenchmarkData data) { int pageCount = data.getPageCount(); Page page = data.getDataPage(); PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < pageCount; i++) { operator.addInput(page); } operator.finish(); }

Target:
public void addPage(BenchmarkData data) { PartitionedOutputOperator operator = data.createPartitionedOutputOperator(); for (int i = 0; i < data.getPageCount(); i++) { operator.addInput(data.getDataPage()); } operator.finish(); }
Source:
void readContainerLogsInSeparateThread( String container, String workspaceId, String machineId, MessageProcessor<LogMessage> logsProcessor) { executor.execute( () -> { boolean test = false; if (test) { throw new RuntimeException("test test 123"); } long lastProcessedLogDate = 0; boolean isContainerRunning = true; int errorsCounter = 0; long lastErrorTime = 0; while (isContainerRunning) { try { docker.getContainerLogs( GetContainerLogsParams.create(container) .withFollow(true) .withSince(lastProcessedLogDate), logsProcessor); isContainerRunning = false; } catch (SocketTimeoutException ste) { lastProcessedLogDate = System.currentTimeMillis() / 1000L; } catch (ContainerNotFoundException e) { isContainerRunning = false; } catch (IOException e) { long errorTime = System.currentTimeMillis(); lastProcessedLogDate = errorTime / 1000L; LOG.warn( "Failed to get logs from machine of workspace backed by container {}, because: {}.", machineId, workspaceId, container, e.getMessage(), e); if (errorTime - lastErrorTime < 20_000L) { if (++errorsCounter == 5) { LOG.error( "Too many errors while streaming logs from machine of workspace backed by container {}. " + "Logs streaming is closed. Last error: {}.", machineId, workspaceId, container, e.getMessage(), e); break; } } else { errorsCounter = 1; } lastErrorTime = errorTime; try { sleep(1_000); } catch (InterruptedException ie) { return; } } } }); }

Target:
void readContainerLogsInSeparateThread( String container, String workspaceId, String machineId, MessageProcessor<LogMessage> logsProcessor) { executor.execute( () -> { long lastProcessedLogDate = 0; boolean isContainerRunning = true; int errorsCounter = 0; long lastErrorTime = 0; while (isContainerRunning) { try { docker.getContainerLogs( GetContainerLogsParams.create(container) .withFollow(true) .withSince(lastProcessedLogDate), logsProcessor); isContainerRunning = false; } catch (SocketTimeoutException ste) { lastProcessedLogDate = System.currentTimeMillis() / 1000L; } catch (ContainerNotFoundException e) { isContainerRunning = false; } catch (IOException e) { long errorTime = System.currentTimeMillis(); lastProcessedLogDate = errorTime / 1000L; LOG.warn( "Failed to get logs from machine of workspace backed by container {}, because: {}.", machineId, workspaceId, container, e.getMessage(), e); if (errorTime - lastErrorTime < 20_000L) { if (++errorsCounter == 5) { LOG.error( "Too many errors while streaming logs from machine of workspace backed by container {}. " + "Logs streaming is closed. Last error: {}.", machineId, workspaceId, container, e.getMessage(), e); break; } } else { errorsCounter = 1; } lastErrorTime = errorTime; try { sleep(1_000); } catch (InterruptedException ie) { return; } } } }); }
Source:
public Object getSparkObject() throws StandardException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeObject(value); out.flush(); return bos.toByteArray(); } catch (IOException e) { throw new RuntimeException(e); } finally { try { bos.close(); } catch (IOException ex) { } } }

Target:
public Object getSparkObject() throws StandardException { if (value instanceof Serializable) { return SerializationUtils.serialize((Serializable) value); } else { return super.getSparkObject(); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final Repository repository = SelectionUtils.getRepository(selection); final GitFlowRepository gfRepo = new GitFlowRepository(repository); Job job = new Job(UIText.FeatureFinishHandler_finishingFeature) { @Override protected IStatus run(IProgressMonitor monitor) { try { new FeatureFinishOperation(gfRepo).execute(monitor); } catch (WrongGitFlowStateException e) { return error(e.getMessage(), e); } catch (CoreException e) { return error(e.getMessage(), e); } catch (IOException e) { return error(e.getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IStructuredSelection selection = (IStructuredSelection) HandlerUtil .getCurrentSelection(event); final Repository repository = SelectionUtils.getRepository(selection); final GitFlowRepository gfRepo = new GitFlowRepository(repository); WorkspaceJob job = new WorkspaceJob( UIText.FeatureFinishHandler_finishingFeature) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { try { new FeatureFinishOperation(gfRepo).execute(monitor); } catch (WrongGitFlowStateException e) { return error(e.getMessage(), e); } catch (CoreException e) { return error(e.getMessage(), e); } catch (IOException e) { return error(e.getMessage(), e); } return Status.OK_STATUS; } }; job.setUser(true); job.schedule(); return null; }
Source:
public Mappings.TargetMapping getPartialMapping(int inputFieldCount) { Mappings.TargetMapping mapping = Mappings.create(MappingType.INVERSE_FUNCTION, inputFieldCount, projects.size()); for (Ord<RexLocalRef> exp : Ord.zip(projects)) { RexInputRef inputRef = (RexInputRef) exprs.get(exp.e.index); mapping.set(inputRef.getIndex(), exp.i); } return mapping; }

Target:
public Mappings.TargetMapping getPartialMapping(int inputFieldCount) { Mappings.TargetMapping mapping = Mappings.create(MappingType.INVERSE_FUNCTION, inputFieldCount, projects.size()); for (Ord<RexLocalRef> exp : Ord.zip(projects)) { RexNode rexNode = expandLocalRef(exp.e); if (rexNode instanceof RexInputRef) { mapping.set(((RexInputRef) rexNode).getIndex(), exp.i); } } return mapping; }
Source:
public void validate(ValidationContext validationContext) { if(name == null || StringUtil.isBlank(CaseInsensitiveString.str(name))) addError("User cannot be blank."); }

Target:
public void validate(ValidationContext validationContext) { if(name == null || name.isBlank()) addError("User cannot be blank."); }
Source:
public void addInput(Page page) { checkState(pendingInput == null); requireNonNull(page, "page is null"); processInput(page); updateMemoryUsage(); }

Target:
public void addInput(Page page) { checkState(!finishing, "Operator is already finishing"); requireNonNull(page, "page is null"); processInput(page); updateMemoryUsage(); }
Source:
public static LiveVariablesAnalysis analyze(ControlFlowGraph cfg, SymbolTable symbols) { return new LiveVariablesAnalysis(cfg, symbols); }

Target:
public static LiveVariablesAnalysis analyze(ControlFlowGraph cfg, SymbolTable symbols) { LiveVariablesAnalysis instance = new LiveVariablesAnalysis(); instance.compute(cfg, symbols); return instance; }
Source:
private void updateTscFrequency() { if (getSelectedCluster() == null || getVmType() == null || getMigrationMode() == null) { return; } boolean isChangeable = ArchitectureType.x86.equals(getSelectedCluster().getArchitecture().getFamily()) && VmType.HighPerformance.equals(getVmType().getSelectedItem()) && MigrationSupport.MIGRATABLE.equals(getMigrationMode().getSelectedItem()); tscFrequency.setIsChangeable(isChangeable); tscFrequency.setEntity(isChangeable); }

Target:
private void updateTscFrequency() { if (getSelectedCluster() == null || getVmType() == null || getMigrationMode() == null) { return; } boolean isChangeable = ArchitectureType.x86.equals(getSelectedCluster().getArchitecture().getFamily()) && VmType.HighPerformance.equals(getVmType().getSelectedItem()) && (MigrationSupport.MIGRATABLE.equals(getMigrationMode().getSelectedItem()) || MigrationSupport.IMPLICITLY_NON_MIGRATABLE.equals(getMigrationMode().getSelectedItem())); tscFrequency.setIsChangeable(isChangeable); tscFrequency.setEntity(isChangeable); }
Source:
public void badResponseHandlerAndRestRequestTest() throws Exception { RestRequest restRequest = new BadRestRequest(); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); responseHandler.shutdown(); ambryBlobStorageService.handleGet(restRequest, restResponseChannel); assertEquals("Unexpected exception", IllegalStateException.class, restResponseChannel.getException().getClass()); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handlePost(restRequest, restResponseChannel); Exception e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handlePut(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof RestServiceException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleDelete(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleHead(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); }

Target:
public void badResponseHandlerAndRestRequestTest() throws Exception { RestRequest restRequest = new BadRestRequest(); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); responseHandler.shutdown(); ambryBlobStorageService.handleGet(restRequest, restResponseChannel); assertEquals("Unexpected exception", IllegalStateException.class, restResponseChannel.getException().getClass()); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handlePost(restRequest, restResponseChannel); Exception e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleDelete(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); responseHandler.reset(); restResponseChannel = new MockRestResponseChannel(); ambryBlobStorageService.handleHead(restRequest, restResponseChannel); e = restResponseChannel.getException(); assertTrue("Unexpected exception", e instanceof IllegalStateException || e instanceof NullPointerException); }
Source:
public static void launchArrangeCommand(DiagramEditPart diagramEditPart, boolean isAfterDiagramEditorInstantiation) { TransactionalEditingDomain editingDomain = diagramEditPart.getEditingDomain(); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsToLayoutMap = getCreatedViewsToLayoutMap(diagramEditPart); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsWithSpecialLayoutMap = getCreatedViewsWithSpecialLayoutMap(diagramEditPart); DiagramDescription diagDesc = new EditPartQuery(diagramEditPart).getDiagramDescription(); if (isAfterDiagramEditorInstantiation && diagDesc != null && diagDesc.getLayout() instanceof CustomLayoutConfiguration) { List<IAdaptable> createdViews = createdViewsToLayoutMap.get(diagramEditPart); createdViewsToLayoutMap.clear(); if (createdViews != null && !createdViews.isEmpty()) { createdViewsToLayoutMap.put(diagramEditPart, createdViews); } } Command layoutCommand = getLayoutCommand(createdViewsToLayoutMap, createdViewsWithSpecialLayoutMap, editingDomain); if (layoutCommand.canExecute()) { editingDomain.getCommandStack().execute(layoutCommand); } }

Target:
private static void launchArrangeCommand(DiagramEditPart diagramEditPart, boolean isAfterDiagramEditorInstantiation) { TransactionalEditingDomain editingDomain = diagramEditPart.getEditingDomain(); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsToLayoutMap = getCreatedViewsToLayoutMap(diagramEditPart); Map<IGraphicalEditPart, List<IAdaptable>> createdViewsWithSpecialLayoutMap = getCreatedViewsWithSpecialLayoutMap(diagramEditPart); DiagramDescription diagDesc = new EditPartQuery(diagramEditPart).getDiagramDescription(); if (isAfterDiagramEditorInstantiation && diagDesc != null && diagDesc.getLayout() instanceof CustomLayoutConfiguration) { List<IAdaptable> createdViews = createdViewsToLayoutMap.get(diagramEditPart); createdViewsToLayoutMap.clear(); if (createdViews != null && !createdViews.isEmpty()) { createdViewsToLayoutMap.put(diagramEditPart, createdViews); } } Command layoutCommand = getLayoutCommand(createdViewsToLayoutMap, createdViewsWithSpecialLayoutMap, editingDomain); if (layoutCommand.canExecute()) { editingDomain.getCommandStack().execute(layoutCommand); } }
Source:
public void register(final Collection<String> componentIds) { final Map<String, SctId> sctIds = Maps.newHashMap(); final Set<String> registeredComponentIds = newHashSet(); LOGGER.debug(String.format("Registering %d component IDs.", componentIds.size())); try { final Collection<String> existingIds = getSctIds(componentIds).stream().filter(id -> id.matches(IdentifierStatus.AVAILABLE, IdentifierStatus.RESERVED)).map(SctId::getSctid).collect(Collectors.toSet()); for (final String componentId : componentIds) { if (!existingIds.contains(componentId)) { final SctId sctId = buildSctId(componentId, IdentifierStatus.ASSIGNED); sctIds.put(componentId, sctId); registeredComponentIds.add(componentId); } else { LOGGER.warn("Cannot register ID as it is already taken.", componentId); } } putSctIds(sctIds); } catch (Exception e) { removeSctIds(registeredComponentIds); throw e; } }

Target:
public void register(final Collection<String> componentIds) { final Map<String, SctId> sctIds = Maps.newHashMap(); final Set<String> registeredComponentIds = newHashSet(); LOGGER.debug(String.format("Registering %d component IDs.", componentIds.size())); try { for (final SctId sctId : getSctIds(componentIds)) { if (!sctId.matches(IdentifierStatus.AVAILABLE, IdentifierStatus.RESERVED)) { LOGGER.warn("Cannot register ID as it is already present with status {}.", sctId.getSctid(), sctId.getStatus()); } else { sctId.setStatus(IdentifierStatus.ASSIGNED.getSerializedName()); } } putSctIds(sctIds); } catch (Exception e) { removeSctIds(registeredComponentIds); throw e; } }
Source:
public Object perform(InvocationContext ctx) throws Throwable { ((DefaultCacheManager) cacheManager).removeCacheLocally(cacheName); return null; }

Target:
public Object perform(InvocationContext ctx) throws Throwable { GlobalComponentRegistry globalComponentRegistry = cacheManager.getGlobalComponentRegistry(); ComponentRegistry cacheComponentRegistry = globalComponentRegistry.getNamedComponentRegistry(cacheName); if (cacheComponentRegistry != null) { cacheComponentRegistry.getComponent(PersistenceManager.class).setClearOnStop(true); cacheComponentRegistry.getComponent(CacheJmxRegistration.class).setUnregisterCacheMBean(true); cacheComponentRegistry.getComponent(PassivationManager.class).skipPassivationOnStop(true); Cache<?, ?> cache = cacheManager.getCache(cacheName, false); if (cache != null) { cache.stop(); } } globalComponentRegistry.removeCache(cacheName); globalComponentRegistry.getComponent(ConfigurationManager.class).removeConfiguration(cacheName); globalComponentRegistry.getComponent(DependencyGraph.class, CACHE_DEPENDENCY_GRAPH).remove(cacheName); return null; }
Source:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; this.lastFlush = System.currentTimeMillis(); }

Target:
FileState(BufferedWriter writer) { this.writer = writer; this.stream = null; }
Source:
public void initialise() { sceneOpaqueFbo = displayResolutionDependentFBOs.get(SCENE_OPAQUE); playerCamera = worldRenderer.getActiveCamera(); wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(SCENE_OPAQUE, displayResolutionDependentFBOs)); }

Target:
public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(READONLY_GBUFFER, displayResolutionDependentFBOs)); sceneOpaqueFbo = displayResolutionDependentFBOs.get(READONLY_GBUFFER); }
Source:
public void shouldAcquireSchemaWriteLockBeforeCreatingUniquenessConstraint() throws Exception { when( constraintIndexCreator.createUniquenessConstraintIndex( transaction, descriptor ) ).thenReturn( 42L ); when( storeReadLayer.constraintsGetForSchema( descriptor.schema() ) ).thenReturn( Collections.emptyIterator() ); operations.uniquePropertyConstraintCreate( descriptor ); verify( locks ).acquireExclusive( LockTracer.NONE, ResourceTypes.LABEL, descriptor.getLabelId() ); }

Target:
public void shouldAcquireSchemaWriteLockBeforeCreatingUniquenessConstraint() throws Exception { when( constraintIndexCreator.createUniquenessConstraintIndex( transaction, descriptor ) ).thenReturn( 42L ); when( storeReadLayer.constraintsGetForSchema( descriptor.schema() ) ).thenReturn( Collections.emptyIterator() ); operations.uniquePropertyConstraintCreate( descriptor ); order.verify( locks ).acquireExclusive( LockTracer.NONE, ResourceTypes.LABEL, descriptor.getLabelId() ); order.verify( txState ).constraintDoAdd( ConstraintDescriptorFactory.uniqueForSchema( descriptor ), 42L ); }
Source:
public static void damageItem(GlowPlayer player, ItemStack holding) { if (player != null && player.getGameMode() == GameMode.CREATIVE) { return; } int durability = holding.getEnchantmentLevel(Enchantment.DURABILITY); if (durability > 0 && ThreadLocalRandom.current().nextDouble() < 1 / (durability + 1)) { return; } holding.setDurability((short) (holding.getDurability() + 1)); if (holding.getDurability() == holding.getType().getMaxDurability() + 1) { if (player != null) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); } holding.setAmount(0); } }

Target:
public static ItemStack damageItem(GlowPlayer player, ItemStack holding) { if (player != null && player.getGameMode() == GameMode.CREATIVE) { return holding; } int durability = holding.getEnchantmentLevel(Enchantment.DURABILITY); if (durability > 0 && ThreadLocalRandom.current().nextDouble() < 1 / (durability + 1)) { return holding; } holding.setDurability((short) (holding.getDurability() + 1)); if (holding.getDurability() == holding.getType().getMaxDurability() + 1) { if (player != null) { EventFactory.callEvent(new PlayerItemBreakEvent(player, holding)); } return createEmptyStack(); } return holding; }
Source:
public Optional<Layout> getCurrentLayout() { if(!serverMap.containsKey(LayoutServer.class)){ throw new IllegalStateException("Layout server is not in a server map."); } LayoutServer layoutServer = (LayoutServer) serverMap.get(LayoutServer.class); return Optional.ofNullable(layoutServer.getCurrentLayout()); }

Target:
public Optional<Layout> getCurrentLayout() { return Optional.ofNullable(serverContext.getCurrentLayout()); }
Source:
private static Customer getSampleCustomer() { return Customer.newBuilder() .setId(CustomerId.newBuilder() .setNumber((int) UUID.randomUUID() .getLeastSignificantBits())) .setName(PersonName.newBuilder() .setGivenName("Socrates") .build()) .addNicknames(PersonName.newBuilder() .setGivenName("Philosopher")) .addNicknames(PersonName.newBuilder() .setGivenName("Wise guy")) .build(); }

Target:
private static Customer getSampleCustomer() { return Customer.newBuilder() .setId(CustomerId.newBuilder() .setNumber((int) UUID.randomUUID() .getLeastSignificantBits())) .setName(PersonName.newBuilder() .setGivenName("John") .build()) .addNicknames(PersonName.newBuilder() .setGivenName("Johnny")) .addNicknames(PersonName.newBuilder() .setGivenName("Big Guy")) .build(); }
Source:
public Response getCredentials() { String user = authenticationService.getPrincipal(); LOGGER.info("getCredentials credentials for user ", user); UserCredentials uc; try { uc = credentials.getUserCredentials(user); return new JsonResponse<>(Status.OK, uc).build(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR).build(); } }

Target:
public Response getCredentials() { String user = authenticationService.getPrincipal(); LOGGER.info("getCredentials for user ", user); UserCredentials uc; try { uc = credentials.getUserCredentials(user); return new JsonResponse<>(Status.OK, uc).build(); } catch (IOException e) { LOGGER.error(e.getMessage(), e); return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR).build(); } }
Source:
public String toString() { final StringBuilder builder = new StringBuilder("{"); final Iterator<Map.Entry<String, JsonValue>> it = unmodifieableBackingMap.entrySet().iterator(); boolean hasNext = it.hasNext(); while (hasNext) { final Map.Entry<String, JsonValue> entry = it.next(); builder.append('"').append(Strings.escape(entry.getKey())).append("\":"); final JsonValue value = entry.getValue(); if (JsonString.class.isInstance(value)) { builder.append(value.toString()); } else { builder.append(value != JsonValue.NULL ? value.toString() : JsonChars.NULL); } hasNext = it.hasNext(); if (hasNext) { builder.append(","); } } return builder.append('}').toString(); }

Target:
public String toString() { final StringBuilder builder = new StringBuilder("{"); final Iterator<Map.Entry<String, JsonValue>> it = unmodifieableBackingMap.entrySet().iterator(); boolean hasNext = it.hasNext(); while (hasNext) { final Map.Entry<String, JsonValue> entry = it.next(); builder.append('"'); Strings.appendEscaped(entry.getKey(), builder); builder.append("\":"); final JsonValue value = entry.getValue(); if (JsonString.class.isInstance(value)) { builder.append(value.toString()); } else { builder.append(value != JsonValue.NULL ? value.toString() : JsonChars.NULL); } hasNext = it.hasNext(); if (hasNext) { builder.append(","); } } return builder.append('}').toString(); }
Source:
public static Field copyField(final Field field, final int newSortOrder) { JsonFieldTransformer jsonFieldTransformer = new JsonFieldTransformer(field); final JSONObject jsonObject = jsonFieldTransformer.jsonObject(); try { jsonObject.put("sortOrder", newSortOrder); } catch (JSONException e) { throw new DotRuntimeException(e); } jsonFieldTransformer = new JsonFieldTransformer(jsonObject.toString()); return jsonFieldTransformer.from(); }

Target:
public static Field copyField(final Field field, final int newSortOrder) { JsonFieldTransformer jsonFieldTransformer = new JsonFieldTransformer(field); final JSONObject jsonObject = jsonFieldTransformer.jsonObject(); try { jsonObject.put("sortOrder", newSortOrder); } catch (JSONException e) { Logger.error(FieldUtil.class, String.format("Eror witg fiels %s: %s", field.name(), e.getMessage())); throw new DotRuntimeException(e); } jsonFieldTransformer = new JsonFieldTransformer(jsonObject.toString()); return jsonFieldTransformer.from(); }
Source:
public void deselectByValue(String value) { List<WebElement> options = element.findElements(By.xpath( ". boolean matched = false; for (WebElement option : options) { setSelected(option, false); if (!isMultiple()) { return; } matched = true; } if (!matched) { throw new NoSuchElementException("Cannot locate option with value: " + value); } }

Target:
public void deselectByValue(String value) { if (!isMultiple()) { throw new UnsupportedOperationException( "You may only deselect options of a multi-select"); } List<WebElement> options = element.findElements(By.xpath( ". boolean matched = false; for (WebElement option : options) { setSelected(option, false); matched = true; } if (!matched) { throw new NoSuchElementException("Cannot locate option with value: " + value); } }
Source:
private static boolean isProtectedOrOverriding(MethodTreeImpl member) { return ModifiersUtils.hasModifier(member.modifiers(), Modifier.PROTECTED) || member.isOverriding(); }

Target:
private static boolean isProtectedOrOverriding(MethodTreeImpl member) { return ModifiersUtils.hasModifier(member.modifiers(), Modifier.PROTECTED) || !Boolean.FALSE.equals(member.isOverriding()); }
Source:
public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); Context context = ApplicationProvider.getApplicationContext(); AppConfig appConfig = Camera2AppConfig.create(context); CameraFactory cameraFactory = appConfig.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } CameraX.initialize(context, appConfig); mCameraInternal = cameraFactory.getCamera(mCameraId); mDefaultConfig = Preview.DEFAULT_CONFIG.getConfig(LensFacing.BACK); mSurfaceFutureSemaphore = new Semaphore( 0); mSaveToReleaseSemaphore = new Semaphore( 0); mCameraSelector = new CameraSelector.Builder().requireLensFacing(LensFacing.BACK).build(); }

Target:
public void setUp() { assumeTrue(CameraUtil.deviceHasCamera()); Context context = ApplicationProvider.getApplicationContext(); AppConfig appConfig = Camera2AppConfig.create(context); CameraFactory cameraFactory = appConfig.getCameraFactory( null); try { mCameraId = cameraFactory.cameraIdForLensFacing(LensFacing.BACK); } catch (Exception e) { throw new IllegalArgumentException( "Unable to attach to camera with LensFacing " + LensFacing.BACK, e); } CameraX.initialize(context, appConfig); mCameraInternal = cameraFactory.getCamera(mCameraId); mDefaultConfig = Preview.DEFAULT_CONFIG.getConfig(LensFacing.BACK); mSurfaceFutureSemaphore = new Semaphore( 0); mSaveToReleaseSemaphore = new Semaphore( 0); }
Source:
public static int getCurrentCounterValue() { return COUNTER.intValue(); }

Target:
static int getCurrentCounterValue() { return COUNTER.intValue(); }
Source:
public void testUpdateKeyWithVersion() { List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); assertTrue(keys.size() > 1); Key key = keys.get(1); assertNotNull(key); String version = key.kid().substring(key.kid().lastIndexOf("/") + 1).trim(); Map<String, String> tags = new HashMap<String, String>(); tags.put("purpose", "testing again"); KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, "/" + version, null, null, tags); assertNotNull(updatedKey); keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); boolean found = false; for (Key k : keys) { if (k.kid().contains(version)) { key = k; found = true; break; } } assertTrue(found); assertEquals(tags, key.tags()); }

Target:
public void testUpdateKeyWithVersion() { List<Key> keys = api().getKeyVersions(vaultUri, KEY_NAME); assertNotNull(keys); assertTrue(keys.size() > 1); Key key = keys.get(1); assertNotNull(key); final String version = key.kid().substring(key.kid().lastIndexOf("/") + 1).trim(); Map<String, String> tags = new HashMap<String, String>(); tags.put("purpose", "testing again"); KeyBundle updatedKey = api().updateKey(vaultUri, KEY_NAME, version, null, null, tags); assertNotNull(updatedKey); FluentIterable<Key> iKeys = FluentIterable.from(api().getKeyVersions(vaultUri, KEY_NAME)); assertTrue(iKeys.anyMatch(new Predicate<Key>() { @Override public boolean apply(Key input) { return input.kid().contains(version); } })); assertEquals(tags, updatedKey.tags()); }
Source:
public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { Assert.assertEquals(daemonThread.getName(), THREAD_NAME); Assert.assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }

Target:
public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { assertEquals(THREAD_NAME, daemonThread.getName()); assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { } } }
Source:
private static List<String> getScopesFromExpression(QueryContext queryContext) { ArrayList<String> scopes = new ArrayList<>(); Queue<QueryContext> bfsQueue = new LinkedList<QueryContext>(); if(queryContext != null) { bfsQueue.add(queryContext); } while(!bfsQueue.isEmpty()) { QueryContext currContext = bfsQueue.poll(); if(currContext.getChildExpressions()!=null) { for(TSDBQueryExpression expression : currContext.getChildExpressions()) { scopes.add(expression.getScope()); } if(currContext.getChildContexts()!=null) { bfsQueue.addAll(currContext.getChildContexts()); } } } return scopes; }

Target:
private static List<String> getScopesFromExpression(QueryContext queryContext) { Set<String> scopes = new HashSet<>(); Queue<QueryContext> bfsQueue = new LinkedList<QueryContext>(); if(queryContext != null) { bfsQueue.add(queryContext); } while(!bfsQueue.isEmpty()) { QueryContext currContext = bfsQueue.poll(); if(currContext.getChildExpressions()!=null) { for(TSDBQueryExpression expression : currContext.getChildExpressions()) { scopes.add(expression.getScope()); } if(currContext.getChildContexts()!=null) { bfsQueue.addAll(currContext.getChildContexts()); } } } return new ArrayList<>(scopes); }
Source:
public static int parseIntegerToShort(String value) { BigInteger result = DatatypeConverter.parseInteger(value); if (result.longValue() > Short.MAX_VALUE) { throw new InvalidValueException("Value " +value+ " greater than Short.MAX_VALUE"); } return result.intValue(); }

Target:
public static int parseIntegerToShort(String value) { BigInteger result = DatatypeConverter.parseInteger(value); if (result.longValue() > Short.MAX_VALUE) { throw new InvalidValueException("Value " +value+ " greater than maximum " + Short.MAX_VALUE); } return result.intValue(); }
Source:
private void updateJobStatus( final JobEntity jobEntity, final JobStatus newStatus, @Nullable final String statusMsg ) { final JobStatus currentStatus = jobEntity.getStatus(); if (currentStatus.isActive()) { jobEntity.setStatus(newStatus); jobEntity.setStatusMsg(statusMsg); if (newStatus.equals(JobStatus.RUNNING)) { jobEntity.setStarted(Instant.now()); } else if (jobEntity.getStarted().isPresent() && newStatus.isFinished()) { jobEntity.setFinished(Instant.now()); } } if (currentStatus != newStatus) { synchronized (this.observers) { this.observers.forEach(o -> o.notifyJobStateChange(jobEntity.getUniqueId(), currentStatus, newStatus)); } } }

Target:
private void updateJobStatus( final JobEntity jobEntity, final JobStatus newStatus, @Nullable final String statusMsg ) { final JobStatus currentStatus = jobEntity.getStatus(); if (currentStatus.isActive()) { jobEntity.setStatus(newStatus); jobEntity.setStatusMsg(statusMsg); if (newStatus.equals(JobStatus.RUNNING)) { jobEntity.setStarted(Instant.now()); } else if (jobEntity.getStarted().isPresent() && newStatus.isFinished()) { jobEntity.setFinished(Instant.now()); } } }
Source:
public void run() { m_taskQueue.offer(this); SiteTasker task = m_taskQueue.peek(); long currentTime = System.nanoTime(); long headOfQueueOfferTime; String taskInfo = ""; if (task != null) { headOfQueueOfferTime = task.getQueueOfferTime(); taskInfo = " Task Info: " + task.getTaskInfo(); } else { headOfQueueOfferTime = currentTime; } if (headOfQueueOfferTime != m_previousTaskTimestamp) { m_previousTaskTimestamp = headOfQueueOfferTime; m_previousTaskPeekTime = currentTime; } else if (currentTime - m_previousTaskPeekTime >= m_procedureLogThreshold) { long waitTime = (currentTime - m_previousTaskPeekTime)/1_000_000_000L; if (m_logger.isDebugEnabled()) { m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.DEBUG, null, TICK_MESSAGE + taskInfo, waitTime, m_partitionId); } else { m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.INFO, null, TICK_MESSAGE, waitTime, m_partitionId); } } }

Target:
public void run() { m_taskQueue.offer(this); SiteTasker task = m_taskQueue.peek(); long currentTime = System.nanoTime(); long headOfQueueOfferTime; if (task != null) { headOfQueueOfferTime = task.getQueueOfferTime(); } else { headOfQueueOfferTime = currentTime; } if (headOfQueueOfferTime != m_previousTaskTimestamp) { m_previousTaskTimestamp = headOfQueueOfferTime; m_previousTaskPeekTime = currentTime; } else if (currentTime - m_previousTaskPeekTime >= m_procedureLogThreshold) { long waitTime = (currentTime - m_previousTaskPeekTime)/1_000_000_000L; if (m_logger.isDebugEnabled()) { String taskInfo = (task == null) ? "" : " Task Info: " + task.getTaskInfo(); m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.DEBUG, null, TICK_MESSAGE + taskInfo, waitTime, m_partitionId); } else { m_logger.rateLimitedLog(SUPPRESS_INTERVAL, Level.INFO, null, TICK_MESSAGE, waitTime, m_partitionId); } } }
Source:
MetricsInterceptor(Registry registry) { this.registry = registry; this.log = LoggerFactory.getLogger(getClass()); this.packageName = this.getClass().getPackage().getName().split("\\.")[1]; }

Target:
MetricsInterceptor(Registry registry) { this.registry = registry; this.log = LoggerFactory.getLogger(getClass()); }
Source:
public String buildPatternTableau() { StringBuilder builder = new StringBuilder(); TreeSet<ColumnIdentifier> patternTableauHead = condition.getContainedColumns(); builder.append(patternTableauHead); List<Map<ColumnIdentifier, String>> conditions = condition.getPatternConditions(); for (Map<ColumnIdentifier, String> condition : conditions) { builder.append("\r\n"); for (ColumnIdentifier column : patternTableauHead) { if (condition.containsKey(column)) { String value = condition.get(column); if (value.length() < column.toString().length()) { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < (column.toString().length() - value.length()) / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append(value); builder.append(whitespaceBuilder); } else { builder.append(value); builder.append(" "); } } else { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < column.toString().length() / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append("-"); builder.append(whitespaceBuilder); } } } return builder.toString(); }

Target:
public String buildPatternTableau() { StringBuilder builder = new StringBuilder(); TreeSet<ColumnIdentifier> patternTableauHead = condition.getContainedColumns(); builder.append(patternTableauHead); List<Map<ColumnIdentifier, String>> conditions = condition.getPatternConditions(); for (Map<ColumnIdentifier, String> condition : conditions) { builder.append(LINESEPARATOR); for (ColumnIdentifier column : patternTableauHead) { if (condition.containsKey(column)) { String value = condition.get(column); if (value.length() < column.toString().length()) { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < (column.toString().length() - value.length()) / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append(value); builder.append(whitespaceBuilder); } else { builder.append(value); builder.append(" "); } } else { StringBuilder whitespaceBuilder = new StringBuilder(); for (int i = 0; i < column.toString().length() / 2; i++) { whitespaceBuilder.append(" "); } builder.append(whitespaceBuilder); builder.append("-"); builder.append(whitespaceBuilder); } } } return builder.toString(); }
Source:
Rgb24ImageRepresentationHandler(final Map<Integer, Integer> bandMap, final int actualBitsPerPixelPerBand) { this.bandMapping = bandMap; this.numOfReadsPerBand = (int) Math.ceil(actualBitsPerPixelPerBand / ((double) Byte.SIZE)); if (actualBitsPerPixelPerBand - Byte.SIZE < 0) { this.bitsToDiscard = 0; } else { this.bitsToDiscard = actualBitsPerPixelPerBand - Byte.SIZE; } }

Target:
Rgb24ImageRepresentationHandler(final Map<Integer, Integer> bandMap, final int actualBitsPerPixelPerBand) { super(bandMap, actualBitsPerPixelPerBand); }
Source:
public void unsuspend(Collection<TabletLocationState> tablets) { for (TabletLocationState tls : tablets) { if (tls.suspend != null) { continue; } TabletMutator tabletMutator = ample.mutateTablet(tls.extent); tabletMutator.deleteSuspension(); tabletMutator.mutate(); } }

Target:
public void unsuspend(Collection<TabletLocationState> tablets) { try (var tabletsMutator = ample.mutateTablets()) { for (TabletLocationState tls : tablets) { if (tls.suspend != null) { continue; } TabletMutator tabletMutator = tabletsMutator.mutateTablet(tls.extent); tabletMutator.deleteSuspension(); tabletMutator.mutate(); } } }
Source:
public void testLoadGeneratorStops() throws InterruptedException, UnknownHostException { LlapLoadGeneratorService service = new LlapLoadGeneratorService(); HiveConf conf = new HiveConf(); HiveConf.setVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES, InetAddress.getLocalHost().getHostName() + ",???"); HiveConf.setFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION, 0.2f); HiveConf.setTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, 5, TimeUnit.MILLISECONDS); service.init(conf); service.start(); Thread.sleep(5000); assertEquals("The number of threads is not correct", Runtime.getRuntime().availableProcessors(), service.threads.length); for(int i = 0; i < service.threads.length; i++) { assertTrue("The thread [" + i + "] should be alive", service.threads[i].isAlive()); } service.stop(); Thread.sleep(5000); for(int i = 0; i < service.threads.length; i++) { Thread.State state = service.threads[i].getState(); assertFalse("The thread [" + i + "] should be terminated", service.threads[i].isAlive()); } }

Target:
public void testLoadGeneratorStops() throws InterruptedException, UnknownHostException { LlapLoadGeneratorService service = new LlapLoadGeneratorService(); HiveConf conf = new HiveConf(); HiveConf.setVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_HOSTNAMES, InetAddress.getLocalHost().getHostName() + ",???"); HiveConf.setFloatVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_UTILIZATION, 0.5f); HiveConf.setTimeVar(conf, HiveConf.ConfVars.HIVE_TEST_LOAD_INTERVAL, 5, TimeUnit.MILLISECONDS); service.init(conf); service.start(); assertEquals("The number of threads is not correct", Runtime.getRuntime().availableProcessors(), service.threads.length); for(int i = 0; i < service.threads.length; i++) { assertTrue("The thread [" + i + "] should be alive", service.threads[i].isAlive()); } service.stop(); Thread.sleep(1000); for(int i = 0; i < service.threads.length; i++) { Thread.State state = service.threads[i].getState(); assertFalse("The thread [" + i + "] should be terminated", service.threads[i].isAlive()); } }
Source:
private static String printMap(Map<String, Object[]> m) { java.util.Iterator<java.util.Map.Entry<String, Object[]>> itr = m.entrySet().iterator(); StringBuffer sb = new StringBuffer(); sb.append("size = ").append(m.size()).append(" "); while (itr.hasNext()) { sb.append("{"); Map.Entry<String, Object[]> entry = itr.next(); sb.append(entry.getKey()); sb.append(", "); printMapValue(entry.getValue(), sb); sb.append("}"); } return sb.toString(); }

Target:
private static String printMap(Map<String, Object[]> m) { Iterator<Map.Entry<String, Object[]>> itr = m.entrySet().iterator(); StringBuffer sb = new StringBuffer(); sb.append("size = ").append(m.size()).append(" "); while (itr.hasNext()) { sb.append("{"); Map.Entry<String, Object[]> entry = itr.next(); sb.append(entry.getKey()); sb.append(", "); printMapValue(entry.getValue(), sb); sb.append("}"); } return sb.toString(); }
Source:
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteDatasetCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("json-schema", new JSONSchemaCommand(console)); jc.addCommand("json-import", new JSONImportCommand(console)); jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("log4j-config", new Log4jConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }

Target:
Main(Logger console) { this.console = console; this.jc = new JCommander(this); this.help = new Help(jc, console); jc.setProgramName(DEFAULT_PROGRAM_NAME); jc.addCommand("help", help, "-h", "-help", "--help"); jc.addCommand("create", new CreateDatasetCommand(console)); jc.addCommand("copy", new CopyCommand(console)); jc.addCommand("transform", new TransformCommand(console)); jc.addCommand("update", new UpdateDatasetCommand(console)); jc.addCommand("delete", new DeleteCommand(console)); jc.addCommand("schema", new SchemaCommand(console)); jc.addCommand("info", new InfoCommand(console)); jc.addCommand("show", new ShowRecordsCommand(console)); jc.addCommand("obj-schema", new ObjectSchemaCommand(console)); jc.addCommand("csv-schema", new CSVSchemaCommand(console)); jc.addCommand("csv-import", new CSVImportCommand(console)); jc.addCommand("json-schema", new JSONSchemaCommand(console)); jc.addCommand("json-import", new JSONImportCommand(console)); jc.addCommand("partition-config", new CreatePartitionStrategyCommand(console)); jc.addCommand("mapping-config", new CreateColumnMappingCommand(console)); jc.addCommand("log4j-config", new Log4jConfigCommand(console)); jc.addCommand("flume-config", new FlumeConfigCommand(console)); }
Source:
public HealthcheckOptionsBuilder(String uri) { this.uri = Optional.of(uri); this.portIndex = Optional.absent(); this.portNumber = Optional.absent(); this.protocol = Optional.absent(); this.startupTimeoutSeconds = Optional.absent(); this.startupDelaySeconds = Optional.absent(); this.startupIntervalSeconds = Optional.absent(); this.intervalSeconds = Optional.absent(); this.responseTimeoutSeconds = Optional.absent(); this.maxRetries = Optional.absent(); this.failureStatusCodes = Optional.absent(); this.healthcheckResultFilePath = Optional.absent(); }

Target:
public HealthcheckOptionsBuilder(String uri) { this(Optional.of(uri)); }
Source:
private void setTabAndViewPagerSynchronisation() { viewPager.setFocusableInTouchMode(true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case CONTRIBUTIONS_TAB_POSITION: Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; updateMenuItem(); break; case NEARBY_TAB_POSITION: Timber.d("Nearby tab selected"); tabLayout.getTabAt(NEARBY_TAB_POSITION).select(); isContributionsFragmentVisible = false; updateMenuItem(); ((NearbyParentFragment)contributionsActivityPagerAdapter.getItem(1)).nearbyParentFragmentPresenter.onTabSelected(); break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); break; } } @Override public void onPageScrollStateChanged(int state) { } }); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }

Target:
private void setTabAndViewPagerSynchronisation() { viewPager.setFocusableInTouchMode(true); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case CONTRIBUTIONS_TAB_POSITION: Timber.d("Contributions tab selected"); tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); isContributionsFragmentVisible = true; updateMenuItem(); break; case NEARBY_TAB_POSITION: Timber.d("Nearby tab selected"); tabLayout.getTabAt(NEARBY_TAB_POSITION).select(); isContributionsFragmentVisible = false; updateMenuItem(); NearbyParentFragmentPresenter.getInstance().onTabSelected(); break; default: tabLayout.getTabAt(CONTRIBUTIONS_TAB_POSITION).select(); break; } } @Override public void onPageScrollStateChanged(int state) { } }); tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); }