auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public String obtainSst(final HttpClient httpClient, final HttpHost httpHost) throws IOException { notNull(httpClient, "client can't be null"); notNull(httpHost, "host can't be null"); log.debug("Obtaining SST"); final HttpPost postLogin = new HttpPost(LOGIN_URL); try { final HttpEntity requestEntity = new StringEntity(createLoginJson(), ContentType.APPLICATION_JSON); postLogin.setEntity(requestEntity); postLogin.setHeader(HttpHeaders.ACCEPT, YAML_CONTENT_TYPE); final HttpResponse response = httpClient.execute(httpHost, postLogin); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { Header requestIdHeader = response.getFirstHeader(X_GDC_REQUEST_HEADER_NAME); HttpEntity responseEntity = response.getEntity(); String message = String.format("Unable to login reason='%s'. Request tracking details httpStatus=%s requestId=%s", (responseEntity != null) ? EntityUtils.toString(responseEntity) : null, status, (requestIdHeader != null) ? requestIdHeader.getValue() : null); log.info(message); throw new GoodDataAuthException(message); } return TokenUtils.extractToken(response); } finally { postLogin.reset(); } }

Target:
public String obtainSst(final HttpClient httpClient, final HttpHost httpHost) throws IOException { notNull(httpClient, "client can't be null"); notNull(httpHost, "host can't be null"); log.debug("Obtaining SST"); final HttpPost postLogin = new HttpPost(LOGIN_URL); try { final HttpEntity requestEntity = new StringEntity(createLoginJson(), ContentType.APPLICATION_JSON); postLogin.setEntity(requestEntity); postLogin.setHeader(HttpHeaders.ACCEPT, YAML_CONTENT_TYPE); final HttpResponse response = httpClient.execute(httpHost, postLogin); int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_OK) { final Header requestIdHeader = response.getFirstHeader(X_GDC_REQUEST_HEADER_NAME); final HttpEntity responseEntity = response.getEntity(); final String message = format("Unable to login reason='%s'. Request tracking details httpStatus=%s requestId=%s", getReason(responseEntity), status, getRequestId(requestIdHeader)); log.info(message); throw new GoodDataAuthException(message); } return TokenUtils.extractToken(response); } finally { postLogin.reset(); } }
Source:
private void executeDeletion() { List<Metacard> allSystemTemplates = retrieveSystemMetacards(); if (allSystemTemplates.isEmpty()) { console.println(ansi().fgBrightRed().a("No system forms exist.").reset()); return; } try { List<String> systemTempIds = singleDeletion != null ? ImmutableList.of(singleDeletion) : retrieveListMetacardIds(allSystemTemplates); List<String> deletedMetacardIds = this.executeSystemTemplateRemoval(systemTempIds); if (deletedMetacardIds.isEmpty()) { console.println(ansi().fgBrightRed().a("No system forms were deleted").reset()); } else { for (String id : deletedMetacardIds) { console.println(ansi().fgBrightYellow().a("Deleted: ").fgGreen().a(id).reset()); } } } catch (IngestException | SourceUnavailableException e) { console.println(ansi().fgBrightRed().a("Error removing system forms").reset()); LOGGER.debug("Error removing system forms", e); } }

Target:
private void executeDeletion() { List<Metacard> allSystemTemplates = retrieveSystemMetacards(); if (allSystemTemplates.isEmpty()) { printColor(WARNING_COLOR, "No system forms exist."); return; } try { List<String> systemTemplateIds = singleDeletion != null ? ImmutableList.of(singleDeletion) : retrieveMetacardIds(allSystemTemplates); List<String> deletedMetacardIds = this.executeSystemTemplateRemoval(systemTemplateIds); if (deletedMetacardIds.isEmpty()) { printColor(WARNING_COLOR, "No system forms were deleted"); } else { for (String id : deletedMetacardIds) { console.println(ansi().fgBrightYellow().a("Deleted: ").fgGreen().a(id).reset()); } } } catch (IngestException | SourceUnavailableException e) { LOGGER.debug("Error removing system forms", e); printErrorMessage("Error removing system forms: " + e.getMessage()); } }
Source:
public String readLine() { String line = System.console().readLine(); log.info("Read from stdin \"" + line + "\"."); return line; }

Target:
public String readLine() { StringBuilder buffer = new StringBuilder(); for (;;) { int character; try { character = System.in.read(); } catch (IOException exception) { log.error( "Error while reading line from standard input. Will " + "consider it the end of the line and continue.", exception ); break; } if (character == -1 || character == '\n') { break; } buffer.append((char) character); } String line = buffer.toString(); log.info("Read from stdin \"" + line + "\"."); return line; }
Source:
public void addToBatch(RowData record) throws SQLException { RowData key = keyExtractor.apply(record); reduceBuffer.put(key, Tuple2.of(changeFlag(record.getRowKind()), valueTransform.apply(record))); }

Target:
public void addToBatch(RowData record) throws SQLException { RowData key = keyExtractor.apply(record); boolean flag = changeFlag(record.getRowKind()); RowData value = valueTransform.apply(record); reduceBuffer.put(key, Tuple2.of(flag, value)); }
Source:
private void filterSortPaginateSanityCheck(Environment environment) { if(environment.filters.isPresent() || environment.sort.isPresent() || environment.offset.isPresent() || environment.first.isPresent()) { throw new IllegalArgumentException("Pagination/Filtering/Sorting is only supported with FETCH operation"); } }

Target:
private void filterSortPaginateSanityCheck(Environment environment) { if(environment.filters.isPresent() || environment.sort.isPresent() || environment.offset.isPresent() || environment.first.isPresent()) { throw new BadRequestException("Pagination/Filtering/Sorting is only supported with FETCH operation"); } }
Source:
private void sendDeletedEvents(List<Entitlement> entsToRevoke) { for (Entitlement entitlement : entsToRevoke) { Consumer consumer = entitlement.getConsumer(); Event event = eventFactory.entitlementDeleted(entitlement); if (!entitlement.isValid() && entitlement.getPool().isUnmappedGuestPool() && consumerCurator.getHost(consumer.getFact("virt.uuid"), consumer.getOwner()) == null) { event = eventFactory.entitlementExpired(entitlement); event.setMessageText(event.getMessageText() + ": " + i18n .tr("Unmapped guest entitlement expired " + "without establishing a host/guest mapping.")); } sink.queueEvent(event); } }

Target:
private void sendDeletedEvents(List<Entitlement> entsToRevoke) { for (Entitlement entitlement : entsToRevoke) { Consumer consumer = entitlement.getConsumer(); Event event = eventFactory.entitlementDeleted(entitlement); if (!entitlement.isValid() && entitlement.getPool().isUnmappedGuestPool() && consumerCurator.getHost(consumer.getFact("virt.uuid"), consumer.getOwner()) == null) { event = eventFactory.entitlementExpired(entitlement); event.setMessageText(event.getMessageText() + ": " + i18n .tr("Unmapped guest entitlement expired without establishing a host/guest mapping.")); } sink.queueEvent(event); } }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); ISelection selection = HandlerUtil.getCurrentSelection(event); if(editor != null && selection != null) { if(selection instanceof ITextSelection) { ITextSelection text = (ITextSelection) selection; IEditorInput input = editor.getEditorInput(); if(input instanceof IFileEditorInput) { try { IFileEditorInput fileInput = (IFileEditorInput) input; IFile file = fileInput.getFile(); String fileExtension = file.getFileExtension(); String title = editor.getTitle(); Set<TaskRepository> repositories = TasksUi.getRepositoryManager().getRepositories(GitHub.CONNECTOR_KIND); TaskRepository repository = repositories.iterator().next(); GitHubService service = new GitHubService(); GitHubCredentials credentials = GitHubCredentials.create(repository); String url = service.createGist(title, fileExtension, text.getText(), credentials); Shell shell = HandlerUtil.getActiveShell(event); GistNotificationPopup popup = new GistNotificationPopup(shell.getDisplay(), url, title); popup.create(); popup.open(); } catch (GitHubServiceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editor = HandlerUtil.getActiveEditor(event); ISelection selection = HandlerUtil.getCurrentSelection(event); IStructuredSelection menuSelection = (IStructuredSelection) HandlerUtil .getActiveMenuSelection(event); if(selection != null && menuSelection == null) { if(selection instanceof ITextSelection) { ITextSelection text = (ITextSelection) selection; IEditorInput input = editor.getEditorInput(); if(input instanceof IFileEditorInput) { IFileEditorInput fileInput = (IFileEditorInput) input; IFile file = fileInput.getFile(); createGistJob(file.getName(), file.getFileExtension(), text.getText()); } } } if(menuSelection != null) { Object obj = menuSelection.getFirstElement(); if(obj instanceof IFile) { IFile file = (IFile) obj; createGistJob(file); } } return null; }
Source:
public boolean sendSerialData(XBee16BitAddress address, byte[] data) throws InvalidOperatingModeException, XBeeException { XBeePacket xbeePacket; XBeePacket receivedPacket; if (address == null || data == null) throw new XBeeException(XBeeException.INVALID_ARGUMENT, "Address and data cannot be null"); switch (getXBeeProtocol()) { case RAW_802_15_4: xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); receivedPacket = sendXBeePacket(xbeePacket); if (receivedPacket instanceof TXStatusPacket) { switch (((TXStatusPacket)receivedPacket).getStatus()) { case SUCCESS: return true; default: return false; } } else return false; default: xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); receivedPacket = sendXBeePacket(xbeePacket); if (receivedPacket instanceof TransmitStatusPacket) { switch (((TransmitStatusPacket)receivedPacket).getDeliveryStatus()) { case SUCCESS: return true; default: return false; } } else return false; } }

Target:
public boolean sendSerialData(XBee16BitAddress address, byte[] data) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); XBeePacket xbeePacket; XBeePacket receivedPacket; if (address == null || data == null) throw new XBeeException(XBeeException.INVALID_ARGUMENT, "Address and data cannot be null"); switch (getXBeeProtocol()) { case RAW_802_15_4: xbeePacket = new TX16Packet(getNextFrameID(), address, XBeeTransmitOptions.NONE, data); receivedPacket = sendXBeePacket(xbeePacket); if (receivedPacket == null) return true; if (receivedPacket instanceof TXStatusPacket) { switch (((TXStatusPacket)receivedPacket).getTransmitStatus()) { case SUCCESS: return true; default: return false; } } else return false; default: xbeePacket = new TransmitPacket(getNextFrameID(), XBee64BitAddress.UNKNOWN_ADDRESS, address, 0, XBeeTransmitOptions.NONE, data); receivedPacket = sendXBeePacket(xbeePacket); if (receivedPacket == null) return true; if (receivedPacket instanceof TransmitStatusPacket) { switch (((TransmitStatusPacket)receivedPacket).getTransmitStatus()) { case SUCCESS: return true; default: return false; } } else return false; } }
Source:
public void recreateConsumerOnServer(ClientConsumerInternal consumerInternal, long consumerId, boolean isSessionStarted) throws ActiveMQException { ClientSession.QueueQuery queueInfo = consumerInternal.getQueueInfo(); if (!queueInfo.isDurable()) { CreateQueueMessage_V2 createQueueRequest = new CreateQueueMessage_V2(queueInfo.getAddress(), queueInfo.getName(), queueInfo.getRoutingType(), queueInfo.getFilterString(), false, queueInfo.isTemporary(), queueInfo.getMaxConsumers(), queueInfo.isPurgeOnNoConsumers(), queueInfo.isAutoCreated(), false); sendPacketWithoutLock(sessionChannel, createQueueRequest); } SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(getConsumerID(consumerInternal), consumerInternal.getQueueName(), consumerInternal.getFilterString(), consumerInternal.isBrowseOnly(), false); sendPacketWithoutLock(sessionChannel, createConsumerRequest); int clientWindowSize = consumerInternal.getClientWindowSize(); if (clientWindowSize != 0) { SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), clientWindowSize); sendPacketWithoutLock(sessionChannel, packet); } else { SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), 1); sendPacketWithoutLock(sessionChannel, packet); } if (isSessionStarted) { SessionForceConsumerDelivery forceDel = new SessionForceConsumerDelivery(consumerId, consumerInternal.getForceDeliveryCount() - 1); sendPacketWithoutLock(sessionChannel, forceDel); } }

Target:
public void recreateConsumerOnServer(ClientConsumerInternal consumerInternal, long consumerId, boolean isSessionStarted) throws ActiveMQException { ClientSession.QueueQuery queueInfo = consumerInternal.getQueueInfo(); if (!queueInfo.isDurable()) { CreateQueueMessage_V2 createQueueRequest = new CreateQueueMessage_V2(queueInfo.getAddress(), queueInfo.getName(), queueInfo.getRoutingType(), queueInfo.getFilterString(), false, queueInfo.isTemporary(), queueInfo.getMaxConsumers(), queueInfo.isPurgeOnNoConsumers(), queueInfo.isAutoCreated(), false); sendPacketWithoutLock(sessionChannel, createQueueRequest); } SessionCreateConsumerMessage createConsumerRequest = new SessionCreateConsumerMessage(getConsumerID(consumerInternal), consumerInternal.getQueueName(), consumerInternal.getFilterString(), consumerInternal.isBrowseOnly(), false); sendPacketWithoutLock(sessionChannel, createConsumerRequest); int clientWindowSize = consumerInternal.getClientWindowSize(); if (clientWindowSize != 0) { SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), clientWindowSize); sendPacketWithoutLock(sessionChannel, packet); } else { SessionConsumerFlowCreditMessage packet = new SessionConsumerFlowCreditMessage(getConsumerID(consumerInternal), 1); sendPacketWithoutLock(sessionChannel, packet); } if (isSessionStarted && consumerInternal.getForceDeliveryCount() > 0) { SessionForceConsumerDelivery forceDel = new SessionForceConsumerDelivery(consumerId, consumerInternal.getForceDeliveryCount() - 1); sendPacketWithoutLock(sessionChannel, forceDel); } }
Source:
private void executeStreamer(IgniteZeroMqStreamer streamer, int clientSocket, byte[] topic) throws InterruptedException { streamer.setSingleTupleExtractor(new ZeroMqStringSingleTupleExtractor()); CacheListener listener = subscribeToPutEvents(); streamer.start(); startZeroMqClient(clientSocket, topic); CountDownLatch latch = listener.getLatch(); latch.await(); unsubscribeToPutEvents(listener); IgniteCache<Integer, String> cache = grid().cache(null); int testId = CACHE_ENTRY_COUNT - 1; String cachedValue = cache.get(testId); assertTrue(cachedValue != null && cachedValue.equals(String.valueOf(testId))); assertTrue(cache.size() == CACHE_ENTRY_COUNT); cache.clear(); }

Target:
private void executeStreamer(IgniteZeroMqStreamer streamer, int clientSocket, byte[] topic) throws Exception { streamer.setSingleTupleExtractor(new ZeroMqStringSingleTupleExtractor()); IgniteCache<Integer, String> cache = grid().cache(null); CacheListener listener = subscribeToPutEvents(); streamer.start(); assertEquals(0, cache.size(CachePeekMode.PRIMARY)); startZeroMqClient(clientSocket, topic); CountDownLatch latch = listener.getLatch(); latch.await(); unsubscribeToPutEvents(listener); int testId = CACHE_ENTRY_COUNT - 1; String cachedValue = cache.get(testId); assertTrue(cachedValue != null && cachedValue.equals(String.valueOf(testId))); assertTrue(cache.size() == CACHE_ENTRY_COUNT); cache.clear(); }
Source:
public EventTypeRepository eventTypeRepository() throws Exception { final EventTypeRepository dbRepo = new EventTypeDbRepository(jdbcTemplate, jsonConfig.jacksonObjectMapper()); final String connectString = zookeeperConfig.zooKeeperHolder().get().getZookeeperClient().getCurrentConnectionString(); final RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3); final CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy); client.start(); return new EventTypeCachedRepository(dbRepo, new EventTypeCache(dbRepo, client)); }

Target:
public EventTypeRepository eventTypeRepository() throws Exception { final EventTypeRepository dbRepo = new EventTypeDbRepository(jdbcTemplate, jsonConfig.jacksonObjectMapper()); final CuratorFramework client = zookeeperConfig.zooKeeperHolder().get(); final EventTypeCache cache = new EventTypeCache(dbRepo, client); return new CachingEventTypeRepository(dbRepo, cache); }
Source:
private void handleAccount(Account account) { if (account == null) { Logger.debug("Authentication failed."); return; } myAccount = account; if (account.isFirst()) { final CommandOutputBuffer co = new CommandOutputBuffer(this); handleBotCommand(new String[]{"show", "firsttime"}, co); if (account.isAdmin()) { sendBotMessage(""); handleBotCommand(new String[]{"show", "firsttime", "admin"}, co); } co.send(); } }

Target:
private void handleAccount(Account account) { if (account == null) { Logger.debug("Authentication failed."); return; } myAccount = account; if (account.isFirst()) { final CommandOutputBuffer co = new CommandOutputBuffer(this); handleBotCommand(new String[]{"show", "firsttime"}, co); if (account.isAdmin()) { sendBotMessage(""); handleBotCommand(new String[]{"show", "firsttime", "admin"}, co); } co.send(); } if (authenticator.getClientType() != null) { clientType = ClientType.getFromName(authenticator.getClientType().toLowerCase()); } }
Source:
private void addBulkMethodEntriesCount(BulkOps op, long count) { LongAdder current = bulkMethodEntries.get(op); if (current == null) { LongAdder newCount = new LongAdder(); current = bulkMethodEntries.putIfAbsent(op, newCount); if (current == null) { current = newCount; } } current.add(count); }

Target:
private void addBulkMethodEntriesCount(BulkOps op, long count) { bulkMethodEntries.get(op).add(count); }
Source:
public final int getSubPartitionIndex() { return subpartitionInfo.getSubPartitionIdx(); }

Target:
public int getSubPartitionIndex() { return subpartitionInfo.getSubPartitionIdx(); }
Source:
public void execute(QueryRunner prestoExecutor, DataSetup dataSetup) { List<Type> expectedTypes = inputs.stream().map(Input::getPrestoResultType).collect(toList()); List<Object> expectedResults = inputs.stream().map(Input::toPrestoQueryResult).collect(toList()); try (TestTable testTable = dataSetup.setupTestTable(unmodifiableList(inputs))) { MaterializedResult materializedRows = prestoExecutor.execute("SELECT * from " + testTable.getName()); assertEquals(materializedRows.getTypes(), expectedTypes); List<Object> actualResults = getOnlyElement(materializedRows).getFields(); assertEquals(actualResults.size(), expectedResults.size(), "lists don't have the same size"); for (int i = 0; i < expectedResults.size(); i++) { assertEquals(actualResults.get(i), expectedResults.get(i), format("Element %s", i)); } } }

Target:
public void execute(QueryRunner prestoExecutor, DataSetup dataSetup) { List<Type> expectedTypes = inputs.stream().map(Input::getPrestoResultType).collect(toList()); List<Object> expectedResults = inputs.stream().map(Input::toPrestoQueryResult).collect(toList()); try (TestTable testTable = dataSetup.setupTestTable(unmodifiableList(inputs))) { MaterializedResult materializedRows = prestoExecutor.execute("SELECT * from " + testTable.getName()); assertEquals(materializedRows.getTypes(), expectedTypes); List<Object> actualResults = getOnlyElement(materializedRows).getFields(); assertEquals(actualResults.size(), expectedResults.size(), "lists don't have the same size"); for (int i = 0; i < expectedResults.size(); i++) { assertEquals(actualResults.get(i), expectedResults.get(i), "Element " + i); } } }
Source:
public void addVirtSpecifier(ICPPASTVirtSpecifier virtSpecifier) { assertNotFrozen(); if (virtSpecifier != null) { assert virtSpecifiers != null; virtSpecifiers = ArrayUtil.append(virtSpecifiers, virtSpecifier); virtSpecifier.setParent(this); virtSpecifier.setPropertyInParent(EXCEPTION_TYPEID); } }

Target:
public void addVirtSpecifier(ICPPASTVirtSpecifier virtSpecifier) { assertNotFrozen(); if (virtSpecifier != null) { assert virtSpecifiers != null; virtSpecifiers = ArrayUtil.append(virtSpecifiers, virtSpecifier); virtSpecifier.setParent(this); virtSpecifier.setPropertyInParent(VIRT_SPECIFIER); } }
Source:
public void fetchMenu(long menuId) { String path = formatPath(MENU_REST_PATH, String.valueOf(menuId)); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { JSONObject menuObject = response.optJSONObject(MENU_KEY); mDelegate.onMenuReceived(HttpURLConnection.HTTP_OK, menuFromJson(menuObject)); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mDelegate.onMenuReceived(statusCodeFromVolleyError(error), null); } }); }

Target:
public int fetchMenu(long menuId) { if (menuId < 0) return -1; final int requestId = ++mRequestCounter; String path = formatPath(MENU_REST_PATH, String.valueOf(menuId)); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { MenuModel result = menuFromJson(response.optJSONObject(MENU_KEY)); List<MenuModel> resultList = new ArrayList<>(); if (result != null) resultList.add(result); mListener.onMenusReceived(requestId, resultList); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { int statusCode = statusCodeFromVolleyError(volleyError); REST_ERROR error = REST_ERROR.FETCH_ERROR; if (statusCode == HTTP_FORBIDDEN) error = REST_ERROR.AUTHENTICATION_ERROR; else if (statusCode == HTTP_BAD_REQUEST) error = REST_ERROR.RESERVED_ID_ERROR; mListener.onErrorResponse(requestId, error); } }); return requestId; }
Source:
private Config loadHazelcastConfig(GeoServerResourceLoader rl) throws IOException{ Resource hzf = getConfigFile(HAZELCAST_FILENAME, HzCluster.class); InputStream hzIn = hzf.in(); try { return new XmlConfigBuilder(hzIn).build(); } finally { hzIn.close(); } }

Target:
private Config loadHazelcastConfig(GeoServerResourceLoader rl) throws IOException{ Resource hzf = getConfigFile(HAZELCAST_FILENAME, HzCluster.class); try (InputStream hzIn = hzf.in()) { return new XmlConfigBuilder(hzIn).build(); } }
Source:
public void testClear() { serverStoreProxy.append(1L, createPayload(100L)); Chain chain = serverStoreProxy.get(1); assertThat(chain.isEmpty(), is(false)); assertThat(readPayLoad(chain.iterator().next().getPayload()), is(100L)); serverStoreProxy.clear(); chain = serverStoreProxy.get(1); assertThat(chain.isEmpty(), is(true)); }

Target:
public void testClear() { serverStoreProxy.append(1L, createPayload(100L)); serverStoreProxy.clear(); Chain chain = serverStoreProxy.get(1); assertThat(chain.isEmpty(), is(true)); }
Source:
public void setValueGenerator (ValueGenerator generator) { this.generator = generator; }

Target:
public void setValueGenerator (ValueGenerator generator) { if (generator == null){ throw new IllegalArgumentException("Parameter generator must not be null."); } this.generator = generator; }
Source:
public synchronized void cancelAllScheduledActions() { if (!isShuttingDown) { stopScheduler(); ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat(String.format(DEBOUNCE_THREAD_NAME_FORMAT)).setDaemon(true).build(); this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(threadFactory); } }

Target:
public synchronized void cancelAllScheduledActions() { if (!isShuttingDown) { futureHandles.keySet().forEach(this::tryCancelScheduledAction); futureHandles.clear(); } }
Source:
private COREEnvelopeRealTimeResponse buildAdapterCORE_X12DSRealTimeResponseMetadata() { COREEnvelopeRealTimeResponse oResponse = new COREEnvelopeRealTimeResponse(); oResponse.setPayloadType("X12_278_Response_005010X279A1"); oResponse.setProcessingMode("RealTime"); oResponse.setPayloadID("a81d44ae-7dec-11d0-a765-00a0c91e6ba0"); oResponse.setTimeStamp("2007-08-30T10:20:34Z"); oResponse.setSenderID("PayerB"); oResponse.setReceiverID("HospitalA"); oResponse.setCORERuleVersion("2.2.0"); oResponse.setPayload("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxDbGluaWNhbERvY3VtZW50\n" + "IG1vb2RDb2RlPSJFVk4iIHhtbG5zPSJ1cm46aGw3LW9yZzp2MyINCiAgICB4bWxuczp4c2k9Imh0"); oResponse.setErrorCode("Success"); oResponse.setErrorMessage(null); return oResponse; }

Target:
private COREEnvelopeRealTimeResponse buildAdapterCORE_X12DSRealTimeResponseMetadata() { COREEnvelopeRealTimeResponse oResponse = new COREEnvelopeRealTimeResponse(); oResponse.setPayloadType("X12_278_Response_005010X279A1"); oResponse.setProcessingMode("RealTime"); oResponse.setPayloadID("a81d44ae-7dec-11d0-a765-00a0c91e6ba0"); oResponse.setTimeStamp("2007-08-30T10:20:34Z"); oResponse.setSenderID("PayerB"); oResponse.setReceiverID("HospitalA"); oResponse.setCORERuleVersion("2.2.0"); oResponse.setPayload("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4NCjxDbGluaWNhbERvY3VtZW50\n" + "IG1vb2RDb2RlPSJFVk4iIHhtbG5zPSJ1cm46aGw3LW9yZzp2MyINCiAgICB4bWxuczp4c2k9Imh0"); oResponse.setErrorCode("Success"); oResponse.setErrorMessage("None"); return oResponse; }
Source:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { if (delta.getElement() instanceof ITask) { ITask updatedReview = (ITask) delta.getElement(); if (updatedReview != null && isTaskAssosciatedWithReviewConnector(updatedReview)) { SynchronizationState taskState = updatedReview.getSynchronizationState(); if (taskState.isIncoming()) { ITask assosciatedTask = getTasksAssociatedWithReviewTask(updatedReview); if (assosciatedTask != null) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedReview); } } } } }

Target:
public void containersChanged(Set<TaskContainerDelta> containers) { for (TaskContainerDelta delta : containers) { if (delta.getElement() instanceof ITask) { ITask updatedReview = (ITask) delta.getElement(); if (isTaskAssosciatedWithReviewConnector(updatedReview)) { SynchronizationState taskState = updatedReview.getSynchronizationState(); if (taskState.isIncoming()) { ITask assosciatedTask = getTaskAssociatedWithReviewTask(updatedReview); if (assosciatedTask != null) { updateTaskWithIncomingReviewState(assosciatedTask, true); } } else { forceFullRefreshFor(updatedReview); } } } } }
Source:
public Boolean checkUserDrinksCaffeine(final Long accountId) { final Optional<Response> optionalResponse = this.getSingleUserResponse(accountId, AccountInfo.Type.CAFFEINE); if(optionalResponse.isPresent()) { final String responseText = optionalResponse.get().response; if (responseText.equalsIgnoreCase("coffee")) { return true; } } return false; }

Target:
public Boolean checkUserDrinksCaffeine(final Long accountId) { final Optional<Response> optionalResponse = this.getSingleUserResponse(accountId, AccountInfo.Type.CAFFEINE); if(optionalResponse.isPresent()) { final String responseText = optionalResponse.get().response; if (responseText.equalsIgnoreCase(RESPONSE_DRINKS_COFFEE)) { return true; } } return false; }
Source:
public boolean equals(Object obj) { if (!(obj instanceof AuthorizationContext)) { return false; } return true; }

Target:
public boolean equals(Object obj) { if (obj == this) { return true; } else if (obj == null || getClass() != obj.getClass()) { return false; } AuthorizationContext other = (AuthorizationContext)obj; return getFsOwner().equals(other.getFsOwner()) && getSupergroup().equals(other.getSupergroup()) && getCallerUgi().equals(other.getCallerUgi()) && Arrays.deepEquals(getInodeAttrs(), other.getInodeAttrs()) && Arrays.deepEquals(getInodes(), other.getInodes()) && Arrays.deepEquals(getPathByNameArr(), other.getPathByNameArr()) && getSnapshotId() == other.getSnapshotId() && getPath().equals(other.getPath()) && getAncestorIndex() == other.getAncestorIndex() && isDoCheckOwner() == other.isDoCheckOwner() && getAncestorAccess() == other.getAncestorAccess() && getParentAccess() == other.getParentAccess() && getAccess() == other.getAccess() && getSubAccess() == other.getSubAccess() && isIgnoreEmptyDir() == other.isIgnoreEmptyDir(); }
Source:
public boolean deleteIndexNamed(final String indexName) throws CheckedQueryException { if (indexName == null || indexName.isEmpty()) { logger.log(Level.WARNING, "TO delete an index, index name should be provided."); return false; } Future<Boolean> result = dbQueue.submitTransaction(new SQLQueueCallable<Boolean>() { @Override public Boolean call(SQLDatabase database) throws Exception { String tableName = QueryConstants.tableNameForIndex(indexName); String sql = String.format("DROP TABLE \"%s\"", tableName); database.execSQL(sql); String where = " index_name = ? "; database.delete(QueryConstants.INDEX_METADATA_TABLE_NAME, where, new String[]{ indexName }); return Boolean.TRUE; } }); boolean success; try { success = result.get(); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Execution error during index deletion:", e); return false; } catch (InterruptedException e) { logger.log(Level.SEVERE, "Execution interrupted error during index deletion:", e); return false; } return success; }

Target:
public boolean deleteIndexNamed(final String indexName) throws CheckedQueryException { if (indexName == null || indexName.isEmpty()) { logger.log(Level.WARNING, "To delete an index, index name should be provided."); return false; } Future<Boolean> result = indexDbQueue.submitTransaction(new SQLQueueCallable<Boolean>() { @Override public Boolean call(SQLDatabase database) throws Exception { String tableName = QueryConstants.tableNameForIndex(indexName); String sql = String.format("DROP TABLE \"%s\"", tableName); database.execSQL(sql); String where = " index_name = ? "; database.delete(QueryConstants.INDEX_METADATA_TABLE_NAME, where, new String[]{ indexName }); return Boolean.TRUE; } }); boolean success; try { success = result.get(); } catch (ExecutionException e) { logger.log(Level.SEVERE, "Execution error during index deletion:", e); return false; } catch (InterruptedException e) { logger.log(Level.SEVERE, "Execution interrupted error during index deletion:", e); return false; } return success; }
Source:
private String shortenPackage(final String pkg) { final int sep = pkg.indexOf('/'); return sep == -1 ? "" : pkg.substring(sep + 1); }

Target:
private static String shortenPackage(final String pkg) { final int sep = pkg.indexOf('/'); return sep == -1 ? "" : pkg.substring(sep + 1); }
Source:
public void testTelemetryStoresUpAndDownEvents() throws Exception { TestUtils.assertMemoryLeak(() -> { serverConfiguration = new PropServerConfiguration(temp.getRoot().getAbsolutePath(), new Properties()) { @Override public CairoConfiguration getCairoConfiguration() { return new DefaultCairoConfiguration(root); } }; configuration = serverConfiguration.getCairoConfiguration(); messageBus = new MessageBusImpl(serverConfiguration); CairoEngine engine = new CairoEngine(configuration, messageBus); TelemetryJob telemetryJob = new TelemetryJob(serverConfiguration, engine, messageBus); Misc.free(telemetryJob); final String expectedEvent = "100\n" + "101\n"; assertColumn(expectedEvent, "telemetry", 1); final String expectedOrigin = "1\n" + "1\n"; assertColumn(expectedOrigin, "telemetry", 2); Misc.free(engine); }); }

Target:
public void testTelemetryStoresUpAndDownEvents() throws Exception { TestUtils.assertMemoryLeak(() -> { serverConfiguration = new PropServerConfiguration(temp.getRoot().getAbsolutePath(), new Properties()) { @Override public CairoConfiguration getCairoConfiguration() { return configuration; } }; configuration = serverConfiguration.getCairoConfiguration(); messageBus = new MessageBusImpl(serverConfiguration); CairoEngine engine = new CairoEngine(configuration, messageBus); TelemetryJob telemetryJob = new TelemetryJob(serverConfiguration, engine, messageBus); Misc.free(telemetryJob); final String expectedEvent = "100\n" + "101\n"; assertColumn(expectedEvent, "telemetry", 1); final String expectedOrigin = "1\n" + "1\n"; assertColumn(expectedOrigin, "telemetry", 2); Misc.free(engine); }); }
Source:
private void testFocus(final boolean withOOPath) { final String str = "package org.kie.test\n" + "global java.util.List list\n" + "rule rule1\n" + "agenda-group \"badfocus\"" + "when\n" + (withOOPath ? " Integer(/intValue{this > 0})\n" : " Integer(intValue > 0)\n") + "then\n" + " list.add( 1 );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); final KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); final List<?> list = new ArrayList<>(); ksession.setGlobal("list", list); ksession.insert(1); ksession.insert(2); ksession.insert(3); ksession.getAgenda().getAgendaGroup("badfocus").setFocus(); ksession.fireAllRules(); assertEquals(3, list.size()); }

Target:
private void testFocus(final boolean withOOPath) { final String str = "package org.kie.test\n" + "global java.util.List list\n" + "rule rule1\n" + "agenda-group \"badfocus\"" + "when\n" + (withOOPath ? " Integer(/intValue{this > 0})\n" : " Integer(intValue > 0)\n") + "then\n" + " list.add( 1 );\n" + "end\n" + "\n"; final KieBase kbase = new KieHelper().addContent(str, ResourceType.DRL).build(); final KieSession ksession = KieServices.get().getStoreServices().newKieSession(kbase, null, env); final List<Integer> list = new ArrayList<>(); ksession.setGlobal("list", list); insertIntRange(ksession, 1, 3); ksession.getAgenda().getAgendaGroup("badfocus").setFocus(); ksession.fireAllRules(); assertThat(list).hasSize(3); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inventory_explorer); toolbar = (Toolbar) findViewById(R.id.toolbar); callback = new PerformOperationCallback(); setUpToolbar(); ViewGroup containerView = (ViewGroup) findViewById(R.id.container); root = TreeNode.root(); holder = root.getViewHolder(); tView = new AndroidTreeView(this, root); tView.setDefaultAnimation(true); tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom); tView.setDefaultViewHolder(IconTreeItemHolder.class); tView.setDefaultNodeClickListener(nodeClickListener); tView.setDefaultNodeLongClickListener(nodeLongClickListener); containerView.addView(tView.getView()); BackendClient.of(this).getFeeds(new FeedsCallback()); if (savedInstanceState != null) { String state = savedInstanceState.getString("tState"); if (!TextUtils.isEmpty(state)) { tView.restoreState(state); } } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_inventory_explorer); callback = new PerformOperationCallback(); setUpBindings(); setUpToolbar(); ViewGroup containerView = (ViewGroup) findViewById(R.id.container); root = TreeNode.root(); holder = root.getViewHolder(); tView = new AndroidTreeView(this, root); tView.setDefaultAnimation(true); tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom); tView.setDefaultViewHolder(IconTreeItemHolder.class); tView.setDefaultNodeClickListener(nodeClickListener); tView.setDefaultNodeLongClickListener(nodeLongClickListener); containerView.addView(tView.getView()); BackendClient.of(this).getFeeds(new FeedsCallback()); if (savedInstanceState != null) { String state = savedInstanceState.getString("tState"); if (!TextUtils.isEmpty(state)) { tView.restoreState(state); } } }
Source:
protected void onPause() { if(isReceiverRegistered) { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); isReceiverRegistered =false; } super.onPause(); }

Target:
protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver); isReceiverRegistered = false; super.onPause(); }
Source:
public void onChange(ConfigChangeEvent changeEvent) { System.out.println("Changes for namespace " + changeEvent.getNamespace()); for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); if (change.getPropertyName().equals(url.getServiceKey() + Constants.CONFIGURATORS_SUFFIX)) { listener.process(change.getNewValue(), ConfigType.CONFIGURATORS, getChangeType(change.getChangeType())); } else if (change.getPropertyName().equals(url.getParameter(Constants.APPLICATION_KEY) + Constants.CONFIGURATORS_SUFFIX)) { listener.process(change.getNewValue(), ConfigType.CONFIGURATORS, getChangeType(change.getChangeType())); } else if (change.getPropertyName().equals(url.getServiceKey() + Constants.ROUTERS_SUFFIX)) { listener.process(change.getNewValue(), ConfigType.ROUTERS, getChangeType(change.getChangeType())); } System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType())); } }

Target:
public void onChange(ConfigChangeEvent changeEvent) { for (String key : changeEvent.changedKeys()) { ConfigChange change = changeEvent.getChange(key); if (change.getPropertyName().endsWith(Constants.CONFIGURATORS_SUFFIX)) { listener.process(new org.apache.dubbo.config.dynamic.ConfigChangeEvent(key, change.getNewValue(), ConfigType.CONFIGURATORS, getChangeType(change.getChangeType()))); } else if (change.getPropertyName().endsWith(Constants.ROUTERS_SUFFIX)) { listener.process(new org.apache.dubbo.config.dynamic.ConfigChangeEvent(key, change.getNewValue(), ConfigType.ROUTERS, getChangeType(change.getChangeType()))); } } }
Source:
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command, ResponseCollector<T> collector, DeliverOrder deliverOrder, long timeout, TimeUnit unit) { long requestId = requests.newRequestId(); logRequest(requestId, command, targets); if (targets.isEmpty()) { return CompletableFuture.completedFuture(collector.finish()); } Address excludedTarget = deliverOrder == DeliverOrder.TOTAL ? null : getAddress(); MultiTargetRequest<T> request = new MultiTargetRequest<>(collector, requestId, requests, targets, excludedTarget); if (!request.isDone()) { try { addRequest(request); boolean checkView = request.onNewView(clusterView.getMembersSet()); sendCommand(targets, command, requestId, deliverOrder, isRsvpCommand(command), checkView); } catch (Throwable t) { request.cancel(true); throw t; } if (timeout > 0) { request.setTimeout(timeoutExecutor, timeout, unit); } } return request; }

Target:
public <T> CompletionStage<T> invokeCommand(Collection<Address> targets, ReplicableCommand command, ResponseCollector<T> collector, DeliverOrder deliverOrder, long timeout, TimeUnit unit) { long requestId = requests.newRequestId(); logRequest(requestId, command, targets); if (targets.isEmpty()) { return CompletableFuture.completedFuture(collector.finish()); } Address excludedTarget = deliverOrder == DeliverOrder.TOTAL ? null : getAddress(); MultiTargetRequest<T> request = new MultiTargetRequest<>(collector, requestId, requests, targets, excludedTarget); if (request.isDone()) { return request; } try { addRequest(request); boolean checkView = request.onNewView(clusterView.getMembersSet()); sendCommand(targets, command, requestId, deliverOrder, isRsvpCommand(command), checkView); } catch (Throwable t) { request.cancel(true); throw t; } if (timeout > 0) { request.setTimeout(timeoutExecutor, timeout, unit); } return request; }
Source:
void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> throwables.assertHasMessageNotContaining(someInfo(), null, "Throwable")) .withMessage(actualIsNull()); }

Target:
void should_fail_if_actual_is_null() { assertThatAssertionErrorIsThrownBy( () -> throwables.assertHasMessageNotContaining(someInfo(), null, "Throwable")) .withMessage(actualIsNull()); }
Source:
public void testThrottlingWhenAllJobsAreKnown() { final int NUM_JOBS = 100; final int MAX_THREADS = 10; TestJob[] jobs = new TestJob[NUM_JOBS]; final JobGroup jobGroup = new JobGroup("JobGroup", MAX_THREADS, NUM_JOBS); final int[] maxThreadsUsed = new int[1]; final TestBarrier barrier = new TestBarrier(); for (int i = 0; i < NUM_JOBS; i++) { jobs[i] = new TestJob("TestJob", 1000000, 10); jobs[i].setJobGroup(jobGroup); jobs[i].schedule(); } maxThreadsUsed[0] = 0; final Thread t = new Thread(() -> { barrier.setStatus(TestBarrier.STATUS_RUNNING); while (jobGroup.getState() != JobGroup.NONE) { List<TestJob> runningJobs = new ArrayList<>(); for (Job job1 : jobGroup.getActiveJobs()) { if (job1.getState() == Job.RUNNING) { runningJobs.add((TestJob) job1); } } int runningJobsSize = runningJobs.size(); if (runningJobsSize > maxThreadsUsed[0]) { maxThreadsUsed[0] = runningJobsSize; } for (Job job2 : runningJobs) { job2.cancel(); waitForCompletion(job2); } } barrier.setStatus(TestBarrier.STATUS_DONE); }); assertEquals("1.0", JobGroup.ACTIVE, jobGroup.getState()); t.start(); barrier.waitForStatus(TestBarrier.STATUS_RUNNING); barrier.waitForStatus(TestBarrier.STATUS_DONE); assertEquals("2.0", JobGroup.NONE, jobGroup.getState()); assertTrue("3.0", maxThreadsUsed[0] > 0); assertTrue("4.0", maxThreadsUsed[0] <= MAX_THREADS); }

Target:
public void testThrottlingWhenAllJobsAreKnown() { final int NUM_JOBS = 100; final int MAX_THREADS = 10; TestJob[] jobs = new TestJob[NUM_JOBS]; final JobGroup jobGroup = new JobGroup("JobGroup", MAX_THREADS, NUM_JOBS); final int[] maxThreadsUsed = new int[1]; final TestBarrier barrier = new TestBarrier(); for (int i = 0; i < NUM_JOBS; i++) { jobs[i] = new TestJob("TestJob", 1000000, 10); jobs[i].setJobGroup(jobGroup); jobs[i].schedule(); } maxThreadsUsed[0] = 0; final Thread t = new Thread(() -> { barrier.setStatus(TestBarrier.STATUS_RUNNING); while (jobGroup.getState() != JobGroup.NONE) { List<TestJob> runningJobs = new ArrayList<>(); for (Job activeJob : jobGroup.getActiveJobs()) { if (activeJob.getState() == Job.RUNNING) { runningJobs.add((TestJob) activeJob); } } int runningJobsSize = runningJobs.size(); if (runningJobsSize > maxThreadsUsed[0]) { maxThreadsUsed[0] = runningJobsSize; } for (Job runningJob : runningJobs) { runningJob.cancel(); waitForCompletion(runningJob); } } barrier.setStatus(TestBarrier.STATUS_DONE); }); assertEquals("1.0", JobGroup.ACTIVE, jobGroup.getState()); t.start(); barrier.waitForStatus(TestBarrier.STATUS_RUNNING); barrier.waitForStatus(TestBarrier.STATUS_DONE); assertEquals("2.0", JobGroup.NONE, jobGroup.getState()); assertTrue("3.0", maxThreadsUsed[0] > 0); assertTrue("4.0", maxThreadsUsed[0] <= MAX_THREADS); }
Source:
public synchronized CompletableFuture<Void> stop() { if (closeFuture != null) { return closeFuture; } metadataService.removeNode(clusterService.getLocalNode()); closeFuture = primitives.stop() .thenComposeAsync(v -> partitions.close(), context) .thenComposeAsync(v -> corePartitionGroup.close(), context) .thenComposeAsync(v -> clusterMessagingService.stop(), context) .thenComposeAsync(v -> clusterEventingService.stop(), context) .thenComposeAsync(v -> clusterService.stop(), context) .thenComposeAsync(v -> metadataService.stop(), context) .thenComposeAsync(v -> messagingService.stop(), context) .thenRunAsync(() -> { executorService.shutdown(); context.close(); started.set(false); LOGGER.info("Stopped"); }); return closeFuture; }

Target:
public synchronized CompletableFuture<Void> stop() { if (shutdownHook != null) { try { Runtime.getRuntime().removeShutdownHook(shutdownHook); shutdownHook = null; } catch (IllegalStateException e) { } } return doStop(); }
Source:
protected String enableLogicalVolume(String lvName) throws EucalyptusCloudException { EucalyptusCloudException ex = null; String result = null; int attempt = 1; final int max_attempts = 9; int timeout = 10; final int timeout_multiplier = 4; do { try { result = LVMWrapper.enableLogicalVolume(lvName); if (attempt > 1) { LOG.info("Enabling " + lvName + "succeeded on retry."); } } catch (EucalyptusCloudException ece) { ex = ece; LOG.error(ece + ", retrying..."); LVMWrapper.scanPhysicalVolume(lvName); try { Thread.sleep(timeout); } catch (InterruptedException ie) { LOG.error(ie); break; } timeout *= timeout_multiplier; } } while (attempt++ < max_attempts); if (ex != null) { throw ex; } return result; }

Target:
protected String enableLogicalVolume(String lvName) throws EucalyptusCloudException { EucalyptusCloudException ex = null; String result = null; int attempt = 1; final int max_attempts = 9; int timeout = 10; final int timeout_multiplier = 4; do { try { LOG.trace("Enabling logical volume " + lvName + ", attempt " + attempt); result = LVMWrapper.enableLogicalVolume(lvName); ex = null; if (attempt > 1) { LOG.info("Enabling " + lvName + "succeeded on retry attempt " + attempt); } } catch (EucalyptusCloudException ece) { ex = ece; LOG.warn("Failed to enable logical volume " + lvName + " on attempt " + attempt, ece); LVMWrapper.scanPhysicalVolume(lvName); try { Thread.sleep(timeout); } catch (InterruptedException ie) { LOG.error(ie); break; } timeout *= timeout_multiplier; } } while (attempt++ < max_attempts); if (ex != null) { LOG.error("Failed to enable logical volume " + lvName + ", all retries exhausted."); throw ex; } return result; }
Source:
private MapContext prepareContext(Position position) { MapContext result = new MapContext(); Method[] methods = position.getClass().getMethods(); for (Method method : methods) { if (method.getName().startsWith("get") && method.getParameterTypes().length == 0 && !method.getName().equals("getClass")) { String name = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); try { if (!method.getReturnType().equals(Map.class)) { result.set(name, method.invoke(position)); } else { for (Object key : ((Map) method.invoke(position)).keySet()) { result.set((String) key, ((Map) method.invoke(position)).get(key)); } } } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } } return result; }

Target:
private MapContext prepareContext(Position position) { MapContext result = new MapContext(); Set<Method> methods = new HashSet<>(Arrays.asList(position.getClass().getMethods())); methods.removeAll(Arrays.asList(Object.class.getMethods())); for (Method method : methods) { if (method.getName().startsWith("get") && method.getParameterTypes().length == 0) { String name = Character.toLowerCase(method.getName().charAt(3)) + method.getName().substring(4); try { if (!method.getReturnType().equals(Map.class)) { result.set(name, method.invoke(position)); } else { for (Object key : ((Map) method.invoke(position)).keySet()) { result.set((String) key, ((Map) method.invoke(position)).get(key)); } } } catch (IllegalAccessException | InvocationTargetException error) { Log.warning(error); } } } return result; }