auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
ShardRewriter createShardRewriter( FileSystemContext fileSystemContext, FileSystem fileSystem, long transactionId, OptionalInt bucketNumber, UUID shardUuid, int shardRowCount, Optional<UUID> deltaShardUuid, boolean tableSupportsDeltaDelete, Map<String, Type> columns) { if (tableSupportsDeltaDelete) { return new DeltaShardRewriter( shardUuid, shardRowCount, deltaShardUuid, deletionExecutor, uuid -> this.getRowsFromUuid(fileSystem, uuid), (columnIds, columnTypes) -> this.createStoragePageSink( fileSystemContext, transactionId, bucketNumber, columnIds, columnTypes, true)); } else { return new InplaceShardRewriter( fileSystem, transactionId, bucketNumber, shardUuid, columns, deletionExecutor, nodeId, this, storageService, shardRecorder, backupManager); } }

Target:
ShardRewriter createShardRewriter( FileSystemContext fileSystemContext, FileSystem fileSystem, long transactionId, OptionalInt bucketNumber, UUID shardUuid, int shardRowCount, Optional<UUID> deltaShardUuid, boolean tableSupportsDeltaDelete, Map<String, Type> columns) { if (tableSupportsDeltaDelete) { return new DeltaShardRewriter( shardUuid, shardRowCount, deltaShardUuid, deletionExecutor, transactionId, bucketNumber, this, fileSystemContext, fileSystem); } return new InplaceShardRewriter( shardUuid, columns, deletionExecutor, transactionId, bucketNumber, nodeId, this, fileSystem, storageService, shardRecorder, backupManager); }
Source:
private Map<String, Pair<NodeTemplate, String>> getOfferingsFromDiscoverer() throws IOException { String idsString = discovererClient.getRequest("discoverer/fetch", Collections.EMPTY_LIST); String[] discoveredIds = discovererClient.getObjectFromJson(idsString, String[].class); Map<String, Pair<NodeTemplate, String>> offerings = new HashMap<>(); for(String offerId:discoveredIds) { ArrayList<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("oid", offerId)); Pair<String, String> discovererResponse = discovererClient.postRequestWithParams("discoverer/fetch", params); if(discovererResponse.first.equals("200")){ String offerStr = discovererResponse.second; Offering offer = discovererClient.getObjectFromJson(offerStr, Offering.class); try { NodeTemplate nt = ToscaSerializer.fromTOSCA(offer.offering).getResult().getTopology().getNodeTemplates().values().iterator().next(); offerings.put(offerId, new Pair<NodeTemplate, String>(nt, offer.offering)); }catch (ParsingException e){ } } } return offerings; }

Target:
private Map<String, Pair<NodeTemplate, String>> getOfferingsFromDiscoverer() throws IOException { ObjectMapper mapper = new ObjectMapper(); String idsString = discovererClient.getRequest("fetch", Collections.EMPTY_LIST); String[] discoveredIds = mapper.readValue(idsString, String[].class); Map<String, Pair<NodeTemplate, String>> offerings = new HashMap<>(); for(String offerId:discoveredIds) { ArrayList<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("oid", offerId)); Pair<String, String> discovererResponse = discovererClient.postRequestWithParams("fetch", params); if(discovererResponse.first.equals("200")){ String offerStr = discovererResponse.second; Offering offer = mapper.readValue(offerStr, Offering.class); try { NodeTemplate nt = ToscaSerializer.fromTOSCA(offer.offering).getResult().getTopology().getNodeTemplates().values().iterator().next(); offerings.put(offerId, new Pair<NodeTemplate, String>(nt, offer.offering)); }catch (ParsingException e){ } } } return offerings; }
Source:
public void publish(List<? extends EventMessage<?>> events) { Stream<MessageMonitor.MonitorCallback> ingested = events.stream().map(messageMonitor::onMessageIngested); if (CurrentUnitOfWork.isStarted()) { UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Assert.state(!unitOfWork.phase().isAfter(PREPARE_COMMIT), () -> "It is not allowed to publish events when the current Unit of Work has already been " + "committed. Please start a new Unit of Work before publishing events."); Assert.state(!unitOfWork.root().phase().isAfter(PREPARE_COMMIT), () -> "It is not allowed to publish events when the root Unit of Work has already been " + "committed."); unitOfWork.afterCommit(u -> ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess)); unitOfWork.onRollback( u -> ingested.forEach(m -> m.reportFailure(u.getExecutionResult().getExceptionResult())) ); eventsQueue(unitOfWork).addAll(events); } else { try { prepareCommit(intercept(events)); commit(events); afterCommit(events); ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess); } catch (Exception e) { ingested.forEach(m -> m.reportFailure(e)); throw e; } } }

Target:
public void publish(List<? extends EventMessage<?>> events) { Stream<MessageMonitor.MonitorCallback> ingested = events.stream().map(messageMonitor::onMessageIngested); if (CurrentUnitOfWork.isStarted()) { UnitOfWork<?> unitOfWork = CurrentUnitOfWork.get(); Assert.state(!unitOfWork.phase().isAfter(PREPARE_COMMIT), () -> "It is not allowed to publish events when the current Unit of Work has already been " + "committed. Please start a new Unit of Work before publishing events."); Assert.state(!unitOfWork.root().phase().isAfter(PREPARE_COMMIT), () -> "It is not allowed to publish events when the root Unit of Work has already been " + "committed."); unitOfWork.afterCommit(u -> ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess)); unitOfWork.onRollback(uow -> ingested.forEach( message -> message.reportFailure(uow.getExecutionResult().getExceptionResult()) )); eventsQueue(unitOfWork).addAll(events); } else { try { prepareCommit(intercept(events)); commit(events); afterCommit(events); ingested.forEach(MessageMonitor.MonitorCallback::reportSuccess); } catch (Exception e) { ingested.forEach(m -> m.reportFailure(e)); throw e; } } }
Source:
public void testGrabChecksumFromDockerHub() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); ContainersApi toolApi = new ContainersApi(webClient); ContainertagsApi toolTagsApi = new ContainertagsApi(webClient); DockstoreTool tool = createManualDockerHubTool(); tool.setDefaultDockerfilePath("/Dockerfile"); tool.setDefaultCwlPath("/Docstore.cwl"); tool = toolApi.registerManual(tool); tool = addDockerHubTag(tool, toolTagsApi, toolApi); List<Tag> tags = verifyChecksumsAreSaved(toolApi, tool); refreshAfterDeletedTag(toolApi, tool, tags); }

Target:
public void testGrabChecksumFromDockerHub() { final ApiClient webClient = getWebClient(USER_2_USERNAME, testingPostgres); ContainersApi toolApi = new ContainersApi(webClient); ContainertagsApi toolTagsApi = new ContainertagsApi(webClient); DockstoreTool tool = createManualDockerHubTool(); tool.setDefaultDockerfilePath("/Dockerfile"); tool.setDefaultCwlPath("/Docstore.cwl"); tool = toolApi.registerManual(tool); tool = addDockerHubTag(tool, toolTagsApi, toolApi); List<Tag> tags = toolApi.getContainer(tool.getId(), null).getWorkflowVersions(); verifyChecksumsAreSaved(tags); refreshAfterDeletedTag(toolApi, tool, tags); testingPostgres.runUpdateStatement("update tool set name = 'thisnamedoesnotexist' where giturl = 'git@bitbucket.org:dockstoretestuser2/dockstore-whalesay-2.git'"); toolApi.refresh(tool.getId()); List<Tag> updatedTags = toolApi.getContainer(tool.getId(), null).getWorkflowVersions(); verifyChecksumsAreSaved(updatedTags); }
Source:
private void addTreeViewerBranch(ITmfStateSystem stateSystem, TmfTreeViewerEntry rootBranch, String branchName) { try { int quark = stateSystem.optQuarkAbsolute(branchName); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE && !stateSystem.getSubAttributes(quark, false).isEmpty()) { TmfTreeViewerEntry branch = new TmfTreeViewerEntry(branchName); rootBranch.addChild(branch); addTreeViewerEntries(stateSystem, branch, stateSystem.getQuarkAbsolute(branchName)); } } catch (AttributeNotFoundException e) { LOGGER.log(Level.WARNING, e::getLocalizedMessage); } }

Target:
private void addTreeViewerBranch(ITmfStateSystem stateSystem, TmfTreeViewerEntry rootBranch, String branchName) { int quark = stateSystem.optQuarkAbsolute(branchName); if (quark != ITmfStateSystem.INVALID_ATTRIBUTE && !stateSystem.getSubAttributes(quark, false).isEmpty()) { TmfTreeViewerEntry branch = new TmfTreeViewerEntry(branchName); rootBranch.addChild(branch); addTreeViewerEntries(stateSystem, branch, quark); } }
Source:
public boolean checkCell(Cell cell) { boolean valid = true; try { Comparable value = column.castValue(cell.value.toString()); if (value.compareTo(column.castValue(threashold)) > 0) valid = false; } catch (InvalidCastException | ConstraintsException e) { valid = false; } return valid; }

Target:
public boolean checkCell(Cell cell) { boolean valid = true; try { Comparable value = column.castValue(cell.value.toString()); if (value.compareTo(column.castValue(threshold)) > 0) valid = false; } catch (InvalidCastException | ConstraintsException e) { valid = false; } return valid; }
Source:
protected Object execute(Object blobInput, String chainOrOperationId, CoreSession session, Map<String, Object> contextParams, Map<String, Object> operationParams) { if (contextParams == null) { contextParams = new HashMap<>(); } if (operationParams == null) { operationParams = new HashMap<>(); } OperationContext ctx = new OperationContext(session); AutomationServer server = Framework.getLocalService(AutomationServer.class); RestBinding binding = server.getOperationBinding(chainOrOperationId); Principal principal = ctx.getPrincipal(); if (binding != null && binding.isAdministrator()) { if (!(principal instanceof NuxeoPrincipal) || !((NuxeoPrincipal) principal).isAdministrator()) { String message = "Not allowed. You must be administrator to use this operation"; log.error(message); throw new WebSecurityException(message); } } ctx.setInput(blobInput); ctx.putAll(contextParams); try { Object result = null; AutomationService as = Framework.getLocalService(AutomationService.class); result = as.run(ctx, chainOrOperationId, operationParams); return result; } catch (OperationException e) { log.error("Error while executing automation batch ", e); throw new NuxeoException(e); } }

Target:
protected Object execute(Object blobInput, String chainOrOperationId, CoreSession session, Map<String, Object> contextParams, Map<String, Object> operationParams) { if (contextParams == null) { contextParams = new HashMap<>(); } if (operationParams == null) { operationParams = new HashMap<>(); } OperationContext ctx = new OperationContext(session); AutomationServer server = Framework.getService(AutomationServer.class); RestBinding binding = server.getOperationBinding(chainOrOperationId); if (binding != null && binding.isAdministrator()) { Principal principal = ctx.getPrincipal(); if (!(principal instanceof NuxeoPrincipal && ((NuxeoPrincipal) principal).isAdministrator())) { String message = "Not allowed. You must be administrator to use this operation"; log.error(message); throw new WebSecurityException(message); } } ctx.setInput(blobInput); ctx.putAll(contextParams); try { Object result = null; AutomationService as = Framework.getLocalService(AutomationService.class); result = as.run(ctx, chainOrOperationId, operationParams); return result; } catch (OperationException e) { log.error("Error while executing automation batch ", e); throw new NuxeoException(e); } }
Source:
public boolean provides(final IOperation operation) { boolean provide = false; String currentDiagramType; final EObject referenceElement = ((View) ((CreateEditPoliciesOperation) operation).getEditPart().getModel()).getElement(); if (((((CreateEditPoliciesOperation) operation).getEditPart() instanceof NodeEditPart) && (operation instanceof CreateEditPoliciesOperation) && (referenceElement instanceof CallBehaviorAction))) { currentDiagramType = ((View) ((CreateEditPoliciesOperation) operation).getEditPart().getModel()).getDiagram().getType(); if ((diagramType != null) && (diagramType.equals(currentDiagramType))) { provide = true; } else { provide = false; } } return provide; }

Target:
public boolean provides(final IOperation operation) { boolean provide = false; String currentDiagramType; final EObject referenceElement = ((View) ((CreateEditPoliciesOperation) operation).getEditPart().getModel()).getElement(); if (((((CreateEditPoliciesOperation) operation).getEditPart() instanceof NodeEditPart) && (operation instanceof CreateEditPoliciesOperation) && (referenceElement instanceof CallBehaviorAction))) { currentDiagramType = ((View) ((CreateEditPoliciesOperation) operation).getEditPart().getModel()).getDiagram().getType(); if ((null != diagramType) && (diagramType.equals(currentDiagramType))) { provide = true; } else { provide = false; } } return provide; }
Source:
public static void deleteSubscription(final BlockingSphereClient client, final Subscription subscription) { if (subscription != null) { Subscription subs = client.executeBlocking(SubscriptionDeleteCommand.of(subscription)); } }

Target:
public static void deleteSubscription(final BlockingSphereClient client, final Subscription subscription) { if (subscription != null) { client.executeBlocking(SubscriptionDeleteCommand.of(subscription)); } }
Source:
public boolean matches(RelOptRuleCall call) { FlinkLogicalAggregate agg = call.rel(0); List<AggregateCall> aggCalls = agg.getAggCallList(); boolean existPandasFunction = false; boolean existGeneralPythonFunction = false; boolean existJavaFunction = false; for (AggregateCall aggCall : aggCalls) { SqlAggFunction aggregation = aggCall.getAggregation(); if (aggregation instanceof AggSqlFunction) { ImperativeAggregateFunction<?, ?> func = ((AggSqlFunction) aggregation).aggregateFunction(); if (func instanceof PythonFunction) { PythonFunction pythonFunction = (PythonFunction) func; if (pythonFunction.getPythonFunctionKind() == PythonFunctionKind.PANDAS) { existPandasFunction = true; } else { existGeneralPythonFunction = true; } } else { existJavaFunction = true; } } } if (existPandasFunction) { if (existGeneralPythonFunction) { throw new TableException("Pandas UDAF cannot be computed with General Python UDAF currently"); } if (existJavaFunction) { throw new TableException("Pandas UDAF cannot be computed with Java/Scala UDAF currently"); } } return existPandasFunction || existGeneralPythonFunction; }

Target:
public boolean matches(RelOptRuleCall call) { FlinkLogicalAggregate agg = call.rel(0); List<AggregateCall> aggCalls = agg.getAggCallList(); boolean existGeneralPythonFunction = aggCalls.stream().anyMatch(x -> PythonUtil.isPythonAggregate(x, PythonFunctionKind.GENERAL)); boolean existPandasFunction = aggCalls.stream().anyMatch(x -> PythonUtil.isPythonAggregate(x, PythonFunctionKind.PANDAS)); boolean existJavaFunction = aggCalls.stream().noneMatch(x -> PythonUtil.isPythonAggregate(x, null)); if (existPandasFunction || existGeneralPythonFunction) { if (existJavaFunction) { throw new TableException("Python UDAF and Java/Scala UDAF cannot be used together."); } if (existPandasFunction && existGeneralPythonFunction) { throw new TableException("Pandas UDAF and non-Pandas UDAF cannot be used together."); } return true; } else { return false; } }
Source:
synchronized boolean startAdb() { if (mAdbOsLocation == null) { Log.e(ADB, "Cannot start adb when AndroidDebugBridge is created without the location of adb."); return false; } Process proc; int status = -1; try { String[] command = new String[2]; command[0] = mAdbOsLocation; command[1] = "start-server"; Log.d(DDMS, String.format("Launching '%1$s %2$s' to ensure ADB is running.", mAdbOsLocation, command[1])); ProcessBuilder processBuilder = new ProcessBuilder(command); if (DdmPreferences.getUseAdbHost()) { String adbHostValue = DdmPreferences.getAdbHostValue(); if (adbHostValue != null && !"".equals(adbHostValue)) { Map<String, String> env = processBuilder.environment(); env.put("ADBHOST", adbHostValue); } } proc = processBuilder.start(); ArrayList<String> errorOutput = new ArrayList<String>(); ArrayList<String> stdOutput = new ArrayList<String>(); status = grabProcessOutput(proc, errorOutput, stdOutput, false ); } catch (IOException ioe) { Log.d(DDMS, "Unable to run 'adb': " + ioe.getMessage()); } catch (InterruptedException ie) { Log.d(DDMS, "Unable to run 'adb': " + ie.getMessage()); } if (status != 0) { Log.w(DDMS, "'adb start-server' failed -- run manually if necessary"); return false; } Log.d(DDMS, "'adb start-server' succeeded"); return true; }

Target:
synchronized boolean startAdb() { if (mAdbOsLocation == null) { Log.e(ADB, "Cannot start adb when AndroidDebugBridge is created without the location of adb."); return false; } Process proc; int status = -1; try { String[] command = new String[2]; command[0] = mAdbOsLocation; command[1] = "start-server"; Log.d(DDMS, String.format("Launching '%1$s %2$s' to ensure ADB is running.", mAdbOsLocation, command[1])); ProcessBuilder processBuilder = new ProcessBuilder(command); if (DdmPreferences.getUseAdbHost()) { String adbHostValue = DdmPreferences.getAdbHostValue(); if (adbHostValue != null && adbHostValue.length() > 0) { Map<String, String> env = processBuilder.environment(); env.put("ADBHOST", adbHostValue); } } proc = processBuilder.start(); ArrayList<String> errorOutput = new ArrayList<String>(); ArrayList<String> stdOutput = new ArrayList<String>(); status = grabProcessOutput(proc, errorOutput, stdOutput, false ); } catch (IOException ioe) { Log.d(DDMS, "Unable to run 'adb': " + ioe.getMessage()); } catch (InterruptedException ie) { Log.d(DDMS, "Unable to run 'adb': " + ie.getMessage()); } if (status != 0) { Log.w(DDMS, "'adb start-server' failed -- run manually if necessary"); return false; } Log.d(DDMS, "'adb start-server' succeeded"); return true; }
Source:
private void addFootnoteRef(MacroMarkerBlock footnoteMacro, Block footnoteRef) { for (ListIterator<Block> it = footnoteMacro.getChildren().listIterator(); it.hasNext();) { it.next(); it.remove(); } footnoteMacro.addChild(footnoteRef); }

Target:
private void addFootnoteRef(MacroMarkerBlock footnoteMacro, Block footnoteRef) { footnoteMacro.getChildren().clear(); footnoteMacro.addChild(footnoteRef); }
Source:
public void testLoadSingle() { storage.reloadTemplateMaps();; ServerTemplate toSearchFor = getFirstTemplateFromMap(); loadTemplateWithAssertEquals(toSearchFor); }

Target:
public void testLoadSingle() { storage.reloadTemplateMaps(); ServerTemplate toSearchFor = getFirstTemplateFromMap(); loadTemplateWithAssertEquals(toSearchFor); }
Source:
private boolean waitForProcessCompletion(IOException originalError) { try { if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) { setError(originalError, MessageFormat.format( JGitText.get().commandClosedStderrButDidntExit, desc, PROCESS_EXIT_TIMEOUT), -1); fail.set(true); return false; } } catch (InterruptedException e) { LOG.error(MessageFormat.format( JGitText.get().threadInterruptedWhileRunning, desc), e); } return true; }

Target:
private boolean waitForProcessCompletion(IOException originalError) { try { if (!p.waitFor(PROCESS_EXIT_TIMEOUT, TimeUnit.SECONDS)) { setError(originalError, MessageFormat.format( JGitText.get().commandClosedStderrButDidntExit, desc, PROCESS_EXIT_TIMEOUT), -1); fail.set(true); return false; } } catch (InterruptedException e) { setError(originalError, MessageFormat.format( JGitText.get().threadInterruptedWhileRunning, desc), -1); fail.set(true); return false; } return true; }
Source:
public void onOpenObjectExplorerEvent(OpenObjectExplorerEvent event) { if (!SourceWindowManager.isMainSourceWindow()) return; Debug.logToRConsole("Opening object explorer"); ObjectExplorerHandle handle = event.getHandle(); for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(handle.getPath())) { ((ObjectExplorerEditingTarget)editors_.get(i)).update(handle); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); }

Target:
public void onOpenObjectExplorerEvent(OpenObjectExplorerEvent event) { if (!SourceWindowManager.isMainSourceWindow()) return; ObjectExplorerHandle handle = event.getHandle(); for (int i = 0; i < editors_.size(); i++) { String path = editors_.get(i).getPath(); if (path != null && path.equals(handle.getPath())) { ((ObjectExplorerEditingTarget)editors_.get(i)).update(handle); ensureVisible(false); view_.selectTab(i); return; } } ensureVisible(true); server_.newDocument( FileTypeRegistry.OBJECT_EXPLORER.getTypeId(), null, (JsObject) handle.cast(), new SimpleRequestCallback<SourceDocument>("Show Object Explorer") { @Override public void onResponseReceived(SourceDocument response) { addTab(response, OPEN_INTERACTIVE); } }); }
Source:
public static String convertToEqualShareFormatHtml(int i) { if (i == Const.INT_UNINITIALIZED) { return "<span class=\"color_neutral\">N/A</span>"; } else if (i == Const.POINTS_NOT_SUBMITTED) { return "<span class=\"color_neutral\"></span>"; } else if (i == Const.POINTS_NOT_SURE) { return "<span class=\"color-negative\">Not Sure</span>"; } else if (i == 0) { return "<span class=\"color-negative\">0%</span>"; } else if (i > 100) { return "<span class=\"color-positive\">Equal Share +" + (i - 100) + "%</span>"; } else if (i < 100) { return "<span class=\"color-negative\">Equal Share -" + (100 - i) + "%</span>"; } else if (i == 100) { return "<span class=\"color_neutral\">Equal Share</span>"; } else { return ""; } }

Target:
public static String convertToEqualShareFormatHtml(int i) { if (i == Const.INT_UNINITIALIZED) { return "<span class=\"color_neutral\">N/A</span>"; } else if (i == Const.POINTS_NOT_SUBMITTED) { return "<span class=\"color_neutral\"></span>"; } else if (i == Const.POINTS_NOT_SURE) { return "<span class=\"color-negative\">Not Sure</span>"; } else if (i == 0) { return "<span class=\"color-negative\">0%</span>"; } else if (i > 100) { return "<span class=\"color-positive\">Equal Share +" + (i - 100) + "%</span>"; } else if (i < 100) { return "<span class=\"color-negative\">Equal Share -" + (100 - i) + "%</span>"; } else { return "<span class=\"color_neutral\">Equal Share</span>"; } }
Source:
private void deleteFromStoresAndNotify(K key, V value, Metadata metadata) { CompletionStages.join(deleteFromStores(key)); CompletionStages.join(cacheNotifier.notifyCacheEntryExpired(key, value, metadata, null)); }

Target:
private void deleteFromStoresAndNotify(K key, V value, Metadata metadata) { CompletionStages.join(CompletionStages.allOf( persistenceManager.deleteFromAllStores(key, keyPartitioner.getSegment(key), PersistenceManager.AccessMode.BOTH), cacheNotifier.notifyCacheEntryExpired(key, value, metadata, null))); }
Source:
public ParseResult beforeInvocation(ParseResult invocationContext) { ParseResult result = super.beforeInvocation(invocationContext); String defaultNameKey = (String) ReflectionUtils.getField( ReflectionUtils.findField(FileSystem.class, "FS_DEFAULT_NAME_KEY"), null); String fs = getHadoopConfiguration().get(defaultNameKey); if (fs != null && fs.length() > 0) { return result; } else { LOG.severe("You must set namenode URL before running fs commands. Refer `hadoop config fs`"); throw new IllegalStateException("You must set fs URL before running fs commands"); } }

Target:
public ParseResult beforeInvocation(ParseResult invocationContext) { ParseResult result = super.beforeInvocation(invocationContext); String defaultNameKey = (String) ReflectionUtils.getField( ReflectionUtils.findField(FileSystem.class, "FS_DEFAULT_NAME_KEY"), null); String fs = getHadoopConfiguration().get(defaultNameKey); if (fs != null && fs.length() > 0) { return result; } else { LOG.severe("You must set namenode URL before running fs commands. Use `hadoop config fs` to configure namenode URL."); throw new IllegalStateException("You must set fs URL before running fs commands"); } }
Source:
private String formatDate(String dateString) { Date date = new Date(); SimpleDateFormat formatedDate = new SimpleDateFormat("EEE"); SimpleDateFormat originalDate = new SimpleDateFormat("yyyy-MM-dd"); try { date = originalDate.parse(dateString); } catch (ParseException e) { LoggingManager.Timber.e(e, "___________DateFormatError___________"); } String formattedString = formatedDate.format(date).toUpperCase(); return formattedString; }

Target:
private String formatDate(String dateString) { Date date = new Date(); SimpleDateFormat formattedDate = new SimpleDateFormat("EEE"); SimpleDateFormat originalDate = new SimpleDateFormat("yyyy-MM-dd"); try { date = originalDate.parse(dateString); } catch (ParseException e) { LoggingManager.Timber.e(e, "___________DateFormatError___________"); } String formattedString = formattedDate.format(date).toUpperCase(); return formattedString; }
Source:
public History[] filterHistory(String... filters) throws Exception { Map<String,String> params = new HashMap<String,String>(); if (filters.length > 0) { for (int i = 0; i < filters.length; i++) { params.put("source_uri[]", filters[i]); } } else { return refreshHistory(); } return constructHistory(params); }

Target:
public History[] filterHistory(String... filters) throws Exception { final Map<String,String> params = new HashMap<>(); if (filters.length > 0) { for (int i = 0; i < filters.length; i++) { params.put("source_uri[]", filters[i]); } } else { return refreshHistory(); } return constructHistory(params); }
Source:
public void setAttribute(String key, String value, Context context) { if (ImplUtils.isNullOrEmpty(value)) { logger.info("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpan(context); if (span != null) { span.setAttribute(key, AttributeValue.stringAttributeValue(value)); } else { logger.warning("Failed to find span to add attribute."); } }

Target:
public void setAttribute(String key, String value, Context context) { if (CoreUtils.isNullOrEmpty(value)) { logger.warning("Failed to set span attribute since value is null or empty."); return; } final Span span = getSpan(context); if (span != null) { span.setAttribute(key, AttributeValue.stringAttributeValue(value)); } else { logger.warning("Failed to find span to add attribute."); } }
Source:
public void testNoBucketNumberHiddenColumn() { assertUpdate("CREATE TABLE test_no_bucket_number AS SELECT * FROM orders", "SELECT count(*) FROM orders"); computeActual("SELECT DISTINCT \"$bucket_number\" FROM test_no_bucket_number"); }

Target:
public void testNoBucketNumberHiddenColumn() { assertUpdate("CREATE TABLE test_no_bucket_number (test bigint)"); computeActual("SELECT DISTINCT \"$bucket_number\" FROM test_no_bucket_number"); }
Source:
@Override public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { System.out.println("Fail once my coproc " + this); if (failOnce) { failOnce = false; throw new IOException(); } }

Target:
public void preBatchMutate(ObserverContext<RegionCoprocessorEnvironment> c, MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException { if (failOnce) { failOnce = false; throw new IOException(); } }
Source:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { int len = params.length; for (int i = 0; i < len; i++) { String objectName = params[i]; ObjectInstance object = state.getObject(objectName); if (object == null) { return BakingActionResult.failure(objectName + " does not exist"); } String className = object.getObjectClass().name; if (!className.equalsIgnoreCase(this.parameterClasses[i])) { return BakingActionResult.failure(objectName + " is not valid for this action"); } } if (!this.canAgentGo(state, params)) { return BakingActionResult.failure(params[0] + " is not a valid agent to take this action"); } return BakingActionResult.success(); }

Target:
public BakingActionResult checkActionIsApplicableInState(State state, String[] params) { for (int i = 0, len = params.length; i < len; i++) { String objectName = params[i]; ObjectInstance object = state.getObject(objectName); if (object == null) { return BakingActionResult.failure(objectName + " does not exist"); } String className = object.getObjectClass().name; if (!className.equalsIgnoreCase(this.parameterClasses[i])) { return BakingActionResult.failure(objectName + " is not valid for this action"); } } if (!this.canAgentGo(state, params)) { return BakingActionResult.failure(params[0] + " is not a valid agent to take this action"); } return BakingActionResult.success(); }
Source:
private long calculateRemainingEntriesIncrementalUpdates(long lastAckedTs, long txStreamTail, StreamIteratorMetadata currentTxStreamProcessedTs) { long noRemainingEntriesToSend = 0; if (txStreamTail <= currentTxStreamProcessedTs.getTimestamp()) { if (currentTxStreamProcessedTs.isStreamsToReplicatePresent()) { if (lastAckedTs == currentTxStreamProcessedTs.getTimestamp()) { log.trace(""); return noRemainingEntriesToSend; } return getTxStreamTotalEntries(lastAckedTs, currentTxStreamProcessedTs.getTimestamp()); } return noRemainingEntriesToSend; } if (currentTxStreamProcessedTs.isStreamsToReplicatePresent()) { return getTxStreamTotalEntries(lastAckedTs, txStreamTail); } return getTxStreamTotalEntries(currentTxStreamProcessedTs.getTimestamp(), txStreamTail); }

Target:
private long calculateRemainingEntriesIncrementalUpdates(long lastAckedTs, long txStreamTail, StreamIteratorMetadata currentTxStreamProcessedTs) { long noRemainingEntriesToSend = 0; if (txStreamTail <= currentTxStreamProcessedTs.getTimestamp()) { if (currentTxStreamProcessedTs.isStreamsToReplicatePresent()) { if (lastAckedTs == currentTxStreamProcessedTs.getTimestamp()) { log.trace("Log Entry Sync up to date, lastAckedTs={}, txStreamTail={}, currentTxProcessedTs={}, containsEntries={}", lastAckedTs, txStreamTail, currentTxStreamProcessedTs.getTimestamp(), currentTxStreamProcessedTs.isStreamsToReplicatePresent()); return noRemainingEntriesToSend; } log.trace("Log Entry Sync pending ACKs, lastAckedTs={}, txStreamTail={}, currentTxProcessedTs={}, containsEntries={}", lastAckedTs, txStreamTail, currentTxStreamProcessedTs.getTimestamp(), currentTxStreamProcessedTs.isStreamsToReplicatePresent()); return getTxStreamTotalEntries(lastAckedTs, currentTxStreamProcessedTs.getTimestamp()); } log.trace("Log Entry Sync up to date, no pending ACKs, lastAckedTs={}, txStreamTail={}, currentTxProcessedTs={}, containsEntries={}", lastAckedTs, txStreamTail, currentTxStreamProcessedTs.getTimestamp(), currentTxStreamProcessedTs.isStreamsToReplicatePresent()); return noRemainingEntriesToSend; } long remainingEntries = getTxStreamTotalEntries(lastAckedTs, txStreamTail); log.trace("Log Entry Sync pending entries for processing, lastAckedTs={}, txStreamTail={}, currentTxProcessedTs={}, containsEntries={}, remaining={}", lastAckedTs, txStreamTail, currentTxStreamProcessedTs.getTimestamp(), currentTxStreamProcessedTs.isStreamsToReplicatePresent(), remainingEntries); if (!currentTxStreamProcessedTs.isStreamsToReplicatePresent()) { return remainingEntries - 1; } return remainingEntries; }
Source:
public static void registerAvailable(Object provider, Console console, Context context) { Predicate<? super Method> predicate = Predicates.<Method>and(ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withAnnotation(Command.class)); Set<Method> commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); for (Method method : commandMethods) { final Class[] paramTypes = method.getParameterTypes(); final Annotation[][] paramAnnotations = method.getParameterAnnotations(); boolean hasSenderAnnotation = false; for (int i = 0; i < paramAnnotations.length; i++) { if(paramTypes[i].getTypeName().equals(ENTITY_REF_NAME)) { if(paramAnnotations[i].length == 0) { logger.error("Command provided by contains a EntityRef without @Sender annotation, may cause a NullPointerException", method.getName(), provider.getClass().getSimpleName()); } else { for (Annotation annotation: paramAnnotations[i]) { if (annotation instanceof Sender) { hasSenderAnnotation = true; } } if(!hasSenderAnnotation){ logger.error("Command provided by contains a EntityRef without @Sender annotation, may cause a NullPointerException", method.getName(), provider.getClass().getSimpleName()); } } } } logger.debug("Registering command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); try { SpecificAccessibleObject<Method> specificMethod = new SpecificAccessibleObject<>(method, provider); MethodCommand command = referringTo(specificMethod, context); console.registerCommand(command); logger.debug("Registered command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); } catch (RuntimeException t) { logger.error("Failed to load command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName(), t); } } }

Target:
public static void registerAvailable(Object provider, Console console, Context context) { Predicate<? super Method> predicate = Predicates.<Method>and(ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withAnnotation(Command.class)); Set<Method> commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); for (Method method : commandMethods) { if(!hasSenderAnnotation(method)){ logger.error("Command provided by contains a EntityRef without @Sender annotation, may cause a NullPointerException", method.getName(), provider.getClass().getSimpleName()); } logger.debug("Registering command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); try { SpecificAccessibleObject<Method> specificMethod = new SpecificAccessibleObject<>(method, provider); MethodCommand command = referringTo(specificMethod, context); console.registerCommand(command); logger.debug("Registered command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName()); } catch (RuntimeException t) { logger.error("Failed to load command method in class {}", method.getName(), method.getDeclaringClass().getCanonicalName(), t); } } }
Source:
public void setEndDate(Date endDate) { this.endDate = new Date(endDate.getTime()); }

Target:
public void setEndDate(Date endDate) { this.endDate = endDate != null ? new Date(endDate.getTime()) : null; }
Source:
protected void setEnvironmentLabel(Map<String, Object> labels, Account account) { labels.put(SystemLabels.LABEL_ENVIRONMENT_ID, account.getUuid()); }

Target:
protected void setEnvironmentLabel(Map<String, Object> labels, Account account) { labels.put(SystemLabels.LABEL_ENVIRONMENT_UUID, account.getUuid()); }
Source:
protected void executeCommand() { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = runVdsCommand(getParameters().isCreateImage() ? VDSCommandType.CreateImage : VDSCommandType.CreateSnapshot, getCreateVDSCommandParameters()); if (vdsReturnValue.getSucceeded()) { getParameters().setVdsmTaskIds(new ArrayList<>()); getParameters().getVdsmTaskIds().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); getTaskIdList().add(getParameters().getVdsmTaskIds().get(0)); setSucceeded(true); } }

Target:
protected void executeCommand() { Guid taskId = persistAsyncTaskPlaceHolder(getParameters().getParentCommand()); VDSReturnValue vdsReturnValue = runVdsCommand(VDSCommandType.CreateSnapshot, getCreateVDSCommandParameters()); if (vdsReturnValue.getSucceeded()) { getParameters().setVdsmTaskIds(new ArrayList<>()); getParameters().getVdsmTaskIds().add( createTask(taskId, vdsReturnValue.getCreationInfo(), getParameters().getParentCommand(), VdcObjectType.Storage, getParameters().getStorageDomainId())); getTaskIdList().add(getParameters().getVdsmTaskIds().get(0)); setSucceeded(true); } }
Source:
public void open() { try { Optional<Path> resolvedPath = FileHelper.expandFilename( databaseContext, linkedFile.getLink(), filePreferences); Optional<ExternalFileType> type = ExternalFileTypes.getInstance().fromLinkedFile(linkedFile, true); boolean successful = false; if (resolvedPath.isPresent()) { successful = JabRefDesktop.openExternalFileAnyFormat(databaseContext, resolvedPath.get().toString(), type); } if (!successful) { dialogService.showErrorDialogAndWait(Localization.lang("File not found"), Localization.lang("Could not find file '%0'.", linkedFile.getLink())); } } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Error opening file '%0'.", linkedFile.getLink()), e); } }

Target:
public void open() { try { Optional<ExternalFileType> type = ExternalFileTypes.getInstance().fromLinkedFile(linkedFile, true); boolean successful = JabRefDesktop.openExternalFileAnyFormat(databaseContext, linkedFile.getLink(), type); if (!successful) { dialogService.showErrorDialogAndWait(Localization.lang("File not found"), Localization.lang("Could not find file '%0'.", linkedFile.getLink())); } } catch (IOException e) { dialogService.showErrorDialogAndWait(Localization.lang("Error opening file '%0'.", linkedFile.getLink()), e); } }
Source:
public String getPropertyString() { return entity.getBukkitEntity() instanceof Creeper ? ((Creeper) entity.getBukkitEntity()).getMaxFuseTicks() + "" : null; }

Target:
public String getPropertyString() { return String.valueOf(((Creeper) entity.getBukkitEntity()).getMaxFuseTicks()); }
Source:
public static void checkKey(Class<?> keyType, Object keyObject) { Objects.requireNonNull(keyObject); if (!keyType.isAssignableFrom(keyObject.getClass())) { throw new ClassCastException("Invalid key type, expected : " + keyType.getName() + " but was : " + keyObject.getClass().getName()); } }

Target:
public static void checkKey(Class<?> keyType, Object keyObject) { if (!keyType.isInstance(Objects.requireNonNull(keyObject))) { throw new ClassCastException("Invalid key type, expected : " + keyType.getName() + " but was : " + keyObject.getClass().getName()); } }
Source:
public void registered_device_with_x509cert_to_server_with_x509cert_rootca_certificate_usage_taa_intca_given() throws NonUniqueSecurityInfoException, CertificateEncodingException { helper.createServerWithX509Cert(helper.serverIntX509CertChain, helper.serverIntPrivateKeyFromCert, helper.trustedCertificates, true); helper.server.start(); helper.setEndpointNameFromX509(helper.clientX509Cert); helper.createX509CertClient(new X509Certificate[] { helper.clientX509Cert }, helper.clientPrivateKeyFromCert, helper.clientTrustStore, helper.serverIntX509CertChain[1], CertificateUsage.TRUST_ANCHOR_ASSERTION); helper.getSecurityStore().add(SecurityInfo.newX509CertInfo(helper.getCurrentEndpoint())); helper.assertClientNotRegisterered(); helper.client.start(); helper.waitForRegistrationAtServerSide(1000); assertNotNull(helper.getCurrentRegistration()); }

Target:
public void registered_device_with_x509cert_to_server_with_x509cert_rootca_certificate_usage_taa_intca_given() throws NonUniqueSecurityInfoException, CertificateEncodingException { helper.createServerWithX509Cert(helper.serverIntX509CertChain, helper.serverIntPrivateKeyFromCert, helper.trustedCertificates, true); helper.server.start(); helper.setEndpointNameFromX509(helper.clientX509Cert); helper.createX509CertClient(new X509Certificate[] { helper.clientX509Cert }, helper.clientPrivateKeyFromCert, helper.clientTrustStore, helper.serverIntX509CertChain[1], CertificateUsage.TRUST_ANCHOR_ASSERTION); helper.getSecurityStore().add(SecurityInfo.newX509CertInfo(helper.getCurrentEndpoint())); helper.assertClientNotRegisterered(); helper.client.start(); helper.waitForRegistrationAtServerSide(1); assertNotNull(helper.getCurrentRegistration()); }
Source:
private boolean addMissingLeaseInfoToVm() { if (getVm().getLeaseStorageDomainId() != null && getVm().getLeaseInfo() == null) { if (!addVmLease(getVm().getLeaseStorageDomainId(), getVm().getId(), false)) { return false; } if (getVm().getLeaseInfo() == null) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getVm().getStoragePoolId(), getVm().getLeaseStorageDomainId(), getParameters().getVmId())); if (retVal == null || !retVal.getSucceeded()) { return false; } getVm().setLeaseInfo(retVal.getActionReturnValue()); vmDynamicDao.updateVmLeaseInfo(getParameters().getVmId(), getVm().getLeaseInfo()); } } return true; }

Target:
private void addMissingLeaseInfoToVm() { if (getVm().getLeaseStorageDomainId() != null && getVm().getLeaseInfo() == null) { ActionReturnValue retVal = runInternalAction(ActionType.GetVmLeaseInfo, new VmLeaseParameters(getVm().getStoragePoolId(), getVm().getLeaseStorageDomainId(), getParameters().getVmId())); if (retVal == null || !retVal.getSucceeded()) { throw new EngineException(EngineError.INVALID_HA_VM_LEASE); } getVm().setLeaseInfo(retVal.getActionReturnValue()); vmDynamicDao.updateVmLeaseInfo(getParameters().getVmId(), getVm().getLeaseInfo()); } return; }
Source:
public Integer getPublishedSequenceNumber() { return systemProperties.getPublishedSequenceNumber(); }

Target:
public Integer getPublishedSequenceNumber() { return publishedSequenceNumber; }
Source:
private boolean checkAtNewTableRow(String line, int lineOffset) { if (lineOffset < line.length()) { Matcher m = cellPattern.matcher(line.substring(lineOffset)); return m.matches(); } return false; }

Target:
private boolean checkAtNewTableRow(String line, int lineOffset) { if (lineOffset < line.length()) { Matcher m = cellPattern.matcher(line); m.region(lineOffset, line.length()); return m.matches(); } return false; }
Source:
private void validateJsonSchemaConstraints(final Schema schema) throws InvalidEventTypeException { final List<SchemaIncompatibility> incompatibilities = schemaCompatibilityChecker.checkConstraints(schema); if (!incompatibilities.isEmpty()) { final String erroMessage = incompatibilities.stream().map(Object::toString) .collect(Collectors.joining(", ")); throw new InvalidEventTypeException("Invalid schema: " + erroMessage); } }

Target:
private void validateJsonSchemaConstraints(final Schema schema) throws InvalidEventTypeException { final List<SchemaIncompatibility> incompatibilities = schemaCompatibilityChecker.checkConstraints(schema); if (!incompatibilities.isEmpty()) { final String errorMessage = incompatibilities.stream().map(Object::toString) .collect(Collectors.joining(", ")); throw new InvalidEventTypeException("Invalid schema: " + errorMessage); } }
Source:
private List<Filter> getWorkspaceQueryFilters(String queryId) { List<Filter> filters = new ArrayList<>(); filters.add(filterBuilder.attribute(Metacard.TAGS).is().text(WORKSPACE_TAG)); filters.add(filterBuilder.attribute(QUERIES_ATTRIBUTE).like().text(queryId)); return filters; }

Target:
private Filter getWorkspaceQueryFilters(String queryId) { return filterBuilder.allOf( filterBuilder.attribute(Core.METACARD_TAGS).is().text(WorkspaceConstants.WORKSPACE_TAG), filterBuilder.attribute(WorkspaceConstants.WORKSPACE_QUERIES).like().text(queryId)); }
Source:
public void invokeAction(ServerControllerActionCallBean bean) throws InvokeActionException { try { final Object controller = controllers.get(bean.getControllerId()); final Class controllerClass = controllerClassMapping.get(bean.getControllerId()); final Method actionMethod = getActionMethod(controller, controllerClass, bean.getActionName()); final List<String> paramNames = getParamNames(actionMethod); final List<Object> args = getArgs(bean, paramNames); ReflectionHelper.invokePrivileged(actionMethod, controller, args.toArray()); } catch (Exception e) { throw new InvokeActionException(e); } }

Target:
public void invokeAction(ServerControllerActionCallBean bean) throws InvokeActionException { try { final Object controller = controllers.get(bean.getControllerId()); final Class controllerClass = controllerClassMapping.get(bean.getControllerId()); final Method actionMethod = getActionMethod(controller, controllerClass, bean.getActionName()); final List<Object> args = getArgs(actionMethod, bean); ReflectionHelper.invokePrivileged(actionMethod, controller, args.toArray()); } catch (Exception e) { throw new InvokeActionException(e); } }
Source:
public static Predicate containsIgnoreCase(final Expression left, final Expression right) { return new BinaryPredicateSupport(left, right) { protected boolean matches(Exchange exchange, Object leftValue, Object rightValue) { if (leftValue == null && rightValue == null) { return true; } else if (leftValue == null || rightValue == null) { return false; } return ObjectHelper.containsIgnoreCase(leftValue, rightValue); } protected String getOperationText() { return "contains"; } }; }

Target:
public static Predicate containsIgnoreCase(final Expression left, final Expression right) { return new BinaryPredicateSupport(left, right) { protected boolean matches(Exchange exchange, Object leftValue, Object rightValue) { if (leftValue == null && rightValue == null) { return true; } else if (leftValue == null || rightValue == null) { return false; } return ObjectHelper.containsIgnoreCase(leftValue, rightValue); } protected String getOperationText() { return "~~"; } }; }
Source:
private TargetRoll getQualityMods(TargetRoll mods, Person tech) { int qualityMod = 0; switch(quality) { case QUALITY_A: qualityMod = 3; break; case QUALITY_B: qualityMod = 2; break; case QUALITY_C: qualityMod = 1; break; case QUALITY_D: qualityMod = 0; break; case QUALITY_E: qualityMod = -1; break; case QUALITY_F: qualityMod = -2; break; } mods.addModifier(qualityMod, getQualityName(quality, campaign.getCampaignOptions().reverseQualityNames())); if(qualityMod > 0 && null != tech && tech.getOptions().booleanOption(PersonnelOptions.TECH_FIXER)) { mods.addModifier(-1, "Mr/Ms Fix-it"); } return mods; }

Target:
private TargetRoll getQualityMods(TargetRoll mods, Person tech) { int qualityMod = 0; switch (quality) { case QUALITY_A: qualityMod = 3; break; case QUALITY_B: qualityMod = 2; break; case QUALITY_C: qualityMod = 1; break; case QUALITY_D: qualityMod = 0; break; case QUALITY_E: qualityMod = -1; break; case QUALITY_F: qualityMod = -2; break; } mods.addModifier(qualityMod, getQualityName(quality, campaign.getCampaignOptions().reverseQualityNames())); if ((qualityMod > 0) && (null != tech) && tech.getOptions().booleanOption(PersonnelOptions.TECH_FIXER)) { mods.addModifier(-1, "Mr/Ms Fix-it"); } return mods; }
Source:
public void processEvent(Event event) { publishers.publishersMatchingType(PubsubSystem.GOOGLE) .stream() .map(p -> (GooglePubsubPublisher) p) .forEach(p -> { String jsonPayload; try { jsonPayload = mapper.writeValueAsString(event); } catch (JsonProcessingException jpe) { log.error("Could not serialize event message: {}", jpe); return; } Map<String, String> attributes = new HashMap<>(); if (event.getDetails() != null) { Metadata m = event.getDetails(); String rawType = m.getType(); if (StringUtils.isNotEmpty(rawType)) { attributes.put("rawType", rawType); String[] eventDetails = rawType.split(":"); if (eventDetails.length == 3) { attributes.put("source", eventDetails[0]); attributes.put("type", eventDetails[1]); attributes.put("status", eventDetails[2]); } } if (StringUtils.isNotEmpty(m.getApplication())) { attributes.put("application", m.getApplication()); } if (m.getAttributes() != null && !m.getAttributes().isEmpty()) { attributes.putAll(m.getAttributes()); } } if (event.getContent() != null && !event.getContent().isEmpty()) { Map content = event.getContent(); String name = content.getOrDefault("name", "").toString(); if (StringUtils.isNotEmpty(name)) { attributes.put("name", name); } String taskName = content.getOrDefault("taskName", "").toString(); if (StringUtils.isNotEmpty(taskName)) { attributes.put("taskName", taskName); } } p.publish(jsonPayload, attributes); }); }

Target:
public void processEvent(Event event) { publishers.publishersMatchingType(PubsubSystem.GOOGLE) .stream() .map(p -> (GooglePubsubPublisher) p) .forEach(p -> publishEvent(p, event)); }
Source:
static long getGeneration(String name) { if (name.isEmpty()) { throw new IllegalArgumentException("Name provided cannot be empty"); } return Long.parseLong(name.substring(name.indexOf(BlobStore.SEPARATOR) + 1, name.length())); }

Target:
static long getGeneration(String name) { if (name.isEmpty()) { throw new IllegalArgumentException("Name provided cannot be empty"); } return Long.parseLong(name.substring(name.indexOf(BlobStore.SEPARATOR) + 1)); }