instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public ApiResponse<List<Doctor>> getNewAndUpdatedDoctorsWithHttpInfo(String albertaApiKey, String updatedAfter) throws ApiException {
com.squareup.okhttp.Call call = getNewAndUpdatedDoctorsValidateBeforeCall(albertaApiKey, updatedAfter, null, null);
Type localVarReturnType = new TypeToken<List<Doctor>>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Daten der neuen und geänderten Ärzte abrufen (asynchronously)
* Szenario - das WaWi fragt bei Alberta nach, wie ob es neue oder geänderte Ärzte gibt
* @param albertaApiKey (required)
* @param updatedAfter 2021-02-21T09:30:00.000Z (im UTC-Format) (required)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call getNewAndUpdatedDoctorsAsync(String albertaApiKey, String updatedAfter, final ApiCallback<List<Doctor>> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) { | progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = getNewAndUpdatedDoctorsValidateBeforeCall(albertaApiKey, updatedAfter, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<List<Doctor>>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\DoctorApi.java | 2 |
请完成以下Java代码 | public class JSONArrayDemo {
public static void main(String[] args) {
System.out.println("6.1. Creating JSON Array: ");
creatingJSONArray();
System.out.println("\n6.2. Creating JSON Array from JSON string: ");
jsonArrayFromJSONString();
System.out.println("\n6.3. Creating JSON Array from Collection Object: ");
jsonArrayFromCollectionObj();
}
public static void creatingJSONArray() {
JSONArray ja = new JSONArray();
ja.put(Boolean.TRUE);
ja.put("lorem ipsum");
// We can also put a JSONObject in JSONArray
JSONObject jo = new JSONObject();
jo.put("name", "jon doe");
jo.put("age", "22");
jo.put("city", "chicago");
ja.put(jo);
System.out.println(ja.toString()); | }
public static void jsonArrayFromJSONString() {
JSONArray ja = new JSONArray("[true, \"lorem ipsum\", 215]");
System.out.println(ja);
}
public static void jsonArrayFromCollectionObj() {
List<String> list = new ArrayList<>();
list.add("California");
list.add("Texas");
list.add("Hawaii");
list.add("Alaska");
JSONArray ja = new JSONArray(list);
System.out.println(ja);
}
} | repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonjava\JSONArrayDemo.java | 1 |
请完成以下Java代码 | public void setIsHideWhenPrinting (final boolean IsHideWhenPrinting)
{
set_Value (COLUMNNAME_IsHideWhenPrinting, IsHideWhenPrinting);
}
@Override
public boolean isHideWhenPrinting()
{
return get_ValueAsBoolean(COLUMNNAME_IsHideWhenPrinting);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
} | @Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_Schema_TemplateLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringBootApacheGeodeClientCacheApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(SpringBootApacheGeodeClientCacheApplication.class)
.web(WebApplicationType.NONE)
.build()
.run(args);
}
@UseMemberName("SpringBootApacheGeodeClientCacheApplication")
static class GeodeConfiguration { }
private final Logger logger = LoggerFactory.getLogger(getClass());
@Bean
ApplicationRunner applicationAssertionRunner(ConfigurableApplicationContext applicationContext) {
return args -> {
Assert.notNull(applicationContext, "ApplicationContext is required"); | Environment environment = applicationContext.getEnvironment();
Assert.notNull(environment, "Environment is required");
Assert.isTrue(ArrayUtils.isEmpty(ArrayUtils.nullSafeArray(environment.getActiveProfiles(), String.class)),
"Expected Active Profiles to be empty");
Assert.isTrue(Arrays.asList(ArrayUtils.nullSafeArray(environment.getDefaultProfiles(), String.class))
.contains("default"), "Expected Default Profiles to contain 'default'");
ClientCache clientCache = applicationContext.getBean(ClientCache.class);
Assert.notNull(clientCache, "ClientCache is expected");
Assert.isTrue(SpringBootApacheGeodeClientCacheApplication.class.getSimpleName().equals(clientCache.getName()),
"ClientCache.name is not correct");
this.logger.info("Application assertions successful!");
};
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-docs\src\main\java\org\springframework\geode\docs\example\app\client\SpringBootApacheGeodeClientCacheApplication.java | 2 |
请完成以下Java代码 | public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public King getSuccessor() {
return successor;
}
public void setSuccessor(King successor) {
this.successor = successor;
}
public List<FatherAndSonRelation> getSons() {
return sons;
} | public void setSons(List<FatherAndSonRelation> sons) {
this.sons = sons;
}
/**
* 添加友谊的关系
* @param
*/
public void addRelation(FatherAndSonRelation fatherAndSonRelation){
if(this.sons == null){
this.sons = new ArrayList<>();
}
this.sons.add(fatherAndSonRelation);
}
} | repos\springBoot-master\springboot-neo4j\src\main\java\cn\abel\neo4j\bean\King.java | 1 |
请完成以下Java代码 | public Connection getConnection()
{
//
// First time => driver initialization
if (conn == null)
{
final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType);
if (dbDriver == null)
{
throw new IllegalStateException("No driver found for database type: " + dbType);
}
}
try
{
if (conn != null && !conn.isClosed()) | {
return conn;
}
final ISQLDatabaseDriver dbDriver = SQLDatabaseDriverFactory.get().getSQLDatabaseDriver(dbType);
conn = dbDriver.getConnection(dbHostname, dbPort, dbName, dbUser, dbPassword);
conn.setAutoCommit(true);
}
catch (final SQLException e)
{
throw new RuntimeException("Failed to get a JDBC connection. Please check your config for : " + this, e);
}
return conn;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\SQLDatabase.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
@Autowired
private UserRepository userRepository;
public Boolean authenticate(final String username, final String password) {
User user = userRepository.findByUsernameAndPassword(username, password);
return user != null;
}
public List<String> search(final String username) {
List<User> userList = userRepository.findByUsernameLikeIgnoreCase(username);
if (userList == null) {
return Collections.emptyList();
}
return userList.stream()
.map(User::getUsername)
.collect(Collectors.toList());
}
public void create(final String username, final String password) {
User newUser = new User(username,digestSHA(password));
newUser.setId(LdapUtils.emptyLdapName());
userRepository.save(newUser);
}
public void modify(final String username, final String password) {
User user = userRepository.findByUsername(username); | user.setPassword(password);
userRepository.save(user);
}
private String digestSHA(final String password) {
String base64;
try {
MessageDigest digest = MessageDigest.getInstance("SHA");
digest.update(password.getBytes());
base64 = Base64.getEncoder()
.encodeToString(digest.digest());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return "{SHA}" + base64;
}
} | repos\tutorials-master\spring-security-modules\spring-security-ldap\src\main\java\com\baeldung\ldap\data\service\UserService.java | 2 |
请完成以下Java代码 | public static int getCode(String define){
try {
return ResultStatus.valueOf(define).code;
} catch (IllegalArgumentException e) {
LOGGER.error("undefined error code: {}", define);
return FAIL.getErrorCode();
}
}
public static String getMsg(String define){
try {
return ResultStatus.valueOf(define).msg;
} catch (IllegalArgumentException e) {
LOGGER.error("undefined error code: {}", define);
return FAIL.getErrorMsg();
}
}
public static String getMsg(int code){
for(ResultStatus err : ResultStatus.values()){
if(err.code==code){ | return err.msg;
}
}
return "errorCode not defined ";
}
public int getErrorCode(){
return code;
}
public String getErrorMsg(){
return msg;
}
} | repos\spring-boot-quick-master\quick-exception\src\main\java\com\quick\exception\utils\ResultStatus.java | 1 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return List.of("timeToLive", "size");
}
@Validated
public static class RouteCacheConfiguration implements HasRouteId {
private @Nullable DataSize size;
private @Nullable Duration timeToLive;
private @Nullable String routeId;
public @Nullable DataSize getSize() {
return size;
}
public RouteCacheConfiguration setSize(@Nullable DataSize size) {
this.size = size;
return this;
}
public @Nullable Duration getTimeToLive() {
return timeToLive;
}
public RouteCacheConfiguration setTimeToLive(@Nullable Duration timeToLive) {
this.timeToLive = timeToLive; | return this;
}
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
@Override
public @Nullable String getRouteId() {
return this.routeId;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getStartDate()));
}
/** Set Training Class.
@param S_Training_Class_ID
The actual training class instance
*/
public void setS_Training_Class_ID (int S_Training_Class_ID)
{
if (S_Training_Class_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, Integer.valueOf(S_Training_Class_ID));
} | /** Get Training Class.
@return The actual training class instance
*/
public int getS_Training_Class_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_Class_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_Training getS_Training() throws RuntimeException
{
return (I_S_Training)MTable.get(getCtx(), I_S_Training.Table_Name)
.getPO(getS_Training_ID(), get_TrxName()); }
/** Set Training.
@param S_Training_ID
Repeated Training
*/
public void setS_Training_ID (int S_Training_ID)
{
if (S_Training_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Training_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID));
}
/** Get Training.
@return Repeated Training
*/
public int getS_Training_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Training_Class.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMessage() {
return message;
}
/**
* Sets the value of the message property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessage(String value) {
this.message = value;
}
/**
* Gets the value of the shortMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShortMessage() {
return shortMessage;
}
/**
* Sets the value of the shortMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShortMessage(String value) {
this.shortMessage = value;
}
/**
* Gets the value of the systemFullMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSystemFullMessage() {
return systemFullMessage;
}
/**
* Sets the value of the systemFullMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemFullMessage(String value) {
this.systemFullMessage = value;
}
/**
* Gets the value of the systemMessage property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getSystemMessage() {
return systemMessage;
}
/**
* Sets the value of the systemMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemMessage(String value) {
this.systemMessage = value;
}
/**
* Gets the value of the systemShortMessage property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSystemShortMessage() {
return systemShortMessage;
}
/**
* Sets the value of the systemShortMessage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSystemShortMessage(String value) {
this.systemShortMessage = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\ws\loginservice\v2_0\types\LoginException.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean grant(@NotEmpty List<Long> roleIds, @NotEmpty List<Long> menuIds, List<Long> dataScopeIds) {
// 删除角色配置的菜单集合
roleMenuService.remove(Wrappers.<RoleMenu>update().lambda().in(RoleMenu::getRoleId, roleIds));
// 组装配置
List<RoleMenu> roleMenus = new ArrayList<>();
roleIds.forEach(roleId -> menuIds.forEach(menuId -> {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenus.add(roleMenu);
}));
// 新增配置
roleMenuService.saveBatch(roleMenus);
// 删除角色配置的数据权限集合
roleScopeService.remove(Wrappers.<RoleScope>update().lambda().in(RoleScope::getRoleId, roleIds));
// 组装配置
List<RoleScope> roleDataScopes = new ArrayList<>();
roleIds.forEach(roleId -> dataScopeIds.forEach(scopeId -> {
RoleScope roleScope = new RoleScope();
roleScope.setRoleId(roleId);
roleScope.setScopeId(scopeId);
roleDataScopes.add(roleScope);
}));
// 新增配置
roleScopeService.saveBatch(roleDataScopes);
return true; | }
@Override
public String getRoleIds(String tenantId, String roleNames) {
List<Role> roleList = baseMapper.selectList(Wrappers.<Role>query().lambda().eq(Role::getTenantId, tenantId).in(Role::getRoleName, Func.toStrList(roleNames)));
if (roleList != null && roleList.size() > 0) {
return roleList.stream().map(role -> Func.toStr(role.getId())).distinct().collect(Collectors.joining(","));
}
return null;
}
@Override
public List<String> getRoleNames(String roleIds) {
return baseMapper.getRoleNames(Func.toLongArray(roleIds));
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\RoleServiceImpl.java | 2 |
请完成以下Java代码 | private static TableRecordReference extractRecordRef(@NonNull final Document document)
{
return TableRecordReference.of(document.getEntityDescriptor().getTableName(), document.getDocumentIdAsInt());
}
@Override
public DocumentId retrieveParentDocumentId(final DocumentEntityDescriptor parentEntityDescriptor, final DocumentQuery childDocumentQuery)
{
throw new UnsupportedOperationException(); // TODO
}
@Override
public Document createNewDocument(final DocumentEntityDescriptor entityDescriptor, @Nullable final Document parentDocument, final IDocumentChangesCollector changesCollector)
{
throw new UnsupportedOperationException();
}
@Override
public void refresh(final @NotNull Document document)
{
final AttributesIncludedTabDataKey key = extractKey(document);
final AttributesIncludedTabData data = attributesIncludedTabService.getData(key);
refreshDocumentFromData(document, data);
}
@Override
public SaveResult save(final @NotNull Document document)
{
final AttributesIncludedTabEntityBinding entityBinding = extractEntityBinding(document);
final AttributesIncludedTabData data = attributesIncludedTabService.updateByKey(
extractKey(document),
entityBinding.getAttributeIds(),
(attributeId, field) -> {
final String fieldName = entityBinding.getFieldNameByAttributeId(attributeId);
final IDocumentFieldView documentField = document.getFieldView(fieldName);
if (!documentField.hasChangesToSave())
{
return field;
}
final AttributesIncludedTabFieldBinding fieldBinding = extractFieldBinding(document, fieldName);
return fieldBinding.updateData( | field != null ? field : newDataField(fieldBinding),
documentField);
});
refreshDocumentFromData(document, data);
// Notify the parent document that one of its children were saved (copied from SqlDocumentsRepository)
document.getParentDocument().onChildSaved(document);
return SaveResult.SAVED;
}
private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding)
{
return AttributesIncludedTabDataField.builder()
.attributeId(fieldBinding.getAttributeId())
.valueType(fieldBinding.getAttributeValueType())
.build();
}
private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data)
{
document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data));
}
@Override
public void delete(final @NotNull Document document)
{
throw new UnsupportedOperationException();
}
@Override
public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;}
@Override
public int retrieveLastLineNo(final DocumentQuery query)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java | 1 |
请完成以下Java代码 | public I_C_Payment_Request createPaymentRequest(final I_C_Invoice invoice, final I_C_Payment_Request paymentRequestTemplate)
{
final I_C_Payment_Request requestForInvoice;
if (paymentRequestTemplate != null)
{
requestForInvoice = createNewFromTemplate(paymentRequestTemplate);
}
else
{
requestForInvoice = InterfaceWrapperHelper.newInstance(I_C_Payment_Request.class, invoice);
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final I_C_BPartner bpartner = bpartnerDAO.getById(bpartnerId);
// | // Find a default partner account
final IBPBankAccountDAO bankAccountDAO = Services.get(IBPBankAccountDAO.class);
final I_C_BP_BankAccount bpBankAccount = bankAccountDAO.retrieveDefaultBankAccountInTrx(bpartnerId)
.orElseThrow(() -> new AdempiereException("No default bank account found for " + bpartner.getName()));
requestForInvoice.setC_BP_BankAccount_ID(bpBankAccount.getC_BP_BankAccount_ID());
//
// Assume the invoice grand total for payment request amount
requestForInvoice.setAmount(invoice.getGrandTotal());
}
requestForInvoice.setC_Invoice(invoice);
InterfaceWrapperHelper.save(requestForInvoice);
return requestForInvoice;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaymentRequestBL.java | 1 |
请完成以下Java代码 | public void setRelativeWeight (BigDecimal RelativeWeight)
{
set_Value (COLUMNNAME_RelativeWeight, RelativeWeight);
}
/** Get Relative Weight.
@return Relative weight of this step (0 = ignored)
*/
public BigDecimal getRelativeWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/ | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CycleStep.java | 1 |
请完成以下Java代码 | public boolean contains(Object o) {
return deque.contains(o);
}
@Override
public Iterator<E> iterator() {
return deque.iterator();
}
@Override
public Object[] toArray() {
return deque.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return deque.toArray(a);
}
@Override
public boolean add(E e) {
return deque.add(e);
}
@Override
public boolean remove(Object o) {
return deque.remove(o);
}
@Override | public boolean containsAll(Collection<?> c) {
return deque.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return deque.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return deque.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return deque.retainAll(c);
}
@Override
public void clear() {
deque.clear();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-4\src\main\java\com\baeldung\collections\dequestack\ArrayLifoStack.java | 1 |
请完成以下Java代码 | public void parseStartEvent(Element startEventElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseSubProcess(Element subProcessElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTask(Element taskElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
@Override
public void parseTransaction(Element transactionElement, ScopeImpl scope, ActivityImpl activity) {
addExecutionListener(activity);
}
private void addExecutionListener(final ActivityImpl activity) {
if (executionListener != null) {
for (String event : EXECUTION_EVENTS) {
addListenerOnCoreModelElement(activity, executionListener, event);
}
}
}
private void addExecutionListener(final TransitionImpl transition) {
if (executionListener != null) {
addListenerOnCoreModelElement(transition, executionListener, EVENTNAME_TAKE);
}
} | private void addListenerOnCoreModelElement(CoreModelElement element,
DelegateListener<?> listener, String event) {
if (skippable) {
element.addListener(event, listener);
} else {
element.addBuiltInListener(event, listener);
}
}
private void addTaskListener(TaskDefinition taskDefinition) {
if (taskListener != null) {
for (String event : TASK_EVENTS) {
if (skippable) {
taskDefinition.addTaskListener(event, taskListener);
} else {
taskDefinition.addBuiltInTaskListener(event, taskListener);
}
}
}
}
/**
* Retrieves task definition.
*
* @param activity the taskActivity
* @return taskDefinition for activity
*/
private TaskDefinition taskDefinition(final ActivityImpl activity) {
final UserTaskActivityBehavior activityBehavior = (UserTaskActivityBehavior) activity.getActivityBehavior();
return activityBehavior.getTaskDefinition();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\event\PublishDelegateParseListener.java | 1 |
请完成以下Java代码 | public class DataGridRow {
protected int index;
protected List<DataGridField> fields = new ArrayList<DataGridField>();
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public List<DataGridField> getFields() {
return fields;
}
public void setFields(List<DataGridField> fields) {
this.fields = fields;
} | public DataGridRow clone() {
DataGridRow clone = new DataGridRow();
clone.setValues(this);
return clone;
}
public void setValues(DataGridRow otherRow) {
setIndex(otherRow.getIndex());
fields = new ArrayList<DataGridField>();
if (otherRow.getFields() != null && !otherRow.getFields().isEmpty()) {
for (DataGridField field : otherRow.getFields()) {
fields.add(field.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\DataGridRow.java | 1 |
请完成以下Java代码 | public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getAuthorizationUserId() {
return authorizationUserId;
}
public String getProcDefId() {
return procDefId;
}
public String getEventSubscriptionName() {
return eventSubscriptionName;
}
public String getEventSubscriptionType() {
return eventSubscriptionType;
}
public String getTenantId() {
return tenantId;
} | public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
@Override
public ProcessDefinitionQueryImpl startableByUser(String userId) {
if (userId == null) {
throw new ActivitiIllegalArgumentException("userId is null");
}
this.authorizationUserId = userId;
return this;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\ProcessDefinitionQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String isbn;
private int price;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private Author author;
@ManyToOne(fetch = FetchType.LAZY)
@JoinFormula("(SELECT b.id FROM book b "
+ "WHERE b.price < price AND b.author_id = author_id "
+ "ORDER BY b.price DESC "
+ "LIMIT 1)")
private Book nextBook;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
} | public void setAuthor(Author author) {
this.author = author;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Book getNextBook() {
return nextBook;
}
public void setNextBook(Book nextBook) {
this.nextBook = nextBook;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", price=" + price + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinFormula\src\main\java\com\bookstore\entity\Book.java | 2 |
请完成以下Java代码 | private I_Revolut_Payment_Export prepareRevolutPaymentExport(@NonNull final RevolutPaymentExport request)
{
final I_Revolut_Payment_Export record = loadOrNew(request.getRevolutPaymentExportId(), I_Revolut_Payment_Export.class);
final Currency currency = currencyDAO.getByCurrencyCode(request.getAmount().getCurrencyCode());
record.setAD_Org_ID(request.getOrgId().getRepoId());
record.setAD_Table_ID(request.getRecordReference().getAdTableId().getRepoId());
record.setRecord_ID(request.getRecordReference().getRecord_ID());
record.setName(request.getName());
record.setC_Currency_ID(currency.getId().getRepoId());
record.setAmount(request.getAmount().getAsBigDecimal());
record.setRecipientType(request.getRecipientType().getCode());
record.setRecipientBankCountryId(NumberUtils.asInt(request.getRecipientBankCountryId(), -1));
record.setAccountNo(request.getAccountNo());
record.setRoutingNo(request.getRoutingNo());
record.setIBAN(request.getIBAN());
record.setSwiftCode(record.getSwiftCode());
record.setPaymentReference(request.getPaymentReference());
record.setRecipientCountryId(NumberUtils.asInt(request.getRecipientCountryId(), -1));
record.setAddressLine1(request.getAddressLine1());
record.setAddressLine2(record.getAddressLine2());
record.setPostalCode(request.getPostalCode());
record.setCity(request.getCity());
record.setRegionName(request.getRegionName());
return record;
}
@NonNull
private RevolutPaymentExport toRevolutExport(@NonNull final I_Revolut_Payment_Export record)
{
final CurrencyId currencyId = CurrencyId.ofRepoId(record.getC_Currency_ID());
final CurrencyCode currencyCode = currencyDAO.getCurrencyCodeById(currencyId);
final Amount amount = Amount.of(record.getAmount(), currencyCode); | final TableRecordReference recordRef = TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID());
return RevolutPaymentExport.builder()
.revolutPaymentExportId(RevolutPaymentExportId.ofRepoId(record.getRevolut_Payment_Export_ID()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.recordReference(recordRef)
.name(record.getName())
.recipientType(RecipientType.ofCode(record.getRecipientType()))
.accountNo(record.getAccountNo())
.routingNo(record.getRoutingNo())
.IBAN(record.getIBAN())
.SwiftCode(record.getSwiftCode())
.amount(amount)
.recipientBankCountryId(CountryId.ofRepoIdOrNull(record.getRecipientBankCountryId()))
.paymentReference(record.getPaymentReference())
.recipientCountryId(CountryId.ofRepoIdOrNull(record.getRecipientCountryId()))
.regionName(record.getRegionName())
.addressLine1(record.getAddressLine1())
.addressLine2(record.getAddressLine2())
.city(record.getCity())
.postalCode(record.getPostalCode())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\RevolutExportRepo.java | 1 |
请完成以下Java代码 | public void bulkDeleteCommentsForTaskIds(Collection<String> taskIds) {
getDbSqlSession().delete("bulkDeleteCommentsForTaskIds", createSafeInValuesList(taskIds), CommentEntityImpl.class);
}
@Override
public void bulkDeleteCommentsForProcessInstanceIds(Collection<String> processInstanceIds) {
getDbSqlSession().delete("bulkDeleteCommentsForProcessInstanceIds", createSafeInValuesList(processInstanceIds), CommentEntityImpl.class);
}
@Override
@SuppressWarnings("unchecked")
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectCommentsByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<Comment> findCommentsByProcessInstanceId(String processInstanceId, String type) {
Map<String, Object> params = new HashMap<>(); | params.put("processInstanceId", processInstanceId);
params.put("type", type);
return getDbSqlSession().selectListWithRawParameter("selectCommentsByProcessInstanceIdAndType", params);
}
@Override
public Comment findComment(String commentId) {
return findById(commentId);
}
@Override
public Event findEvent(String commentId) {
return findById(commentId);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisCommentDataManager.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public int hashCode() {
return Objects.hash(address, id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CustomerSlim)) {
return false;
}
CustomerSlim other = (CustomerSlim) obj;
return Objects.equals(address, other.address) && id == other.id && Objects.equals(name, other.name);
}
@Override | public String toString() {
return "CustomerSlim [id=" + id + ", name=" + name + ", address=" + address + "]";
}
public static CustomerSlim[] fromCustomers(Customer[] customers) {
CustomerSlim[] feedback = new CustomerSlim[customers.length];
for (int i = 0; i < customers.length; i++) {
Customer aCustomer = customers[i];
CustomerSlim newOne = new CustomerSlim();
newOne.setId(aCustomer.getId());
newOne.setName(aCustomer.getFirstName() + " " + aCustomer.getLastName());
newOne.setAddress(aCustomer.getStreet() + ", " + aCustomer.getCity() + " " + aCustomer.getState() + " " + aCustomer.getPostalCode());
feedback[i] = newOne;
}
return feedback;
}
} | repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonoptimization\CustomerSlim.java | 1 |
请完成以下Java代码 | public List<String> remove(Object key) {
return headers.remove(key);
}
@Override
public void putAll(Map<? extends String, ? extends List<String>> m) {
headers.putAll(m);
}
@Override
public void clear() {
headers.clear();
}
@Override
public Set<String> keySet() {
return headers.keySet();
}
@Override
public Collection<List<String>> values() {
return headers.values();
}
@Override
public Set<Entry<String, List<String>>> entrySet() {
return headers.entrySet();
}
public void add(String headerName, String headerValue) {
headers.computeIfAbsent(headerName, key -> new ArrayList<>()).add(headerValue);
}
public String formatAsString() {
return formatAsString(false);
}
public String formatAsString(boolean maskValues) {
if (rawStringHeaders != null && !maskValues) {
return rawStringHeaders;
}
StringBuilder sb = new StringBuilder();
for (Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
for (String headerValue : entry.getValue()) {
sb.append(headerName);
if (headerValue != null) {
sb.append(": ").append(maskValues ? HEADER_VALUE_MASK : headerValue);
} else {
sb.append(":"); | }
sb.append('\n');
}
}
if (sb.length() > 0) {
// Delete the last new line (\n)
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
public static HttpHeaders parseFromString(String headersString) {
HttpHeaders headers = new HttpHeaders(headersString);
if (StringUtils.isNotEmpty(headersString)) {
try (BufferedReader reader = new BufferedReader(new StringReader(headersString))) {
String line = reader.readLine();
while (line != null) {
int colonIndex = line.indexOf(':');
if (colonIndex > 0) {
String headerName = line.substring(0, colonIndex);
if (line.length() > colonIndex + 2) {
headers.add(headerName, StringUtils.strip(line.substring(colonIndex + 1)));
} else {
headers.add(headerName, "");
}
line = reader.readLine();
} else {
throw new FlowableIllegalArgumentException("Header line '" + line + "' is invalid");
}
}
} catch (IOException ex) {
throw new FlowableException("IO exception occurred", ex);
}
}
return headers;
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpHeaders.java | 1 |
请完成以下Java代码 | private boolean updateRecursive(@NonNull final IAttributeStorage huAttributes)
{
boolean updated = update(huAttributes);
for (final IAttributeStorage childHUAttributes : huAttributes.getChildAttributeStorages(true))
{
if (updateRecursive(childHUAttributes))
{
updated = true;
}
}
return updated;
}
private boolean update(@NonNull final IAttributeStorage huAttributes)
{
if (!huAttributes.hasAttribute(AttributeConstants.ATTR_MonthsUntilExpiry))
{
return false;
}
final OptionalInt monthsUntilExpiry = computeMonthsUntilExpiry(huAttributes, today);
final int monthsUntilExpiryOld = huAttributes.getValueAsInt(AttributeConstants.ATTR_MonthsUntilExpiry);
if (monthsUntilExpiry.orElse(0) == monthsUntilExpiryOld)
{
return false;
}
huAttributes.setSaveOnChange(true);
if (monthsUntilExpiry.isPresent())
{
huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, monthsUntilExpiry.getAsInt());
}
else
{ | huAttributes.setValue(AttributeConstants.ATTR_MonthsUntilExpiry, null);
}
huAttributes.saveChangesIfNeeded();
return true;
}
static OptionalInt computeMonthsUntilExpiry(@NonNull final IAttributeStorage huAttributes, @NonNull final LocalDate today)
{
final LocalDate bestBeforeDate = huAttributes.getValueAsLocalDate(AttributeConstants.ATTR_BestBeforeDate);
if (bestBeforeDate == null)
{
return OptionalInt.empty();
}
final int monthsUntilExpiry = (int)ChronoUnit.MONTHS.between(today, bestBeforeDate);
return OptionalInt.of(monthsUntilExpiry);
}
private IAttributeStorage getHUAttributes(@NonNull final HuId huId, @NonNull final IHUContext huContext)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
return huContext
.getHUAttributeStorageFactory()
.getAttributeStorage(hu);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\UpdateMonthsUntilExpiryCommand.java | 1 |
请完成以下Java代码 | public void removeCurrentValue() {
deque.removeFirst();
updateMdcWithCurrentValue();
}
public void clearMdcProperty() {
if (isNotBlank(mdcName)) {
MdcAccess.remove(mdcName);
}
}
public void updateMdcWithCurrentValue() {
if (isNotBlank(mdcName)) {
String currentValue = getCurrentValue();
if (isNull(currentValue)) {
MdcAccess.remove(mdcName);
} else {
MdcAccess.put(mdcName, currentValue);
}
}
}
}
protected static class ProcessDataSections {
/**
* Keeps track of when we added values to which stack (as we do not add
* a new value to every stack with every update, but only changed values)
*/
protected Deque<List<ProcessDataStack>> sections = new ArrayDeque<>();
protected boolean currentSectionSealed = true;
/**
* Adds a stack to the current section. If the current section is already sealed,
* a new section is created.
*/
public void addToCurrentSection(ProcessDataStack stack) {
List<ProcessDataStack> currentSection; | if (currentSectionSealed) {
currentSection = new ArrayList<>();
sections.addFirst(currentSection);
currentSectionSealed = false;
} else {
currentSection = sections.peekFirst();
}
currentSection.add(stack);
}
/**
* Pops the current section and removes the
* current values from the referenced stacks (including updates
* to the MDC)
*/
public void popCurrentSection() {
List<ProcessDataStack> section = sections.pollFirst();
if (section != null) {
section.forEach(ProcessDataStack::removeCurrentValue);
}
currentSectionSealed = true;
}
/**
* After a section is sealed, a new section will be created
* with the next call to {@link #addToCurrentSection(ProcessDataStack)}
*/
public void sealCurrentSection() {
currentSectionSealed = true;
}
public int size() {
return sections.size();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ProcessDataContext.java | 1 |
请完成以下Java代码 | public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver");
settings.put(Environment.URL, "jdbc:hsqldb:mem:transient");
settings.put(Environment.USER, "sa");
settings.put(Environment.PASS, "");
settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect");
// enable to show Hibernate generated SQL
settings.put(Environment.SHOW_SQL, "false");
settings.put(Environment.FORMAT_SQL, "true");
settings.put(Environment.USE_SQL_COMMENTS, "true");
settings.put(Environment.HBM2DDL_AUTO, "update");
configuration.setProperties(settings); | configuration.addAnnotatedClass(Comment.class);
configuration.addAnnotatedClass(Post.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
} | repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\detachedentity\HibernateUtil.java | 1 |
请完成以下Java代码 | public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
public Profile getProfile() { | return profile;
}
public UserDO setProfile(Profile profile) {
this.profile = profile;
return this;
}
@Override
public String toString() {
return "UserDO{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", createTime=" + createTime +
", profile=" + profile +
'}';
}
} | repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\dataobject\UserDO.java | 1 |
请完成以下Java代码 | public boolean isDefaultCollapsed()
{
return defaultCollapsed;
}
@Override
public ListModel<ISideAction> getActions()
{
return actions;
}
@Override
public List<ISideAction> getActionsList()
{
final ISideAction[] actionsArr = new ISideAction[actions.getSize()];
actions.copyInto(actionsArr);
return ImmutableList.copyOf(actionsArr);
}
@Override
public void removeAllActions()
{
actions.clear();
}
@Override
public void addAction(final ISideAction action)
{
if (actions.contains(action))
{
return;
} | actions.addElement(action);
}
@Override
public void removeAction(final int index)
{
actions.remove(index);
}
@Override
public void setActions(final Iterable<? extends ISideAction> actions)
{
this.actions.clear();
if (actions != null)
{
final List<ISideAction> actionsList = ListUtils.copyAsList(actions);
Collections.sort(actionsList, ISideAction.COMPARATOR_ByDisplayName);
for (final ISideAction action : actionsList)
{
this.actions.addElement(action);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\SideActionsGroupModel.java | 1 |
请完成以下Java代码 | public CaseExecutionResource getCaseExecution(String caseExecutionId) {
return new CaseExecutionResourceImpl(getProcessEngine(), caseExecutionId, getObjectMapper());
}
@Override
public List<CaseExecutionDto> getCaseExecutions(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryCaseExecutions(queryDto, firstResult, maxResults);
}
@Override
public List<CaseExecutionDto> queryCaseExecutions(CaseExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseExecutionQuery query = queryDto.toQuery(engine);
List<CaseExecution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults);
List<CaseExecutionDto> executionResults = new ArrayList<CaseExecutionDto>();
for (CaseExecution execution : matchingExecutions) {
CaseExecutionDto resultExecution = CaseExecutionDto.fromCaseExecution(execution);
executionResults.add(resultExecution);
}
return executionResults;
}
@Override | public CountResultDto getCaseExecutionsCount(UriInfo uriInfo) {
CaseExecutionQueryDto queryDto = new CaseExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryCaseExecutionsCount(queryDto);
}
@Override
public CountResultDto queryCaseExecutionsCount(CaseExecutionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
CaseExecutionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\CaseExecutionRestServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Future<ResponseTransfer> getAccounts() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthAccounts result = web3Service.getEthAccounts();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
@RequestMapping(value = Constants.API_TRANSACTIONS, method = RequestMethod.GET)
public Future<ResponseTransfer> getTransactions() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthGetTransactionCount result = web3Service.getTransactionCount();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION); | }
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
@RequestMapping(value = Constants.API_BALANCE, method = RequestMethod.GET)
public Future<ResponseTransfer> getBalance() {
ResponseTransfer responseTransfer = new ResponseTransfer();
Instant start = TimeHelper.start();
return CompletableFuture.supplyAsync(() -> {
try {
EthGetBalance result = web3Service.getEthBalance();
responseTransfer.setMessage(result.toString());
} catch (Exception e) {
responseTransfer.setMessage(GENERIC_EXCEPTION);
}
return responseTransfer;
}).thenApplyAsync(result -> {
result.setPerformance(TimeHelper.stop(start));
return result;
});
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\controllers\EthereumRestController.java | 2 |
请完成以下Java代码 | public void setM_HU_Item_Storage(final de.metas.handlingunits.model.I_M_HU_Item_Storage M_HU_Item_Storage)
{
set_ValueFromPO(COLUMNNAME_M_HU_Item_Storage_ID, de.metas.handlingunits.model.I_M_HU_Item_Storage.class, M_HU_Item_Storage);
}
@Override
public void setM_HU_Item_Storage_ID (final int M_HU_Item_Storage_ID)
{
if (M_HU_Item_Storage_ID < 1)
set_Value (COLUMNNAME_M_HU_Item_Storage_ID, null);
else
set_Value (COLUMNNAME_M_HU_Item_Storage_ID, M_HU_Item_Storage_ID);
}
@Override
public int getM_HU_Item_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_ID);
}
@Override
public void setM_HU_Item_Storage_Snapshot_ID (final int M_HU_Item_Storage_Snapshot_ID)
{
if (M_HU_Item_Storage_Snapshot_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Item_Storage_Snapshot_ID, M_HU_Item_Storage_Snapshot_ID);
}
@Override
public int getM_HU_Item_Storage_Snapshot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Item_Storage_Snapshot_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSnapshot_UUID (final java.lang.String Snapshot_UUID)
{
set_Value (COLUMNNAME_Snapshot_UUID, Snapshot_UUID);
}
@Override
public java.lang.String getSnapshot_UUID()
{
return get_ValueAsString(COLUMNNAME_Snapshot_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Item_Storage_Snapshot.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class IntegerType implements VariableType {
public static final String TYPE_NAME = "integer";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
if (valueFields.getLongValue() != null) {
return Integer.valueOf(valueFields.getLongValue().intValue());
}
return null;
} | @Override
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
valueFields.setLongValue(((Integer) value).longValue());
valueFields.setTextValue(value.toString());
} else {
valueFields.setLongValue(null);
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Integer.class.isAssignableFrom(value.getClass()) || int.class.isAssignableFrom(value.getClass());
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\IntegerType.java | 2 |
请完成以下Java代码 | public void deleteScript(@PathVariable("filename") final String filename)
{
assertAuth();
final Path scriptPath = getMigrationScriptPath(filename);
deleteScript(scriptPath);
}
private ResponseEntity<byte[]> getScript(@NonNull final Path scriptPath, final boolean inline)
{
final String contentDispositionType = inline ? "inline" : "attachment";
final byte[] content = getScriptContent(scriptPath);
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.set(HttpHeaders.CONTENT_DISPOSITION, contentDispositionType + "; filename=\"" + scriptPath.getFileName() + "\"");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(content, headers, HttpStatus.OK);
}
private byte[] getScriptContent(@NonNull final Path scriptPath)
{
try
{
final ArrayList<String> lines = new ArrayList<>();
lines.add("--");
lines.add("-- Script: " + scriptPath);
lines.add("-- User: " + getUserName());
lines.add("-- OS user: " + System.getProperty("user.name"));
lines.add("--");
lines.add("");
lines.add("");
lines.addAll(Files.readAllLines(scriptPath));
return toByteArray(lines);
}
catch (final IOException ex)
{
throw new AdempiereException("Failed reading content of " + scriptPath, ex);
}
}
private static byte[] toByteArray(final List<String> lines)
{
try (final ByteArrayOutputStream out = new ByteArrayOutputStream())
{
lines.stream()
.map(s -> s + "\n")
.map(s -> s.getBytes(StandardCharsets.UTF_8))
.forEach(bytes -> { | try
{
out.write(bytes);
}
catch (final IOException ex)
{
// shall never happen
throw AdempiereException.wrapIfNeeded(ex);
}
});
return out.toByteArray();
}
catch (final IOException ex)
{
// shall never happen
throw AdempiereException.wrapIfNeeded(ex);
}
}
private void deleteScript(@NonNull final Path scriptPath)
{
try
{
Files.delete(scriptPath);
}
catch (final IOException ex)
{
throw new AdempiereException("Failed deleting " + scriptPath, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\rest\MigrationScriptRestControllerTemplate.java | 1 |
请完成以下Java代码 | protected void registerConnectors(Map<String, Connector<?>> connectors, ClassLoader classLoader) {
ServiceLoader<ConnectorProvider> providers = ServiceLoader.load(ConnectorProvider.class, classLoader);
for (ConnectorProvider provider : providers) {
registerProvider(connectors, provider);
}
}
protected void registerProvider(Map<String, Connector<?>> connectors, ConnectorProvider provider) {
String connectorId = provider.getConnectorId();
if (connectors.containsKey(connectorId)) {
throw LOG.multipleConnectorProvidersFound(connectorId);
} else {
Connector<?> connectorInstance = provider.createConnectorInstance();
LOG.connectorProviderDiscovered(provider, connectorId, connectorInstance);
connectors.put(connectorId, connectorInstance);
}
}
protected void registerConnectorInstance(String connectorId, Connector<?> connector) {
ensureConnectorProvidersInitialized();
synchronized (Connectors.class) {
availableConnectors.put(connectorId, connector);
}
}
protected void unregisterConnectorInstance(String connectorId) {
ensureConnectorProvidersInitialized();
synchronized (Connectors.class) { | availableConnectors.remove(connectorId);
}
}
@SuppressWarnings("rawtypes")
protected void applyConfigurators(Map<String, Connector<?>> connectors, ClassLoader classLoader) {
ServiceLoader<ConnectorConfigurator> configurators = ServiceLoader.load(ConnectorConfigurator.class, classLoader);
for (ConnectorConfigurator configurator : configurators) {
LOG.connectorConfiguratorDiscovered(configurator);
applyConfigurator(connectors, configurator);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void applyConfigurator(Map<String, Connector<?>> connectors, ConnectorConfigurator configurator) {
for (Connector<?> connector : connectors.values()) {
if (configurator.getConnectorClass().isAssignableFrom(connector.getClass())) {
configurator.configure(connector);
}
}
}
} | repos\camunda-bpm-platform-master\connect\core\src\main\java\org\camunda\connect\Connectors.java | 1 |
请完成以下Java代码 | public void addLineItem(OrderLine orderLine) {
checkNotNull(orderLine);
orderLines.add(orderLine);
totalCost = totalCost.plus(orderLine.cost());
}
public List<OrderLine> getOrderLines() {
return new ArrayList<>(orderLines);
}
public void removeLineItem(int line) {
OrderLine removedLine = orderLines.remove(line);
totalCost = totalCost.minus(removedLine.cost());
}
public Money totalCost() { | return totalCost;
}
private Money calculateTotalCost() {
return orderLines.stream()
.map(OrderLine::cost)
.reduce(Money::plus)
.get();
}
private static void checkNotNull(Object par) {
if (par == null) {
throw new NullPointerException("Parameter cannot be null");
}
}
} | repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\Order.java | 1 |
请完成以下Java代码 | boolean loadDat(String path)
{
ByteArray byteArray = ByteArray.createByteArray(path + Predefine.BIN_EXT);
if (byteArray == null) return false;
int size = byteArray.nextInt();
Attribute[] attributeArray = new Attribute[size];
for (int i = 0; i < attributeArray.length; ++i)
{
int length = byteArray.nextInt();
Attribute attribute = new Attribute(length);
for (int j = 0; j < attribute.dependencyRelation.length; ++j)
{
attribute.dependencyRelation[j] = byteArray.nextString();
attribute.p[j] = byteArray.nextFloat();
}
attributeArray[i] = attribute;
}
return trie.load(byteArray, attributeArray);
}
public Attribute get(String key)
{
return trie.get(key);
}
/**
* 打分
* @param from
* @param to
* @return
*/
public Edge getEdge(Node from, Node to)
{
// 首先尝试词+词
Attribute attribute = get(from.compiledWord, to.compiledWord);
if (attribute == null) attribute = get(from.compiledWord, WordNatureWeightModelMaker.wrapTag(to.label));
if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), to.compiledWord);
if (attribute == null) attribute = get(WordNatureWeightModelMaker.wrapTag(from.label), WordNatureWeightModelMaker.wrapTag(to.label));
if (attribute == null)
{
attribute = Attribute.NULL;
}
if (HanLP.Config.DEBUG)
{
System.out.println(from + " 到 " + to + " : " + attribute);
}
return new Edge(from.id, to.id, attribute.dependencyRelation[0], attribute.p[0]);
}
public Attribute get(String from, String to)
{
return get(from + "@" + to);
}
static class Attribute
{
final static Attribute NULL = new Attribute("未知", 10000.0f);
/**
* 依存关系
*/
public String[] dependencyRelation;
/**
* 概率
*/
public float[] p;
public Attribute(int size)
{
dependencyRelation = new String[size];
p = new float[size];
} | Attribute(String dr, float p)
{
dependencyRelation = new String[]{dr};
this.p = new float[]{p};
}
/**
* 加权
* @param boost
*/
public void setBoost(float boost)
{
for (int i = 0; i < p.length; ++i)
{
p[i] *= boost;
}
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder(dependencyRelation.length * 10);
for (int i = 0; i < dependencyRelation.length; ++i)
{
sb.append(dependencyRelation[i]).append(' ').append(p[i]).append(' ');
}
return sb.toString();
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\bigram\WordNatureDependencyModel.java | 1 |
请完成以下Java代码 | public String getDueDate() {
return dueDate;
}
public void setDueDate(String dueDate) {
this.dueDate = dueDate;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getOwner() {
return owner;
} | public void setOwner(String owner) {
this.owner = owner;
}
public List<String> getCandidateUsers() {
return candidateUsers;
}
public void setCandidateUsers(List<String> candidateUsers) {
this.candidateUsers = candidateUsers;
}
public List<String> getCandidateGroups() {
return candidateGroups;
}
public void setCandidateGroups(List<String> candidateGroups) {
this.candidateGroups = candidateGroups;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateHumanTaskBeforeContext.java | 1 |
请完成以下Java代码 | private void copyProposalLines(
@NonNull final I_C_Order fromProposal,
@NonNull final I_C_Order newOrder)
{
CopyRecordFactory.getCopyRecordSupport(I_C_Order.Table_Name)
.onChildRecordCopied(this::onRecordCopied)
.copyChildren(
InterfaceWrapperHelper.getPO(newOrder),
InterfaceWrapperHelper.getPO(fromProposal));
}
private void onRecordCopied(@NonNull final PO to, @NonNull final PO from, @NonNull final CopyTemplate template)
{
if (InterfaceWrapperHelper.isInstanceOf(to, I_C_OrderLine.class)
&& InterfaceWrapperHelper.isInstanceOf(from, I_C_OrderLine.class))
{
final I_C_OrderLine newOrderLine = InterfaceWrapperHelper.create(to, I_C_OrderLine.class);
final I_C_OrderLine fromProposalLine = InterfaceWrapperHelper.create(from, I_C_OrderLine.class);
newOrderLine.setRef_ProposalLine_ID(fromProposalLine.getC_OrderLine_ID());
orderDAO.save(newOrderLine);
createPurchaseOrderAllocRecord(newOrderLine, fromProposalLine);
}
}
private void createPurchaseOrderAllocRecord(final I_C_OrderLine newOrderLine, final I_C_OrderLine fromOrderLine)
{
final I_C_PurchaseCandidate_Alloc alloc = queryBL.createQueryBuilder(I_C_PurchaseCandidate_Alloc.class)
.addEqualsFilter(I_C_PurchaseCandidate_Alloc.COLUMN_C_OrderLinePO_ID, fromOrderLine.getC_OrderLine_ID())
.create().first();
if(alloc == null)
{
return;
}
final I_C_PurchaseCandidate_Alloc purchaseCandidateAlloc = InterfaceWrapperHelper.copy()
.setFrom(alloc)
.copyToNew(I_C_PurchaseCandidate_Alloc.class);
purchaseCandidateAlloc.setC_OrderPO_ID(newOrderLine.getC_Order_ID());
purchaseCandidateAlloc.setC_OrderLinePO_ID(newOrderLine.getC_OrderLine_ID());
InterfaceWrapperHelper.save(purchaseCandidateAlloc);
markProcessed(PurchaseCandidateId.ofRepoId(purchaseCandidateAlloc.getC_PurchaseCandidate_ID()));
} | private void markProcessed(final PurchaseCandidateId cPurchaseCandidateId)
{
final I_C_PurchaseCandidate candidate = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class)
.addEqualsFilter(I_C_PurchaseCandidate.COLUMN_C_PurchaseCandidate_ID, cPurchaseCandidateId)
.create()
.first();
Check.assumeNotNull(candidate, "Could not find a Purchase candidate for line C_PurchaseCandidate_ID {}", cPurchaseCandidateId);
candidate.setProcessed(true);
InterfaceWrapperHelper.save(candidate);
}
private void completePurchaseOrderIfNeeded(final I_C_Order newOrder)
{
if (completeIt)
{
documentBL.processEx(newOrder, IDocument.ACTION_Complete, IDocument.STATUS_Completed);
}
else
{
newOrder.setDocAction(IDocument.ACTION_Prepare);
orderDAO.save(newOrder);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\command\CreatePurchaseOrderFromRequisitionCommand.java | 1 |
请完成以下Java代码 | public String formatAsString() {
return formatAsString(false);
}
public String formatAsString(boolean maskValues) {
if (rawStringHeaders != null && !maskValues) {
return rawStringHeaders;
}
StringBuilder sb = new StringBuilder();
for (Entry<String, List<String>> entry : headers.entrySet()) {
String headerName = entry.getKey();
for (String headerValue : entry.getValue()) {
sb.append(headerName);
if (headerValue != null) {
sb.append(": ").append(maskValues ? HEADER_VALUE_MASK : headerValue);
} else {
sb.append(":");
}
sb.append('\n');
}
}
if (sb.length() > 0) {
// Delete the last new line (\n)
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
} | public static HttpHeaders parseFromString(String headersString) {
HttpHeaders headers = new HttpHeaders(headersString);
if (StringUtils.isNotEmpty(headersString)) {
try (BufferedReader reader = new BufferedReader(new StringReader(headersString))) {
String line = reader.readLine();
while (line != null) {
int colonIndex = line.indexOf(':');
if (colonIndex > 0) {
String headerName = line.substring(0, colonIndex);
if (line.length() > colonIndex + 2) {
headers.add(headerName, StringUtils.strip(line.substring(colonIndex + 1)));
} else {
headers.add(headerName, "");
}
line = reader.readLine();
} else {
throw new FlowableIllegalArgumentException("Header line '" + line + "' is invalid");
}
}
} catch (IOException ex) {
throw new FlowableException("IO exception occurred", ex);
}
}
return headers;
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\api\HttpHeaders.java | 1 |
请完成以下Java代码 | /* package */final class PlainProductionMaterial extends AbstractProductionMaterial
{
private final I_M_Product product;
private final BigDecimal qty;
private final I_C_UOM uom;
private final ProductionMaterialType type;
private BigDecimal qtyDeliveredPercOfRaw = BigDecimal.ZERO;
private BigDecimal qtyDeliveredAvg = BigDecimal.ZERO;
private final IHandlingUnitsInfo handlingUnitsInfo = null;
public PlainProductionMaterial(
@NonNull final ProductionMaterialType type,
@NonNull final I_M_Product product,
@NonNull final BigDecimal qty,
@NonNull final I_C_UOM uom)
{
this.product = product;
this.qty = qty;
this.uom = uom;
this.type = type;
}
@Override
public String toString()
{
return "PlainProductionMaterial ["
+ "product=" + product.getName()
+ ", qty=" + qty + " " + uom.getUOMSymbol()
+ ", type=" + type
+ "]";
}
@Override
public I_M_Product getM_Product()
{
return product;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public ProductionMaterialType getType()
{
return type;
}
@Override
public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw)
{
Check.assumeNotNull(qtyDeliveredPercOfRaw, "qtyDeliveredPercOfRaw not null");
this.qtyDeliveredPercOfRaw = qtyDeliveredPercOfRaw;
}
@Override
public BigDecimal getQM_QtyDeliveredPercOfRaw() | {
return qtyDeliveredPercOfRaw;
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
Check.assumeNotNull(qtyDeliveredAvg, "qtyDeliveredAvg not null");
this.qtyDeliveredAvg = qtyDeliveredAvg;
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return qtyDeliveredAvg;
}
@Override
public String getVariantGroup()
{
return null;
}
@Override
public BOMComponentType getComponentType()
{
return null;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
return handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainProductionMaterial.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Date extractDate(@NonNull final Map<String, Object> map, @NonNull final String key)
{
final Object value = getValue(map, key);
if (value == null)
{
return null;
}
if (value instanceof Date)
{
return (Date)value;
}
//
// Fallback: try parsing the dates from strings using some common predefined formats
// NOTE: this shall not happen very often because we take care of dates when we are parsing the Excel file.
final String valueStr = value.toString().trim();
if (valueStr.isEmpty())
{
return null;
}
for (final DateFormat dateFormat : dateFormats) | {
try
{
return dateFormat.parse(valueStr);
}
catch (final ParseException e)
{
// ignore it
}
}
return null;
}
private static <T> T coalesce(final T value, final T defaultValue)
{
return value == null ? defaultValue : value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\excelimport\Excel_OLCand_Row_Builder.java | 2 |
请完成以下Java代码 | public static String toValue(@Nullable final ExternalId externalId)
{
if (externalId == null)
{
return null;
}
return externalId.getValue();
}
/**
* @return {@code true} if the given {@code externalId} is the same as {@link #INVALID}.
*/
public static boolean isInvalid(@Nullable final ExternalId externalId)
{
if (externalId == null)
{
return false;
} | return externalId == INVALID;
}
@JsonValue
@NonNull
public String getValue()
{
return value;
}
@Override
public int compareTo(@NonNull final ExternalId o)
{
return value.compareTo(o.value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\ExternalId.java | 1 |
请完成以下Java代码 | public Criteria andFinishOrderAmountNotIn(List<BigDecimal> values) {
addCriterion("finish_order_amount not in", values, "finishOrderAmount");
return (Criteria) this;
}
public Criteria andFinishOrderAmountBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("finish_order_amount between", value1, value2, "finishOrderAmount");
return (Criteria) this;
}
public Criteria andFinishOrderAmountNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("finish_order_amount not between", value1, value2, "finishOrderAmount");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() { | return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTagExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getCompletedBy() {
return completedBy;
}
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue; | }
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | public Stream<DocumentFilter> stream()
{
return filtersById.values().stream();
}
public DocumentFilterList mergeWith(@NonNull final DocumentFilterList other)
{
if (isEmpty())
{
return other;
}
else if (other.isEmpty())
{
return this;
}
else
{
final LinkedHashMap<String, DocumentFilter> filtersByIdNew = new LinkedHashMap<>(this.filtersById);
filtersByIdNew.putAll(other.filtersById);
return ofMap(filtersByIdNew);
}
}
public DocumentFilterList mergeWith(@NonNull final DocumentFilter filter)
{
if (isEmpty())
{
return of(filter);
}
else
{
final LinkedHashMap<String, DocumentFilter> filtersByIdNew = new LinkedHashMap<>(this.filtersById);
filtersByIdNew.put(filter.getFilterId(), filter);
return ofMap(filtersByIdNew);
}
}
public DocumentFilterList mergeWithNullable(@Nullable final DocumentFilter filter)
{
return filter != null ? mergeWith(filter) : this;
}
public Optional<DocumentFilter> getFilterById(@NonNull final String filterId)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
return Optional.ofNullable(filter);
}
private DocumentFilter getFilterByIdOrNull(@NonNull final String filterId)
{
return filtersById.get(filterId);
}
public void forEach(@NonNull final Consumer<DocumentFilter> consumer)
{
filtersById.values().forEach(consumer);
} | @Nullable
public String getParamValueAsString(final String filterId, final String parameterName)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return null;
}
return filter.getParameterValueAsString(parameterName);
}
public int getParamValueAsInt(final String filterId, final String parameterName, final int defaultValue)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return defaultValue;
}
return filter.getParameterValueAsInt(parameterName, defaultValue);
}
public boolean getParamValueAsBoolean(final String filterId, final String parameterName, final boolean defaultValue)
{
final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null)
{
return defaultValue;
}
return filter.getParameterValueAsBoolean(parameterName, defaultValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterList.java | 1 |
请完成以下Java代码 | private List<Integer> selectIntegers(final String preparedStatement,
final int parameter, final String trxName)
{
ResultSet rs = null;
PreparedStatement pstmt = null;
List<Integer> result = new ArrayList<Integer>();
try
{
pstmt = DB.prepareStatement(preparedStatement, trxName);
pstmt.setInt(1, parameter);
rs = pstmt.executeQuery();
while (rs.next())
{
result.add(rs.getInt(1));
}
return result;
}
catch (SQLException e)
{
MetasfreshLastError.saveError(logger, "Unable to select an integer. SQL statement: "
+ preparedStatement + "; parameter: " + parameter, e);
throw new RuntimeException(e);
}
finally
{
DB.close(rs, pstmt);
}
}
private void updateIsSummary(final int categoryId, final char isSummary,
final String trxName)
{
ResultSet rs = null;
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement(SQL_UPDATE_ISSUMMARY, trxName);
pstmt.setString(1, Character.toString(isSummary));
pstmt.setInt(2, categoryId);
pstmt.executeUpdate();
} | catch (SQLException e)
{
MetasfreshLastError.saveError(logger, "Unable to update IsSummary", e);
}
finally
{
DB.close(rs, pstmt);
}
}
private void setIntOrNull(final PreparedStatement pstmt, final int idx,
final Integer param) throws SQLException
{
if (param == null)
{
pstmt.setNull(idx, Types.INTEGER);
}
else
{
pstmt.setInt(idx, param);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\modelvalidator\MProductCategoryValidator.java | 1 |
请完成以下Java代码 | public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Note.
@param Note
Optional additional user defined information
*/
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Achievement.
@param PA_Achievement_ID
Performance Achievement
*/
public void setPA_Achievement_ID (int PA_Achievement_ID)
{
if (PA_Achievement_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, Integer.valueOf(PA_Achievement_ID));
}
/** Get Achievement.
@return Performance Achievement
*/
public int getPA_Achievement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Achievement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_Measure getPA_Measure() throws RuntimeException
{ | return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name)
.getPO(getPA_Measure_ID(), get_TrxName()); }
/** Set Measure.
@param PA_Measure_ID
Concrete Performance Measurement
*/
public void setPA_Measure_ID (int PA_Measure_ID)
{
if (PA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID));
}
/** Get Measure.
@return Concrete Performance Measurement
*/
public int getPA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java | 1 |
请完成以下Java代码 | public void addMaterialTrackingListener(final String tableName, @NonNull final IMaterialTrackingListener listener)
{
Check.assumeNotEmpty(tableName, "tableName not empty");
List<IMaterialTrackingListener> listeners = tableName2listeners.get(tableName);
if (listeners == null)
{
listeners = new CopyOnWriteArrayList<>();
tableName2listeners.put(tableName, listeners);
}
// Don't add it again if it was already added
if (listeners.contains(listener))
{
return;
}
listeners.add(listener);
}
@Override
public void beforeModelLinked(
@NonNull final MTLinkRequest request,
@NonNull final I_M_Material_Tracking_Ref materialTrackingRef)
{
for (final IMaterialTrackingListener listener : getListenersForModel(request.getModel()))
{
listener.beforeModelLinked(request, materialTrackingRef);
}
}
@Override
public void afterModelLinked(final MTLinkRequest request)
{
for (final IMaterialTrackingListener listener : getListenersForModel(request.getModel()))
{
listener.afterModelLinked(request);
}
}
@Override
public void afterModelUnlinked(final Object model,
final I_M_Material_Tracking materialTrackingOld)
{
for (final IMaterialTrackingListener listener : getListenersForModel(model))
{
listener.afterModelUnlinked(model, materialTrackingOld);
}
}
@Override
public void afterQtyIssuedChanged(
@NonNull final I_M_Material_Tracking_Ref materialTrackingRef,
@NonNull final BigDecimal oldValue)
{ | final String tableName = Services.get(IADTableDAO.class).retrieveTableName(materialTrackingRef.getAD_Table_ID());
for (final IMaterialTrackingListener listener : getListenersForTableName(tableName))
{
listener.afterQtyIssuedChanged(materialTrackingRef, oldValue);
}
}
private List<IMaterialTrackingListener> getListenersForModel(final Object model)
{
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
return getListenersForTableName(tableName);
}
private List<IMaterialTrackingListener> getListenersForTableName(final String tableName)
{
final List<IMaterialTrackingListener> listeners = tableName2listeners.get(tableName);
if (listeners == null || listeners.isEmpty())
{
return Collections.emptyList();
}
return listeners;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\listeners\CompositeMaterialTrackingListener.java | 1 |
请完成以下Java代码 | public ResponseEntity<List<Foo>> getAllFoos() {
List<Foo> fooList = (List<Foo>) repository.findAll();
if (fooList.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(fooList, HttpStatus.OK);
}
@GetMapping(value = "{id}")
public ResponseEntity<Foo> getFooById(@PathVariable("id") Long id) {
Optional<Foo> foo = repository.findById(id);
return foo.map(value -> new ResponseEntity<>(value, HttpStatus.OK))
.orElseGet(() -> new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
@PostMapping
public ResponseEntity<Foo> addFoo(@RequestBody @Valid Foo foo) {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setLocation(linkTo(FooController.class).slash(foo.getId())
.toUri());
Foo savedFoo;
try {
savedFoo = repository.save(foo);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(savedFoo, httpHeaders, HttpStatus.CREATED);
} | @DeleteMapping("/{id}")
public ResponseEntity<Void> deleteFoo(@PathVariable("id") long id) {
try {
repository.deleteById(id);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@PutMapping("/{id}")
public ResponseEntity<Foo> updateFoo(@PathVariable("id") long id, @RequestBody Foo foo) {
boolean isFooPresent = repository.existsById(id);
if (!isFooPresent) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Foo updatedFoo = repository.save(foo);
return new ResponseEntity<>(updatedFoo, HttpStatus.OK);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\restdocopenapi\FooController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void inactivateDiscountSchemaBreakRecords(@NonNull final PricingConditionsBreak db)
{
final I_M_DiscountSchemaBreak record = getPricingConditionsBreakbyId(db.getId());
record.setIsActive(false);
saveRecord(record);
}
@Override
public boolean isSingleProductId(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final Set<ProductId> distinctProductIds = retrieveDistinctProductIdsForSelection(selectionFilter);
return distinctProductIds.size() == 1;
}
@Override
public ProductId retrieveUniqueProductIdForSelectionOrNull(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final Set<ProductId> distinctProductsForSelection = retrieveDistinctProductIdsForSelection(selectionFilter);
if (distinctProductsForSelection.isEmpty())
{
return null;
}
if (distinctProductsForSelection.size() > 1)
{
throw new AdempiereException("Multiple products or none in the selected rows")
.appendParametersToMessage()
.setParameter("selectionFilter", selectionFilter);
}
final ProductId uniqueProductId = distinctProductsForSelection.iterator().next(); | return uniqueProductId;
}
private Set<ProductId> retrieveDistinctProductIdsForSelection(final IQueryFilter<I_M_DiscountSchemaBreak> selectionFilter)
{
final IQuery<I_M_DiscountSchemaBreak> breaksQuery = queryBL.createQueryBuilder(I_M_DiscountSchemaBreak.class)
.filter(selectionFilter)
.create();
final List<Integer> distinctProductRecordIds = breaksQuery.listDistinct(I_M_DiscountSchemaBreak.COLUMNNAME_M_Product_ID, Integer.class);
return ProductId.ofRepoIds(distinctProductRecordIds);
}
public I_M_DiscountSchemaBreak getPricingConditionsBreakbyId(@NonNull PricingConditionsBreakId discountSchemaBreakId)
{
return load(discountSchemaBreakId.getDiscountSchemaBreakId(), I_M_DiscountSchemaBreak.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\impl\PricingConditionsRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | final List<JsonTag> computeTags(@NonNull final Document document)
{
final ImmutableList.Builder<JsonTag> tags = ImmutableList.builder();
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ID, document.getId()));
if (document.isArchived() != null)
{
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ARCHIVED, String.valueOf(document.isArchived())));
}
final BigDecimal therapyId = document.getTherapyId();
if (therapyId != null)
{
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_THERAPYID, String.valueOf(therapyId)));
}
final BigDecimal therapyTypeId = document.getTherapyTypeId();
if (therapyTypeId != null)
{
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_THERAPYTYPEID, String.valueOf(therapyTypeId)));
} | final OffsetDateTime createdAt = document.getCreatedAt();
if (createdAt != null)
{
final Instant createdAtInstant = AlbertaUtil.asInstant(createdAt);
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_CREATEDAT, String.valueOf(createdAtInstant)));
}
final OffsetDateTime updatedAt = document.getUpdatedAt();
if (updatedAt != null)
{
final Instant updatedAtInstant = AlbertaUtil.asInstant(updatedAt);
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_UPDATEDAT, String.valueOf(updatedAtInstant)));
}
tags.add(JsonTag.of(GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ENDPOINT, GetAttachmentRouteConstants.ALBERTA_DOCUMENT_ENDPOINT_VALUE));
return tags.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\attachment\processor\DocumentProcessor.java | 2 |
请完成以下Java代码 | public int getAlberta_OrderedArticleLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Alberta_OrderedArticleLine_ID);
}
@Override
public void setC_OLCand_ID (final int C_OLCand_ID)
{
if (C_OLCand_ID < 1)
set_Value (COLUMNNAME_C_OLCand_ID, null);
else
set_Value (COLUMNNAME_C_OLCand_ID, C_OLCand_ID);
}
@Override
public int getC_OLCand_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCand_ID);
}
@Override
public void setDurationAmount (final @Nullable BigDecimal DurationAmount)
{
set_Value (COLUMNNAME_DurationAmount, DurationAmount);
}
@Override
public BigDecimal getDurationAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_DurationAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setExternalId (final String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setExternallyUpdatedAt (final @Nullable java.sql.Timestamp ExternallyUpdatedAt)
{
set_Value (COLUMNNAME_ExternallyUpdatedAt, ExternallyUpdatedAt);
}
@Override
public java.sql.Timestamp getExternallyUpdatedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_ExternallyUpdatedAt);
}
@Override
public void setIsPrivateSale (final boolean IsPrivateSale)
{
set_Value (COLUMNNAME_IsPrivateSale, IsPrivateSale);
} | @Override
public boolean isPrivateSale()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrivateSale);
}
@Override
public void setIsRentalEquipment (final boolean IsRentalEquipment)
{
set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment);
}
@Override
public boolean isRentalEquipment()
{
return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment);
}
@Override
public void setSalesLineId (final @Nullable String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java | 1 |
请完成以下Java代码 | public Collection<Decision> getDecisions() {
return decisionCollection.get(this);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
public Collection<Relationship> getRelationships() {
return relationshipCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Definitions.class, CMMN_ELEMENT_DEFINITIONS)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelElementTypeBuilder.ModelTypeInstanceProvider<Definitions>() {
public Definitions newInstance(ModelTypeInstanceContext instanceContext) {
return new DefinitionsImpl(instanceContext);
}
});
idAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_ID)
.idAttribute()
.build();
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
targetNamespaceAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_NAMESPACE)
.required()
.build();
expressionLanguageAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPRESSION_LANGUAGE)
.defaultValue(XPATH_NS)
.build();
exporterAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER)
.build();
exporterVersionAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXPORTER_VERSION)
.build();
authorAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_AUTHOR)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
importCollection = sequenceBuilder.elementCollection(Import.class)
.build(); | caseFileItemDefinitionCollection = sequenceBuilder.elementCollection(CaseFileItemDefinition.class)
.build();
caseCollection = sequenceBuilder.elementCollection(Case.class)
.build();
processCollection = sequenceBuilder.elementCollection(Process.class)
.build();
decisionCollection = sequenceBuilder.elementCollection(Decision.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.minOccurs(0)
.maxOccurs(1)
.build();
relationshipCollection = sequenceBuilder.elementCollection(Relationship.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DefinitionsImpl.java | 1 |
请完成以下Java代码 | private Date addSeconds(Date date, int amount) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.SECOND, amount);
return c.getTime();
}
public int getCountEmptyRuns() {
return countEmptyRuns;
}
public void setCountEmptyRuns(int countEmptyRuns) {
this.countEmptyRuns = countEmptyRuns;
}
public boolean isImmediatelyDue() {
return immediatelyDue;
}
public void setImmediatelyDue(boolean immediatelyDue) {
this.immediatelyDue = immediatelyDue;
}
public int getMinuteFrom() {
return minuteFrom; | }
public void setMinuteFrom(int minuteFrom) {
this.minuteFrom = minuteFrom;
}
public int getMinuteTo() {
return minuteTo;
}
public void setMinuteTo(int minuteTo) {
this.minuteTo = minuteTo;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\historycleanup\HistoryCleanupJobHandlerConfiguration.java | 1 |
请完成以下Java代码 | protected List<User> executeUsersQuery(final String searchExpression) {
LDAPTemplate ldapTemplate = new LDAPTemplate(ldapConfigurator);
return ldapTemplate.execute(new LDAPCallBack<List<User>>() {
@Override
public List<User> executeInContext(InitialDirContext initialDirContext) {
List<User> result = new ArrayList<>();
try {
String baseDn = ldapConfigurator.getUserBaseDn() != null ? ldapConfigurator.getUserBaseDn() : ldapConfigurator.getBaseDn();
NamingEnumeration<?> namingEnum = initialDirContext.search(baseDn, searchExpression, createSearchControls());
while (namingEnum.hasMore()) {
SearchResult searchResult = (SearchResult) namingEnum.next();
UserEntity user = new UserEntityImpl();
mapSearchResultToUser(searchResult, user);
result.add(user);
}
namingEnum.close();
} catch (NamingException ne) {
LOGGER.debug("Could not execute LDAP query: {}", ne.getMessage(), ne);
return null;
}
return result;
}
});
}
protected void mapSearchResultToUser(SearchResult result, UserEntity user) throws NamingException { | if (ldapConfigurator.getUserIdAttribute() != null) {
user.setId(result.getAttributes().get(ldapConfigurator.getUserIdAttribute()).get().toString());
}
if (ldapConfigurator.getUserFirstNameAttribute() != null) {
try {
user.setFirstName(result.getAttributes().get(ldapConfigurator.getUserFirstNameAttribute()).get().toString());
} catch (NullPointerException e) {
user.setFirstName("");
}
}
if (ldapConfigurator.getUserLastNameAttribute() != null) {
try {
user.setLastName(result.getAttributes().get(ldapConfigurator.getUserLastNameAttribute()).get().toString());
} catch (NullPointerException e) {
user.setLastName("");
}
}
if (ldapConfigurator.getUserEmailAttribute() != null) {
try {
user.setEmail(result.getAttributes().get(ldapConfigurator.getUserEmailAttribute()).get().toString());
} catch (NullPointerException e) {
user.setEmail("");
}
}
}
protected SearchControls createSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(ldapConfigurator.getSearchTimeLimit());
return searchControls;
}
} | repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\impl\LDAPUserQueryImpl.java | 1 |
请完成以下Java代码 | public Optional<BPartnerContact> extractContact(@NonNull final Predicate<BPartnerContact> filter)
{
return createFilteredContactStream(filter)
.findAny();
}
private Stream<BPartnerContact> createFilteredContactStream(@NonNull final Predicate<BPartnerContact> filter)
{
return getContacts()
.stream()
.filter(filter);
}
/**
* Changes this instance by removing all contacts whose IDs are not in the given set
*/
public void retainContacts(@NonNull final Set<BPartnerContactId> contactIdsToRetain)
{
contacts.removeIf(contact -> !contactIdsToRetain.contains(contact.getId()));
}
public Optional<BPartnerLocation> extractLocation(@NonNull final BPartnerLocationId bPartnerLocationId)
{
final Predicate<BPartnerLocation> predicate = l -> bPartnerLocationId.equals(l.getId());
return createFilteredLocationStream(predicate).findAny();
}
public Optional<BPartnerLocation> extractBillToLocation()
{
final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsBillToOr(false);
return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsBillToDefaultOr(false)));
}
public Optional<BPartnerLocation> extractShipToLocation()
{
final Predicate<BPartnerLocation> predicate = l -> l.getLocationType().getIsShipToOr(false);
return createFilteredLocationStream(predicate).min(Comparator.comparing(l -> !l.getLocationType().getIsShipToDefaultOr(false)));
}
public Optional<BPartnerLocation> extractLocationByHandle(@NonNull final String handle)
{
return extractLocation(bpLocation -> bpLocation.containsHandle(handle));
}
public Optional<BPartnerLocation> extractLocation(@NonNull final Predicate<BPartnerLocation> filter)
{
return createFilteredLocationStream(filter).findAny();
}
private Stream<BPartnerLocation> createFilteredLocationStream(@NonNull final Predicate<BPartnerLocation> filter)
{ | return getLocations()
.stream()
.filter(filter);
}
public void addBankAccount(@NonNull final BPartnerBankAccount bankAccount)
{
bankAccounts.add(bankAccount);
}
public Optional<BPartnerBankAccount> getBankAccountByIBAN(@NonNull final String iban)
{
Check.assumeNotEmpty(iban, "iban is not empty");
return bankAccounts.stream()
.filter(bankAccount -> iban.equals(bankAccount.getIban()))
.findFirst();
}
public void addCreditLimit(@NonNull final BPartnerCreditLimit creditLimit)
{
creditLimits.add(creditLimit);
}
@NonNull
public Stream<BPartnerContactId> streamContactIds()
{
return this.getContacts().stream().map(BPartnerContact::getId);
}
@NonNull
public Stream<BPartnerLocationId> streamBPartnerLocationIds()
{
return this.getLocations().stream().map(BPartnerLocation::getId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerComposite.java | 1 |
请完成以下Java代码 | public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{ | if (R_RequestType_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestTypeUpdates.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void reactivateLine(@NonNull final PickingJobLine line)
{
line.getSteps().forEach(this::reactivateStepIfNeeded);
}
private void reactivateStepIfNeeded(@NonNull final PickingJobStep step)
{
final IMutableHUContext huContext = huService.createMutableHUContextForProcessing();
step.getPickFroms().getKeys()
.stream()
.map(key -> step.getPickFroms().getPickFrom(key))
.map(PickingJobStepPickFrom::getPickedTo)
.filter(Objects::nonNull)
.map(PickingJobStepPickedTo::getActualPickedHUs)
.flatMap(List::stream)
.filter(pickStepHu -> huIdsToPick.containsKey(pickStepHu.getActualPickedHU().getId())) | .forEach(pickStepHU -> {
final HuId huId = pickStepHU.getActualPickedHU().getId();
final I_M_HU hu = huService.getById(huId);
shipmentScheduleService.addQtyPickedAndUpdateHU(AddQtyPickedRequest.builder()
.scheduleId(step.getScheduleId())
.qtyPicked(CatchWeightHelper.extractQtys(
huContext,
step.getProductId(),
pickStepHU.getQtyPicked(),
hu))
.tuOrVHU(hu)
.huContext(huContext)
.anonymousHuPickedOnTheFly(huIdsToPick.get(huId).isAnonymousHuPickedOnTheFly())
.build());
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\PickingJobReopenCommand.java | 2 |
请完成以下Java代码 | public boolean isContentTypeOptionsDisabled() {
return contentTypeOptionsDisabled;
}
public void setContentTypeOptionsDisabled(boolean contentTypeOptionsDisabled) {
this.contentTypeOptionsDisabled = contentTypeOptionsDisabled;
}
public String getContentTypeOptionsValue() {
return contentTypeOptionsValue;
}
public void setContentTypeOptionsValue(String contentTypeOptionsValue) {
this.contentTypeOptionsValue = contentTypeOptionsValue;
}
public boolean isHstsDisabled() {
return hstsDisabled;
}
public void setHstsDisabled(boolean hstsDisabled) {
this.hstsDisabled = hstsDisabled;
}
public boolean isHstsIncludeSubdomainsDisabled() {
return hstsIncludeSubdomainsDisabled;
}
public void setHstsIncludeSubdomainsDisabled(boolean hstsIncludeSubdomainsDisabled) {
this.hstsIncludeSubdomainsDisabled = hstsIncludeSubdomainsDisabled;
}
public String getHstsValue() {
return hstsValue;
}
public void setHstsValue(String hstsValue) {
this.hstsValue = hstsValue;
}
public String getHstsMaxAge() { | return hstsMaxAge;
}
public void setHstsMaxAge(String hstsMaxAge) {
this.hstsMaxAge = hstsMaxAge;
}
@Override
public String toString() {
StringJoiner joinedString = joinOn(this.getClass())
.add("xssProtectionDisabled=" + xssProtectionDisabled)
.add("xssProtectionOption=" + xssProtectionOption)
.add("xssProtectionValue=" + xssProtectionValue)
.add("contentSecurityPolicyDisabled=" + contentSecurityPolicyDisabled)
.add("contentSecurityPolicyValue=" + contentSecurityPolicyValue)
.add("contentTypeOptionsDisabled=" + contentTypeOptionsDisabled)
.add("contentTypeOptionsValue=" + contentTypeOptionsValue)
.add("hstsDisabled=" + hstsDisabled)
.add("hstsMaxAge=" + hstsMaxAge)
.add("hstsIncludeSubdomainsDisabled=" + hstsIncludeSubdomainsDisabled)
.add("hstsValue=" + hstsValue);
return joinedString.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\HeaderSecurityProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void delete(Set<Long> ids) {
// 清理缓存
List<Dict> dicts = dictRepository.findByIdIn(ids);
for (Dict dict : dicts) {
delCaches(dict);
}
dictRepository.deleteByIdIn(ids);
}
@Override
public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DictDto dictDTO : dictDtos) {
if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
for (DictDetailDto dictDetail : dictDTO.getDictDetails()) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", dictDetail.getLabel());
map.put("字典值", dictDetail.getValue());
map.put("创建日期", dictDetail.getCreateTime());
list.add(map);
}
} else {
Map<String,Object> map = new LinkedHashMap<>(); | map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", null);
map.put("字典值", null);
map.put("创建日期", dictDTO.getCreateTime());
list.add(map);
}
}
FileUtil.downloadExcel(list, response);
}
public void delCaches(Dict dict){
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BootGeodeAsyncInlineCachingClientApplication {
private static final String APPLICATION_NAME = "GolfClientApplication";
public static void main(String[] args) {
SpringApplication.run(BootGeodeAsyncInlineCachingClientApplication.class, args);
}
// tag::application-configuration[]
@Configuration
@EnableScheduling
static class GolfApplicationConfiguration {
// tag::application-runner[]
@Bean
ApplicationRunner runGolfTournament(PgaTourService pgaTourService) {
return args -> {
GolfTournament golfTournament = GolfTournament.newGolfTournament("The Masters")
.at(GolfCourseBuilder.buildAugustaNational())
.register(GolferBuilder.buildGolfers(GolferBuilder.FAVORITE_GOLFER_NAMES))
.buildPairings()
.play();
pgaTourService.manage(golfTournament);
}; | }
// end::application-runner[]
}
// end::application-configuration[]
// tag::geode-configuration[]
@Configuration
@UseMemberName(APPLICATION_NAME)
@EnableCachingDefinedRegions(serverRegionShortcut = RegionShortcut.REPLICATE)
static class GeodeConfiguration { }
// end::geode-configuration[]
// tag::peer-cache-configuration[]
@PeerCacheApplication
@Profile("peer-cache")
@Import({ AsyncInlineCachingConfiguration.class, AsyncInlineCachingRegionConfiguration.class })
static class PeerCacheApplicationConfiguration { }
// end::peer-cache-configuration[]
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\BootGeodeAsyncInlineCachingClientApplication.java | 2 |
请完成以下Java代码 | public int getRowCount()
{
return p_table.getRowCount();
}
private IInfoQueryCriteria getInfoQueryCriteria(final I_AD_InfoColumn infoColumn, final boolean getDefaultIfNotFound)
{
final int infoColumnId = infoColumn.getAD_InfoColumn_ID();
if (criteriasById.containsKey(infoColumnId))
{
return criteriasById.get(infoColumnId);
}
final IInfoQueryCriteria criteria;
final String classname = infoColumn.getClassname();
if (Check.isEmpty(classname, true))
{
if (getDefaultIfNotFound)
{
criteria = new InfoQueryCriteriaGeneral();
}
else
{
return null;
}
}
else
{
criteria = Util.getInstance(IInfoQueryCriteria.class, classname);
}
criteria.init(this, infoColumn, searchText);
criteriasById.put(infoColumnId, criteria);
return criteria;
}
private IInfoColumnController getInfoColumnControllerOrNull(final I_AD_InfoColumn infoColumn)
{
final IInfoQueryCriteria criteria = getInfoQueryCriteria(infoColumn, false); // don't retrieve the default
if (criteria == null)
{
return null;
}
if (criteria instanceof IInfoColumnController)
{
final IInfoColumnController columnController = (IInfoColumnController)criteria;
return columnController;
}
return null;
}
@Override | protected void prepareTable(final Info_Column[] layout, final String from, final String staticWhere, final String orderBy)
{
super.prepareTable(layout, from, staticWhere, orderBy);
setupInfoColumnControllerBindings();
}
private void setupInfoColumnControllerBindings()
{
for (int i = 0; i < p_layout.length; i++)
{
final int columnIndexModel = i;
final Info_Column infoColumn = p_layout[columnIndexModel];
final IInfoColumnController columnController = infoColumn.getColumnController();
final List<Info_Column> dependentColumns = infoColumn.getDependentColumns();
if (columnController == null
&& (dependentColumns == null || dependentColumns.isEmpty()))
{
// if there is no controller on this column and there are no dependent columns
// then there is no point for adding a binder
continue;
}
final TableModel tableModel = getTableModel();
final InfoColumnControllerBinder binder = new InfoColumnControllerBinder(this, infoColumn, columnIndexModel);
tableModel.addTableModelListener(binder);
}
}
@Override
public void setValue(final Info_Column infoColumn, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(infoColumn);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void setValueByColumnName(final String columnName, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(columnName);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimple.java | 1 |
请完成以下Java代码 | public String getDeadLetterJobExceptionStacktrace(String jobId) {
return commandExecutor.execute(new GetJobExceptionStacktraceCmd(jobId, JobType.DEADLETTER));
}
public Map<String, String> getProperties() {
return commandExecutor.execute(new GetPropertiesCmd());
}
public String databaseSchemaUpgrade(final Connection connection, final String catalog, final String schema) {
CommandConfig config = commandExecutor.getDefaultConfig().transactionNotSupported();
return commandExecutor.execute(
config,
new Command<String>() {
public String execute(CommandContext commandContext) {
DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext
.getSessionFactories()
.get(DbSqlSession.class);
DbSqlSession dbSqlSession = new DbSqlSession(
dbSqlSessionFactory,
commandContext.getEntityCache(),
connection,
catalog,
schema
);
commandContext.getSessions().put(DbSqlSession.class, dbSqlSession);
return dbSqlSession.dbSchemaUpdate();
}
}
);
}
public <T> T executeCommand(Command<T> command) {
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(command);
}
public <T> T executeCommand(CommandConfig config, Command<T> command) {
if (config == null) {
throw new ActivitiIllegalArgumentException("The config is null"); | }
if (command == null) {
throw new ActivitiIllegalArgumentException("The command is null");
}
return commandExecutor.execute(config, command);
}
@Override
public <MapperType, ResultType> ResultType executeCustomSql(
CustomSqlExecution<MapperType, ResultType> customSqlExecution
) {
Class<MapperType> mapperClass = customSqlExecution.getMapperClass();
return commandExecutor.execute(
new ExecuteCustomSqlCmd<MapperType, ResultType>(mapperClass, customSqlExecution)
);
}
@Override
public List<EventLogEntry> getEventLogEntries(Long startLogNr, Long pageSize) {
return commandExecutor.execute(new GetEventLogEntriesCmd(startLogNr, pageSize));
}
@Override
public List<EventLogEntry> getEventLogEntriesByProcessInstanceId(String processInstanceId) {
return commandExecutor.execute(new GetEventLogEntriesCmd(processInstanceId));
}
@Override
public void deleteEventLogEntry(long logNr) {
commandExecutor.execute(new DeleteEventLogEntry(logNr));
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ManagementServiceImpl.java | 1 |
请完成以下Java代码 | public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gesamtbetrag.
@param TotalAmt Gesamtbetrag */
@Override
public void setTotalAmt (java.math.BigDecimal TotalAmt)
{
set_Value (COLUMNNAME_TotalAmt, TotalAmt);
}
/** Get Gesamtbetrag.
@return Gesamtbetrag */
@Override
public java.math.BigDecimal getTotalAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate.java | 1 |
请完成以下Java代码 | private String buildDefaultPackingInfo(@NonNull final I_M_ReceiptSchedule receiptSchedule)
{
final I_M_HU_LUTU_Configuration lutuConfig = getCurrentLUTUConfiguration(receiptSchedule);
adjustLUTUConfiguration(lutuConfig, receiptSchedule);
return HUPackingInfoFormatter.newInstance()
.setShowLU(false) // NOTE: don't show LU info because makes the whole label to long. see https://github.com/metasfresh/metasfresh-webui-frontend/issues/315#issuecomment-280624562
.format(HUPackingInfos.of(lutuConfig));
}
@Override
protected boolean isUpdateReceiptScheduleDefaultConfiguration()
{
return false;
}
@Override
protected I_M_HU_LUTU_Configuration createM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration template)
{
final I_M_HU_LUTU_Configuration lutuConfigurationNew = InterfaceWrapperHelper.copy()
.setFrom(template)
.copyToNew(I_M_HU_LUTU_Configuration.class);
adjustLUTUConfiguration(lutuConfigurationNew, getM_ReceiptSchedule());
// NOTE: don't save it
return lutuConfigurationNew;
}
private void adjustLUTUConfiguration(final I_M_HU_LUTU_Configuration lutuConfig, final I_M_ReceiptSchedule receiptSchedule)
{
if (lutuConfigurationFactory.isNoLU(lutuConfig))
{
//
// Adjust TU
lutuConfig.setIsInfiniteQtyTU(false);
lutuConfig.setQtyTU(BigDecimal.ONE);
}
else
{
//
// Adjust LU
lutuConfig.setIsInfiniteQtyLU(false);
lutuConfig.setQtyLU(BigDecimal.ONE);
//
// Adjust TU
// * if the standard QtyTU is less than how much is available to be received => enforce the available Qty | // * else always take the standard QtyTU
// see https://github.com/metasfresh/metasfresh-webui/issues/228
{
final BigDecimal qtyToMoveTU = huReceiptScheduleBL.getQtyToMoveTU(receiptSchedule);
if (qtyToMoveTU.signum() > 0 && qtyToMoveTU.compareTo(lutuConfig.getQtyTU()) < 0)
{
lutuConfig.setQtyTU(qtyToMoveTU);
}
}
// Adjust CU if TU can hold an infinite qty, but the material receipt is of course finite, so we need to adjust the LUTU Configuration.
// Otherwise, receiving using the default configuration will not work.
final BigDecimal qtyTU = lutuConfig.getQtyTU();
if (lutuConfig.isInfiniteQtyCU() && qtyTU.signum() > 0)
{
lutuConfig.setIsInfiniteQtyCU(false);
final BigDecimal qtyToMoveCU = receiptSchedule.getQtyToMove().divide(qtyTU, RoundingMode.UP);
lutuConfig.setQtyCUsPerTU(qtyToMoveCU);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_UsingDefaults.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private <S> void addMainCallback(ListenableFuture<S> saveFuture, final FutureCallback<Void> callback) {
if (callback == null) return;
addMainCallback(saveFuture, result -> callback.onSuccess(null), callback::onFailure);
}
private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess) {
addMainCallback(saveFuture, onSuccess, null);
}
private <S> void addMainCallback(ListenableFuture<S> saveFuture, Consumer<S> onSuccess, Consumer<Throwable> onFailure) {
DonAsynchron.withCallback(saveFuture, onSuccess, onFailure, tsCallBackExecutor);
}
private void checkInternalEntity(EntityId entityId) {
if (EntityType.API_USAGE_STATE.equals(entityId.getEntityType())) {
throw new RuntimeException("Can't update API Usage State!");
}
}
private FutureCallback<TimeseriesSaveResult> getApiUsageCallback(TenantId tenantId, CustomerId customerId, boolean sysTenant) {
return new FutureCallback<>() {
@Override
public void onSuccess(TimeseriesSaveResult result) {
Integer dataPoints = result.getDataPoints(); | if (!sysTenant && dataPoints != null && dataPoints > 0) {
apiUsageClient.report(tenantId, customerId, ApiUsageRecordKey.STORAGE_DP_COUNT, dataPoints);
}
}
@Override
public void onFailure(Throwable t) {}
};
}
private FutureCallback<Void> getCalculatedFieldCallback(FutureCallback<List<String>> originalCallback, List<String> keys) {
return new FutureCallback<>() {
@Override
public void onSuccess(Void unused) {
originalCallback.onSuccess(keys);
}
@Override
public void onFailure(Throwable t) {
originalCallback.onFailure(t);
}
};
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultTelemetrySubscriptionService.java | 2 |
请完成以下Java代码 | private void processInvoiceCandidates(@NonNull final Set<InvoiceCandidateId> invoiceCandidateIds)
{
generateInvoicesForAsyncBatch(invoiceCandidateIds);
}
@NonNull
public List<I_C_Invoice_Candidate> retrieveInvoiceCandsByInOutLines(@NonNull final List<I_M_InOutLine> shipmentLines)
{
return shipmentLines.stream()
.map(invoiceCandDAO::retrieveInvoiceCandidatesForInOutLine)
.flatMap(List::stream)
.collect(ImmutableList.toImmutableList());
}
private void generateInvoicesForAsyncBatch(@NonNull final Set<InvoiceCandidateId> invoiceCandIds)
{
final AsyncBatchId asyncBatchId = asyncBatchBL.newAsyncBatch(C_Async_Batch_InternalName_InvoiceCandidate_Processing);
final PInstanceId invoiceCandidatesSelectionId = DB.createT_Selection(invoiceCandIds, Trx.TRXNAME_None);
final IInvoiceCandidateEnqueuer enqueuer = invoiceCandBL.enqueueForInvoicing()
.setContext(getCtx())
.setAsyncBatchId(asyncBatchId)
.setInvoicingParams(createDefaultIInvoicingParams())
.setFailIfNothingEnqueued(true);
// this creates workpackages
enqueuer.prepareSelection(invoiceCandidatesSelectionId); | final Supplier<IEnqueueResult> enqueueInvoiceCandidates = () -> enqueuer
.enqueueSelection(invoiceCandidatesSelectionId);
asyncBatchService.executeBatch(enqueueInvoiceCandidates, asyncBatchId);
}
@NonNull
private IInvoicingParams createDefaultIInvoicingParams()
{
final PlainInvoicingParams invoicingParams = new PlainInvoicingParams();
invoicingParams.setIgnoreInvoiceSchedule(false);
invoicingParams.setDateInvoiced(LocalDate.now());
return invoicingParams;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoice\InvoiceService.java | 1 |
请完成以下Java代码 | public Annotation[] getAnnotations() {
return annotations;
}
/**
* Obtain the evaluated parameter values that will be passed to the method to which the associated expression
* resolves.
*
* @return The evaluated parameters.
*/
public Object[] getEvaluatedParameters() {
return evaluatedParameters;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(annotations);
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + Arrays.deepHashCode(evaluatedParameters);
result = prime * result + ((methodInfo == null) ? 0 : methodInfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) { | return false;
}
MethodReference other = (MethodReference) obj;
if (!Arrays.equals(annotations, other.annotations)) {
return false;
}
if (base == null) {
if (other.base != null) {
return false;
}
} else if (!base.equals(other.base)) {
return false;
}
if (!Arrays.deepEquals(evaluatedParameters, other.evaluatedParameters)) {
return false;
}
if (methodInfo == null) {
return other.methodInfo == null;
} else {
return methodInfo.equals(other.methodInfo);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodReference.java | 1 |
请完成以下Java代码 | public void removeHUsFromPickingSlot(final I_M_ShipperTransportation shipperTransportation)
{
final IHUPickingSlotBL huPickingSlotBL = Services.get(IHUPickingSlotBL.class);
final IHUPackageDAO huPackageDAO = Services.get(IHUPackageDAO.class);
final IShipperTransportationDAO shipperTransportationDAO = Services.get(IShipperTransportationDAO.class);
//
// Retrieve all HUs which we need to remove from their picking slots
final Set<I_M_HU> husToRemove = new TreeSet<>(HUByIdComparator.instance);
for (final I_M_ShippingPackage shippingPackage : shipperTransportationDAO.retrieveShippingPackages(ShipperTransportationId.ofRepoId(shipperTransportation.getM_ShipperTransportation_ID())))
{
final I_M_Package mpackage = shippingPackage.getM_Package();
final List<I_M_HU> hus = huPackageDAO.retrieveHUs(mpackage);
husToRemove.addAll(hus);
}
//
// Remove collected HUs from their picking slots
for (final I_M_HU hu : husToRemove)
{
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(hu);
}
}
// 08743
// ported from other branch, but not required yet | // @DocValidate(timings = ModelValidator.TIMING_BEFORE_REACTIVATE)
// public void addHUsToPickingSlots(final I_M_ShipperTransportation shipperTransportation)
// {
// final IHUPackageBL huPackageBL = Services.get(IHUPackageBL.class);
//
// for (final I_M_ShippingPackage shippingPackage : Services.get(IShipperTransportationDAO.class).retrieveShippingPackages(shipperTransportation))
// {
// final I_M_Package mpackage = shippingPackage.getM_Package();
// huPackageBL.addHUsToPickingSlots(mpackage);
// }
// }
//
// @DocValidate(timings = ModelValidator.TIMING_BEFORE_VOID)
// public void destroyHUPackages(final I_M_ShipperTransportation shipperTransportation)
// {
// throw new AdempiereException("Not allowed");
// }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_ShipperTransportation.java | 1 |
请完成以下Java代码 | public PageData<ProfileEntityIdInfo> findProfileEntityIdInfosByTenantId(UUID tenantId, PageLink pageLink) {
log.debug("Find profile device id infos by tenantId[{}], pageLink [{}]", tenantId, pageLink);
return nativeDeviceRepository.findProfileEntityIdInfosByTenantId(tenantId, DaoUtil.toPageable(pageLink));
}
@Override
public Device findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(deviceRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Device findByTenantIdAndName(UUID tenantId, String name) {
return findDeviceByTenantIdAndName(tenantId, name).orElse(null);
}
@Override
public PageData<Device> findByTenantId(UUID tenantId, PageLink pageLink) {
return findDevicesByTenantId(tenantId, pageLink);
}
@Override
public DeviceId getExternalIdByInternal(DeviceId internalId) { | return Optional.ofNullable(deviceRepository.getExternalIdById(internalId.getId()))
.map(DeviceId::new).orElse(null);
}
@Override
public PageData<Device> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<DeviceFields> findNextBatch(UUID id, int batchSize) {
return deviceRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.DEVICE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\device\JpaDeviceDao.java | 1 |
请完成以下Java代码 | private Class<?> getTargetClass(Object target) {
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
if (targetClass == null && target != null) {
targetClass = target.getClass();
}
return targetClass;
}
/**
* 通过cache名称获取cache列表
*
* @param annotatedCacheNames
* @return
*/
public Collection<? extends Cache> getCache(Set<String> annotatedCacheNames) {
Collection<String> cacheNames = generateValue(annotatedCacheNames);
if (cacheNames == null) {
return Collections.emptyList();
} else {
Collection<Cache> result = new ArrayList<Cache>();
for (String cacheName : cacheNames) {
Cache cache = this.cacheManager.getCache(cacheName);
if (cache == null) {
throw new IllegalArgumentException("Cannot find cache named '" + cacheName + "' for ");
}
result.add(cache); | }
return result;
}
}
private String getInvocationCacheKey(String cacheKey) {
return cacheKey + INVOCATION_CACHE_KEY_SUFFIX;
}
/**
* 获取注解上的value属性值(cacheNames)
*
* @param annotatedCacheNames
* @return
*/
private Collection<String> generateValue(Set<String> annotatedCacheNames) {
Collection<String> cacheNames = new HashSet<>();
for (final String cacheName : annotatedCacheNames) {
String[] cacheParams = cacheName.split(SEPARATOR);
// 截取名称获取真实的value值
String realCacheName = cacheParams[0];
cacheNames.add(realCacheName);
}
return cacheNames;
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CacheSupportImpl.java | 1 |
请完成以下Java代码 | public class Recurring extends JavaProcess
{
/**
* Prepare - e.g., get Parameters.
*/
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else
log.error("Unknown Parameter: " + name); | }
} // prepare
/**
* Perform process.
* @return Message (clear text)
* @throws Exception if not successful
*/
protected String doIt() throws Exception
{
MRecurring rec = new MRecurring (getCtx(), getRecord_ID(), get_TrxName());
log.info(rec.toString());
return rec.executeRun();
} // doIt
} // Recurring | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\Recurring.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_Value (COLUMNNAME_AD_Table_ID, null);
else
set_Value (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get Table.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/
public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** ModerationType AD_Reference_ID=395 */
public static final int MODERATIONTYPE_AD_Reference_ID=395;
/** Not moderated = N */
public static final String MODERATIONTYPE_NotModerated = "N";
/** Before Publishing = B */
public static final String MODERATIONTYPE_BeforePublishing = "B";
/** After Publishing = A */
public static final String MODERATIONTYPE_AfterPublishing = "A";
/** Set Moderation Type.
@param ModerationType
Type of moderation
*/
public void setModerationType (String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
} | /** Get Moderation Type.
@return Type of moderation
*/
public String getModerationType ()
{
return (String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatType.java | 1 |
请完成以下Java代码 | public Money convertAmount(@NonNull final Money amount)
{
if (amount.getCurrencyId().equals(toCurrencyId))
{
return amount;
}
if (!amount.getCurrencyId().equals(fromCurrencyId))
{
throw new AdempiereException("Cannot convert " + amount + " to " + toCurrencyId + " using " + this);
}
final BigDecimal convertedAmount = convertAmount(amount.toBigDecimal());
return Money.of(convertedAmount, toCurrencyId);
}
/**
* Convert Money from "toCurrency" to "fromCurrency" (ie. do the reverse conversion).
* <p>
* Example:
* <pre>
* this.fromCurrency = EUR
* this.toCurrency = CHF
* this.conversionRate = X
*
* amount = Money in CHF
* </pre>
* This method converts the amount from CHF to EUR using the conversionRate of EUR->CHF. The precision and rounding are those of EUR, for correctness. | *
* @param amount amount in {@link #toCurrencyId}
*/
public Money reverseConvertAmount(@NonNull final Money amount)
{
if (amount.getCurrencyId().equals(fromCurrencyId))
{
return amount;
}
if (!amount.getCurrencyId().equals(toCurrencyId))
{
throw new AdempiereException("Cannot convert " + amount + " to " + fromCurrencyId + " using " + this);
}
final BigDecimal convertedAmount = amount.toBigDecimal().divide(conversionRate, fromCurrencyPrecision.toInt(), fromCurrencyPrecision.getRoundingMode());
return Money.of(convertedAmount, fromCurrencyId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyRate.java | 1 |
请完成以下Java代码 | public MigrationRestService getMigrationRestService(@PathParam("name") String engineName) {
return super.getMigrationRestService(engineName);
}
@Override
@Path("/{name}" + ModificationRestService.PATH)
public ModificationRestService getModificationRestService(@PathParam("name") String engineName) {
return super.getModificationRestService(engineName);
}
@Override
@Path("/{name}" + BatchRestService.PATH)
public BatchRestService getBatchRestService(@PathParam("name") String engineName) {
return super.getBatchRestService(engineName);
}
@Override
@Path("/{name}" + TenantRestService.PATH)
public TenantRestService getTenantRestService(@PathParam("name") String engineName) {
return super.getTenantRestService(engineName);
}
@Override
@Path("/{name}" + SignalRestService.PATH)
public SignalRestService getSignalRestService(@PathParam("name") String engineName) {
return super.getSignalRestService(engineName);
}
@Override
@Path("/{name}" + ConditionRestService.PATH)
public ConditionRestService getConditionRestService(@PathParam("name") String engineName) {
return super.getConditionRestService(engineName);
}
@Path("/{name}" + OptimizeRestService.PATH)
public OptimizeRestService getOptimizeRestService(@PathParam("name") String engineName) {
return super.getOptimizeRestService(engineName);
}
@Path("/{name}" + VersionRestService.PATH)
public VersionRestService getVersionRestService(@PathParam("name") String engineName) {
return super.getVersionRestService(engineName);
}
@Path("/{name}" + SchemaLogRestService.PATH)
public SchemaLogRestService getSchemaLogRestService(@PathParam("name") String engineName) {
return super.getSchemaLogRestService(engineName);
}
@Override
@Path("/{name}" + EventSubscriptionRestService.PATH)
public EventSubscriptionRestService getEventSubscriptionRestService(@PathParam("name") String engineName) {
return super.getEventSubscriptionRestService(engineName);
}
@Override
@Path("/{name}" + TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService(@PathParam("name") String engineName) { | return super.getTelemetryRestService(engineName);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<ProcessEngineDto> getProcessEngineNames() {
ProcessEngineProvider provider = getProcessEngineProvider();
Set<String> engineNames = provider.getProcessEngineNames();
List<ProcessEngineDto> results = new ArrayList<ProcessEngineDto>();
for (String engineName : engineNames) {
ProcessEngineDto dto = new ProcessEngineDto();
dto.setName(engineName);
results.add(dto);
}
return results;
}
@Override
protected URI getRelativeEngineUri(String engineName) {
return UriBuilder.fromResource(NamedProcessEngineRestServiceImpl.class).path("{name}").build(engineName);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\NamedProcessEngineRestServiceImpl.java | 1 |
请完成以下Java代码 | public void saveIfHasChanges()
{
final Set<DocumentId> savedOrDeletedDocumentIds = new HashSet<>();
for (final Document document : getChangedDocuments())
{
final DocumentSaveStatus saveStatus = document.saveIfHasChanges();
if (saveStatus.isSaved())
{
savedOrDeletedDocumentIds.add(document.getDocumentId());
}
else if (saveStatus.isDeleted())
{
document.markAsDeleted();
savedOrDeletedDocumentIds.add(document.getDocumentId());
}
}
if (!savedOrDeletedDocumentIds.isEmpty())
{
savedOrDeletedDocumentIds.forEach(this::forgetChangedDocument);
}
}
@Override
public void onChildSaved(final Document document)
{
if (!document.hasChangesRecursivelly())
{
forgetChangedDocument(document.getDocumentId());
}
}
@Override
public void onChildChanged(final Document document)
{
// NOTE: we assume the document has changes
// if(document.hasChangesRecursivelly())
addChangedDocument(document);
}
@Override
public void markStaleAll()
{
staled = true;
parentDocument.getChangesCollector().collectStaleDetailId(parentDocumentPath, detailId);
}
@Override
public void markStale(@NonNull final DocumentIdsSelection rowIds)
{
// TODO: implement staling only given rowId
markStaleAll();
}
@Override
public boolean isStale()
{
return staled;
}
@Override
public int getNextLineNo()
{
final int lastLineNo = DocumentQuery.builder(entityDescriptor)
.setParentDocument(parentDocument)
.setExistingDocumentsSupplier(this::getChangedDocumentOrNull)
.setChangesCollector(NullDocumentChangesCollector.instance)
.retrieveLastLineNo();
final int nextLineNo = lastLineNo / 10 * 10 + 10;
return nextLineNo;
}
//
//
//
@AllArgsConstructor | private final class ActionsContext implements IncludedDocumentsCollectionActionsContext
{
@Override
public boolean isParentDocumentProcessed()
{
return parentDocument.isProcessed();
}
@Override
public boolean isParentDocumentActive()
{
return parentDocument.isActive();
}
@Override
public boolean isParentDocumentNew()
{
return parentDocument.isNew();
}
@Override
public boolean isParentDocumentInvalid()
{
return !parentDocument.getValidStatus().isValid();
}
@Override
public Collection<Document> getIncludedDocuments()
{
return getChangedDocuments();
}
@Override
public Evaluatee toEvaluatee()
{
return parentDocument.asEvaluatee();
}
@Override
public void collectAllowNew(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{
parentDocument.getChangesCollector().collectAllowNew(parentDocumentPath, detailId, allowNew);
}
@Override
public void collectAllowDelete(final DocumentPath parentDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
parentDocument.getChangesCollector().collectAllowDelete(parentDocumentPath, detailId, allowDelete);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadWriteIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
final String tableName = getTableName();
final I_R_Request request;
if (I_C_BPartner.Table_Name.equals(tableName))
{
final I_C_BPartner bPartner = bPartnerDAO.getById(getProcessInfo().getRecord_ID());
request = createRequestFromBPartner(bPartner);
}
else if (I_M_InOut.Table_Name.equals(tableName))
{
final I_M_InOut shipment = inOutDAO.getById(InOutId.ofRepoId(getProcessInfo().getRecord_ID()));
request = createRequestFromShipment(shipment);
}
else if (I_AD_User.Table_Name.equals(tableName))
{
final I_AD_User user = userDAO.getById(UserId.ofRepoId(getProcessInfo().getRecord_ID()));
request = createRequestFromUser(user);
}
else
{
throw new IllegalStateException("Not supported: " + tableName);
}
save(request);
getResult().setRecordToOpen(TableRecordReference.of(request), requestWindowId.get().getRepoId(), OpenTarget.SingleDocumentModal);
return MSG_OK;
}
private I_R_Request createEmptyRequest()
{
final I_R_Request request = requestDAO.createEmptyRequest();
request.setR_RequestType_ID(requestTypeDAO.retrieveDefaultRequestTypeIdOrFirstActive().getRepoId());
final Timestamp date = SystemTime.asDayTimestamp();
request.setDateTrx(date);
request.setStartTime(date);
return request;
}
private I_R_Request createRequestFromBPartner(final I_C_BPartner bpartner)
{
final I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bpartner, I_AD_User.class);
final I_R_Request request = createEmptyRequest();
request.setSalesRep_ID(getAD_User_ID());
request.setC_BPartner_ID(bpartner.getC_BPartner_ID());
if (defaultContact != null)
{
request.setAD_User_ID(defaultContact.getAD_User_ID());
}
return request;
} | private I_R_Request createRequestFromShipment(final I_M_InOut shipment)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(shipment.getC_BPartner_ID());
final I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bPartner, I_AD_User.class);
final I_R_Request request = createEmptyRequest();
request.setSalesRep_ID(getAD_User_ID());
request.setC_BPartner_ID(shipment.getC_BPartner_ID());
request.setM_InOut_ID(shipment.getM_InOut_ID());
request.setDateDelivered(shipment.getMovementDate());
if (defaultContact != null)
{
request.setAD_User_ID(defaultContact.getAD_User_ID());
}
return request;
}
private I_R_Request createRequestFromUser(final I_AD_User user)
{
final I_R_Request request = createEmptyRequest();
request.setAD_User_ID(user.getAD_User_ID());
request.setC_BPartner_ID(user.getC_BPartner_ID());
return request;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\request\process\WEBUI_CreateRequest.java | 1 |
请完成以下Java代码 | public Builder attributes(Consumer<Map<String, Object>> attributesConsumer) {
attributesConsumer.accept(this.attributes);
return this;
}
/**
* Builds a new {@link OAuth2Authorization}.
* @return the {@link OAuth2Authorization}
*/
public OAuth2Authorization build() {
Assert.hasText(this.principalName, "principalName cannot be empty");
Assert.notNull(this.authorizationGrantType, "authorizationGrantType cannot be null");
OAuth2Authorization authorization = new OAuth2Authorization();
if (!StringUtils.hasText(this.id)) { | this.id = UUID.randomUUID().toString();
}
authorization.id = this.id;
authorization.registeredClientId = this.registeredClientId;
authorization.principalName = this.principalName;
authorization.authorizationGrantType = this.authorizationGrantType;
authorization.authorizedScopes = Collections.unmodifiableSet(!CollectionUtils.isEmpty(this.authorizedScopes)
? new HashSet<>(this.authorizedScopes) : new HashSet<>());
authorization.tokens = Collections.unmodifiableMap(this.tokens);
authorization.attributes = Collections.unmodifiableMap(this.attributes);
return authorization;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2Authorization.java | 1 |
请完成以下Java代码 | public class BatchQueryDto extends AbstractQueryDto<BatchQuery> {
private static final String SORT_BY_BATCH_ID_VALUE = "batchId";
private static final String SORT_BY_TENANT_ID_VALUE = "tenantId";
protected String batchId;
protected String type;
protected List<String> tenantIds;
protected Boolean withoutTenantId;
protected Boolean suspended;
private static final List<String> VALID_SORT_BY_VALUES;
static {
VALID_SORT_BY_VALUES = new ArrayList<String>();
VALID_SORT_BY_VALUES.add(SORT_BY_BATCH_ID_VALUE);
VALID_SORT_BY_VALUES.add(SORT_BY_TENANT_ID_VALUE);
}
public BatchQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) {
super(objectMapper, queryParameters);
}
@CamundaQueryParam("batchId")
public void setBatchId(String batchId) {
this.batchId = batchId;
}
@CamundaQueryParam("type")
public void setType(String type) {
this.type = type;
}
@CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class)
public void setTenantIdIn(List<String> tenantIds) {
this.tenantIds = tenantIds;
}
@CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class)
public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value="suspended", converter = BooleanConverter.class)
public void setSuspended(Boolean suspended) {
this.suspended = suspended;
}
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
} | protected BatchQuery createNewQuery(ProcessEngine engine) {
return engine.getManagementService().createBatchQuery();
}
protected void applyFilters(BatchQuery query) {
if (batchId != null) {
query.batchId(batchId);
}
if (type != null) {
query.type(type);
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(suspended)) {
query.suspended();
}
if (FALSE.equals(suspended)) {
query.active();
}
}
protected void applySortBy(BatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) {
query.orderById();
}
else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchQueryDto.java | 1 |
请完成以下Java代码 | static final class ClientAuthenticationMethodConverter extends StdConverter<JsonNode, ClientAuthenticationMethod> {
@Override
public ClientAuthenticationMethod convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
return ClientAuthenticationMethod.valueOf(value);
}
}
static final class AuthorizationGrantTypeConverter extends StdConverter<JsonNode, AuthorizationGrantType> {
@Override
public AuthorizationGrantType convert(JsonNode jsonNode) {
String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthorizationGrantType.AUTHORIZATION_CODE.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.AUTHORIZATION_CODE;
}
if (AuthorizationGrantType.CLIENT_CREDENTIALS.getValue().equalsIgnoreCase(value)) {
return AuthorizationGrantType.CLIENT_CREDENTIALS;
}
return new AuthorizationGrantType(value);
}
}
static final class AuthenticationMethodConverter extends StdConverter<JsonNode, AuthenticationMethod> {
@Override
public AuthenticationMethod convert(JsonNode jsonNode) { | String value = JsonNodeUtils.findStringValue(jsonNode, "value");
if (AuthenticationMethod.HEADER.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.HEADER;
}
if (AuthenticationMethod.FORM.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.FORM;
}
if (AuthenticationMethod.QUERY.getValue().equalsIgnoreCase(value)) {
return AuthenticationMethod.QUERY;
}
return null;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\jackson\StdConverters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setIBAN(String value) {
this.iban = value;
}
/**
*
* Owner of the bank account.
*
*
* @return
* possible object is
* {@link String }
*
*/
public String getBankAccountOwner() {
return bankAccountOwner;
}
/**
* Sets the value of the bankAccountOwner property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBankAccountOwner(String value) {
this.bankAccountOwner = value;
}
/**
*
* The creditor ID of the SEPA direct debit.
*
*
* @return
* possible object is
* {@link String }
*
*/
public String getCreditorID() {
return creditorID;
}
/**
* Sets the value of the creditorID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCreditorID(String value) {
this.creditorID = value;
}
/**
*
* The mandate reference of the SEPA direct debit.
*
*
* @return
* possible object is
* {@link String }
*
*/
public String getMandateReference() {
return mandateReference;
} | /**
* Sets the value of the mandateReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMandateReference(String value) {
this.mandateReference = value;
}
/**
*
* The debit collection date.
*
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDebitCollectionDate() {
return debitCollectionDate;
}
/**
* Sets the value of the debitCollectionDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDebitCollectionDate(XMLGregorianCalendar value) {
this.debitCollectionDate = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\SEPADirectDebitType.java | 2 |
请完成以下Java代码 | public boolean isRunInTransaction()
{
return true;
}
@Override
public boolean isAllowRetryOnError()
{
return true;
}
@Override
public final Optional<ILock> getElementsLock()
{
final String elementsLockOwnerName = getParameters().getParameterAsString(PARAMETERNAME_ElementsLockOwner);
if (Check.isBlank(elementsLockOwnerName))
{
return Optional.empty(); // no lock was created for this workpackage
}
final LockOwner elementsLockOwner = LockOwner.forOwnerName(elementsLockOwnerName);
try
{
final ILock existingLockForOwner = Services.get(ILockManager.class).getExistingLockForOwner(elementsLockOwner);
return Optional.of(existingLockForOwner);
}
catch (final LockFailedException e)
{
// this can happen, if e.g. there was a restart, or if the WP was flagged as error once
Loggables.addLog("Missing lock for ownerName={}; was probably cleaned up meanwhile", elementsLockOwnerName);
return Optional.empty();
}
}
/**
* Returns the {@link NullLatchStrategy}.
*/ | @Override
public ILatchStragegy getLatchStrategy()
{
return NullLatchStrategy.INSTANCE;
}
public final <T> List<T> retrieveItems(final Class<T> modelType)
{
return Services.get(IQueueDAO.class).retrieveAllItemsSkipMissing(getC_Queue_WorkPackage(), modelType);
}
/**
* Retrieves all active POs, even the ones that are caught in other packages
*/
public final <T> List<T> retrieveAllItems(final Class<T> modelType)
{
return Services.get(IQueueDAO.class).retrieveAllItems(getC_Queue_WorkPackage(), modelType);
}
public final List<I_C_Queue_Element> retrieveQueueElements(final boolean skipAlreadyScheduledItems)
{
return Services.get(IQueueDAO.class).retrieveQueueElements(getC_Queue_WorkPackage(), skipAlreadyScheduledItems);
}
/**
* retrieves all active PO's IDs, even the ones that are caught in other packages
*/
public final Set<Integer> retrieveAllItemIds()
{
return Services.get(IQueueDAO.class).retrieveAllItemIds(getC_Queue_WorkPackage());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\WorkpackageProcessorAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ExtendedPeriodType getCumulativeReceivedQuantityLastPeriod() {
return cumulativeReceivedQuantityLastPeriod;
}
/**
* Sets the value of the cumulativeReceivedQuantityLastPeriod property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setCumulativeReceivedQuantityLastPeriod(ExtendedPeriodType value) {
this.cumulativeReceivedQuantityLastPeriod = value;
}
/**
* Gets the value of the cumulativeReceivedQuantitySummary property.
*
* @return
* possible object is
* {@link ExtendedPeriodType }
*
*/
public ExtendedPeriodType getCumulativeReceivedQuantitySummary() {
return cumulativeReceivedQuantitySummary;
}
/**
* Sets the value of the cumulativeReceivedQuantitySummary property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setCumulativeReceivedQuantitySummary(ExtendedPeriodType value) {
this.cumulativeReceivedQuantitySummary = value;
}
/**
* Gets the value of the planningHorizion property.
*
* @return
* possible object is
* {@link ExtendedPeriodType }
*
*/
public ExtendedPeriodType getPlanningHorizion() {
return planningHorizion;
}
/**
* Sets the value of the planningHorizion property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setPlanningHorizion(ExtendedPeriodType value) {
this.planningHorizion = value;
}
/**
* Gets the value of the materialAuthorization property.
*
* @return
* possible object is
* {@link ExtendedPeriodType }
*
*/
public ExtendedPeriodType getMaterialAuthorization() { | return materialAuthorization;
}
/**
* Sets the value of the materialAuthorization property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setMaterialAuthorization(ExtendedPeriodType value) {
this.materialAuthorization = value;
}
/**
* Gets the value of the productionAuthorization property.
*
* @return
* possible object is
* {@link ExtendedPeriodType }
*
*/
public ExtendedPeriodType getProductionAuthorization() {
return productionAuthorization;
}
/**
* Sets the value of the productionAuthorization property.
*
* @param value
* allowed object is
* {@link ExtendedPeriodType }
*
*/
public void setProductionAuthorization(ExtendedPeriodType value) {
this.productionAuthorization = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalForecastInformationType.java | 2 |
请完成以下Java代码 | public boolean hasElement() {
return false;
}
@Override
public boolean isEmpty() {
return true;
}
@Override
public T getElement() throws NullPointerException {
throw new NullPointerException();
}
@Override
public void detach() {
return;
}
@Override
public DoublyLinkedList<T> getListReference() {
return list;
}
@Override
public LinkedListNode<T> setPrev(LinkedListNode<T> next) {
return next;
}
@Override
public LinkedListNode<T> setNext(LinkedListNode<T> prev) {
return prev; | }
@Override
public LinkedListNode<T> getPrev() {
return this;
}
@Override
public LinkedListNode<T> getNext() {
return this;
}
@Override
public LinkedListNode<T> search(T value) {
return this;
}
} | repos\tutorials-master\data-structures\src\main\java\com\baeldung\lrucache\DummyNode.java | 1 |
请完成以下Java代码 | public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override | public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner.java | 1 |
请完成以下Java代码 | public String getName()
{
return name;
}
public boolean isAvailableToWork()
{
return this.executor.hasAvailablePermits();
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("executor", executor)
.toString();
}
@Override
public void shutdownExecutor()
{
shutdownLock.lock();
try
{
shutdown0();
}
finally
{
shutdownLock.unlock();
}
} | @Override
protected void executeTask(@NonNull final WorkpackageProcessorTask task)
{
logger.debug("Going to submit task={} to executor={}", task, executor);
executor.execute(task);
logger.debug("Done submitting task");
}
private void shutdown0()
{
logger.info("shutdown - Shutdown started for executor={}", executor);
executor.shutdown();
int retryCount = 5;
boolean terminated = false;
while (!terminated && retryCount > 0)
{
logger.info("shutdown - waiting for executor to be terminated; retries left={}; executor={}", retryCount, executor);
try
{
terminated = executor.awaitTermination(5 * 1000, TimeUnit.MICROSECONDS);
}
catch (final InterruptedException e)
{
logger.warn("Failed shutting down executor for " + name + ". Retry " + retryCount + " more times.");
terminated = false;
}
retryCount--;
}
executor.shutdownNow();
logger.info("Shutdown finished");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\ThreadPoolQueueProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
}
@Override
public List<Task> list() {
cachedCandidateGroups = null;
return super.list();
}
@Override
public List<Task> listPage(int firstResult, int maxResults) {
cachedCandidateGroups = null;
return super.listPage(firstResult, maxResults);
}
@Override
public long count() {
cachedCandidateGroups = null;
return super.count();
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups; | }
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\TaskQueryImpl.java | 2 |
请完成以下Java代码 | public class LongestSubstringNonRepeatingCharacters {
public static String getUniqueCharacterSubstringBruteForce(String input) {
String output = "";
for (int start = 0; start < input.length(); start++) {
Set<Character> visited = new HashSet<>();
int end = start;
for (; end < input.length(); end++) {
char currChar = input.charAt(end);
if (visited.contains(currChar)) {
break;
} else {
visited.add(currChar);
}
}
if (output.length() < end - start + 1) {
output = input.substring(start, end);
}
}
return output;
}
public static String getUniqueCharacterSubstring(String input) {
Map<Character, Integer> visited = new HashMap<>();
String output = "";
for (int start = 0, end = 0; end < input.length(); end++) { | char currChar = input.charAt(end);
if (visited.containsKey(currChar)) {
start = Math.max(visited.get(currChar) + 1, start);
}
if (output.length() < end - start + 1) {
output = input.substring(start, end + 1);
}
visited.put(currChar, end);
}
return output;
}
public static void main(String[] args) {
if(args.length > 0) {
System.out.println(getUniqueCharacterSubstring(args[0]));
} else {
System.err.println("This program expects command-line input. Please try again!");
}
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\string\LongestSubstringNonRepeatingCharacters.java | 1 |
请完成以下Java代码 | public class TelemetryDataDto {
protected String installation;
protected ProductDto product;
public TelemetryDataDto(String installation, ProductDto product) {
this.installation = installation;
this.product = product;
}
public String getInstallation() {
return installation;
}
public void setInstallation(String installation) {
this.installation = installation; | }
public ProductDto getProduct() {
return product;
}
public void setProduct(ProductDto product) {
this.product = product;
}
public static TelemetryDataDto fromEngineDto(TelemetryData other) {
return new TelemetryDataDto(
other.getInstallation(),
ProductDto.fromEngineDto(other.getProduct()));
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\TelemetryDataDto.java | 1 |
请完成以下Java代码 | public Integer getUseCount() {
return useCount;
}
public void setUseCount(Integer useCount) {
this.useCount = useCount;
}
public Integer getReceiveCount() {
return receiveCount;
}
public void setReceiveCount(Integer receiveCount) {
this.receiveCount = receiveCount;
}
public Date getEnableTime() {
return enableTime;
}
public void setEnableTime(Date enableTime) {
this.enableTime = enableTime;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Integer getMemberLevel() {
return memberLevel;
}
public void setMemberLevel(Integer memberLevel) {
this.memberLevel = memberLevel;
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", type=").append(type);
sb.append(", name=").append(name);
sb.append(", platform=").append(platform);
sb.append(", count=").append(count);
sb.append(", amount=").append(amount);
sb.append(", perLimit=").append(perLimit);
sb.append(", minPoint=").append(minPoint);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", useType=").append(useType);
sb.append(", note=").append(note);
sb.append(", publishCount=").append(publishCount);
sb.append(", useCount=").append(useCount);
sb.append(", receiveCount=").append(receiveCount);
sb.append(", enableTime=").append(enableTime);
sb.append(", code=").append(code);
sb.append(", memberLevel=").append(memberLevel);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCoupon.java | 1 |
请完成以下Java代码 | public int getOrder() {
return this.order;
}
/**
* Set the order.
* @param order the order.
* @see Ordered
*/
public void setOrder(int order) {
this.order = order;
}
/**
* Add a message post processor to the map of decompressing MessageProcessors.
* @param contentEncoding the content encoding; messages will be decompressed with this post processor
* if its {@code content-encoding} property matches, or begins with this key followed by ":".
* @param decompressor the decompressing {@link MessagePostProcessor}.
*/
public void addDecompressor(String contentEncoding, MessagePostProcessor decompressor) {
this.decompressors.put(contentEncoding, decompressor);
}
/**
* Remove the decompressor for this encoding; content will not be decompressed even if the
* {@link org.springframework.amqp.core.MessageProperties#SPRING_AUTO_DECOMPRESS} header is true.
* @param contentEncoding the content encoding.
* @return the decompressor if it was present.
*/
public MessagePostProcessor removeDecompressor(String contentEncoding) {
return this.decompressors.remove(contentEncoding);
}
/**
* Replace all the decompressors.
* @param decompressors the decompressors.
*/
public void setDecompressors(Map<String, MessagePostProcessor> decompressors) {
this.decompressors.clear();
this.decompressors.putAll(decompressors);
}
@Override
public Message postProcessMessage(Message message) throws AmqpException {
String encoding = message.getMessageProperties().getContentEncoding(); | if (encoding == null) {
return message;
}
int delimAt = encoding.indexOf(':');
if (delimAt < 0) {
delimAt = encoding.indexOf(',');
}
if (delimAt > 0) {
encoding = encoding.substring(0, delimAt);
}
MessagePostProcessor decompressor = this.decompressors.get(encoding);
if (decompressor != null) {
return decompressor.postProcessMessage(message);
}
return message;
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\postprocessor\DelegatingDecompressingPostProcessor.java | 1 |
请完成以下Java代码 | public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Grand Total.
@param GrandTotal
Total amount of document
*/
public void setGrandTotal (BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Grand Total.
@return Total amount of document
*/
public BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Include All Currencies.
@param IsAllCurrencies
Report not just foreign currency Invoices
*/
public void setIsAllCurrencies (boolean IsAllCurrencies)
{
set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies));
}
/** Get Include All Currencies.
@return Report not just foreign currency Invoices
*/
public boolean isAllCurrencies ()
{
Object oo = get_Value(COLUMNNAME_IsAllCurrencies);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_InvoiceGL.java | 1 |
请完成以下Java代码 | public class AntiXssUtils {
public static URI getHost(URI uri) {
URI effectiveURI = null;
try {
effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
} catch (Throwable var4) {
effectiveURI = null;
}
return effectiveURI;
}
public static String cleanString(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
value = value.toLowerCase();
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("onload", "0nl0ad");
value = value.replaceAll("xml", "xm1");
value = value.replaceAll("window", "wind0w");
value = value.replaceAll("click", "cl1ck"); | value = value.replaceAll("var", "v0r");
value = value.replaceAll("let", "1et");
value = value.replaceAll("function", "functi0n");
value = value.replaceAll("return", "retu1n");
value = value.replaceAll("$", "");
value = value.replaceAll("document", "d0cument");
value = value.replaceAll("const", "c0nst");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "scr1pt");
value = value.replaceAll("insert", "1nsert");
value = value.replaceAll("drop", "dr0p");
value = value.replaceAll("create", "cre0ate");
value = value.replaceAll("update", "upd0ate");
value = value.replaceAll("alter", "a1ter");
value = value.replaceAll("from", "fr0m");
value = value.replaceAll("where", "wh1re");
value = value.replaceAll("database", "data1base");
value = value.replaceAll("table", "tab1e");
value = value.replaceAll("tb", "tb0");
return value;
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\util\AntiXssUtils.java | 1 |
请完成以下Java代码 | public ITranslatableString getProcessNameById(final AdProcessId id)
{
final I_AD_Process process = getById(id);
return InterfaceWrapperHelper.getModelTranslationMap(process)
.getColumnTrl(I_AD_Process.COLUMNNAME_Name, process.getName());
}
@NonNull
public ImmutableList<I_AD_Process> getProcessesByType(@NonNull final Set<ProcessType> processTypeSet)
{
final Set<String> types = processTypeSet.stream().map(ProcessType::getCode).collect(Collectors.toSet());
return queryBL.createQueryBuilder(I_AD_Process.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_AD_Process.COLUMNNAME_Type, types)
.create()
.list()
.stream()
.collect(ImmutableList.toImmutableList());
}
@NonNull
public ImmutableList<I_AD_Process_Para> getProcessParamsByProcessIds(@NonNull final Set<Integer> processIDs)
{
return queryBL.createQueryBuilder(I_AD_Process_Para.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_AD_Process_Para.COLUMNNAME_AD_Process_ID, processIDs)
.create()
.list()
.stream()
.collect(ImmutableList.toImmutableList());
}
@Override
public void save(final I_AD_Process process)
{
InterfaceWrapperHelper.save(process);
}
@Override
public void updateColumnNameByAdElementId(
@NonNull final AdElementId adElementId,
@Nullable final String newColumnName)
{ | // NOTE: accept newColumnName to be null and expect to fail in case there is an AD_Process_Para which is using given AD_Element_ID
DB.executeUpdateAndThrowExceptionOnFail(
// Inline parameters because this sql will be logged into the migration script.
"UPDATE " + I_AD_Process_Para.Table_Name + " SET ColumnName=" + DB.TO_STRING(newColumnName) + " WHERE AD_Element_ID=" + adElementId.getRepoId(),
ITrx.TRXNAME_ThreadInherited);
}
@Override
public ProcessType retrieveProcessType(@NonNull final AdProcessId processId)
{
final I_AD_Process process = InterfaceWrapperHelper.loadOutOfTrx(processId, I_AD_Process.class);
return ProcessType.ofCode(process.getType());
}
@Override
public ImmutableSet<AdProcessId> retrieveAllActiveAdProcesIds()
{
return queryBL.createQueryBuilderOutOfTrx(I_AD_Process.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_Process.COLUMNNAME_AD_Process_ID)
.create()
.idsAsSet(AdProcessId::ofRepoId);
}
@NonNull
@Override
public List<I_AD_Process> retrieveProcessRecordsByValRule(@NonNull final AdValRuleId valRuleId)
{
return queryBL.createQueryBuilder(I_AD_Process.class)
.addOnlyActiveRecordsFilter()
.filter(new ValidationRuleQueryFilter<>(I_AD_Process.Table_Name, valRuleId))
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADProcessDAO.java | 1 |
请完成以下Java代码 | public void setDocStatus (java.lang.String DocStatus)
{
set_Value (COLUMNNAME_DocStatus, DocStatus);
}
/** Get Belegstatus.
@return The current status of the document
*/
@Override
public java.lang.String getDocStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocStatus);
}
/** Set Nr..
@param DocumentNo
Document sequence number of the document
*/
@Override
public void setDocumentNo (java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
/** Get Nr..
@return Document sequence number of the document
*/
@Override
public java.lang.String getDocumentNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_DocumentNo);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID | */
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_RV_Prepared_And_Drafted_Documents.java | 1 |
请完成以下Java代码 | public IHUAssignmentBuilder setQty(final BigDecimal qty)
{
this.qty = qty;
return this;
}
@Override
public IHUAssignmentBuilder setIsTransferPackingMaterials(final boolean isTransferPackingMaterials)
{
this.isTransferPackingMaterials = isTransferPackingMaterials;
return this;
}
@Override
public IHUAssignmentBuilder setIsActive(final boolean isActive)
{
this.isActive = isActive;
return this;
}
@Override
public boolean isActive()
{
return isActive;
}
@Override
public I_M_HU_Assignment getM_HU_Assignment()
{
return assignment;
}
@Override
public boolean isNewAssignment()
{
return InterfaceWrapperHelper.isNew(assignment);
}
@Override
public IHUAssignmentBuilder initializeAssignment(final Properties ctx, final String trxName)
{
final I_M_HU_Assignment assignment = InterfaceWrapperHelper.create(ctx, I_M_HU_Assignment.class, trxName);
setAssignmentRecordToUpdate(assignment);
return this;
}
@Override
public IHUAssignmentBuilder setTemplateForNewRecord(final I_M_HU_Assignment assignmentRecord)
{
this.assignment = newInstance(I_M_HU_Assignment.class);
return updateFromRecord(assignmentRecord);
}
@Override
public IHUAssignmentBuilder setAssignmentRecordToUpdate(@NonNull final I_M_HU_Assignment assignmentRecord)
{
this.assignment = assignmentRecord;
return updateFromRecord(assignmentRecord);
}
private IHUAssignmentBuilder updateFromRecord(final I_M_HU_Assignment assignmentRecord)
{
setTopLevelHU(assignmentRecord.getM_HU()); | setM_LU_HU(assignmentRecord.getM_LU_HU());
setM_TU_HU(assignmentRecord.getM_TU_HU());
setVHU(assignmentRecord.getVHU());
setQty(assignmentRecord.getQty());
setIsTransferPackingMaterials(assignmentRecord.isTransferPackingMaterials());
setIsActive(assignmentRecord.isActive());
return this;
}
@Override
public I_M_HU_Assignment build()
{
Check.assumeNotNull(model, "model not null");
Check.assumeNotNull(topLevelHU, "topLevelHU not null");
Check.assumeNotNull(assignment, "assignment not null");
TableRecordCacheLocal.setReferencedValue(assignment, model);
assignment.setM_HU(topLevelHU);
assignment.setM_LU_HU(luHU);
assignment.setM_TU_HU(tuHU);
assignment.setVHU(vhu);
assignment.setQty(qty);
assignment.setIsTransferPackingMaterials(isTransferPackingMaterials);
assignment.setIsActive(isActive);
InterfaceWrapperHelper.save(assignment);
return assignment;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUAssignmentBuilder.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Alternative Group.
@param M_BOMAlternative_ID
Product BOM Alternative Group
*/
public void setM_BOMAlternative_ID (int M_BOMAlternative_ID)
{
if (M_BOMAlternative_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BOMAlternative_ID, Integer.valueOf(M_BOMAlternative_ID));
}
/** Get Alternative Group.
@return Product BOM Alternative Group
*/
public int getM_BOMAlternative_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BOMAlternative_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); | }
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOMAlternative.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
try {
User user = userRepository.findByEmail(email);
if (user == null) {
throw new UsernameNotFoundException("No user found with username: " + email);
}
return new org.springframework.security.core.userdetails.User(user.getEmail(),
user.getPassword(),
user.isEnabled(),
true,
true,
true,
getAuthorities(user.getRoles()));
} catch (final Exception e) {
throw new RuntimeException(e); | }
}
private Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roles) {
List<GrantedAuthority> authorities = new ArrayList<>();
for (Role role: roles) {
authorities.add(new SimpleGrantedAuthority(role.getName()));
authorities.addAll(role.getPrivileges()
.stream()
.map(p -> new SimpleGrantedAuthority(p.getName()))
.collect(Collectors.toList()));
}
return authorities;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\MyUserDetailsService.java | 2 |
请完成以下Java代码 | public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) { | this.icon = icon;
}
public String getUsersAccess() {
return usersAccess;
}
public void setUsersAccess(String usersAccess) {
this.usersAccess = usersAccess;
}
public String getGroupsAccess() {
return groupsAccess;
}
public void setGroupsAccess(String groupsAccess) {
this.groupsAccess = groupsAccess;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\BaseAppModel.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.