auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response add(Event event) { validateParameters(event, "origin", "severity", "customId", "description"); validateEnums(Event.class, event); EntityExternalStatus entityExternalStatus = null; if (event.isSetHost() && event.getHost().isSetExternalStatus()) { entityExternalStatus = EntityExternalStatus.fromValue(event.getHost().getExternalStatus().getState()); return performCreate(VdcActionType.AddExternalEvent, new AddExternalEventParameters(map(event), HostMapper.map(entityExternalStatus, null)), new QueryIdResolver<Long>(VdcQueryType.GetAuditLogById, GetAuditLogByIdParameters.class)); } AddExternalEventParameters parameters = new AddExternalEventParameters(map(event), null); if (event.isSetHost() && event.getHost().isSetExternalStatus()) { parameters.setExternalStatus(ExternalStatus.valueOf(event.getHost().getExternalStatus().getState())); } return performCreate(VdcActionType.AddExternalEvent, parameters, new QueryIdResolver<Long>(VdcQueryType.GetAuditLogById, GetAuditLogByIdParameters.class)); }

Target:
public Response add(Event event) { validateParameters(event, "origin", "severity", "customId", "description"); validateEnums(Event.class, event); boolean isExternalStateDefined = event.isSetHost() && event.getHost().isSetExternalStatus() && event.getHost().getExternalStatus().isSetState(); AddExternalEventParameters parameters = isExternalStateDefined ? new AddExternalEventParameters(map(event), HostMapper.map(EntityExternalStatus.fromValue( event.getHost().getExternalStatus().getState()), null)) : new AddExternalEventParameters(map(event), null); return performCreate(VdcActionType.AddExternalEvent, parameters, new QueryIdResolver<Long>(VdcQueryType.GetAuditLogById, GetAuditLogByIdParameters.class)); }
Source:
public void write(Text key, Text value) throws IOException { String solrFieldName; SolrInputDocument document; Type schemaType = new TypeToken<Schema>() { }.getType(); Schema inputSchema = new Gson().fromJson(key.toString(), schemaType); StructuredRecord structuredRecord = StructuredRecordStringConverter.fromJsonString(value.toString(), inputSchema); document = new SolrInputDocument(); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (config.getOutputFieldMap().containsKey(solrFieldName)) { document.addField(config.getOutputFieldMap().get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); try { if (documentList.size() == Integer.parseInt(conf.get(BATCH_SIZE))) { solrClient.add(documentList); solrClient.commit(); documentList.clear(); } } catch (SolrServerException e) { e.printStackTrace(); } }

Target:
public void write(Text key, Text value) throws IOException { String solrFieldName; SolrInputDocument document = new SolrInputDocument(); Schema inputSchema = GSON.fromJson(key.toString(), SCHEMA_TYPE); StructuredRecord structuredRecord = StructuredRecordStringConverter.fromJsonString(value.toString(), inputSchema); for (Schema.Field field : structuredRecord.getSchema().getFields()) { solrFieldName = field.getName(); if (config.getOutputFieldMap().containsKey(solrFieldName)) { document.addField(config.getOutputFieldMap().get(solrFieldName), structuredRecord.get(solrFieldName)); } else { document.addField(solrFieldName, structuredRecord.get(solrFieldName)); } } documentList.add(document); try { if (documentList.size() == Integer.parseInt(conf.get(BATCH_SIZE))) { solrClient.add(documentList); solrClient.commit(); documentList.clear(); } } catch (SolrServerException e) { throw new IllegalArgumentException("Exception while indexing the documents to Solr. For more details, Please " + "check the logs.", e); } }
Source:
protected AbstractAttributeEditor createAttributeEditor(TaskAttribute attribute) { if (attribute == null) { return null; } String type = attribute.getMetaData().getType(); int index = taskEditorPage.getTaskRepository() .getProperties() .get(IRepositoryConstants.PROPERTY_HIDDEN) .indexOf(attribute.getId()); if (index == -1) { if (type != null) { AttributeEditorFactory attributeEditorFactory = getTaskEditorPage().getAttributeEditorFactory(); AbstractAttributeEditor editor = attributeEditorFactory.createEditor(type, attribute); if (editor instanceof RichTextAttributeEditor) { boolean spellChecking = getTaskEditorPage().getAttributeEditorToolkit().hasSpellChecking(attribute); ((RichTextAttributeEditor) editor).setSpellCheckingEnabled(spellChecking); } attributeIds.add(attribute.getId()); return editor; } } return null; }

Target:
protected AbstractAttributeEditor createAttributeEditor(TaskAttribute attribute) { if (attribute == null) { return null; } String type = attribute.getMetaData().getType(); String hiddenAttributes = taskEditorPage.getTaskRepository() .getProperties() .get(IRepositoryConstants.PROPERTY_HIDDEN); if (hiddenAttributes == null || !hiddenAttributes.contains(attribute.getId())) { if (type != null) { AttributeEditorFactory attributeEditorFactory = getTaskEditorPage().getAttributeEditorFactory(); AbstractAttributeEditor editor = attributeEditorFactory.createEditor(type, attribute); if (editor instanceof RichTextAttributeEditor) { boolean spellChecking = getTaskEditorPage().getAttributeEditorToolkit().hasSpellChecking(attribute); ((RichTextAttributeEditor) editor).setSpellCheckingEnabled(spellChecking); } attributeIds.add(attribute.getId()); return editor; } } return null; }
Source:
private static long fromMetastoreDistinctValuesCount(long distinctValuesCount, long nullsCount, long rowCount) { long nonNullsCount = rowCount - nullsCount; if (nullsCount > 0 && (distinctValuesCount > 1 || nonNullsCount == 0)) { distinctValuesCount--; } if (distinctValuesCount > nonNullsCount) { return nonNullsCount; } return distinctValuesCount; }

Target:
private static long fromMetastoreDistinctValuesCount(long distinctValuesCount, long nullsCount, long rowCount) { long nonNullsCount = rowCount - nullsCount; if (nullsCount > 0 && distinctValuesCount > 0) { distinctValuesCount--; } if (nonNullsCount > 0 && distinctValuesCount == 0) { distinctValuesCount = 1; } if (distinctValuesCount > nonNullsCount) { return nonNullsCount; } return distinctValuesCount; }
Source:
public ConnectionPoolConfig(VerifiableProperties verifiableProperties) { connectionPoolReadBufferSizeBytes = verifiableProperties.getIntInRange("connectionpool.read.buffer.size.bytes", 1048576, 1, 1024 * 1024 * 1024); connectionPoolWriteBufferSizeBytes = verifiableProperties.getIntInRange("connectionpool.write.buffer.size.bytes", 1048576, 1, 1024 * 1024 * 1024); connectionPoolReadTimeoutMs = verifiableProperties.getIntInRange("connectionpool.read.timeout.ms", 1500, 1, 100000); connectionPoolConnectTimeoutMs = verifiableProperties.getIntInRange("connectionpool.connect.timeout.ms", 800, 1, 100000); connectionPoolMaxConnectionsPerPortPlainText = verifiableProperties.getIntInRange("connectionpool.max.connections.per.port.plain.text", 5, 1, 20); connectionPoolMaxConnectionsPerPortSSL = verifiableProperties.getIntInRange("connectionpool.max.connections.per.port.ssl", 2, 1, 20); connectionPoolMaxConnectFailuresToCleanUpAvailablePool = verifiableProperties.getInt("connectionpool.max.connect.failures.to.clean.up.available.pool", 0); }

Target:
public ConnectionPoolConfig(VerifiableProperties verifiableProperties) { connectionPoolReadBufferSizeBytes = verifiableProperties.getIntInRange("connectionpool.read.buffer.size.bytes", 1048576, 1, 1024 * 1024 * 1024); connectionPoolWriteBufferSizeBytes = verifiableProperties.getIntInRange("connectionpool.write.buffer.size.bytes", 1048576, 1, 1024 * 1024 * 1024); connectionPoolReadTimeoutMs = verifiableProperties.getIntInRange("connectionpool.read.timeout.ms", 1500, 1, 100000); connectionPoolConnectTimeoutMs = verifiableProperties.getIntInRange("connectionpool.connect.timeout.ms", 800, 1, 100000); connectionPoolMaxConnectionsPerPortPlainText = verifiableProperties.getIntInRange("connectionpool.max.connections.per.port.plain.text", 5, 1, 20); connectionPoolMaxConnectionsPerPortSSL = verifiableProperties.getIntInRange("connectionpool.max.connections.per.port.ssl", 2, 1, 20); }
Source:
public FindJobExecutionEventsRequest(final Integer pageSize, final Integer pageNumber) { setPageSize(pageSize); setPageNumber(pageNumber); }

Target:
public FindJobExecutionEventsRequest(final Integer pageSize, final Integer pageNumber) { super(pageSize, pageNumber, null, null); }
Source:
public LambdaBeanPropertyMemberAccessor(Method getterMethod) { this.getterMethod = getterMethod; Class<?> declaringClass = getterMethod.getDeclaringClass(); if (!ReflectionHelper.isGetterMethod(getterMethod)) { throw new IllegalArgumentException("The getterMethod (" + getterMethod + ") is not a valid getter."); } propertyType = getterMethod.getReturnType(); propertyName = ReflectionHelper.getGetterPropertyName(getterMethod); MethodHandles.Lookup lookup = MethodHandles.lookup(); CallSite getterSite; try { getterSite = LambdaMetafactory.metafactory(lookup, "apply", MethodType.methodType(Function.class), MethodType.methodType(Object.class, Object.class), lookup.findVirtual(declaringClass, getterMethod.getName(), MethodType.methodType(propertyType)), MethodType.methodType(propertyType, declaringClass)); } catch (LambdaConversionException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalArgumentException("Lambda creation failed for getterMethod (" + getterMethod + ").", e); } try { getterFunction = (Function) getterSite.getTarget().invokeExact(); } catch (Throwable e) { throw new IllegalArgumentException("Lambda creation failed for getterMethod (" + getterMethod + ").", e); } setterMethod = ReflectionHelper.getSetterMethod(declaringClass, getterMethod.getReturnType(), propertyName); if (setterMethod != null) { CallSite setterSite; try { setterSite = LambdaMetafactory.metafactory(lookup, "accept", MethodType.methodType(BiConsumer.class), MethodType.methodType(void.class, Object.class, Object.class), lookup.findVirtual(declaringClass, setterMethod.getName(), MethodType.methodType(void.class, propertyType)), MethodType.methodType(void.class, declaringClass, propertyType)); } catch (LambdaConversionException | NoSuchMethodException | IllegalAccessException e) { throw new IllegalArgumentException("Lambda creation failed for getterMethod (" + getterMethod + ").", e); } try { setterFunction = (BiConsumer) setterSite.getTarget().invokeExact(); } catch (Throwable e) { throw new IllegalArgumentException("Lambda creation failed for getterMethod (" + getterMethod + ").", e); } } else { setterFunction = null; } }

Target:
public LambdaBeanPropertyMemberAccessor(Method getterMethod) { this.getterMethod = getterMethod; Class<?> declaringClass = getterMethod.getDeclaringClass(); if (!ReflectionHelper.isGetterMethod(getterMethod)) { throw new IllegalArgumentException("The getterMethod (" + getterMethod + ") is not a valid getter."); } propertyType = getterMethod.getReturnType(); propertyName = ReflectionHelper.getGetterPropertyName(getterMethod); MethodHandles.Lookup lookup = MethodHandles.lookup(); getterFunction = createGetterFunction(lookup); setterMethod = ReflectionHelper.getSetterMethod(declaringClass, getterMethod.getReturnType(), propertyName); setterFunction = createSetterFunction(lookup); }
Source:
public void testListUser() { Iterable<User> users = env.enterprise.listUsers(); assertEquals(Iterables.size(users), 2); users = filter(env.enterprise.listUsers(), nick(env.user.getNick())); assertEquals(size(users), 1); users = filter(env.enterprise.listUsers(), nick(env.user.getName() + "FAIL")); assertEquals(size(users), 0); users = env.enterprise.listUsers(UserOptions.builder().limit(1).startWith(0).build()); assertEquals(Iterables.size(users), 1); }

Target:
public void testListUser() { Iterable<User> users = env.enterprise.listUsers(); assertEquals(size(users), 2); users = filter(env.enterprise.listUsers(), nick(env.user.getNick())); assertEquals(size(users), 1); users = filter(env.enterprise.listUsers(), nick(env.user.getName() + "FAIL")); assertEquals(size(users), 0); }
Source:
public BasicBrooklynCatalog(final ManagementContext mgmt, final CatalogDto dto) { this.mgmt = mgmt; this.catalog = new CatalogDo(dto); mgmt.getExecutionManager().submit(MutableMap.of("name", "loading catalog"), new Runnable() { public void run() { log.debug("Loading catalog for "+mgmt); catalog.load(mgmt, null); if (log.isDebugEnabled()) log.debug("Loaded catalog for "+mgmt+": "+catalog); } }); }

Target:
public BasicBrooklynCatalog(final ManagementContext mgmt, final CatalogDto dto) { this.mgmt = Preconditions.checkNotNull(mgmt, "managementContext"); this.catalog = new CatalogDo(dto); mgmt.getExecutionManager().submit(MutableMap.of("name", "loading catalog"), new Runnable() { public void run() { log.debug("Loading catalog for "+mgmt); catalog.load(mgmt, null); if (log.isDebugEnabled()) log.debug("Loaded catalog for "+mgmt+": "+catalog); } }); }
Source:
private void deleteReferenceSetEntry(int referenceSetID) throws EamDbException{ Connection conn = connect(); PreparedStatement preparedStatement = null; String sql = "DELETE FROM reference_sets WHERE id=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setInt(1, referenceSetID); preparedStatement.executeUpdate(); } catch (SQLException ex) { throw new EamDbException("Error deleting reference set", ex); } finally { EamDbUtil.closePreparedStatement(preparedStatement); EamDbUtil.closeConnection(conn); } }

Target:
private void deleteReferenceSetEntry(int referenceSetID) throws EamDbException{ Connection conn = connect(); PreparedStatement preparedStatement = null; String sql = "DELETE FROM reference_sets WHERE id=?"; try { preparedStatement = conn.prepareStatement(sql); preparedStatement.setInt(1, referenceSetID); preparedStatement.executeUpdate(); } catch (SQLException ex) { throw new EamDbException("Error deleting reference set " + referenceSetID, ex); } finally { EamDbUtil.closePreparedStatement(preparedStatement); EamDbUtil.closeConnection(conn); } }
Source:
void performDestroyView() { if (mChildFragmentManager != null) { mChildFragmentManager.dispatchDestroyView(); } mState = CREATED; mCalled = false; onDestroyView(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroyView()"); } LoaderManager.getInstance(this).markForRedelivery(); mPerformedCreateView = false; }

Target:
void performDestroyView() { if (mView != null) { mViewLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); } if (mChildFragmentManager != null) { mChildFragmentManager.dispatchDestroyView(); } mState = CREATED; mCalled = false; onDestroyView(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroyView()"); } LoaderManager.getInstance(this).markForRedelivery(); mPerformedCreateView = false; }
Source:
public void open(Configuration parameters) { ValueStateDescriptor<Tuple2<String, String>> descriptor = new ValueStateDescriptor<>( "state", TypeInformation.of(new TypeHint<Tuple2<String, String>>(){})); state = getRuntimeContext().getState(descriptor); }

Target:
public void open(Configuration parameters) { ValueStateDescriptor<Tuple2<String, String>> descriptor = new ValueStateDescriptor<>( "state", Types.TUPLE(Types.STRING, Types.STRING)); state = getRuntimeContext().getState(descriptor); }
Source:
public void start(J project, boolean newInstance) { this.job = project; try { if (spec != null) { this.tabs = CronTabList.create(spec, Hash.from(project.getFullName())); } } catch (ANTLRException e) { LOGGER.log(Level.WARNING, String.format("Failed to parse crontab spec %s in job %s", spec, project.getFullName()), e); } }

Target:
public void start(J project, boolean newInstance) { this.job = project; try { if (spec != null) { this.tabs = CronTabList.create(spec, Hash.from(project.getFullName())); } else { LOGGER.log(Level.WARNING, "The job {0} has a null crontab spec which is incorrect", job.getFullName()); } } catch (ANTLRException e) { LOGGER.log(Level.WARNING, String.format("Failed to parse crontab spec %s in job %s", spec, project.getFullName()), e); } }
Source:
public void shouldScanOnlyIfRequestContentTypeIsXml() throws Exception { String test = "/test"; this.nano.addHandler( new NanoServerHandler(test) { @Override protected NanoHTTPD.Response serve(NanoHTTPD.IHTTPSession session) { consumeBody(session); String response = "<foo>root:*:0:0:System Administrator:/var/root:/bin/sh</foo>"; return newFixedLengthResponse( NanoHTTPD.Response.Status.OK, NanoHTTPD.MIME_PLAINTEXT, response); } }); HttpMessage msg = this.getHttpMessage(test); msg.setRequestBody("<?xml version=\"1.0\"?><comment><text>test</text></comment>"); msg.getRequestHeader().setHeader("Content-Type", "application/json"); msg.getRequestHeader().setMethod("POST"); rule.init(msg, parent); rule.scan(); assertThat(countMessagesSent, equalTo(0)); }

Target:
public void shouldScanOnlyIfRequestContentTypeIsXml() throws HttpMalformedHeaderException { HttpMessage msg = this.getHttpMessage("/test"); msg.getRequestHeader().setHeader("Content-Type", "application/json"); msg.setRequestBody("<?xml version=\"1.0\"?><comment><text>test</text></comment>"); msg.getRequestHeader().setMethod("POST"); rule.init(msg, parent); rule.scan(); assertThat(countMessagesSent, equalTo(0)); }
Source:
protected void onChanged() { if (owningEntity != null) { ((EntityInternal)owningEntity).requestPersist(); } }

Target:
protected void onChanged() { if (owningEntity != null) { ((EntityInternal) owningEntity).requestPersist(); } else { super.onChanged(); } }
Source:
public String toString() { StringBuffer buffer = new StringBuffer(); if (queries != null) { for (Term q : queries) { buffer.append(q); buffer.append(","); } } buffer.append("^"); buffer.append(boost); buffer.append("tieBraker:"); buffer.append(tieBraker); return buffer.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); if (queries != null) { for (Term q : queries) { builder.append(q).append(","); } } builder.append("^").append(boost).append("tieBraker:").append(tieBraker); return builder.toString(); }
Source:
public boolean updateDatastream(Datastream datastream) { String path = KeyBuilder.datastream(_cluster, datastream.getName()); if (!_zkclient.exists(path)) { LOG.warn("trying to update znode of datastream that does not exist. Datastream name: " + datastream.getName()); return false; } String data = DatastreamJSonUtil.getJSonStringFromDatastream(datastream); _zkclient.writeData(path, data); return true; }

Target:
public boolean updateDatastream(Datastream datastream) { String path = KeyBuilder.datastream(_cluster, datastream.getName()); if (!_zkclient.exists(path)) { LOG.warn("trying to update znode of datastream that does not exist. Datastream name: " + datastream.getName()); return false; } String data = DatastreamJSonUtil.getJSonStringFromDatastream(datastream); _zkclient.updateDataSerialized(path, old -> data); return true; }
Source:
public void removeFile(IndexedFile file) { int i = file.getJsonID(); JSONArray movedItem = (JSONArray) mFilesArray.remove(i); if (movedItem != null) getFile(movedItem).setJsonID(i); mFiles.remove(file.getUID()); file.unresolveLink(); saveChanges(); }

Target:
public void removeFile(IndexedFile file) { int i = file.getJsonID(); Object movedItem = mFilesArray.remove(i).getMovedElement(); if (movedItem != null && movedItem instanceof JSONArray) { getFile((JSONArray)movedItem).setJsonID(i); } mFiles.remove(file.getUID()); file.unresolveLink(); saveChanges(); }
Source:
private void setUpException() { expected.expect(ClientException.class); expected.expectMessage("500 Internal Server Error: /var/log/httpd/error_log"); }

Target:
private void setUpException() { expected.expect(ClientException.class); expected.expectMessage(CUSTOM_CLIENT_EXCEPTION.getMessage()); }
Source:
private static void copyProperties(PackageProperties src, PackageProperties tgt){ tgt.setCategoryProperty(src.getCategoryProperty().orElse(null)); tgt.setContentStatusProperty(src.getContentStatusProperty().orElse(null)); tgt.setContentTypeProperty(src.getContentTypeProperty().orElse(null)); tgt.setCreatorProperty(src.getCreatorProperty().orElse(null)); tgt.setDescriptionProperty(src.getDescriptionProperty().orElse(null)); tgt.setIdentifierProperty(src.getIdentifierProperty().orElse(null)); tgt.setKeywordsProperty(src.getKeywordsProperty().orElse(null)); tgt.setLanguageProperty(src.getLanguageProperty().orElse(null)); tgt.setRevisionProperty(src.getRevisionProperty().orElse(null)); tgt.setSubjectProperty(src.getSubjectProperty().orElse(null)); tgt.setTitleProperty(src.getTitleProperty().orElse(null)); tgt.setVersionProperty(src.getVersionProperty().orElse(null)); }

Target:
private static void copyProperties(PackageProperties src, PackageProperties tgt) { tgt.setCategoryProperty(src.getCategoryProperty()); tgt.setContentStatusProperty(src.getContentStatusProperty()); tgt.setContentTypeProperty(src.getContentTypeProperty()); tgt.setCreatorProperty(src.getCreatorProperty()); tgt.setDescriptionProperty(src.getDescriptionProperty()); tgt.setIdentifierProperty(src.getIdentifierProperty()); tgt.setKeywordsProperty(src.getKeywordsProperty()); tgt.setLanguageProperty(src.getLanguageProperty()); tgt.setRevisionProperty(src.getRevisionProperty()); tgt.setSubjectProperty(src.getSubjectProperty()); tgt.setTitleProperty(src.getTitleProperty()); tgt.setVersionProperty(src.getVersionProperty()); }
Source:
private String updateStackStatus(Stack stack, SyncResult result, List<ProviderSyncResult> providerSyncResults, int alreadyDeletedCount) { DetailedStackStatus status = providerSyncResults == null ? result.getStatus() : getStackStatus(providerSyncResults, result, alreadyDeletedCount); if (status != stack.getStackStatus().getDetailedStackStatus()) { if (autoSyncConfig.isUpdateStatus()) { if (flowLogService.isOtherFlowRunning(stack.getId())) { throw new InterruptSyncingException(":::Auto sync::: interrupt syncing in updateStackStatus, flow is running on freeipa stack " + stack.getName()); } else { stackUpdater.updateStackStatus(stack, status, result.getMessage()); } } else { LOGGER.info(":::Auto sync::: The stack status would be had to update from to {}", stack.getStackStatus().getDetailedStackStatus(), status); } } return String.format("freeipa %s is %s. ", stack.getResourceCrn(), status.getStatus().toString()); }

Target:
private void updateStackStatus(Stack stack, SyncResult result, List<ProviderSyncResult> providerSyncResults, int alreadyDeletedCount) { DetailedStackStatus status = providerSyncResults == null ? result.getStatus() : getStackStatus(providerSyncResults, result, alreadyDeletedCount); if (status != stack.getStackStatus().getDetailedStackStatus()) { if (autoSyncConfig.isUpdateStatus()) { if (flowLogService.isOtherFlowRunning(stack.getId())) { throw new InterruptSyncingException(":::Auto sync::: interrupt syncing in updateStackStatus, flow is running on freeipa stack " + stack.getName()); } else { stackUpdater.updateStackStatus(stack, status, result.getMessage()); } } else { LOGGER.info(":::Auto sync::: The stack status would be had to update from to {}", stack.getStackStatus().getDetailedStackStatus(), status); } } }
Source:
public List<String> getFields() { ArrayList<String> fields = new ArrayList<String>(); Metadata metadata; try { metadata = layer.getDataSource().getMetadata(); String retainedFiledName = null; for (int i = 0; i < metadata.getFieldCount(); i++) { int currentType = metadata.getFieldType(i).getTypeCode(); if (currentType == 4 || (currentType >= 16 && currentType <= 256)) { retainedFiledName = metadata.getFieldName(i); fields.add(retainedFiledName); } } } catch (DriverException ex) { Logger.getLogger(ChoroplethDataModel.class.getName()).log(Level.SEVERE, null, ex); } return fields; }

Target:
public List<String> getFields() { ArrayList<String> fields = new ArrayList<String>(); Metadata metadata; try { metadata = layer.getDataSource().getMetadata(); String retainedFiledName = null; for (int i = 0; i < metadata.getFieldCount(); i++) { int currentType = metadata.getFieldType(i).getTypeCode(); if (currentType == Type.BYTE || (currentType >= Type.DOUBLE && currentType <= Type.SHORT)) { retainedFiledName = metadata.getFieldName(i); fields.add(retainedFiledName); } } } catch (DriverException ex) { LOGGER.error(I18N.tr("Unable to load the map data header"), ex); } return fields; }
Source:
private AuthenticatedUser createAuthenticatedUserForView (Object[] dbRowValues, String roles, int rowNum){ AuthenticatedUser user = new AuthenticatedUser(); user.setRowNum(rowNum); user.setId(new Long((Integer)dbRowValues[0])); user.setUserIdentifier((String)dbRowValues[1]); user.setLastName(UserUtil.getStringOrNull(dbRowValues[2])); user.setFirstName(UserUtil.getStringOrNull(dbRowValues[3])); user.setEmail(UserUtil.getStringOrNull(dbRowValues[4])); user.setAffiliation(UserUtil.getStringOrNull(dbRowValues[5])); user.setSuperuser((Boolean)(dbRowValues[6])); user.setPosition(UserUtil.getStringOrNull(dbRowValues[7])); user.setModificationTime(UserUtil.getTimestampOrNull(dbRowValues[8])); user.setAuthProviderId(UserUtil.getStringOrNull(dbRowValues[9])); user.setAuthProviderFactoryAlias(UserUtil.getStringOrNull(dbRowValues[10])); user.setRoles(roles); return user; }

Target:
private AuthenticatedUser createAuthenticatedUserForView (Object[] dbRowValues, String roles, int rowNum){ AuthenticatedUser user = new AuthenticatedUser(); user.setId(new Long((int)dbRowValues[0])); user.setUserIdentifier((String)dbRowValues[1]); user.setLastName(UserUtil.getStringOrNull(dbRowValues[2])); user.setFirstName(UserUtil.getStringOrNull(dbRowValues[3])); user.setEmail(UserUtil.getStringOrNull(dbRowValues[4])); user.setAffiliation(UserUtil.getStringOrNull(dbRowValues[5])); user.setSuperuser((Boolean)(dbRowValues[6])); user.setPosition(UserUtil.getStringOrNull(dbRowValues[7])); user.setCreatedTime(UserUtil.getTimestampOrNull(dbRowValues[8])); user.setLastLoginTime(UserUtil.getTimestampOrNull(dbRowValues[9])); user.setLastApiUseTime(UserUtil.getTimestampOrNull(dbRowValues[10])); user.setAuthProviderId(UserUtil.getStringOrNull(dbRowValues[11])); user.setAuthProviderFactoryAlias(UserUtil.getStringOrNull(dbRowValues[12])); user.setRoles(roles); return user; }
Source:
private ListenableFuture<Map<Cell, byte[]>> getFromKeyValueService( TableReference tableRef, Set<Cell> cells, AsyncKeyValueService asyncKeyValueService, AsyncTransactionService asyncTransactionService) { Map<Cell, Long> toRead = Cells.constantValueMap(cells, getStartTimestamp()); ListenableFuture<Collection<Map.Entry<Cell, byte[]>>> futureBuilder = Futures.transformAsync( asyncKeyValueService.getAsync(tableRef, toRead), rawResults -> getWithPostFilteringAsync( tableRef, rawResults, Value.GET_VALUE, asyncKeyValueService, asyncTransactionService), MoreExecutors.directExecutor()); return Futures.transform( futureBuilder, input -> ImmutableMap.<Cell, byte[]>builderWithExpectedSize(cells.size()).putAll(input).build(), MoreExecutors.directExecutor()); }

Target:
private ListenableFuture<Map<Cell, byte[]>> getFromKeyValueService( TableReference tableRef, Set<Cell> cells, AsyncKeyValueService asyncKeyValueService, AsyncTransactionService asyncTransactionService) { Map<Cell, Long> toRead = Cells.constantValueMap(cells, getStartTimestamp()); ListenableFuture<Collection<Map.Entry<Cell, byte[]>>> postFilteredResults = Futures.transformAsync( asyncKeyValueService.getAsync(tableRef, toRead), rawResults -> getWithPostFilteringAsync( tableRef, rawResults, Value.GET_VALUE, asyncKeyValueService, asyncTransactionService), MoreExecutors.directExecutor()); return Futures.transform(postFilteredResults, ImmutableMap::copyOf, MoreExecutors.directExecutor()); }
Source:
public void workspacePut( @RequestBody WorkspaceInfo workspace, @PathVariable String workspaceName, UriComponentsBuilder builder) { if ("default".equals(workspaceName)) { catalog.setDefaultWorkspace(workspace); } else { WorkspaceInfo wks = catalog.getWorkspaceByName(workspaceName); if (wks == null) { throw new RestException( "Can't change a non existant workspace (" + workspaceName + ")", HttpStatus.NOT_FOUND); } String infoName = workspace.getName(); if (infoName != null && infoName.isEmpty()) { throw new RestException("Can't change name of workspace", HttpStatus.FORBIDDEN); } new CatalogBuilder(catalog).updateWorkspace(wks, workspace); catalog.save(wks); } }

Target:
public void workspacePut( @RequestBody WorkspaceInfo workspace, @PathVariable String workspaceName, UriComponentsBuilder builder) { if ("default".equals(workspaceName)) { catalog.setDefaultWorkspace(workspace); } else { WorkspaceInfo wks = catalog.getWorkspaceByName(workspaceName); if (wks == null) { throw new RestException( "Can't change a non existant workspace (" + workspaceName + ")", HttpStatus.NOT_FOUND); } String infoName = workspace.getName(); if (infoName != null && infoName.isEmpty()) { throw new RestException("The workspace name cannot be empty", HttpStatus.FORBIDDEN); } new CatalogBuilder(catalog).updateWorkspace(wks, workspace); catalog.save(wks); } }
Source:
public String toString() { return StringFactory.vertexProgramString(this, "alpha=" + this.alpha + ", iterations=" + this.totalIterations + ", epsilon=" + this.epsilon); }

Target:
public String toString() { return StringFactory.vertexProgramString(this, "alpha=" + this.alpha + ", epsilon=" + this.epsilon + ", iterations=" + this.maxIterations); }
Source:
private Dialog createDeleteDialog(){ return new android.app.AlertDialog.Builder(this) .setMessage(R.string.remove_device_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeDevice(mDevice.deviceID); finish(); }) .setNegativeButton(android.R.string.no, (dialog, which) -> mIsShowingDeleteDialog = false) .setOnCancelListener(dialog -> mIsShowingDeleteDialog = false) .create(); }

Target:
private Dialog createDeleteDialog(){ return new android.app.AlertDialog.Builder(this) .setMessage(R.string.remove_device_confirm) .setPositiveButton(android.R.string.yes, (dialogInterface, i) -> { getApi().removeDevice(mDevice.deviceID); finish(); }) .setNegativeButton(android.R.string.no, null) .create(); }
Source:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); addAdditionalColumns( anyMappingEnd ); }

Target:
void addRevisionType(Element anyMapping, Element anyMappingEnd, boolean isKey) { final Element revTypeProperty = MetadataTools.addProperty( anyMapping, verEntCfg.getRevisionTypePropName(), verEntCfg.getRevisionTypePropType(), true, isKey ); revTypeProperty.addAttribute( "type", "org.hibernate.envers.internal.entities.RevisionTypeType" ); }
Source:
public Response intercept(Chain chain) throws IOException { if (NetworkUtils.isImageAllowed()) { return chain.proceed(chain.request()); } else { return new Response.Builder() .code(420) .protocol(Protocol.HTTP_2) .message("Dummy response") .body(new RealResponseBody(null, 0, null)) .request(chain.request()) .build(); } }

Target:
public Response intercept(Chain chain) throws IOException { if (NetworkUtils.isImageAllowed()) { return chain.proceed(chain.request()); } else { return new Response.Builder() .protocol(Protocol.HTTP_2) .code(420) .message("Policy Not Fulfilled") .body(ResponseBody.create(null, new byte[0])) .request(chain.request()) .build(); } }
Source:
public SCTVerificationResult verifySingleSCT(SignedCertificateTimestamp sct, CertificateEntry entry) { String algorithm = sct.getSignature().getAlgorithm(); try { byte[] toVerify = sct.encodeTBS(entry); Signature signature = Signature.getInstance(algorithm); signature.initVerify(publicKey); signature.update(toVerify); if (!signature.verify(sct.getSignature().getSignature())) { return new SCTVerificationResult(sct, SCTVerificationResult.Status.BAD_SIGNATURE, this); } return new SCTVerificationResult(sct, SCTVerificationResult.Status.VALID, this); } catch (SerializationException e) { return new SCTVerificationResult(sct, SCTVerificationResult.Status.OTHER, this); } catch (NoSuchAlgorithmException e) { return new SCTVerificationResult(sct, SCTVerificationResult.Status.OTHER, this); } catch (InvalidKeyException e) { return new SCTVerificationResult(sct, SCTVerificationResult.Status.OTHER, this); } catch (SignatureException e) { throw new RuntimeException(e); } }

Target:
public SCTVerificationResult.Status verifySingleSCT(SignedCertificateTimestamp sct, CertificateEntry entry) { if (!Arrays.equals(sct.getLogID(), getID())) { return SCTVerificationResult.Status.UNKNOWN_LOG; } byte[] toVerify; try { toVerify = sct.encodeTBS(entry); } catch (SerializationException e) { return SCTVerificationResult.Status.INVALID_SCT; } Signature signature; try { String algorithm = sct.getSignature().getAlgorithm(); signature = Signature.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { return SCTVerificationResult.Status.INVALID_SCT; } try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { return SCTVerificationResult.Status.INVALID_SCT; } try { signature.update(toVerify); if (!signature.verify(sct.getSignature().getSignature())) { return SCTVerificationResult.Status.INVALID_SIGNATURE; } return SCTVerificationResult.Status.VALID; } catch (SignatureException e) { throw new RuntimeException(e); } }
Source:
private boolean evaluateExpressionOnEntity(String expression, Entity entity) { if (expression == null) { return true; } else { Object value; try { value = jsMagmaScriptEvaluator.eval(expression, entity); } catch (ScriptExecutionException see) { return false; } return value != null ? Boolean.valueOf(value.toString()) : false; } }

Target:
private boolean evaluateExpressionOnEntity(String expression, Entity entity) { if (expression == null) { return true; } else { Object value = jsMagmaScriptEvaluator.eval(expression, entity); return value != null ? Boolean.valueOf(value.toString()) : false; } }
Source:
public boolean isLaunched(Agent agent, InstanceProcess process, Instance machine) throws MachineException { Command command = new CommandImpl(format("Wait for %s, try %d", agent.getName(), ++counter), format("ps -fC %s 1>/dev/null && echo 0 || echo 1", processNameToWait), "test"); try (ListLineConsumer lineConsumer = new ListLineConsumer();) { InstanceProcess waitProcess = machine.createProcess(command, null); waitProcess.start(lineConsumer); return lineConsumer.getText().endsWith("[STDOUT] 0"); } catch (ConflictException e) { throw new MachineException(e.getServiceError()); } }

Target:
public boolean isLaunched(Agent agent, InstanceProcess process, Instance machine) throws MachineException { Command command = new CommandImpl(format("Wait for %s, try %d", agent.getName(), ++counter), format("ps -fC %s 1>/dev/null && echo 0 || echo 1", processNameToWait), "test"); try (ListLineConsumer lineConsumer = new ListLineConsumer()) { InstanceProcess waitProcess = machine.createProcess(command, null); waitProcess.start(lineConsumer); return lineConsumer.getText().endsWith("[STDOUT] 0"); } catch (ConflictException e) { throw new MachineException(e.getServiceError()); } }
Source:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } orderSet.setRetireReason(retireReason); return saveOrderSetInternal(orderSet); }

Target:
public OrderSet retireOrderSet(OrderSet orderSet, String retireReason) throws APIException { if (!StringUtils.hasLength(retireReason)) { throw new IllegalArgumentException("reitreReason cannot be empty or null"); } return saveOrderSetInternal(orderSet); }
Source:
public void onServiceConnected(ComponentName name, IBinder service) { s2cService = (ISend2CgeoService) service; uiHandler.sendEmptyMessage(Send2CgeoService.SEND2CGEO_STARTED); try { s2cService.registerStatusCallback(s2cCallback); } catch (RemoteException e) { e.printStackTrace(); } }

Target:
public void onServiceConnected(ComponentName name, IBinder service) { s2cService = (ISend2CgeoService) service; uiHandler.sendEmptyMessage(Send2CgeoService.SEND2CGEO_STARTED); try { s2cService.registerStatusCallback(s2cCallback); } catch (RemoteException e) { Log.e("Remote exception has been fired by onServiceConnection " + e.getMessage()); } }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { String trigger = redisWrapperClient.get(NORMAL_REPAY_JOB_TRIGGER_KEY); if (trigger != null && Integer.valueOf(trigger) > 0) { payWrapperClient.normalRepayCallback(); } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { logger.info("trigger NormalRepayCallbackJob job start... "); String trigger = redisWrapperClient.get(NORMAL_REPAY_JOB_TRIGGER_KEY); if (trigger != null && Integer.valueOf(trigger) > 0) { payWrapperClient.normalRepayInvestPayback(); } logger.info("trigger NormalRepayCallbackJob job end... "); }
Source:
public synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final String dataType, final int numUnits, final TraceInfo traceInfo) { if (ongoingMigrations.containsKey(operationId)) { notifyFailure(operationId, "Already registered id : " + operationId); } else { ongoingMigrations.put(operationId, new MigrationInfo(senderId, receiverId, dataType)); sender.get().sendCtrlMsg(senderId, dataType, receiverId, numUnits, operationId, traceInfo); } }

Target:
public synchronized void startMigration(final String operationId, final String senderId, final String receiverId, final String dataType, final int numUnits, final TraceInfo traceInfo) { if (ongoingMigrations.containsKey(operationId)) { LOG.log(Level.WARNING, "Failed to register migration with id {0}. Already exists", operationId); return; } if (!partitionManager.checkDataType(senderId, dataType)) { final String reason = new StringBuilder() .append("No data is movable in ").append(senderId) .append(" of type ").append(dataType) .append(". Requested numUnits: ").append(numUnits) .toString(); notifyFailure(operationId, reason); return; } ongoingMigrations.put(operationId, new Migration(senderId, receiverId, dataType)); sender.get().sendCtrlMsg(senderId, dataType, receiverId, numUnits, operationId, traceInfo); }
Source:
public WorkflowVersion getTagVersion(GHRepository ghRepository, String gitReference, Workflow workflow) { try { String refName = "tags/" + gitReference; GHRef ghRef = ghRepository.getRef(refName); Triple<String, Date, String> ref = getRef(ghRef, ghRepository); if (ref == null) { LOG.info(gitUsername + ": Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag."); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } Optional<WorkflowVersion> existingVersion = workflow.getVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getReference(), gitReference)).findFirst(); Map<String, WorkflowVersion> existingDefaults = new HashMap<>(); if (existingVersion.isPresent()) { existingDefaults.put(gitReference, existingVersion.get()); } return setupWorkflowVersionsHelper(ghRepository.getFullName(), workflow, ref, Optional.of(workflow), existingDefaults, ghRepository); } catch (IOException e) { LOG.info(gitUsername + ": Cannot retrieve the workflow reference from GitHub", e); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } }

Target:
public WorkflowVersion getTagVersion(GHRepository ghRepository, String gitReference, Workflow workflow) { try { String refName = "tags/" + gitReference; GHRef ghRef = ghRepository.getRef(refName); Triple<String, Date, String> ref = getRef(ghRef, ghRepository); if (ref == null) { LOG.error(gitUsername + ": Cannot retrieve the workflow reference from GitHub, ensure that " + gitReference + " is a valid tag."); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } Optional<WorkflowVersion> existingVersion = workflow.getVersions().stream().filter(workflowVersion -> Objects.equals(workflowVersion.getReference(), gitReference)).findFirst(); Map<String, WorkflowVersion> existingDefaults = new HashMap<>(); if (existingVersion.isPresent()) { existingDefaults.put(gitReference, existingVersion.get()); } return setupWorkflowVersionsHelper(ghRepository.getFullName(), workflow, ref, Optional.of(workflow), existingDefaults, ghRepository); } catch (IOException e) { LOG.error(gitUsername + ": Cannot retrieve the workflow reference from GitHub", e); throw new CustomWebApplicationException("Could not reach GitHub, please try again later", HttpStatus.SC_SERVICE_UNAVAILABLE); } }
Source:
private boolean hasDescription(List<? extends Node> nodes) { return nodes.stream().anyMatch(it -> ((AbstractDescribedNode) it).getDescription() != null); }

Target:
private boolean hasDescription(List<? extends Node> nodes) { return nodes.stream().filter(it -> it instanceof AbstractDescribedNode).anyMatch(it -> ((AbstractDescribedNode) it).getDescription() != null); }
Source:
public void doSaveProperties(long version) { if (version < lastCacheChanged.get()) { return; } if (file == null) { return; } try { File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw")) { try (FileChannel channel = raf.getChannel()) { FileLock lock = channel.tryLock(); if (lock == null) { throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } try { if (!file.exists()) { file.createNewFile(); } try (FileOutputStream outputFile = new FileOutputStream(file)) { properties.store(outputFile, "Dubbo Registry Cache"); } } finally { lock.release(); } } } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e); } }

Target:
public void doSaveProperties(long version) { if (version < lastCacheChanged.get()) { return; } if (file == null) { return; } try { File lockfile = new File(file.getAbsolutePath() + ".lock"); if (!lockfile.exists()) { lockfile.createNewFile(); } try (RandomAccessFile raf = new RandomAccessFile(lockfile, "rw"); FileChannel channel = raf.getChannel(); FileLock lock = channel.tryLock()) { if (lock == null) { throw new IOException("Can not lock the registry cache file " + file.getAbsolutePath() + ", ignore and retry later, maybe multi java process use the file, please config: dubbo.registry.file=xxx.properties"); } if (!file.exists()) { file.createNewFile(); } try (FileOutputStream outputFile = new FileOutputStream(file)) { properties.store(outputFile, "Dubbo Registry Cache"); } } } catch (Throwable e) { if (version < lastCacheChanged.get()) { return; } else { registryCacheExecutor.execute(new SaveProperties(lastCacheChanged.incrementAndGet())); } logger.warn("Failed to save registry store file, cause: " + e.getMessage(), e); } }
Source:
public boolean isUpstreamRequired(final PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "url cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPSTREAM_ISSUE_NOT_REQUIRED.matcher(body); return !m.find(); }

Target:
public boolean isUpstreamRequired(final PullRequest pullRequest) { Objects.requireNonNull(pullRequest, "pull request cannot be null"); checkIssueTrackerExists(); final String body = pullRequest.getBody(); final Matcher m = UPSTREAM_ISSUE_NOT_REQUIRED.matcher(body); return !m.find(); }
Source:
public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forClassLoader( ClasspathHelper.contextClassLoader(), ClasspathHelper.staticClassLoader() ) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix(this.prefix) ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") && !name.endsWith("DyTxn") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }

Target:
public Iterable<Class<?>> allTypes() { return Iterables.filter( new Reflections( new ConfigurationBuilder() .setScanners( new SubTypesScanner(false), new ResourcesScanner() ) .setUrls( ClasspathHelper.forPackage(this.prefix) ).filterInputsBy( new FilterBuilder().include( FilterBuilder.prefix(this.prefix) ) ) ).getSubTypesOf(Object.class), new Predicate<Class<?>>() { @Override public boolean apply(final Class<?> input) { final String name = input.getName(); return !name.endsWith("Test") && !name.endsWith("ITCase") && !name.endsWith("ClasspathRule") && !name.endsWith("RepoRule") && !name.endsWith("DyTxn") && (input.getEnclosingClass() == null || name.endsWith("Smart")); } } ); }
Source:
public static Tree firstAncestorOfKind(Tree tree, Kind... kinds) { return firstAncestor(tree, t -> Arrays.asList(kinds).contains(t.getKind())); }

Target:
public static Tree firstAncestorOfKind(Tree tree, Kind... kinds) { return firstAncestor(tree, t -> t.is(kinds)); }
Source:
protected boolean invalidParam(String url) { return TextUtils.isEmpty(url); }

Target:
private boolean invalidParam(String url) { return TextUtils.isEmpty(url); }
Source:
public void testInitialEmptyFile() { observer.checkAndNotify(); verify(fileListener, times(0)).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, times(0)).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, times(0)).onFileDelete(any(File.class), any(Synchronization.class)); }

Target:
public void testInitialEmptyFile() { observer.checkAndNotify(); verify(fileListener, never()).onFileCreate(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileChange(any(File.class), any(Synchronization.class)); verify(fileListener, never()).onFileDelete(any(File.class), any(Synchronization.class)); }
Source:
public void testConcatFunctionInTopology() { String templateUrl = "classpath://templates EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity entity = Iterators.getOnlyElement(app.getChildren().iterator()); String value = entity.sensors().get(Sensors.newStringSensor("tosca.attribute.my_message")); assertEquals(value, "Message: It Works!"); }

Target:
public void testConcatFunctionInTopology() { String templateUrl = "classpath://templates/concat-function.yaml"; EntitySpec<? extends Application> spec = transformer.createApplicationSpec( new ResourceUtils(mgmt).getResourceAsString(templateUrl)); assertNotNull(spec); Application app = this.mgmt.getEntityManager().createEntity(spec); assertEquals(app.getChildren().size(), 1); Entity entity = Iterators.getOnlyElement(app.getChildren().iterator()); String value = entity.sensors().get(Sensors.newStringSensor("tosca.attribute.my_message")); assertEquals(value, "Message: It Works!"); }