instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class Comment {
@Id
private Integer id;
private Integer year;
private boolean approved;
private String content;
@ManyToOne
private Post post;
public Comment() {
}
public Comment(int id, int year, boolean approved, String content, Post post) {
this.id = id;
this.year = year;
this.approved = approved;
this.content = content;
this.post = post;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
|
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Comment)) {
return false;
}
Comment comment = (Comment) o;
return getId().equals(comment.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\aggregation\model\Comment.java
| 2
|
请完成以下Java代码
|
public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess)
{
final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache();
final Inventory inventory = getInventory(wfProcess);
return WFProcessHeaderProperties.builder()
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("DocumentNo"))
.value(inventory.getDocumentNo())
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("MovementDate"))
.value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate()))
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID"))
.value(inventory.getWarehouseId() != null
? warehouses.getById(inventory.getWarehouseId()).getWarehouseName()
: "")
.build())
|
.build();
}
@NonNull
public static Inventory getInventory(final @NonNull WFProcess wfProcess)
{
return wfProcess.getDocumentAs(Inventory.class);
}
public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper)
{
final Inventory inventory = getInventory(wfProcess);
final Inventory inventoryChanged = mapper.apply(inventory);
return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java
| 1
|
请完成以下Java代码
|
public class CustomKafkaListener implements Runnable {
private static final Logger log = Logger.getLogger(CustomKafkaListener.class.getName());
private final String topic;
private final KafkaConsumer<String, String> consumer;
private Consumer<String> recordConsumer;
public CustomKafkaListener(String topic, KafkaConsumer<String, String> consumer) {
this.topic = topic;
this.consumer = consumer;
this.recordConsumer = record -> log.info("received: " + record);
}
public CustomKafkaListener(String topic, String bootstrapServers) {
this(topic, defaultKafkaConsumer(bootstrapServers));
}
private static KafkaConsumer<String, String> defaultKafkaConsumer(String boostrapServers) {
Properties props = new Properties();
props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, boostrapServers);
props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "test_group_id");
props.setProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
props.setProperty(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.setProperty(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
|
return new KafkaConsumer<>(props);
}
public CustomKafkaListener onEach(Consumer<String> newConsumer) {
recordConsumer = recordConsumer.andThen(newConsumer);
return this;
}
@Override
public void run() {
consumer.subscribe(Arrays.asList(topic));
while (true) {
consumer.poll(Duration.ofMillis(100))
.forEach(record -> recordConsumer.accept(record.value()));
}
}
}
|
repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\kafka\consumer\CustomKafkaListener.java
| 1
|
请完成以下Java代码
|
public void notifyDecommissionFailed(
@NonNull final UserId responsibleId,
@NonNull final DecommissionResponse response)
{
sendNotification(
responsibleId,
MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE,
TableRecordReference.of(org.compiere.model.I_M_Inventory.Table_Name, response.getInventoryId()));
}
@Override
public void notifyUndoDecommissionFailed(
@NonNull final UserId responsibleId,
@NonNull final UndoDecommissionResponse response)
{
sendNotification(
responsibleId,
MSG_SECURPHARM_ACTION_RESULT_ERROR_NOTIFICATION_MESSAGE,
TableRecordReference.of(org.compiere.model.I_M_Inventory.Table_Name, response.getInventoryId()));
}
|
private void sendNotification(
@NonNull final UserId recipientUserId,
@NonNull final String notificationADMessage,
@NonNull final TableRecordReference recordRef)
{
final String message = Services.get(IMsgBL.class).getMsg(Env.getCtx(), notificationADMessage);
final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder()
.recipientUserId(recipientUserId)
.contentPlain(message)
.targetAction(UserNotificationRequest.TargetRecordAction.of(recordRef))
.build();
Services.get(INotificationBL.class).sendAfterCommit(userNotificationRequest);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\notifications\DefaultSecurPharmUserNotifications.java
| 1
|
请完成以下Java代码
|
public List<I_M_InOut> getReceiptsToReverse(final Collection<? extends IHUAware> huAwareList)
{
if (huAwareList == null || huAwareList.isEmpty())
{
return ImmutableList.of();
}
return getReceiptsToReverse(huAwareList
.stream()
.map(huAware -> huAware.getM_HU().getM_HU_ID()));
}
public List<I_M_InOut> getReceiptsToReverseFromHUIds(final Collection<Integer> huIds)
{
if (huIds == null || huIds.isEmpty())
{
return ImmutableList.of();
}
return getReceiptsToReverse(huIds.stream());
}
private final List<I_M_InOut> getReceiptsToReverse(final Stream<Integer> huIds)
{
return huIds
.map(huId -> getReceiptOrNull(huId))
// skip if no receipt found because
// * it could be that user selected not a top level HU.... skip it for now
// * or we were really asked to as much as we can
.filter(receipt -> receipt != null)
.collect(GuavaCollectors.toImmutableList());
}
/**
* Get all HUs which are assigned to given receipts.
*
* @param receipts
* @return HUs
*/
public Set<I_M_HU> getHUsForReceipts(final Collection<? extends I_M_InOut> receipts)
{
final Set<I_M_HU> hus = new TreeSet<>(HUByIdComparator.instance);
for (final I_M_InOut receipt : receipts)
{
final int inoutId = receipt.getM_InOut_ID();
final Collection<I_M_HU> husForReceipt = inoutId2hus.get(inoutId);
if (Check.isEmpty(husForReceipt))
{
continue;
}
hus.addAll(husForReceipt);
}
return hus;
}
public static final class Builder
{
private I_M_ReceiptSchedule receiptSchedule;
|
private boolean tolerateNoHUsFound = false;
private Builder()
{
super();
}
public ReceiptCorrectHUsProcessor build()
{
return new ReceiptCorrectHUsProcessor(this);
}
public Builder setM_ReceiptSchedule(final I_M_ReceiptSchedule receiptSchedule)
{
this.receiptSchedule = receiptSchedule;
return this;
}
private I_M_ReceiptSchedule getM_ReceiptSchedule()
{
Check.assumeNotNull(receiptSchedule, "Parameter receiptSchedule is not null");
return receiptSchedule;
}
public Builder tolerateNoHUsFound()
{
tolerateNoHUsFound = true;
return this;
}
private boolean isFailOnNoHUsFound()
{
return !tolerateNoHUsFound;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\ReceiptCorrectHUsProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Event {
@Id
@Column(name = "event_id")
private Long id;
@Column(name = "title")
private String title;
@ElementCollection
@Immutable
private Set<String> guestList;
public Event() {}
public Event(Long id, String title, Set<String> guestList) {
this.id = id;
this.title = title;
this.guestList = guestList;
}
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;
}
@Cascade({ CascadeType.SAVE_UPDATE, CascadeType.DELETE })
public Set<String> getGuestList() {
return guestList;
}
public void setGuestList(Set<String> guestList) {
this.guestList = guestList;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-annotations-2\src\main\java\com\baeldung\hibernate\immutable\entities\Event.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CamundaBpmAutoConfiguration {
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Configuration
class ProcessEngineConfigurationImplDependingConfiguration {
@Autowired
protected ProcessEngineConfigurationImpl processEngineConfigurationImpl;
@Bean
public ProcessEngineFactoryBean processEngineFactoryBean() {
final ProcessEngineFactoryBean factoryBean = new ProcessEngineFactoryBean();
factoryBean.setProcessEngineConfiguration(processEngineConfigurationImpl);
return factoryBean;
}
@Bean
@Primary
public CommandExecutor commandExecutorTxRequired() {
return processEngineConfigurationImpl.getCommandExecutorTxRequired();
}
@Bean
public CommandExecutor commandExecutorTxRequiresNew() {
|
return processEngineConfigurationImpl.getCommandExecutorTxRequiresNew();
}
@Bean
public CommandExecutor commandExecutorSchemaOperations() {
return processEngineConfigurationImpl.getCommandExecutorSchemaOperations();
}
}
@Bean
public CamundaBpmVersion camundaBpmVersion() {
return new CamundaBpmVersion();
}
@Bean
public ProcessApplicationEventPublisher processApplicationEventPublisher(ApplicationEventPublisher publisher) {
return new ProcessApplicationEventPublisher(publisher);
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\CamundaBpmAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public class X_C_Workplace_ProductCategory extends org.compiere.model.PO implements I_C_Workplace_ProductCategory, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1076525619L;
/** Standard Constructor */
public X_C_Workplace_ProductCategory (final Properties ctx, final int C_Workplace_ProductCategory_ID, @Nullable final String trxName)
{
super (ctx, C_Workplace_ProductCategory_ID, trxName);
}
/** Load Constructor */
public X_C_Workplace_ProductCategory (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
|
@Override
public void setC_Workplace_ProductCategory_ID (final int C_Workplace_ProductCategory_ID)
{
if (C_Workplace_ProductCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_ProductCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_ProductCategory_ID, C_Workplace_ProductCategory_ID);
}
@Override
public int getC_Workplace_ProductCategory_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ProductCategory_ID);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_ProductCategory.java
| 1
|
请完成以下Java代码
|
public String getId() {
return id;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getBusinessKey() {
return businessKey;
}
public String getTenantId() {
return tenantId;
}
public boolean isActive() {
return active;
}
public boolean isCompleted() {
return completed;
}
public boolean isTerminated() {
return terminated;
|
}
public static CaseInstanceDto fromCaseInstance(CaseInstance instance) {
CaseInstanceDto result = new CaseInstanceDto();
result.id = instance.getId();
result.caseDefinitionId = instance.getCaseDefinitionId();
result.businessKey = instance.getBusinessKey();
result.tenantId = instance.getTenantId();
result.active = instance.isActive();
result.completed = instance.isCompleted();
result.terminated = instance.isTerminated();
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\CaseInstanceDto.java
| 1
|
请完成以下Java代码
|
public List<Student> getStudentsOfGradeStateAndGenderWithPositionalParams(int grade, String state, String gender) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = ? and state = ? and gender = ?";
return jdbcClient.sql(sql)
.param(grade)
.param(state)
.param(gender)
.query(new StudentRowMapper()).list();
}
public List<Student> getStudentsOfGradeStateAndGenderWithParamIndex(int grade, String state, String gender) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = ? and state = ? and gender = ?";
return jdbcClient.sql(sql)
.param(1,grade)
.param(2, state)
.param(3, gender)
.query(new StudentResultExtractor());
}
public Student getStudentsOfGradeStateAndGenderWithParamsInVarargs(int grade, String state, String gender) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = ? and state = ? and gender = ? limit 1";
return jdbcClient.sql(sql)
.params(grade, state, gender)
.query(new StudentRowMapper()).single();
}
public Optional<Student> getStudentsOfGradeStateAndGenderWithParamsInList(List params) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = ? and state = ? and gender = ? limit 1";
return jdbcClient.sql(sql)
.params(params)
.query(new StudentRowMapper()).optional();
}
|
public int getCountOfStudentsOfGradeStateAndGenderWithNamedParam(int grade, String state, String gender) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = :grade and state = :state and gender = :gender";
RowCountCallbackHandler countCallbackHandler = new RowCountCallbackHandler();
jdbcClient.sql(sql)
.param("grade", grade)
.param("state", state)
.param("gender", gender)
.query(countCallbackHandler);
return countCallbackHandler.getRowCount();
}
public List<Student> getStudentsOfGradeStateAndGenderWithParamMap(Map<String, ?> paramMap) {
String sql = "select student_id, student_name, age, grade, gender, state from student"
+ " where grade = :grade and state = :state and gender = :gender";
return jdbcClient.sql(sql)
.params(paramMap)
.query(new StudentRowMapper()).list();
}
}
|
repos\tutorials-master\persistence-modules\spring-jdbc-2\src\main\java\com\baeldung\jdbcclient\dao\StudentDao.java
| 1
|
请完成以下Java代码
|
public class ApiError {
private HttpStatus status;
private String message;
private List<String> errors;
//
public ApiError() {
super();
}
public ApiError(final HttpStatus status, final String message, final List<String> errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public ApiError(final HttpStatus status, final String message, final String error) {
super();
this.status = status;
this.message = message;
errors = Arrays.asList(error);
}
//
public HttpStatus getStatus() {
return status;
}
public void setStatus(final HttpStatus status) {
this.status = status;
}
public String getMessage() {
return message;
}
|
public void setMessage(final String message) {
this.message = message;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(final List<String> errors) {
this.errors = errors;
}
public void setError(final String error) {
errors = Arrays.asList(error);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-rest\src\main\java\com\baeldung\errorhandling\ApiError.java
| 1
|
请完成以下Java代码
|
public boolean containsValue(Object value)
{
return false;
}
@Override
public V get(Object key)
{
return get(key.toString());
}
@Override
public int build(TreeMap<String, V> keyValueMap)
{
int size = keyValueMap.size();
int[] indexArray = new int[size];
valueArray = (V[]) keyValueMap.values().toArray();
List<String> keyList = new ArrayList<String>(size);
int i = 0;
for (Entry<String, V> entry : keyValueMap.entrySet())
{
indexArray[i] = i;
valueArray[i] = entry.getValue();
keyList.add(entry.getKey());
++i;
}
build(keyList, indexArray);
return 0;
}
@Override
public boolean save(DataOutputStream out)
{
return false;
}
@Override
public boolean load(ByteArray byteArray, V[] value)
{
return false;
}
@Override
public V get(char[] key)
{
return get(new String(key));
}
public V get(String key)
{
int id = exactMatchSearch(key);
if (id == -1) return null;
return valueArray[id];
}
@Override
public V[] getValueArray(V[] a)
{
return valueArray;
}
/**
* 前缀查询
* @param key
* @param offset
* @param maxResults
* @return
*/
public ArrayList<Pair<String, V>> commonPrefixSearch(String key, int offset, int maxResults)
{
byte[] keyBytes = key.getBytes(utf8);
List<Pair<Integer, Integer>> pairList = commonPrefixSearch(keyBytes, offset, maxResults);
ArrayList<Pair<String, V>> resultList = new ArrayList<Pair<String, V>>(pairList.size());
for (Pair<Integer, Integer> pair : pairList)
{
resultList.add(new Pair<String, V>(new String(keyBytes, 0, pair.first), valueArray[pair.second]));
|
}
return resultList;
}
public ArrayList<Pair<String, V>> commonPrefixSearch(String key)
{
return commonPrefixSearch(key, 0, Integer.MAX_VALUE);
}
@Override
public V put(String key, V value)
{
throw new UnsupportedOperationException("双数组不支持增量式插入");
}
@Override
public V remove(Object key)
{
throw new UnsupportedOperationException("双数组不支持删除");
}
@Override
public void putAll(Map<? extends String, ? extends V> m)
{
throw new UnsupportedOperationException("双数组不支持增量式插入");
}
@Override
public void clear()
{
throw new UnsupportedOperationException("双数组不支持");
}
@Override
public Set<String> keySet()
{
throw new UnsupportedOperationException("双数组不支持");
}
@Override
public Collection<V> values()
{
return Arrays.asList(valueArray);
}
@Override
public Set<Entry<String, V>> entrySet()
{
throw new UnsupportedOperationException("双数组不支持");
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DartMap.java
| 1
|
请完成以下Java代码
|
public int getSuspendedJobCount() {
return suspendedJobCount;
}
public void setSuspendedJobCount(int suspendedJobCount) {
this.suspendedJobCount = suspendedJobCount;
}
public int getDeadLetterJobCount() {
return deadLetterJobCount;
}
public void setDeadLetterJobCount(int deadLetterJobCount) {
this.deadLetterJobCount = deadLetterJobCount;
}
public int getVariableCount() {
return variableCount;
}
public void setVariableCount(int variableCount) {
this.variableCount = variableCount;
}
public int getIdentityLinkCount() {
return identityLinkCount;
}
public void setIdentityLinkCount(int identityLinkCount) {
this.identityLinkCount = identityLinkCount;
}
@Override
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
@Override
public Integer getAppVersion() {
return appVersion;
}
|
//toString /////////////////////////////////////////////////////////////////
public String toString() {
if (isProcessInstanceType()) {
return "ProcessInstance[" + getId() + "]";
} else {
StringBuilder strb = new StringBuilder();
if (isScope) {
strb.append("Scoped execution[ id '" + getId() + "' ]");
} else if (isMultiInstanceRoot) {
strb.append("Multi instance root execution[ id '" + getId() + "' ]");
} else {
strb.append("Execution[ id '" + getId() + "' ]");
}
if (activityId != null) {
strb.append(" - activity '" + activityId);
}
if (parentId != null) {
strb.append(" - parent '" + parentId + "'");
}
return strb.toString();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java
| 1
|
请完成以下Java代码
|
public String getNbOfDays() {
return nbOfDays;
}
/**
* Sets the value of the nbOfDays property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfDays(String value) {
this.nbOfDays = value;
}
/**
* Gets the value of the actlDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
|
public XMLGregorianCalendar getActlDt() {
return actlDt;
}
/**
* Sets the value of the actlDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setActlDt(XMLGregorianCalendar value) {
this.actlDt = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashBalanceAvailabilityDate1.java
| 1
|
请完成以下Java代码
|
public BPartnerContact extract(@NonNull final ExternalIdentifier contactIdentifier)
{
final BPartnerContact result = extract0(contactIdentifier);
if (result != null)
{
id2UnusedContact.remove(result.getId());
}
return result;
}
private BPartnerContact extract0(@NonNull final ExternalIdentifier contactIdentifier)
{
switch (contactIdentifier.getType())
{
case METASFRESH_ID:
if (bpartnerId != null)
{
final BPartnerContactId bpartnerContactId = BPartnerContactId.of(bpartnerId, UserId.ofRepoId(contactIdentifier.asMetasfreshId().getValue()));
return id2Contact.get(bpartnerContactId);
}
else
{
return null;
}
case EXTERNAL_REFERENCE:
throw new AdempiereException("Type EXTERNAL_REFERENCE is not allowed. The identifier should be resolved to a METASFRESH_ID.");
default:
throw new InvalidIdentifierException(contactIdentifier.getRawValue());
}
}
public BPartnerContact newContact(@NonNull final ExternalIdentifier contactIdentifier)
{
final BPartnerContact contact;
final BPartnerContactBuilder contactBuilder = BPartnerContact.builder();
switch (contactIdentifier.getType())
{
case METASFRESH_ID:
throw new AdempiereException("No inserts are allowed with this type. External identifier: " + contactIdentifier.getRawValue());
case EXTERNAL_REFERENCE:
contact = contactBuilder.build();
break;
default:
throw new InvalidIdentifierException(contactIdentifier.getRawValue());
}
bpartnerComposite
.getContacts()
.add(contact);
|
return contact;
}
public Collection<BPartnerContact> getUnusedContacts()
{
return id2UnusedContact.values();
}
public void resetDefaultContactFlags()
{
for (final BPartnerContact bpartnerContact : getUnusedContacts())
{
bpartnerContact.getContactType().setDefaultContact(false);
}
}
public void resetShipToDefaultFlags()
{
for (final BPartnerContact bpartnerContact : getUnusedContacts())
{
bpartnerContact.getContactType().setShipToDefault(false);
}
}
public void resetPurchaseDefaultFlags()
{
for (final BPartnerContact bpartnerContact : getUnusedContacts())
{
bpartnerContact.getContactType().setPurchaseDefault(false);
}
}
public void resetSalesDefaultFlags()
{
for (final BPartnerContact bpartnerContact : getUnusedContacts())
{
bpartnerContact.getContactType().setSalesDefault(false);
}
}
public void resetBillToDefaultFlags()
{
for (final BPartnerContact bpartnerContact : getUnusedContacts())
{
bpartnerContact.getContactType().setBillToDefault(false);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\bpartnercomposite\jsonpersister\ShortTermContactIndex.java
| 1
|
请完成以下Java代码
|
String readSocketResponse(@NonNull final InputStream in) throws IOException
{
return readLineSocketResponse(in);
}
@Nullable
private String readLineSocketResponse(@NonNull final InputStream in) throws IOException
{
try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, ICmd.DEFAULT_CMD_CHARSET)))
{
String result = null;
String lastReadLine = bufferedReader.readLine();
if (returnLastLine)
{
while (lastReadLine != null)
{
result = lastReadLine;
lastReadLine = readLineWithTimeout(bufferedReader);
}
logger.debug("Result (last line) as read from the socket: {}", result);
}
else
{
result = lastReadLine;
logger.debug("Result (first line) as read from the socket: {}", result);
}
return result;
}
}
|
@Nullable
private String readLineWithTimeout(@NonNull final BufferedReader in) throws IOException
{
try
{
final String lastReadLine = in.readLine();
logger.debug("Read line from the socket: {}", lastReadLine);
return lastReadLine;
}
catch (final SocketTimeoutException e)
{
logger.debug("Socket timeout; return null; exception-message={}", e.getMessage());
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\endpoint\TcpConnectionReadLineEndPoint.java
| 1
|
请完成以下Java代码
|
public static final class Builder {
private final String registeredClientId;
private final String principalName;
private final Set<GrantedAuthority> authorities = new HashSet<>();
private Builder(String registeredClientId, String principalName) {
this(registeredClientId, principalName, Collections.emptySet());
}
private Builder(String registeredClientId, String principalName, Set<GrantedAuthority> authorities) {
this.registeredClientId = registeredClientId;
this.principalName = principalName;
if (!CollectionUtils.isEmpty(authorities)) {
this.authorities.addAll(authorities);
}
}
/**
* Adds a scope to the collection of {@code authorities} in the resulting
* {@link OAuth2AuthorizationConsent}, wrapping it in a
* {@link SimpleGrantedAuthority}, prefixed by {@code SCOPE_}. For example, a
* {@code message.write} scope would be stored as {@code SCOPE_message.write}.
* @param scope the scope
* @return the {@code Builder} for further configuration
*/
public Builder scope(String scope) {
authority(new SimpleGrantedAuthority(AUTHORITIES_SCOPE_PREFIX + scope));
return this;
}
/**
* Adds a {@link GrantedAuthority} to the collection of {@code authorities} in the
* resulting {@link OAuth2AuthorizationConsent}.
* @param authority the {@link GrantedAuthority}
* @return the {@code Builder} for further configuration
*/
|
public Builder authority(GrantedAuthority authority) {
this.authorities.add(authority);
return this;
}
/**
* A {@code Consumer} of the {@code authorities}, allowing the ability to add,
* replace or remove.
* @param authoritiesConsumer a {@code Consumer} of the {@code authorities}
* @return the {@code Builder} for further configuration
*/
public Builder authorities(Consumer<Set<GrantedAuthority>> authoritiesConsumer) {
authoritiesConsumer.accept(this.authorities);
return this;
}
/**
* Validate the authorities and build the {@link OAuth2AuthorizationConsent}.
* There must be at least one {@link GrantedAuthority}.
* @return the {@link OAuth2AuthorizationConsent}
*/
public OAuth2AuthorizationConsent build() {
Assert.notEmpty(this.authorities, "authorities cannot be empty");
return new OAuth2AuthorizationConsent(this.registeredClientId, this.principalName, this.authorities);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationConsent.java
| 1
|
请完成以下Java代码
|
public void setRef_OrderLine_ID (int Ref_OrderLine_ID)
{
if (Ref_OrderLine_ID < 1)
set_Value (COLUMNNAME_Ref_OrderLine_ID, null);
else
set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID));
}
/** Get Referenced Order Line.
@return Reference to corresponding Sales/Purchase Order
*/
public int getRef_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ressourcenzuordnung.
@param S_ResourceAssignment_ID
Ressourcenzuordnung
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
|
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Ressourcenzuordnung.
@return Ressourcenzuordnung
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
| 1
|
请完成以下Java代码
|
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_Value (COLUMNNAME_M_ProductGroup_ID, null);
else
set_Value (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
}
@Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
|
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@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.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_Agg.java
| 1
|
请完成以下Java代码
|
public void setType_Conditions (final java.lang.String Type_Conditions)
{
set_ValueNoCheck (COLUMNNAME_Type_Conditions, Type_Conditions);
}
@Override
public java.lang.String getType_Conditions()
{
return get_ValueAsString(COLUMNNAME_Type_Conditions);
}
/**
* Type_Flatrate AD_Reference_ID=540264
* Reference name: Type_Flatrate
*/
public static final int TYPE_FLATRATE_AD_Reference_ID=540264;
/** NONE = NONE */
public static final String TYPE_FLATRATE_NONE = "NONE";
/** Corridor_Percent = LIPE */
|
public static final String TYPE_FLATRATE_Corridor_Percent = "LIPE";
/** Reported Quantity = RPTD */
public static final String TYPE_FLATRATE_ReportedQuantity = "RPTD";
@Override
public void setType_Flatrate (final java.lang.String Type_Flatrate)
{
set_Value (COLUMNNAME_Type_Flatrate, Type_Flatrate);
}
@Override
public java.lang.String getType_Flatrate()
{
return get_ValueAsString(COLUMNNAME_Type_Flatrate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Conditions.java
| 1
|
请完成以下Java代码
|
public class SyncInfoVo {
/**
* 成功的信息
*/
private List<String> successInfo;
/**
* 失败的信息
*/
private List<String> failInfo;
public SyncInfoVo() {
this.successInfo = new ArrayList<>();
this.failInfo = new ArrayList<>();
}
|
public SyncInfoVo(List<String> successInfo, List<String> failInfo) {
this.successInfo = successInfo;
this.failInfo = failInfo;
}
public SyncInfoVo addSuccessInfo(String info) {
this.successInfo.add(info);
return this;
}
public SyncInfoVo addFailInfo(String info) {
this.failInfo.add(info);
return this;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\thirdapp\SyncInfoVo.java
| 1
|
请完成以下Java代码
|
public Document initializeAsNewDocument(final DocumentId newDocumentId, final String version)
{
return initializeAsNewDocument(new SimpleDocumentValuesSupplier(newDocumentId, version));
}
public Document initializeAsNewDocument(final Supplier<DocumentId> newDocumentIdSupplier, final String version)
{
return initializeAsNewDocument(new SimpleDocumentValuesSupplier(newDocumentIdSupplier, version));
}
public Document initializeAsNewDocument(final IntSupplier newDocumentIdSupplier, final String version)
{
return initializeAsNewDocument(new SimpleDocumentValuesSupplier(DocumentId.supplier(newDocumentIdSupplier), version));
}
public Document initializeAsExistingRecord(@NonNull final DocumentValuesSupplier documentValuesSupplier)
{
_fieldInitializerMode = FieldInitializationMode.Load;
_documentValuesSupplier = documentValuesSupplier;
return build();
}
private DocumentId getDocumentId()
{
return _documentValuesSupplier.getDocumentId();
}
private FieldInitializationMode getFieldInitializerMode()
{
return _fieldInitializerMode;
}
private boolean isNewDocument()
{
return _fieldInitializerMode == FieldInitializationMode.NewDocument;
}
private Document getParentDocument()
{
return _parentDocument;
}
private DocumentPath getDocumentPath()
{
if (_documentPath == null)
{
final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor();
final DocumentId documentId = getDocumentId();
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
_documentPath = DocumentPath.rootDocumentPath(entityDescriptor.getDocumentType(), entityDescriptor.getDocumentTypeId(), documentId);
}
else
{
_documentPath = parentDocument.getDocumentPath().createChildPath(entityDescriptor.getDetailId(), documentId);
}
}
return _documentPath;
}
private int getWindowNo()
{
if (_windowNo == null)
{
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
_windowNo = _nextWindowNo.incrementAndGet();
}
else
{
|
_windowNo = parentDocument.getWindowNo();
}
}
return _windowNo;
}
private boolean isWritable()
{
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return isNewDocument();
}
else
{
return parentDocument.isWritable();
}
}
private ReentrantReadWriteLock createLock()
{
// don't create locks for any other entity which is not window
final DocumentEntityDescriptor entityDescriptor = getEntityDescriptor();
if (entityDescriptor.getDocumentType() != DocumentType.Window)
{
return null;
}
//
final Document parentDocument = getParentDocument();
if (parentDocument == null)
{
return new ReentrantReadWriteLock();
}
else
{
// don't create lock for included documents
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\Document.java
| 1
|
请完成以下Java代码
|
public String getStrokeValue() {
return "none";
}
@Override
public String getDValue() {
return "M 10 0 C 4.4771525 0 0 4.4771525 0 10 C 0 15.522847 4.4771525 20 10 20 C 15.522847 20 20 15.522847 20 10 C 20 4.4771525 15.522847 1.1842379e-15 10 0 z M 9.09375 1.03125 C 9.2292164 1.0174926 9.362825 1.0389311 9.5 1.03125 L 9.5 3.5 L 10.5 3.5 L 10.5 1.03125 C 15.063526 1.2867831 18.713217 4.9364738 18.96875 9.5 L 16.5 9.5 L 16.5 10.5 L 18.96875 10.5 C 18.713217 15.063526 15.063526 18.713217 10.5 18.96875 L 10.5 16.5 L 9.5 16.5 L 9.5 18.96875 C 4.9364738 18.713217 1.2867831 15.063526 1.03125 10.5 L 3.5 10.5 L 3.5 9.5 L 1.03125 9.5 C 1.279102 5.0736488 4.7225326 1.4751713 9.09375 1.03125 z M 9.5 5 L 9.5 8.0625 C 8.6373007 8.2844627 8 9.0680195 8 10 C 8 11.104569 8.8954305 12 10 12 C 10.931981 12 11.715537 11.362699 11.9375 10.5 L 14 10.5 L 14 9.5 L 11.9375 9.5 C 11.756642 8.7970599 11.20294 8.2433585 10.5 8.0625 L 10.5 5 L 9.5 5 z ";
}
public void drawIcon(
final int imageX,
final int imageYo,
final int iconPadding,
final ProcessDiagramSVGGraphics2D svgGenerator
) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX) + "," + (imageYo) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getAnchorValue() {
return null;
}
@Override
|
public String getStyleValue() {
return null;
}
@Override
public Integer getWidth() {
return 20;
}
@Override
public Integer getHeight() {
return 20;
}
@Override
public String getStrokeWidth() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\TimerIconType.java
| 1
|
请完成以下Java代码
|
public void setIsEmployee (boolean IsEmployee)
{
set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee));
}
/** Get Employee.
@return Indicates if this Business Partner is an employee
*/
public boolean isEmployee ()
{
Object oo = get_Value(COLUMNNAME_IsEmployee);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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_C_Job.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ObservationRegistry getObservationRegistry() {
ApplicationContext context = getBuilder().getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(ObservationRegistry.class);
if (names.length == 1) {
return context.getBean(ObservationRegistry.class);
}
else {
return ObservationRegistry.NOOP;
}
}
/**
* Allows registering {@link RequestMatcher} instances that should be ignored (even if
* the {@link HttpServletRequest} matches the
* {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}.
*
* @author Rob Winch
* @since 4.0
*/
private class IgnoreCsrfProtectionRegistry extends AbstractRequestMatcherRegistry<IgnoreCsrfProtectionRegistry> {
IgnoreCsrfProtectionRegistry(ApplicationContext context) {
setApplicationContext(context);
}
@Override
protected IgnoreCsrfProtectionRegistry chainRequestMatchers(List<RequestMatcher> requestMatchers) {
CsrfConfigurer.this.ignoredCsrfProtectionMatchers.addAll(requestMatchers);
return this;
}
|
}
private static final class SpaCsrfTokenRequestHandler implements CsrfTokenRequestHandler {
private final CsrfTokenRequestAttributeHandler plain = new CsrfTokenRequestAttributeHandler();
private final CsrfTokenRequestAttributeHandler xor = new XorCsrfTokenRequestAttributeHandler();
SpaCsrfTokenRequestHandler() {
this.xor.setCsrfRequestAttributeName(null);
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, Supplier<CsrfToken> csrfToken) {
this.xor.handle(request, response, csrfToken);
}
@Override
public String resolveCsrfTokenValue(HttpServletRequest request, CsrfToken csrfToken) {
String headerValue = request.getHeader(csrfToken.getHeaderName());
return (StringUtils.hasText(headerValue) ? this.plain : this.xor).resolveCsrfTokenValue(request, csrfToken);
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\CsrfConfigurer.java
| 2
|
请完成以下Java代码
|
protected String getPropertyValueAsString(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsString(name, objectNode);
}
protected boolean getPropertyValueAsBoolean(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsBoolean(name, objectNode);
}
protected List<String> getPropertyValueAsList(String name, JsonNode objectNode) {
return JsonConverterUtil.getPropertyValueAsList(name, objectNode);
}
protected JsonNode getProperty(String name, JsonNode objectNode) {
return JsonConverterUtil.getProperty(name, objectNode);
}
|
protected String convertListToCommaSeparatedString(List<String> stringList) {
String resultString = null;
if (stringList != null && stringList.size() > 0) {
StringBuilder expressionBuilder = new StringBuilder();
for (String singleItem : stringList) {
if (expressionBuilder.length() > 0) {
expressionBuilder.append(",");
}
expressionBuilder.append(singleItem);
}
resultString = expressionBuilder.toString();
}
return resultString;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BaseBpmnJsonConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
FileSystemWatcherFactory getFileSystemWatcherFactory() {
return this::newFileSystemWatcher;
}
private FileSystemWatcher newFileSystemWatcher() {
Restart restartProperties = this.properties.getRestart();
FileSystemWatcher watcher = new FileSystemWatcher(true, restartProperties.getPollInterval(),
restartProperties.getQuietPeriod());
String triggerFile = restartProperties.getTriggerFile();
if (StringUtils.hasLength(triggerFile)) {
watcher.setTriggerFilter(new TriggerFileFilter(triggerFile));
}
return watcher;
}
|
@Bean
ClassPathRestartStrategy classPathRestartStrategy() {
return new PatternClassPathRestartStrategy(this.properties.getRestart().getAllExclude());
}
@Bean
ClassPathChangeUploader classPathChangeUploader(ClientHttpRequestFactory requestFactory,
@Value("${remoteUrl}") String remoteUrl) {
String url = remoteUrl + this.properties.getRemote().getContextPath() + "/restart";
return new ClassPathChangeUploader(url, requestFactory);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\remote\client\RemoteClientConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SpringIdmEngineConfiguration idmEngineConfiguration(DataSource dataSource, PlatformTransactionManager platformTransactionManager) {
SpringIdmEngineConfiguration configuration = new SpringIdmEngineConfiguration();
configuration.setTransactionManager(platformTransactionManager);
configureEngine(configuration, dataSource);
return configuration;
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = {
"org.flowable.spring.SpringProcessEngineConfiguration"
})
@ConditionalOnMissingBean(type = {
"org.flowable.app.spring.SpringAppEngineConfiguration"
})
public static class IdmEngineProcessConfiguration extends BaseEngineConfigurationWithConfigurers<SpringIdmEngineConfiguration> {
@Bean
@ConditionalOnMissingBean(name = "idmProcessEngineConfigurationConfigurer")
public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> idmProcessEngineConfigurationConfigurer(
IdmEngineConfigurator idmEngineConfigurator
) {
return processEngineConfiguration -> processEngineConfiguration.setIdmEngineConfigurator(idmEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public IdmEngineConfigurator idmEngineConfigurator(SpringIdmEngineConfiguration configuration) {
SpringIdmEngineConfigurator idmEngineConfigurator = new SpringIdmEngineConfigurator();
idmEngineConfigurator.setIdmEngineConfiguration(configuration);
invokeConfigurers(configuration);
return idmEngineConfigurator;
|
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = {
"org.flowable.app.spring.SpringAppEngineConfiguration"
})
public static class IdmEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringIdmEngineConfiguration> {
@Bean
@ConditionalOnMissingBean(name = "idmAppEngineConfigurationConfigurer")
public EngineConfigurationConfigurer<SpringAppEngineConfiguration> idmAppEngineConfigurationConfigurer(
IdmEngineConfigurator idmEngineConfigurator
) {
return appEngineConfiguration -> appEngineConfiguration.setIdmEngineConfigurator(idmEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public IdmEngineConfigurator idmEngineConfigurator(SpringIdmEngineConfiguration configuration) {
SpringIdmEngineConfigurator idmEngineConfigurator = new SpringIdmEngineConfigurator();
idmEngineConfigurator.setIdmEngineConfiguration(configuration);
invokeConfigurers(configuration);
return idmEngineConfigurator;
}
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\idm\IdmEngineAutoConfiguration.java
| 2
|
请完成以下Java代码
|
default void setBatchingStrategy(BatchingStrategy batchingStrategy) {
}
/**
* Return this endpoint's batching strategy, or null.
* @return the strategy.
* @since 2.4.7
*/
default @Nullable BatchingStrategy getBatchingStrategy() {
return null;
}
/**
* Override the container factory's {@link AcknowledgeMode}.
* @return the acknowledgment mode.
* @since 2.2
*/
default @Nullable AcknowledgeMode getAckMode() {
return null;
}
/**
* Return a {@link ReplyPostProcessor} to post process a reply message before it is
* sent.
* @return the post processor.
* @since 2.2.5
*/
default @Nullable ReplyPostProcessor getReplyPostProcessor() {
|
return null;
}
/**
* Get the reply content type.
* @return the content type.
* @since 2.3
*/
default @Nullable String getReplyContentType() {
return null;
}
/**
* Return whether the content type set by a converter prevails or not.
* @return false to always apply the reply content type.
* @since 2.3
*/
default boolean isConverterWinsContentType() {
return true;
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\RabbitListenerEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BankAccount getBankAccountById(@NonNull final BankAccountId bankAccountId)
{
return bpBankAccountDAO.getById(bankAccountId);
}
public List<I_C_BankStatementLine> getBankStatementLinesByBankStatementId(@NonNull final BankStatementId bankStatementId)
{
return bankStatementBL.getLinesByBankStatementId(bankStatementId);
}
public BankStatementLineReferenceList getBankStatementLineReferences(@NonNull final BankStatementLineId bankStatementLineId)
{
return bankStatementDAO.getLineReferences(bankStatementLineId);
}
public BankStatementLineReferenceList getBankStatementLineReferences(final Collection<BankStatementLineId> bankStatementLineIds)
{
return bankStatementDAO.getLineReferences(bankStatementLineIds);
}
public void save(final I_C_BankStatementLine line)
{
bankStatementDAO.save(line);
}
public void findOrCreateSinglePaymentAndLinkIfPossible(
final I_C_BankStatement bankStatement,
final I_C_BankStatementLine line,
final Set<PaymentId> excludePaymentIds)
{
bankStatmentPaymentBL.findOrCreateSinglePaymentAndLinkIfPossible(bankStatement, line, excludePaymentIds);
}
public void markReconciled(final List<PaymentReconcileRequest> requests)
|
{
paymentBL.markReconciled(requests);
}
public void markBankStatementLinesAsProcessed(final BankStatementId bankStatementId)
{
final boolean processed = true;
bankStatementDAO.updateBankStatementLinesProcessedFlag(bankStatementId, processed);
}
public void deleteFactsForBankStatement(final I_C_BankStatement bankStatement)
{
factAcctDAO.deleteForDocumentModel(bankStatement);
}
public void unreconcile(@NonNull final List<I_C_BankStatementLine> lines)
{
bankStatementBL.unreconcile(lines);
}
public String getMsg(final AdMessageKey adMessage)
{
return msgBL.getMsg(Env.getCtx(), adMessage);
}
public String getMsg(final Properties ctx, final AdMessageKey adMessage)
{
return msgBL.getMsg(ctx, adMessage);
}
public String translate(final Properties ctx, final String adMessageOrColumnName)
{
return msgBL.translate(ctx, adMessageOrColumnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\service\BankStatementDocumentHandlerRequiredServicesFacade.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getUsername2() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@RolesAllowed({ "ROLE_VIEWER", "ROLE_EDITOR" })
public boolean isValidUsername2(String username) {
return userRoleRepository.isValidUsername(username);
}
@PreAuthorize("hasRole('ROLE_VIEWER')")
public String getUsernameInUpperCase() {
return getUsername().toUpperCase();
}
@PreAuthorize("hasAuthority('SYS_ADMIN')")
public String getUsernameLC() {
return getUsername().toLowerCase();
}
@PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')")
public boolean isValidUsername3(String username) {
return userRoleRepository.isValidUsername(username);
}
@PreAuthorize("#username == authentication.principal.username")
public String getMyRoles(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("#username == authentication.principal.username")
public String getMyRoles2(String username) {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser loadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
@PreFilter("filterObject != authentication.principal.username")
public String joinUsernames(List<String> usernames) {
return usernames.stream().collect(Collectors.joining(";"));
}
|
@PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames")
public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) {
return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";"));
}
@PostFilter("filterObject != authentication.principal.username")
public List<String> getAllUsernamesExceptCurrent() {
return userRoleRepository.getAllUsernames();
}
@IsViewer
public String getUsername4() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
@PreAuthorize("#username == authentication.principal.username")
@PostAuthorize("returnObject.username == authentication.principal.nickName")
public CustomUser securedLoadUserDetail(String username) {
return userRoleRepository.loadUserByUserName(username);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java
| 2
|
请完成以下Java代码
|
public class SequenceFlowParseHandler extends AbstractBpmnParseHandler<SequenceFlow> {
public static final String PROPERTYNAME_CONDITION = "condition";
public static final String PROPERTYNAME_CONDITION_TEXT = "conditionText";
@Override
public Class<? extends BaseElement> getHandledType() {
return SequenceFlow.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, SequenceFlow sequenceFlow) {
ScopeImpl scope = bpmnParse.getCurrentScope();
ActivityImpl sourceActivity = scope.findActivity(sequenceFlow.getSourceRef());
ActivityImpl destinationActivity = scope.findActivity(sequenceFlow.getTargetRef());
Expression skipExpression;
if (StringUtils.isNotEmpty(sequenceFlow.getSkipExpression())) {
ExpressionManager expressionManager = bpmnParse.getExpressionManager();
skipExpression = expressionManager.createExpression(sequenceFlow.getSkipExpression());
} else {
skipExpression = null;
}
|
TransitionImpl transition = sourceActivity.createOutgoingTransition(sequenceFlow.getId(), skipExpression);
bpmnParse.getSequenceFlows().put(sequenceFlow.getId(), transition);
transition.setProperty("name", sequenceFlow.getName());
transition.setProperty("documentation", sequenceFlow.getDocumentation());
transition.setDestination(destinationActivity);
if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) {
Condition expressionCondition = new UelExpressionCondition(sequenceFlow.getConditionExpression());
transition.setProperty(PROPERTYNAME_CONDITION_TEXT, sequenceFlow.getConditionExpression());
transition.setProperty(PROPERTYNAME_CONDITION, expressionCondition);
}
createExecutionListenersOnTransition(bpmnParse, sequenceFlow.getExecutionListeners(), transition);
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SequenceFlowParseHandler.java
| 1
|
请完成以下Java代码
|
public boolean isEnabled(@NonNull final UserId userId)
{
return getSecretKey(userId).isPresent();
}
public boolean isDisabled(@NonNull final UserId userId)
{
return !isEnabled(userId);
}
private Optional<SecretKey> getSecretKey(final @NonNull UserId userId)
{
return extractSecretKey(userDAO.getById(userId));
}
private static Optional<SecretKey> extractSecretKey(final I_AD_User user)
{
return SecretKey.optionalOfString(user.getSecretKey_2FA());
}
public TOTPInfo enable(@NonNull final UserId userId, final boolean regenerateSecretKey)
{
final I_AD_User user = userDAO.getById(userId);
final String account = CoalesceUtil.firstNotBlank(user::getEMail, user::getLogin, user::getName);
final String companyName = clientDAO.getClientNameById(ClientId.ofRepoId(user.getAD_Client_ID()));
SecretKey secretKey = extractSecretKey(user).orElse(null);
if (secretKey == null || regenerateSecretKey)
{
secretKey = SecretKey.random();
}
user.setSecretKey_2FA(secretKey.getAsString());
userDAO.save(user);
return TOTPInfo.builder()
.userId(userId)
.secretKey(secretKey)
.account(account)
.issuer(companyName)
.build();
|
}
public void disable(@NonNull final UserId userId)
{
final I_AD_User user = userDAO.getById(userId);
user.setSecretKey_2FA(null);
userDAO.save(user);
}
public boolean isValidOTP(@NonNull final UserId userId, @NonNull final OTP otp)
{
final SecretKey secretKey = getSecretKey(userId).orElse(null);
if (secretKey == null)
{
// 2FA is not enabled for this user
return false;
}
return secretKey.isValid(otp);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\User2FAService.java
| 1
|
请完成以下Java代码
|
void reportProgress(final PPOrderActivityProcessReport report)
{
changeStatusTo(PPOrderRoutingActivityStatus.IN_PROGRESS);
if (getDateStart() == null)
{
setDateStart(report.getFinishDate().minus(report.getDuration()));
}
if (getDateFinish() == null || getDateFinish().isBefore(report.getFinishDate()))
{
setDateFinish(report.getFinishDate());
}
if (report.getQtyProcessed() != null)
{
setQtyDelivered(getQtyDelivered().add(report.getQtyProcessed()));
}
if (report.getQtyScrapped() != null)
{
setQtyScrapped(getQtyScrapped().add(report.getQtyScrapped()));
}
if (report.getQtyRejected() != null)
{
setQtyRejected(getQtyRejected().add(report.getQtyRejected()));
}
setDurationReal(getDurationReal().plus(report.getDuration()));
setSetupTimeReal(getSetupTimeReal().plus(report.getSetupTime()));
}
void closeIt()
{
if (getStatus() == PPOrderRoutingActivityStatus.CLOSED)
{
logger.warn("Activity already closed - {}", this);
return;
}
else if (getStatus() == PPOrderRoutingActivityStatus.IN_PROGRESS)
{
completeIt();
}
changeStatusTo(PPOrderRoutingActivityStatus.CLOSED);
if (getDateFinish() != null)
{
setDateFinish(SystemTime.asInstant());
}
if (!Objects.equals(getDurationRequired(), getDurationReal()))
{
// addDescription(Services.get(IMsgBL.class).parseTranslation(getCtx(), "@closed@ ( @Duration@ :" + getDurationRequiered() + ") ( @QtyRequiered@ :" + getQtyRequiered() + ")"));
setDurationRequired(getDurationReal());
setQtyRequired(getQtyDelivered());
}
}
void uncloseIt()
{
|
if (getStatus() != PPOrderRoutingActivityStatus.CLOSED)
{
logger.warn("Only Closed activities can be unclosed - {}", this);
return;
}
changeStatusTo(PPOrderRoutingActivityStatus.IN_PROGRESS);
}
void voidIt()
{
if (getStatus() == PPOrderRoutingActivityStatus.VOIDED)
{
logger.warn("Activity already voided - {}", this);
return;
}
changeStatusTo(PPOrderRoutingActivityStatus.VOIDED);
setQtyRequired(getQtyRequired().toZero());
setSetupTimeRequired(Duration.ZERO);
setDurationRequired(Duration.ZERO);
}
public void completeIt()
{
changeStatusTo(PPOrderRoutingActivityStatus.COMPLETED);
if (getDateFinish() == null)
{
setDateFinish(SystemTime.asInstant());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingActivity.java
| 1
|
请完成以下Java代码
|
public IRfQResponseProducer newRfQResponsesProducerFor(final I_C_RfQ rfq)
{
if (!Services.get(IPMM_RfQ_BL.class).isProcurement(rfq))
{
return null;
}
return new PMMRfQResponseProducer();
}
private static class PMMRfQResponseProducer extends DefaultRfQResponseProducer
{
@Override
protected I_C_RfQResponseLine createRfqResponseLine(final Supplier<I_C_RfQResponse> responseSupplier, final de.metas.rfq.model.I_C_RfQLine rfqLine)
{
final de.metas.rfq.model.I_C_RfQResponseLine rfqResponseLine = super.createRfqResponseLine(responseSupplier, rfqLine);
|
if (rfqResponseLine == null)
{
return null;
}
final I_C_RfQResponseLine pmmRfqResponseLine = InterfaceWrapperHelper.create(rfqResponseLine, I_C_RfQResponseLine.class);
//
// From RfQ Line
final I_C_RfQLine pmmRfqLine = InterfaceWrapperHelper.create(rfqLine, I_C_RfQLine.class);
pmmRfqResponseLine.setPMM_Product(pmmRfqLine.getPMM_Product());
return pmmRfqResponseLine;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\rfq\PMMRfQResponseProducerFactory.java
| 1
|
请完成以下Java代码
|
public String createNext()
{
return encodeUsingDigits(nextViewId.getAndIncrement(), VIEW_DIGITS);
}
@VisibleForTesting
String encodeUsingDigits(final long value, char[] digits)
{
if (value == 0)
{
return String.valueOf(digits[0]);
}
final int base = digits.length;
final StringBuilder buf = new StringBuilder();
long currentValue = value;
while (currentValue > 0)
{
final int remainder = (int)(currentValue % base);
currentValue = currentValue / base;
buf.append(digits[remainder]);
}
return buf.reverse().toString();
}
|
public void setRandomUUIDSource(@NonNull final Supplier<String> newRandomUUIDSource)
{
randomUUIDSource = newRandomUUIDSource;
}
public void reset()
{
nextViewId.set(1);
randomUUIDSource = null;
}
public String createRandomUUID()
{
return coalesceSuppliers(randomUUIDSource, DEFAULT_RANDOM_UUID_SOURCE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\lang\UIDStringUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isCompleted() {
return completed;
}
/**
* Sets the completed.
*
* @param completed the new completed
*/
public void setCompleted(boolean completed) {
this.completed = completed;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the comments
*/
public CommentCollectionResource getComments() {
return comments;
}
/**
* @param comments the comments to set
*/
public void setComments(CommentCollectionResource comments) {
this.comments = comments;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((comments == null) ? 0 : comments.hashCode());
result = prime * result + (completed ? 1231 : 1237);
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((taskId == null) ? 0 : taskId.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
|
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TaskDTO other = (TaskDTO) obj;
if (comments == null) {
if (other.comments != null)
return false;
} else if (!comments.equals(other.comments))
return false;
if (completed != other.completed)
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (taskId == null) {
if (other.taskId != null)
return false;
} else if (!taskId.equals(other.taskId))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TaskDTO [taskId=" + taskId + ", description=" + description + ", completed=" + completed + ", userName="
+ userName + ", comments=" + comments + "]";
}
}
|
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\dtos\TaskDTO.java
| 2
|
请完成以下Java代码
|
public String getCaption(final String adLanguage)
{
return caption.translate(adLanguage);
}
public String getDescription(final String adLanguage)
{
return description.translate(adLanguage);
}
public List<DocumentLayoutSectionDescriptor> getSections()
{
return sections;
}
public List<DocumentLayoutElementDescriptor> getElements()
{
List<DocumentLayoutElementDescriptor> elements = _elements;
if (elements == null)
{
elements = sections.stream()
.flatMap(section -> section.getColumns().stream())
.flatMap(column -> column.getElementGroups().stream())
.flatMap(elementGroup -> elementGroup.getElementLines().stream())
.flatMap(elementLine -> elementLine.getElements().stream())
.collect(ImmutableList.toImmutableList());
}
_elements = elements;
return elements;
}
public boolean isEmpty()
{
return sections.isEmpty();
}
public static final class Builder
{
public WindowId windowId;
private ITranslatableString caption;
private ITranslatableString description;
private NotFoundMessages notFoundMessages;
private final ArrayList<DocumentLayoutSectionDescriptor.Builder> sectionBuilders = new ArrayList<>();
private Builder()
{
super();
}
public DocumentLayoutSingleRow build()
{
return new DocumentLayoutSingleRow(this);
}
private List<DocumentLayoutSectionDescriptor> buildSections()
{
return sectionBuilders
.stream()
.filter(DocumentLayoutSectionDescriptor.Builder::isValid)
.map(DocumentLayoutSectionDescriptor.Builder::build)
.filter(DocumentLayoutSectionDescriptor::hasColumns)
.collect(ImmutableList.toImmutableList());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("caption", caption)
.add("sections-count", sectionBuilders.size())
.toString();
}
public Builder setWindowId(final WindowId windowId)
|
{
this.windowId = windowId;
return this;
}
public Builder setCaption(final ITranslatableString caption)
{
this.caption = caption;
return this;
}
public Builder setDescription(final ITranslatableString description)
{
this.description = description;
return this;
}
public Builder notFoundMessages(@Nullable NotFoundMessages notFoundMessages)
{
this.notFoundMessages = notFoundMessages;
return this;
}
public Builder addSection(@NonNull final DocumentLayoutSectionDescriptor.Builder sectionBuilderToAdd)
{
sectionBuilders.add(sectionBuilderToAdd);
return this;
}
public Builder addSections(@NonNull final Collection<DocumentLayoutSectionDescriptor.Builder> sectionBuildersToAdd)
{
sectionBuilders.addAll(sectionBuildersToAdd);
return this;
}
public boolean isEmpty()
{
return sectionBuilders.isEmpty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutSingleRow.java
| 1
|
请完成以下Java代码
|
public int getM_Material_Tracking_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Material Tracking Reference.
@param M_Material_Tracking_Ref_ID Material Tracking Reference */
@Override
public void setM_Material_Tracking_Ref_ID (int M_Material_Tracking_Ref_ID)
{
if (M_Material_Tracking_Ref_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Ref_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Material_Tracking_Ref_ID, Integer.valueOf(M_Material_Tracking_Ref_ID));
}
/** Get Material Tracking Reference.
@return Material Tracking Reference */
@Override
public int getM_Material_Tracking_Ref_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Material_Tracking_Ref_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungsdatum.
@param MovementDate
Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde
*/
@Override
public void setMovementDate (java.sql.Timestamp MovementDate)
{
throw new IllegalArgumentException ("MovementDate is virtual column"); }
/** Get Bewegungsdatum.
@return Datum, an dem eine Produkt in oder aus dem Bestand bewegt wurde
*/
@Override
public java.sql.Timestamp getMovementDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_MovementDate);
}
/** Set Ausgelagerte Menge.
@param QtyIssued Ausgelagerte Menge */
@Override
public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Empfangene Menge.
|
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived)
{
throw new IllegalArgumentException ("QtyReceived is virtual column"); }
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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.materialtracking\src\main\java-gen\de\metas\materialtracking\model\X_M_Material_Tracking_Ref.java
| 1
|
请完成以下Java代码
|
public void setCCUser(final I_AD_User ccUser)
{
setAttribute(VAR_CC_User, ccUser);
setAttribute(VAR_CC_User_ID, ccUser != null ? ccUser.getAD_User_ID() : null);
}
public Builder setEmail(final String email)
{
setAttribute(VAR_EMail, email);
return this;
}
public Builder setCCEmail(final String ccEmail)
{
setAttribute(VAR_CC_EMail, ccEmail);
return this;
}
public Builder setAD_Org_ID(final int adOrgId)
{
setAttribute(VAR_AD_Org_ID, adOrgId);
return this;
}
public Builder setCustomAttribute(final String attributeName, final Object value)
{
setAttribute(attributeName, value);
return this;
}
}
}
public interface SourceDocument
{
String NAME = "__SourceDocument";
default int getWindowNo()
{
return Env.WINDOW_None;
}
boolean hasFieldValue(String fieldName);
Object getFieldValue(String fieldName);
default int getFieldValueAsInt(final String fieldName, final int defaultValue)
{
final Object value = getFieldValue(fieldName);
return value != null ? (int)value : defaultValue;
}
@Nullable
default <T extends RepoIdAware> T getFieldValueAsRepoId(final String fieldName, final Function<Integer, T> idMapper)
{
final int id = getFieldValueAsInt(fieldName, -1);
if (id > 0)
{
return idMapper.apply(id);
}
else
{
return null;
}
}
static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{
return (SourceDocument)obj;
}
final PO po = getPO(obj);
|
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName)
{
return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
}
@AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java
| 1
|
请完成以下Java代码
|
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public Date getJoinDate() {
return joinDate;
}
public void setJoinDate(Date joinDate) {
this.joinDate = joinDate;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-annotations-2\src\main\java\com\baeldung\queryhint\Employee.java
| 1
|
请完成以下Java代码
|
private void assertFieldIsWritable(BeanWrapper beanWrapper, String fieldName) {
Supplier<String> pdxFieldNotWritableExceptionMessageSupplier = () ->
String.format("Field [%1$s] of Object [%2$s] is not writable", fieldName, getClassName());
assertCondition(beanWrapper.isWritableProperty(fieldName),
() -> new PdxFieldNotWritableException(pdxFieldNotWritableExceptionMessageSupplier.get()));
}
private void assertValueIsTypeMatch(BeanWrapper beanWrapper, String fieldName, Object value) {
PropertyDescriptor property = beanWrapper.getPropertyDescriptor(fieldName);
Supplier<String> typeMismatchExceptionMessageSupplier = () ->
String.format("Value [%1$s] of type [%2$s] does not match field [%3$s] of type [%4$s] on Object [%5$s]",
value, ObjectUtils.nullSafeClassName(value), fieldName, property.getPropertyType().getName(), getClassName());
assertCondition(isTypeMatch(property, value),
() -> new PdxFieldTypeMismatchException(typeMismatchExceptionMessageSupplier.get()));
}
private boolean isTypeMatch(PropertyDescriptor property, Object value) {
return value == null || property.getPropertyType().isInstance(value);
}
@Override
public String getClassName() {
return getParent().getClassName();
}
@Override
public boolean isDeserializable() {
return getParent().isDeserializable();
}
@Override
public boolean isEnum() {
return getParent().isEnum();
}
@Override
public Object getField(String fieldName) {
return getParent().getField(fieldName);
}
@Override
public List<String> getFieldNames() {
return getParent().getFieldNames();
}
@Override
public boolean isIdentityField(String fieldName) {
return getParent().isIdentityField(fieldName);
}
|
@Override
public Object getObject() {
return getParent().getObject();
}
@Override
public WritablePdxInstance createWriter() {
return this;
}
@Override
public boolean hasField(String fieldName) {
return getParent().hasField(fieldName);
}
};
}
/**
* Determines whether the given {@link String field name} is a {@link PropertyDescriptor property}
* on the underlying, target {@link Object}.
*
* @param fieldName {@link String} containing the name of the field to match against
* a {@link PropertyDescriptor property} from the underlying, target {@link Object}.
* @return a boolean value that determines whether the given {@link String field name}
* is a {@link PropertyDescriptor property} on the underlying, target {@link Object}.
* @see #getFieldNames()
*/
@Override
public boolean hasField(String fieldName) {
return getFieldNames().contains(fieldName);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\pdx\ObjectPdxInstanceAdapter.java
| 1
|
请完成以下Java代码
|
public boolean updateContext(final Properties ctx)
{
final int sessionId = getAD_Session_ID();
if (sessionId <= 0)
{
log.warn("Cannot update context because session is not saved yet");
return false;
}
if (!sessionPO.isActive())
{
log.debug("Cannot update context because session is not active");
return false;
}
if (isDestroyed())
{
log.debug("Cannot update context because session is destroyed");
return false;
}
//
// If not force, update the context only if the context #AD_Session_ID is same as our session ID.
// Even if there is no value in context, the session won't be updated.
// Keep this logic because we are calling this method on afterSave too.
final int ctxSessionId = Env.getContextAsInt(ctx, Env.CTXNAME_AD_Session_ID);
if (ctxSessionId > 0 && ctxSessionId != sessionId)
{
log.debug("Different AD_Session_ID found in context and force=false.");
}
Env.setContext(ctx, Env.CTXNAME_AD_Session_ID, sessionId);
final PO po = InterfaceWrapperHelper.getStrictPO(sessionPO);
final int cols = po.get_ColumnCount();
for (int i = 0; i < cols; i++)
{
if (!isContextAttribute(i))
{
continue;
}
final String columnName = po.get_ColumnName(i);
final String value = po.get_ValueAsString(columnName);
Env.setContext(ctx, CTX_Prefix + columnName, value);
}
return true;
}
private boolean isContextAttribute(final int columnIndex)
{
if (columnIndex < 0)
{
|
return false;
}
final PO po = InterfaceWrapperHelper.getStrictPO(sessionPO);
final String columnName = po.get_ColumnName(columnIndex);
if (columnName == null)
{
return false;
}
if (CTX_IgnoredColumnNames.contains(columnName))
{
return false;
}
final POInfo poInfo = po.getPOInfo();
final int displayType = poInfo.getColumnDisplayType(columnIndex);
if (displayType == DisplayType.String)
{
return poInfo.getFieldLength(columnIndex) <= 60;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\session\MFSession.java
| 1
|
请完成以下Java代码
|
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public de.metas.handlingunits.model.I_PP_Order_IssueSchedule getPP_Order_IssueSchedule()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_IssueSchedule_ID, de.metas.handlingunits.model.I_PP_Order_IssueSchedule.class);
}
@Override
public void setPP_Order_IssueSchedule(final de.metas.handlingunits.model.I_PP_Order_IssueSchedule PP_Order_IssueSchedule)
{
set_ValueFromPO(COLUMNNAME_PP_Order_IssueSchedule_ID, de.metas.handlingunits.model.I_PP_Order_IssueSchedule.class, PP_Order_IssueSchedule);
}
@Override
public void setPP_Order_IssueSchedule_ID (final int PP_Order_IssueSchedule_ID)
{
if (PP_Order_IssueSchedule_ID < 1)
set_Value (COLUMNNAME_PP_Order_IssueSchedule_ID, null);
else
set_Value (COLUMNNAME_PP_Order_IssueSchedule_ID, PP_Order_IssueSchedule_ID);
}
@Override
public int getPP_Order_IssueSchedule_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_IssueSchedule_ID);
}
@Override
|
public void setPP_Order_Qty_ID (final int PP_Order_Qty_ID)
{
if (PP_Order_Qty_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Qty_ID, PP_Order_Qty_ID);
}
@Override
public int getPP_Order_Qty_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Qty_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_PP_Order_Qty.java
| 1
|
请完成以下Java代码
|
public TbQueueConsumer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsEventsConsumer() {
return new InMemoryTbQueueConsumer<>(storage, edqsConfig.getEventsTopic());
}
@Override
public TbQueueConsumer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsEventsToBackupConsumer() {
throw new UnsupportedOperationException();
}
@Override
public TbQueueConsumer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsStateConsumer() {
throw new UnsupportedOperationException();
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdqsMsg>> createEdqsStateProducer() {
throw new UnsupportedOperationException();
}
@Override
public PartitionedQueueResponseTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> createEdqsResponseTemplate(TbQueueHandler<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> handler) {
TbQueueProducer<TbProtoQueueMsg<FromEdqsMsg>> responseProducer = new InMemoryTbQueueProducer<>(storage, edqsConfig.getResponsesTopic());
return PartitionedQueueResponseTemplate.<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>>builder()
|
.key("edqs")
.handler(handler)
.requestsTopic(edqsConfig.getRequestsTopic())
.consumerCreator(tpi -> new InMemoryTbQueueConsumer<>(storage, edqsConfig.getRequestsTopic()))
.responseProducer(responseProducer)
.pollInterval(edqsConfig.getPollInterval())
.requestTimeout(edqsConfig.getMaxRequestTimeout())
.maxPendingRequests(edqsConfig.getMaxPendingRequests())
.consumerExecutor(edqsExecutors.getConsumersExecutor())
.callbackExecutor(edqsExecutors.getRequestExecutor())
.consumerTaskExecutor(edqsExecutors.getConsumerTaskExecutor())
.stats(statsFactory.createMessagesStats(StatsType.EDQS.getName()))
.build();
}
@Override
public TbQueueAdmin getEdqsQueueAdmin() {
return queueAdmin;
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\edqs\InMemoryEdqsQueueFactory.java
| 1
|
请完成以下Java代码
|
protected void deleteProcessDefinitions(ProcessDefinitionGroup group) {
ProcessDefinitionEntity newLatestProcessDefinition = findNewLatestProcessDefinition(group);
CommandContext commandContext = Context.getCommandContext();
UserOperationLogManager userOperationLogManager = commandContext.getOperationLogManager();
ProcessDefinitionManager definitionManager = commandContext.getProcessDefinitionManager();
List<ProcessDefinitionEntity> processDefinitions = group.processDefinitions;
for (ProcessDefinitionEntity processDefinition : processDefinitions) {
String processDefinitionId = processDefinition.getId();
if (writeUserOperationLog) {
userOperationLogManager.logProcessDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, processDefinitionId, processDefinition.getKey(),
new PropertyChange("cascade", false, cascadeToHistory));
}
definitionManager.deleteProcessDefinition(processDefinition, processDefinitionId, cascadeToHistory, cascadeToInstances, skipCustomListeners, skipIoMappings);
}
if (newLatestProcessDefinition != null) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
DeploymentCache deploymentCache = configuration.getDeploymentCache();
newLatestProcessDefinition = deploymentCache.resolveProcessDefinition(newLatestProcessDefinition);
List<Deployer> deployers = configuration.getDeployers();
for (Deployer deployer : deployers) {
if (deployer instanceof BpmnDeployer) {
((BpmnDeployer) deployer).addEventSubscriptions(newLatestProcessDefinition);
((BpmnDeployer) deployer).addTimerDeclarations(newLatestProcessDefinition);
}
}
}
}
private static class ProcessDefinitionGroup {
String key;
String tenant;
List<ProcessDefinitionEntity> processDefinitions = new ArrayList<ProcessDefinitionEntity>();
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((tenant == null) ? 0 : tenant.hashCode());
return result;
}
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProcessDefinitionGroup other = (ProcessDefinitionGroup) obj;
if (key == null) {
if (other.key != null)
return false;
} else if (!key.equals(other.key))
return false;
if (tenant == null) {
if (other.tenant != null)
return false;
} else if (!tenant.equals(other.tenant))
return false;
return true;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteProcessDefinitionsByIdsCmd.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ReaderConsumerServiceImpl implements ReaderConsumerService {
private final WebClient webClient;
private static final ObjectMapper mapper = new ObjectMapper();
public ReaderConsumerServiceImpl(WebClient webClient) {
this.webClient = webClient;
}
@Override
public List<Book> processReaderDataFromObjectArray() {
Mono<Object[]> response = webClient.get()
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Object[].class).log();
Object[] objects = response.block();
return Arrays.stream(objects)
.map(object -> mapper.convertValue(object, Reader.class))
.map(Reader::getFavouriteBook)
.collect(Collectors.toList());
}
@Override
public List<Book> processReaderDataFromReaderArray() {
Mono<Reader[]> response =
webClient.get()
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Reader[].class).log();
Reader[] readers = response.block();
return Arrays.stream(readers)
.map(Reader::getFavouriteBook)
.collect(Collectors.toList());
}
@Override
public List<Book> processReaderDataFromReaderList() {
Mono<List<Reader>> response = webClient.get()
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<Reader>>() {});
List<Reader> readers = response.block();
return readers.stream()
.map(Reader::getFavouriteBook)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedReaderDataFromReaderArray() {
Mono<Reader[]> response = webClient.get()
|
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(Reader[].class).log();
Reader[] readers = response.block();
return Arrays.stream(readers)
.flatMap(reader -> reader.getBooksRead().stream())
.map(Book::getAuthor)
.collect(Collectors.toList());
}
@Override
public List<String> processNestedReaderDataFromReaderList() {
Mono<List<Reader>> response = webClient.get()
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.bodyToMono(new ParameterizedTypeReference<List<Reader>>() {});
List<Reader> readers = response.block();
return readers.stream()
.flatMap(reader -> reader.getBooksRead().stream())
.map(Book::getAuthor)
.collect(Collectors.toList());
}
}
|
repos\tutorials-master\spring-reactive-modules\spring-reactive-client\src\main\java\com\baeldung\webclient\json\ReaderConsumerServiceImpl.java
| 2
|
请完成以下Java代码
|
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public static Integer getOK() {
return OK;
}
public static Integer getERROR() {
return ERROR;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
|
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
|
repos\SpringBoot-Learning-master\1.x\Chapter3-1-6\src\main\java\com\didispace\dto\ErrorInfo.java
| 1
|
请完成以下Java代码
|
public Factory from(Object source) {
assertNotNull(source, "Source object to serialize to PDX must not be null");
RegionService regionService = getRegionService();
Optional.of(regionService)
.filter(GemFireCache.class::isInstance)
.map(GemFireCache.class::cast)
.map(GemFireCache::getPdxReadSerialized)
.filter(Boolean.TRUE::equals)
.orElseThrow(() -> new IllegalStateException("PDX read-serialized must be set to true"));
PdxInstanceFactory factory = regionService.createPdxInstanceFactory(source.getClass().getName());
factory.writeObject("source", source);
AtomicReference<Object> resolvedSource = new AtomicReference<>(null);
return () -> Optional.of(factory)
.map(PdxInstanceFactory::create)
.map(pdxInstance -> resolvedSource.updateAndGet(it -> pdxInstance.getField("source")))
.filter(PdxInstance.class::isInstance)
.map(PdxInstance.class::cast)
.orElseThrow(() -> {
String message = String.format("Expected an instance of PDX but was an instance of type [%s];"
+ " Was PDX read-serialized set to true", nullSafeClassName(resolvedSource.get()));
return new IllegalArgumentException(message);
});
}
private String nullSafeClassName(Object target) {
|
return target != null ? target.getClass().getName() : null;
}
@FunctionalInterface
public interface Factory {
/**
* Creates a {@link PdxInstance}.
*
* @return the created {@link PdxInstance}.
* @throws IllegalArgumentException Depending on the implementation, an {@link IllegalArgumentException}
* may be thrown if the {@link Object created object} is not of type {@link PdxInstance}.
* @throws ClassCastException Depending on the implementation, a {@link ClassCastException} may be thrown
* if the {@link Object created object} is not of type {@link PdxInstance}.
* @see org.apache.geode.pdx.PdxInstance
*/
PdxInstance create();
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\pdx\PdxInstanceBuilder.java
| 1
|
请完成以下Java代码
|
public String getAttributeValue(String namespace, String name) {
List<ExtensionAttribute> attributes = getAttributes().get(name);
if (attributes != null && !attributes.isEmpty()) {
for (ExtensionAttribute attribute : attributes) {
if ((namespace == null && attribute.getNamespace() == null) || namespace.equals(attribute.getNamespace())) {
return attribute.getValue();
}
}
}
return null;
}
@Override
public void addAttribute(ExtensionAttribute attribute) {
if (attribute != null && StringUtils.isNotEmpty(attribute.getName())) {
List<ExtensionAttribute> attributeList = null;
if (!this.attributes.containsKey(attribute.getName())) {
attributeList = new ArrayList<>();
this.attributes.put(attribute.getName(), attributeList);
}
this.attributes.get(attribute.getName()).add(attribute);
}
}
@Override
public void setAttributes(Map<String, List<ExtensionAttribute>> attributes) {
this.attributes = attributes;
}
public void setValues(BaseElement otherElement) {
setId(otherElement.getId());
extensionElements = new LinkedHashMap<>();
if (otherElement.getExtensionElements() != null && !otherElement.getExtensionElements().isEmpty()) {
|
for (String key : otherElement.getExtensionElements().keySet()) {
List<ExtensionElement> otherElementList = otherElement.getExtensionElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<ExtensionElement> elementList = new ArrayList<>();
for (ExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
extensionElements.put(key, elementList);
}
}
}
attributes = new LinkedHashMap<>();
if (otherElement.getAttributes() != null && !otherElement.getAttributes().isEmpty()) {
for (String key : otherElement.getAttributes().keySet()) {
List<ExtensionAttribute> otherAttributeList = otherElement.getAttributes().get(key);
if (otherAttributeList != null && !otherAttributeList.isEmpty()) {
List<ExtensionAttribute> attributeList = new ArrayList<>();
for (ExtensionAttribute extensionAttribute : otherAttributeList) {
attributeList.add(extensionAttribute.clone());
}
attributes.put(key, attributeList);
}
}
}
}
@Override
public abstract BaseElement clone();
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\BaseElement.java
| 1
|
请完成以下Java代码
|
public boolean isFailed() {
return state == FAILED.getStateCode();
}
public boolean isSuspended() {
return state == SUSPENDED.getStateCode();
}
public boolean isClosed() {
return state == CLOSED.getStateCode();
}
@Override
public String toString() {
return this.getClass().getSimpleName()
|
+ "[businessKey=" + businessKey
+ ", startUserId=" + createUserId
+ ", superCaseInstanceId=" + superCaseInstanceId
+ ", superProcessInstanceId=" + superProcessInstanceId
+ ", durationInMillis=" + durationInMillis
+ ", createTime=" + startTime
+ ", closeTime=" + endTime
+ ", id=" + id
+ ", eventType=" + eventType
+ ", caseExecutionId=" + caseExecutionId
+ ", caseDefinitionId=" + caseDefinitionId
+ ", caseInstanceId=" + caseInstanceId
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricCaseInstanceEventEntity.java
| 1
|
请完成以下Java代码
|
public void onError(Exception e) {
tellFailure(ctx, tbMsg, e);
}
@Override
public void onSuccess(InvokeRequest request, InvokeResult invokeResult) {
try {
if (config.isTellFailureIfFuncThrowsExc() && invokeResult.getFunctionError() != null) {
throw new RuntimeException(getPayload(invokeResult));
}
tellSuccess(ctx, getResponseMsg(tbMsg, invokeResult));
} catch (Exception e) {
tellFailure(ctx, processException(tbMsg, invokeResult, e), e);
}
}
});
}
private InvokeRequest toRequest(String requestBody, String functionName, String qualifier) {
return new InvokeRequest()
.withFunctionName(functionName)
.withPayload(requestBody)
.withQualifier(qualifier);
}
private String getPayload(InvokeResult invokeResult) {
ByteBuffer buf = invokeResult.getPayload();
if (buf == null) {
throw new RuntimeException("Payload from result of AWS Lambda function execution is null.");
}
byte[] responseBytes = new byte[buf.remaining()];
buf.get(responseBytes);
return new String(responseBytes);
}
private TbMsg getResponseMsg(TbMsg originalMsg, InvokeResult invokeResult) {
TbMsgMetaData metaData = originalMsg.getMetaData().copy();
metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId());
String data = getPayload(invokeResult);
return originalMsg.transform()
.metaData(metaData)
.data(data)
|
.build();
}
private TbMsg processException(TbMsg origMsg, InvokeResult invokeResult, Throwable t) {
TbMsgMetaData metaData = origMsg.getMetaData().copy();
metaData.putValue("error", t.getClass() + ": " + t.getMessage());
metaData.putValue("requestId", invokeResult.getSdkResponseMetadata().getRequestId());
return origMsg.transform()
.metaData(metaData)
.build();
}
@Override
public void destroy() {
if (client != null) {
try {
client.shutdown();
} catch (Exception e) {
log.error("Failed to shutdown Lambda client during destroy", e);
}
}
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\aws\lambda\TbAwsLambdaNode.java
| 1
|
请完成以下Java代码
|
public class RetourenavisAnfragenResponse {
@XmlElement(name = "return", namespace = "")
protected RetourenavisAnfrageAntwort _return;
/**
* Gets the value of the return property.
*
* @return
* possible object is
* {@link RetourenavisAnfrageAntwort }
*
*/
public RetourenavisAnfrageAntwort getReturn() {
return _return;
|
}
/**
* Sets the value of the return property.
*
* @param value
* allowed object is
* {@link RetourenavisAnfrageAntwort }
*
*/
public void setReturn(RetourenavisAnfrageAntwort value) {
this._return = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfragenResponse.java
| 1
|
请完成以下Java代码
|
public boolean hasErrors()
{
return parseError != null
|| (cells != null && cells.stream().anyMatch(ImpDataCell::isCellError));
}
public String getErrorMessageAsStringOrNull()
{
return getErrorMessageAsStringOrNull(-1);
}
public String getErrorMessageAsStringOrNull(final int maxLength)
{
final int maxLengthEffective = maxLength > 0 ? maxLength : Integer.MAX_VALUE;
final StringBuilder result = new StringBuilder();
if (parseError != null)
{
result.append(parseError.getMessage());
}
if (cells != null)
{
for (final ImpDataCell cell : cells)
{
if (!cell.isCellError())
{
continue;
}
final String cellErrorMessage = cell.getCellErrorMessage().getMessage();
if (result.length() > 0)
{
result.append("; ");
}
result.append(cellErrorMessage);
if (result.length() >= maxLengthEffective)
{
break;
}
}
}
return result.length() > 0
? StringUtils.trunc(result.toString(), maxLengthEffective)
: null;
}
|
public List<Object> getJdbcValues(@NonNull final List<ImpFormatColumn> columns)
{
final int columnsCount = columns.size();
if (parseError != null)
{
final ArrayList<Object> nulls = new ArrayList<>(columnsCount);
for (int i = 0; i < columnsCount; i++)
{
nulls.add(null);
}
return nulls;
}
else
{
final ArrayList<Object> values = new ArrayList<>(columnsCount);
final int cellsCount = cells.size();
for (int i = 0; i < columnsCount; i++)
{
if (i < cellsCount)
{
values.add(cells.get(i).getJdbcValue());
}
else
{
values.add(null);
}
}
return values;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\ImpDataLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private AvailableToPromiseResultGroupBuilder newGroup(
@NonNull final AddToResultGroupRequest request,
@NonNull final AttributesKey storageAttributesKey)
{
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(request.getBpartner())
.warehouse(WarehouseClassifier.specific(request.getWarehouseId()))
.productId(request.getProductId())
.storageAttributesKey(storageAttributesKey)
.build();
groups.add(group);
return group;
}
void addDefaultEmptyGroupIfPossible()
{
if (product.isAny())
{
return;
}
final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null);
if (defaultAttributesKey == null)
{
return;
}
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(bpartner)
.warehouse(warehouse)
.productId(ProductId.ofRepoId(product.getProductId()))
.storageAttributesKey(defaultAttributesKey)
|
.build();
groups.add(group);
}
@VisibleForTesting
boolean isZeroQty()
{
if (groups.isEmpty())
{
return true;
}
for (AvailableToPromiseResultGroupBuilder group : groups)
{
if (!group.isZeroQty())
{
return false;
}
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultBucket.java
| 2
|
请完成以下Java代码
|
public static boolean shouldLogJobException(ProcessEngineConfiguration processEngineConfiguration, JobEntity currentJob) {
boolean enableReducedJobExceptionLogging = processEngineConfiguration.isEnableReducedJobExceptionLogging();
return currentJob == null || !enableReducedJobExceptionLogging || enableReducedJobExceptionLogging && currentJob.getRetries() <= 1;
}
public static boolean shouldLogCmdException(ProcessEngineConfiguration processEngineConfiguration) {
return processEngineConfiguration.isEnableCmdExceptionLogging();
}
public void processEngineCreated(String name) {
logInfo("001", "Process Engine {} created.", name);
}
public void processEngineAlreadyInitialized() {
logInfo("002", "Process engine already initialized");
}
public void initializingProcessEngineForResource(URL resourceUrl) {
logInfo(
"003", "Initializing process engine for resource {}", resourceUrl);
}
public void initializingProcessEngine(String name) {
logInfo(
"004", "Initializing process engine {}", name);
}
public void exceptionWhileInitializingProcessengine(Throwable e) {
logError("005", "Exception while initializing process engine {}", e.getMessage(), e);
}
public void exceptionWhileClosingProcessEngine(String string, Exception e) {
logError("006", "Exception while closing process engine {}", string, e);
}
|
public void processEngineClosed(String name) {
logInfo("007", "Process Engine {} closed", name);
}
public void historyCleanupJobReconfigurationFailure(Exception exception) {
logInfo(
"008",
"History Cleanup Job reconfiguration failed on Process Engine Bootstrap. Possible concurrent execution with the JobExecutor: {}",
exception.getMessage()
);
}
public void couldNotDetermineIp(Exception e) {
logWarn(
"009", "Could not determine local IP address for generating a host name", e);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessEngineLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public XMLGregorianCalendar getTransportDocumentDate() {
return transportDocumentDate;
}
/**
* Sets the value of the transportDocumentDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setTransportDocumentDate(XMLGregorianCalendar value) {
this.transportDocumentDate = value;
}
/**
* Gets the value of the scac property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSCAC() {
|
return scac;
}
/**
* Sets the value of the scac property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSCAC(String value) {
this.scac = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ShipperExtensionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public final class PackingItemPart
{
@NonNull
private final PackingItemPartId id;
@NonNull
private final ProductId productId;
@NonNull
private final BPartnerId bpartnerId;
@NonNull
private final BPartnerLocationId bpartnerLocationId;
@Nullable
private final HUPIItemProductId packingMaterialId;
@NonNull
private final WarehouseId warehouseId;
@NonNull
private final DeliveryRule deliveryRule;
@NonNull
private final TableRecordReference sourceDocumentLineRef;
@NonNull
private final Quantity qty;
public ShipmentScheduleId getShipmentScheduleId()
|
{
return id.getShipmentScheduleId();
}
public PackingItemPart withQty(@NonNull final Quantity qty)
{
if (Objects.equals(this.qty, qty))
{
return this;
}
return toBuilder().qty(qty).build();
}
public PackingItemPart addQty(@NonNull final Quantity qtyToAdd)
{
return withQty(this.qty.add(qtyToAdd));
}
public PackingItemPart subtractQty(@NonNull final Quantity qtyToSubtract)
{
return withQty(this.qty.subtract(qtyToSubtract));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemPart.java
| 2
|
请完成以下Java代码
|
public String getLanguageVersion() {
return "2.1";
}
public String getMethodCallSyntax(String obj, String method, String... arguments) {
throw new UnsupportedOperationException("Method getMethodCallSyntax is not supported");
}
public List<String> getMimeTypes() {
return mimeTypes;
}
public List<String> getNames() {
return names;
}
public String getOutputStatement(String toDisplay) {
// We will use out:print function to output statements
StringBuilder stringBuffer = new StringBuilder();
stringBuffer.append("out:print(\"");
int length = toDisplay.length();
for (int i = 0; i < length; i++) {
char c = toDisplay.charAt(i);
switch (c) {
case '"':
stringBuffer.append("\\\"");
break;
case '\\':
stringBuffer.append("\\\\");
break;
default:
stringBuffer.append(c);
break;
}
}
stringBuffer.append("\")");
return stringBuffer.toString();
}
|
public String getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName();
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return getEngineVersion();
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return getLanguageVersion();
} else if (key.equals("THREADING")) {
return "MULTITHREADED";
} else {
return null;
}
}
public String getProgram(String... statements) {
// Each statement is wrapped in '${}' to comply with EL
StringBuilder buf = new StringBuilder();
if (statements.length != 0) {
for (int i = 0; i < statements.length; i++) {
buf.append("${");
buf.append(statements[i]);
buf.append("} ");
}
}
return buf.toString();
}
public ScriptEngine getScriptEngine() {
return new JuelScriptEngine(this);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\scripting\JuelScriptEngineFactory.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static class CustomizerConfiguration {
@Bean
@ConditionalOnBean(Customizer.class)
SpringLiquibaseCustomizer springLiquibaseCustomizer(Customizer<Liquibase> customizer) {
return (springLiquibase) -> springLiquibase.setCustomizer(customizer);
}
}
static final class LiquibaseDataSourceCondition extends AnyNestedCondition {
LiquibaseDataSourceCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(DataSource.class)
private static final class DataSourceBeanCondition {
}
@ConditionalOnBean(JdbcConnectionDetails.class)
private static final class JdbcConnectionDetailsCondition {
}
@ConditionalOnProperty("spring.liquibase.url")
private static final class LiquibaseUrlCondition {
}
}
static class LiquibaseAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("db/changelog/**");
}
}
/**
* Adapts {@link LiquibaseProperties} to {@link LiquibaseConnectionDetails}.
*/
static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails {
private final LiquibaseProperties properties;
PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) {
this.properties = properties;
}
@Override
public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
|
return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName();
return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public DataResponse<HistoricVariableInstanceResponse> getHistoricActivityInstances(@ApiParam(hidden = true) @RequestParam Map<String, String> allRequestParams) {
HistoricVariableInstanceQueryRequest query = new HistoricVariableInstanceQueryRequest();
// Populate query based on request
if (allRequestParams.get("excludeTaskVariables") != null) {
query.setExcludeTaskVariables(Boolean.valueOf(allRequestParams.get("excludeTaskVariables")));
}
if (allRequestParams.get("taskId") != null) {
query.setTaskId(allRequestParams.get("taskId"));
}
if (allRequestParams.get("planItemInstanceId") != null) {
query.setPlanItemInstanceId(allRequestParams.get("planItemInstanceId"));
}
if (allRequestParams.get("caseInstanceId") != null) {
query.setCaseInstanceId(allRequestParams.get("caseInstanceId"));
|
}
if (allRequestParams.get("variableName") != null) {
query.setVariableName(allRequestParams.get("variableName"));
}
if (allRequestParams.get("variableNameLike") != null) {
query.setVariableNameLike(allRequestParams.get("variableNameLike"));
}
if (allRequestParams.get("excludeLocalVariables") != null) {
query.setExcludeLocalVariables(Boolean.valueOf(allRequestParams.get("excludeLocalVariables")));
}
return getQueryResponse(query, allRequestParams);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\variable\HistoricVariableInstanceCollectionResource.java
| 2
|
请完成以下Java代码
|
private void addSslHostConfig(AbstractHttp11Protocol<?> protocol, String serverName, SslBundle sslBundle) {
SSLHostConfig sslHostConfig = new SSLHostConfig();
sslHostConfig.setHostName(serverName);
configureSslClientAuth(sslHostConfig);
applySslBundle(protocol, sslHostConfig, sslBundle);
protocol.addSslHostConfig(sslHostConfig, true);
}
private void applySslBundle(AbstractHttp11Protocol<?> protocol, SSLHostConfig sslHostConfig, SslBundle sslBundle) {
SslBundleKey key = sslBundle.getKey();
SslStoreBundle stores = sslBundle.getStores();
SslOptions options = sslBundle.getOptions();
sslHostConfig.setSslProtocol(sslBundle.getProtocol());
SSLHostConfigCertificate certificate = new SSLHostConfigCertificate(sslHostConfig, Type.UNDEFINED);
String keystorePassword = (stores.getKeyStorePassword() != null) ? stores.getKeyStorePassword() : "";
certificate.setCertificateKeystorePassword(keystorePassword);
if (key.getPassword() != null) {
certificate.setCertificateKeyPassword(key.getPassword());
}
if (key.getAlias() != null) {
certificate.setCertificateKeyAlias(key.getAlias());
}
sslHostConfig.addCertificate(certificate);
if (options.getCiphers() != null) {
String ciphers = StringUtils.arrayToCommaDelimitedString(options.getCiphers());
sslHostConfig.setCiphers(ciphers);
}
configureSslStores(sslHostConfig, certificate, stores);
configureEnabledProtocols(sslHostConfig, options);
}
private void configureEnabledProtocols(SSLHostConfig sslHostConfig, SslOptions options) {
if (options.getEnabledProtocols() != null) {
String enabledProtocols = StringUtils.arrayToDelimitedString(options.getEnabledProtocols(), "+");
sslHostConfig.setProtocols(enabledProtocols);
}
|
}
private void configureSslClientAuth(SSLHostConfig config) {
config.setCertificateVerification(ClientAuth.map(this.clientAuth, "none", "optional", "required"));
}
private void configureSslStores(SSLHostConfig sslHostConfig, SSLHostConfigCertificate certificate,
SslStoreBundle stores) {
try {
if (stores.getKeyStore() != null) {
certificate.setCertificateKeystore(stores.getKeyStore());
}
if (stores.getTrustStore() != null) {
sslHostConfig.setTrustStore(stores.getTrustStore());
}
}
catch (Exception ex) {
throw new IllegalStateException("Could not load store: " + ex.getMessage(), ex);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\SslConnectorCustomizer.java
| 1
|
请完成以下Java代码
|
public boolean reActivateIt()
{
fireDocValidateEvent(ModelValidator.TIMING_BEFORE_REACTIVATE);
handler.reactivateIt(model);
fireDocValidateEvent(ModelValidator.TIMING_AFTER_REACTIVATE);
return true;
}
@Override
public String getSummary()
{
return handler.getSummary(model);
}
@Override
public String getDocumentInfo()
{
return handler.getDocumentInfo(model);
}
@Override
public LocalDate getDocumentDate()
{
return handler.getDocumentDate(model);
}
@Override
public String getDocumentNo()
{
return model.getDocumentNo();
}
@Override
public File createPDF()
{
return handler.createPDF(model);
}
@Override
public String getProcessMsg()
{
return processMsg;
}
@Override
public int getDoc_User_ID()
{
return handler.getDoc_User_ID(model);
}
@Override
public int getC_Currency_ID()
{
return handler.getC_Currency_ID(model);
}
@Override
public BigDecimal getApprovalAmt()
{
return handler.getApprovalAmt(model);
}
@Override
public int getAD_Client_ID()
{
return model.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return model.getAD_Org_ID();
}
|
@Override
public String getDocAction()
{
return model.getDocAction();
}
@Override
public boolean save()
{
InterfaceWrapperHelper.save(model);
return true;
}
@Override
public Properties getCtx()
{
return InterfaceWrapperHelper.getCtx(model);
}
@Override
public int get_ID()
{
return InterfaceWrapperHelper.getId(model);
}
@Override
public int get_Table_ID()
{
return InterfaceWrapperHelper.getModelTableId(model);
}
@Override
public String get_TrxName()
{
return InterfaceWrapperHelper.getTrxName(model);
}
@Override
public void set_TrxName(final String trxName)
{
InterfaceWrapperHelper.setTrxName(model, trxName);
}
@Override
public boolean isActive()
{
return model.isActive();
}
@Override
public Object getModel()
{
return getDocumentModel();
}
@Override
public Object getDocumentModel()
{
return model;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocumentWrapper.java
| 1
|
请完成以下Java代码
|
public List<String> getBundleNames() {
List<String> names = new ArrayList<>(this.registeredBundles.keySet());
Collections.sort(names);
return Collections.unmodifiableList(names);
}
private RegisteredSslBundle getRegistered(String name) throws NoSuchSslBundleException {
Assert.notNull(name, "'name' must not be null");
RegisteredSslBundle registered = this.registeredBundles.get(name);
if (registered == null) {
throw new NoSuchSslBundleException(name, "SSL bundle name '%s' cannot be found".formatted(name));
}
return registered;
}
private static class RegisteredSslBundle {
private final String name;
private final List<Consumer<SslBundle>> updateHandlers = new CopyOnWriteArrayList<>();
private volatile SslBundle bundle;
RegisteredSslBundle(String name, SslBundle bundle) {
this.name = name;
this.bundle = bundle;
}
|
void update(SslBundle updatedBundle) {
Assert.notNull(updatedBundle, "'updatedBundle' must not be null");
this.bundle = updatedBundle;
if (this.updateHandlers.isEmpty()) {
logger.warn(LogMessage.format(
"SSL bundle '%s' has been updated but may be in use by a technology that doesn't support SSL reloading",
this.name));
}
this.updateHandlers.forEach((handler) -> handler.accept(updatedBundle));
}
SslBundle getBundle() {
return this.bundle;
}
void addUpdateHandler(Consumer<SslBundle> updateHandler) {
Assert.notNull(updateHandler, "'updateHandler' must not be null");
this.updateHandlers.add(updateHandler);
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\DefaultSslBundleRegistry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PPOrderWeightingRunId implements RepoIdAware
{
@JsonCreator
public static PPOrderWeightingRunId ofRepoId(final int repoId)
{
return new PPOrderWeightingRunId(repoId);
}
public static PPOrderWeightingRunId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PPOrderWeightingRunId(repoId) : null;
}
public static Optional<PPOrderWeightingRunId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
|
public static int toRepoId(@Nullable final PPOrderWeightingRunId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
private PPOrderWeightingRunId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Weighting_Run_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunId.java
| 2
|
请完成以下Java代码
|
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
/**
* CU_TU_PLU AD_Reference_ID=541906
* Reference name: CU_TU_PLU
*/
public static final int CU_TU_PLU_AD_Reference_ID=541906;
/** CU = CU */
public static final String CU_TU_PLU_CU = "CU";
/** TU = TU */
public static final String CU_TU_PLU_TU = "TU";
@Override
public void setCU_TU_PLU (final String CU_TU_PLU)
{
set_Value (COLUMNNAME_CU_TU_PLU, CU_TU_PLU);
}
@Override
public String getCU_TU_PLU()
{
return get_ValueAsString(COLUMNNAME_CU_TU_PLU);
}
@Override
public void setExternalSystem_Config_LeichMehl_ProductMapping_ID (final int ExternalSystem_Config_LeichMehl_ProductMapping_ID)
{
if (ExternalSystem_Config_LeichMehl_ProductMapping_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, ExternalSystem_Config_LeichMehl_ProductMapping_ID);
}
@Override
public int getExternalSystem_Config_LeichMehl_ProductMapping_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID);
}
@Override
public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup()
{
return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class);
}
@Override
public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup)
{
set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup);
}
|
@Override
public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID)
{
if (LeichMehl_PluFile_ConfigGroup_ID < 1)
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null);
else
set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID);
}
@Override
public int getLeichMehl_PluFile_ConfigGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_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 setPLU_File (final String PLU_File)
{
set_Value (COLUMNNAME_PLU_File, PLU_File);
}
@Override
public String getPLU_File()
{
return get_ValueAsString(COLUMNNAME_PLU_File);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String takeQueueTask() throws InterruptedException {
return blockingQueue.take();
}
@SuppressWarnings("unchecked")
private Map<String, Integer> getPdfImageCaches() {
Map<String, Integer> map = new HashMap<>();
try {
map = (Map<String, Integer>) toObject(db.get(FILE_PREVIEW_PDF_IMGS_KEY.getBytes()));
} catch (RocksDBException | IOException | ClassNotFoundException e) {
LOGGER.error("Get from RocksDB Exception" + e);
}
return map;
}
private byte[] toByteArray(Object obj) throws IOException {
byte[] bytes;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
bytes = bos.toByteArray();
oos.close();
bos.close();
return bytes;
}
private Object toObject(byte[] bytes) throws IOException, ClassNotFoundException {
Object obj;
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
|
bis.close();
return obj;
}
private void cleanPdfCache() throws IOException, RocksDBException {
Map<String, String> initPDFCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_KEY.getBytes(), toByteArray(initPDFCache));
}
private void cleanImgCache() throws IOException, RocksDBException {
Map<String, List<String>> initIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_IMGS_KEY.getBytes(), toByteArray(initIMGCache));
}
private void cleanPdfImgCache() throws IOException, RocksDBException {
Map<String, Integer> initPDFIMGCache = new HashMap<>();
db.put(FILE_PREVIEW_PDF_IMGS_KEY.getBytes(), toByteArray(initPDFIMGCache));
}
private void cleanMediaConvertCache() throws IOException, RocksDBException {
Map<String, String> initMediaConvertCache = new HashMap<>();
db.put(FILE_PREVIEW_MEDIA_CONVERT_KEY.getBytes(), toByteArray(initMediaConvertCache));
}
}
|
repos\kkFileView-master\server\src\main\java\cn\keking\service\cache\impl\CacheServiceRocksDBImpl.java
| 2
|
请完成以下Java代码
|
public EmptiesInOutLinesProducer create()
{
super.create();
return this;
}
/** @return set of M_InOutLine_IDs which were created/updated by this processor */
public Set<Integer> getAffectedInOutLinesId()
{
return affectedInOutLinesId;
}
private final I_M_InOut getM_InOut()
{
return _inoutRef.getValue();
}
public EmptiesInOutLinesProducer addSource(final I_M_HU_PackingMaterial packingMaterial, final int qty)
{
addSource(PlainPackingMaterialDocumentLineSource.of(packingMaterial, qty));
return this;
}
@Override
protected void assertValid(final IPackingMaterialDocumentLineSource source)
{
Check.assumeInstanceOf(source, PlainPackingMaterialDocumentLineSource.class, "source");
}
@Override
protected IPackingMaterialDocumentLine createPackingMaterialDocumentLine(@NonNull final ProductId productId)
{
final I_M_InOut inout = getM_InOut();
final I_M_InOutLine inoutLine = inOutBL.newInOutLine(inout, I_M_InOutLine.class);
final UomId uomId = productBL.getStockUOMId(ProductId.toRepoId( productId));
inoutLine.setM_Product_ID(ProductId.toRepoId( productId));
inoutLine.setC_UOM_ID(uomId.getRepoId()); // prevent the system from picking its default-UOM; there might be no UOM-conversion to/from the product's UOM
// NOTE: don't save it
return new EmptiesInOutLinePackingMaterialDocumentLine(inoutLine);
}
private final EmptiesInOutLinePackingMaterialDocumentLine toImpl(final IPackingMaterialDocumentLine pmLine)
{
return (EmptiesInOutLinePackingMaterialDocumentLine)pmLine;
}
|
@Override
protected void removeDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine)
{
final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine);
final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine();
if (!InterfaceWrapperHelper.isNew(inoutLine))
{
InterfaceWrapperHelper.delete(inoutLine);
}
}
@Override
protected void createDocumentLine(@NonNull final IPackingMaterialDocumentLine pmLine)
{
final EmptiesInOutLinePackingMaterialDocumentLine inoutLinePMLine = toImpl(pmLine);
final I_M_InOut inout = getM_InOut();
InterfaceWrapperHelper.save(inout); // make sure inout header is saved
final I_M_InOutLine inoutLine = inoutLinePMLine.getM_InOutLine();
inoutLine.setM_InOut(inout); // make sure inout line is linked to our M_InOut_ID (in case it was just saved)
inoutLine.setIsActive(true); // just to be sure
// task FRESH-273
inoutLine.setIsPackagingMaterial(true);
final boolean wasNew = InterfaceWrapperHelper.isNew(inoutLine);
InterfaceWrapperHelper.save(inoutLine);
if (wasNew)
{
affectedInOutLinesId.add(inoutLine.getM_InOutLine_ID());
}
}
@Override
protected void linkSourceToDocumentLine(final IPackingMaterialDocumentLineSource source, final IPackingMaterialDocumentLine pmLine)
{
// nothing
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\empties\EmptiesInOutLinesProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
ManagementErrorEndpoint errorEndpoint(ErrorAttributes errorAttributes, WebProperties webProperties) {
return new ManagementErrorEndpoint(errorAttributes, webProperties.getError());
}
@Bean
@ConditionalOnBean(ErrorAttributes.class)
ManagementErrorPageCustomizer managementErrorPageCustomizer(WebProperties webProperties) {
return new ManagementErrorPageCustomizer(webProperties);
}
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
// Ensure the parent configuration does not leak down to us
dispatcherServlet.setDetectAllHandlerAdapters(false);
dispatcherServlet.setDetectAllHandlerExceptionResolvers(false);
dispatcherServlet.setDetectAllHandlerMappings(false);
dispatcherServlet.setDetectAllViewResolvers(false);
return dispatcherServlet;
}
@Bean(name = DispatcherServletAutoConfiguration.DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
DispatcherServletRegistrationBean dispatcherServletRegistrationBean(DispatcherServlet dispatcherServlet) {
return new DispatcherServletRegistrationBean(dispatcherServlet, "/");
}
@Bean(name = DispatcherServlet.HANDLER_MAPPING_BEAN_NAME)
CompositeHandlerMapping compositeHandlerMapping() {
return new CompositeHandlerMapping();
}
@Bean(name = DispatcherServlet.HANDLER_ADAPTER_BEAN_NAME)
CompositeHandlerAdapter compositeHandlerAdapter(ListableBeanFactory beanFactory) {
return new CompositeHandlerAdapter(beanFactory);
}
|
@Bean(name = DispatcherServlet.HANDLER_EXCEPTION_RESOLVER_BEAN_NAME)
CompositeHandlerExceptionResolver compositeHandlerExceptionResolver() {
return new CompositeHandlerExceptionResolver();
}
@Bean
@ConditionalOnMissingBean({ RequestContextListener.class, RequestContextFilter.class })
RequestContextFilter requestContextFilter() {
return new OrderedRequestContextFilter();
}
/**
* {@link WebServerFactoryCustomizer} to add an {@link ErrorPage} so that the
* {@link ManagementErrorEndpoint} can be used.
*/
static class ManagementErrorPageCustomizer
implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
private final WebProperties properties;
ManagementErrorPageCustomizer(WebProperties properties) {
this.properties = properties;
}
@Override
public void customize(ConfigurableServletWebServerFactory factory) {
factory.addErrorPages(new ErrorPage(this.properties.getError().getPath()));
}
@Override
public int getOrder() {
return 10; // Run after ManagementWebServerFactoryCustomizer
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\WebMvcEndpointChildContextConfiguration.java
| 2
|
请完成以下Java代码
|
public void setSalesRep_ID (final int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID);
}
@Override
public int getSalesRep_ID()
{
return get_ValueAsInt(COLUMNNAME_SalesRep_ID);
}
@Override
public void setSendEMail (final boolean SendEMail)
{
set_Value (COLUMNNAME_SendEMail, SendEMail);
}
@Override
public boolean isSendEMail()
{
return get_ValueAsBoolean(COLUMNNAME_SendEMail);
}
@Override
public org.compiere.model.I_C_ElementValue getUser1()
{
return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser1(final org.compiere.model.I_C_ElementValue User1)
{
set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1);
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
}
@Override
public org.compiere.model.I_C_ElementValue getUser2()
{
return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class);
}
@Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2)
{
set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2);
}
@Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
|
@Override
public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOut.java
| 1
|
请完成以下Java代码
|
public int getTotalMethodCount() {
return totalMethodCount;
}
/**
* @return the publicMethodCount
*/
public int getPublicMethodCount() {
return publicMethodCount;
}
/**
* @return the protectedMethodCount
*/
public int getProtectedMethodCount() {
return protectedMethodCount;
}
|
/**
* @return the privateMethodCount
*/
public int getPrivateMethodCount() {
return privateMethodCount;
}
/**
* @return the privateMethodCount
*/
public int getPackagePrivateMethodCount() {
return packagePrivateMethodCount;
}
}
}
|
repos\tutorials-master\libraries-transform\src\main\java\com\baeldung\spoon\ClassReporter.java
| 1
|
请完成以下Java代码
|
private static MailboxRouting fromRecord(final I_AD_MailConfig record)
{
return MailboxRouting.builder()
.mailboxId(MailboxId.ofRepoId(record.getAD_MailBox_ID()))
.userToColumnName(StringUtils.trimBlankToNull(record.getColumnUserTo()))
.clientId(ClientId.ofRepoId(record.getAD_Client_ID()))
.orgId(OrgId.ofRepoIdOrAny(record.getAD_Org_ID()))
.docBaseAndSubType(DocBaseAndSubType.ofNullable(record.getDocBaseType(), record.getDocSubType()))
.adProcessId(AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID()))
.emailCustomType(EMailCustomType.ofNullableCode(record.getCustomType()))
.build();
}
//
//
//
//
//
//
@Value
@Builder
private static class MailboxEntry
{
@NonNull MailboxId id;
boolean active;
@NonNull Mailbox mailbox;
}
private static class MailboxesMap
{
private final ImmutableMap<MailboxId, MailboxEntry> byId;
private MailboxesMap(final List<MailboxEntry> list)
{
this.byId = Maps.uniqueIndex(list, MailboxEntry::getId);
|
}
public Mailbox getById(final MailboxId mailboxId)
{
return getEntryById(mailboxId).getMailbox();
}
private MailboxEntry getEntryById(final MailboxId mailboxId)
{
final MailboxEntry entry = byId.get(mailboxId);
if (entry == null)
{
throw new AdempiereException("No mailbox found for " + mailboxId);
}
return entry;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\mailboxes\MailboxRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void buildAndAttachContext(@NonNull final Exchange exchange)
{
final JsonProduct jsonProduct = exchange.getIn().getBody(JsonProduct.class);
final PushRawMaterialsRouteContext routeContext = PushRawMaterialsRouteContext.builder()
.jsonProduct(jsonProduct)
.build();
exchange.setProperty(ROUTE_PROPERTY_PUSH_RAW_MATERIALS_CONTEXT, routeContext);
}
private void prepareBPartnerProducts(@NonNull final Exchange exchange)
{
final PushRawMaterialsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange,
ROUTE_PROPERTY_PUSH_RAW_MATERIALS_CONTEXT,
PushRawMaterialsRouteContext.class);
if (Check.isEmpty(context.getJsonProduct().getBPartnerProducts()))
{
exchange.getIn().setBody(ImmutableList.of());
return;
}
final ImmutableList<JsonBPartnerProduct> bPartnerProducts = context.getJsonProduct().getBPartnerProducts()
.stream()
.filter(jsonBPartnerProduct -> jsonBPartnerProduct.getAttachmentAdditionalInfos() != null
&& !Check.isEmpty(jsonBPartnerProduct.getAttachmentAdditionalInfos().getAttachments()))
.collect(ImmutableList.toImmutableList());
exchange.getIn().setBody(bPartnerProducts);
}
private void prepareAttachments(@NonNull final Exchange exchange)
{
final JsonBPartnerProduct bPartnerProduct = exchange.getIn().getBody(JsonBPartnerProduct.class);
|
final JsonBPartnerProductAdditionalInfo additionalInfo = bPartnerProduct.getAttachmentAdditionalInfos();
if (additionalInfo == null || Check.isEmpty(additionalInfo.getAttachments()))
{
exchange.getIn().setBody(ImmutableList.of());
return;
}
final JsonMetasfreshId bpartnerId = Optional.ofNullable(bPartnerProduct.getBPartnerMetasfreshId())
.map(Integer::parseInt)
.map(JsonMetasfreshId::of)
.orElseThrow(() -> new RuntimeCamelException("Missing mandatory JsonBPartnerProduct.METASFRESHID!"));
final PushRawMaterialsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange,
ROUTE_PROPERTY_PUSH_RAW_MATERIALS_CONTEXT,
PushRawMaterialsRouteContext.class);
context.setCurrentBPartnerID(bpartnerId);
exchange.getIn().setBody(ImmutableList.copyOf(additionalInfo.getAttachments()));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\product\PushRawMaterialsRouteBuilder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ProductPrice
{
@NonNull
ProductId productId;
@NonNull
UomId uomId;
@NonNull
@Getter(AccessLevel.NONE)
Money money;
public Money toMoney()
{
return money;
}
public BigDecimal toBigDecimal()
{
return money.toBigDecimal();
}
public CurrencyId getCurrencyId()
{
return money.getCurrencyId();
}
|
public ProductPrice withValueAndUomId(@NonNull final BigDecimal moneyAmount, @NonNull final UomId uomId)
{
return toBuilder()
.money(Money.of(moneyAmount, getCurrencyId()))
.uomId(uomId)
.build();
}
public ProductPrice negate()
{
return this.toBuilder().money(money.negate()).build();
}
public boolean isEqualByComparingTo(@Nullable final ProductPrice other)
{
if (other == null)
{
return false;
}
return other.uomId.equals(uomId) && other.money.isEqualByComparingTo(money);
}
public <T> T transform(@NonNull final Function<ProductPrice, T> mapper)
{
return mapper.apply(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\ProductPrice.java
| 2
|
请完成以下Java代码
|
public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (PARAM_SINCE.equals(parameter.getColumnName()))
{
return retrieveSinceValue();
}
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
/**
* Needed so we also have a "since" when the process is run via AD_Scheduler.
* This might be the process's last invocation time. Note that oftentimes, there is also a runtime-parameter with the actual value used by the external system.
*/
@NonNull
protected Timestamp extractEffectiveSinceTimestamp()
{
return CoalesceUtil.coalesceSuppliersNotNull(() -> since, this::retrieveSinceValue, () -> Timestamp.from(Instant.ofEpochSecond(0)));
}
private Timestamp retrieveSinceValue()
{
final ProcessInfo processInfo = getProcessInfo();
return pInstanceDAO.getLastRunDate(processInfo.getAdProcessId(), processInfo.getPinstanceId());
}
private Map<String, String> extractParameters(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
final Map<String, String> parameters = new HashMap<>();
final Map<String, String> childSpecificParams = extractExternalSystemParameters(externalSystemParentConfig);
if (childSpecificParams != null && !childSpecificParams.isEmpty())
{
|
parameters.putAll(childSpecificParams);
}
runtimeParametersRepository.getByConfigIdAndRequest(externalSystemParentConfig.getId(), externalRequest)
.forEach(runtimeParameter -> parameters.put(runtimeParameter.getName(), runtimeParameter.getValue()));
return parameters;
}
protected String getOrgCode(@NonNull final ExternalSystemParentConfig externalSystemParentConfig)
{
return orgDAO.getById(getOrgId()).getValue();
}
@Nullable
protected Timestamp getSinceParameterValue()
{
return since;
}
protected abstract IExternalSystemChildConfigId getExternalChildConfigId();
protected abstract Map<String, String> extractExternalSystemParameters(ExternalSystemParentConfig externalSystemParentConfig);
protected abstract String getTabName();
protected abstract ExternalSystemType getExternalSystemType();
protected abstract long getSelectedRecordCount(final IProcessPreconditionsContext context);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeExternalSystemProcess.java
| 1
|
请完成以下Java代码
|
final class CompositeFlatrateTermEventListener implements IFlatrateTermEventListener
{
public static final IFlatrateTermEventListener compose(final IFlatrateTermEventListener handler, final IFlatrateTermEventListener handlerToAdd)
{
if (handler == null)
{
return handlerToAdd;
}
if (handlerToAdd == null)
{
return handler;
}
if (handler instanceof CompositeFlatrateTermEventListener)
{
final CompositeFlatrateTermEventListener handlerComposite = (CompositeFlatrateTermEventListener)handler;
handlerComposite.addHandler(handlerToAdd);
return handlerComposite;
}
else
{
final CompositeFlatrateTermEventListener handlerComposite = new CompositeFlatrateTermEventListener();
handlerComposite.addHandler(handler);
handlerComposite.addHandler(handlerToAdd);
return handlerComposite;
}
}
private final CopyOnWriteArrayList<IFlatrateTermEventListener> handlers = new CopyOnWriteArrayList<>();
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("handlers", handlers)
.toString();
}
public void addHandler(final IFlatrateTermEventListener handler)
{
Check.assumeNotNull(handler, "handler not null");
|
handlers.addIfAbsent(handler);
}
@Override
public void beforeFlatrateTermReactivate(final I_C_Flatrate_Term term)
{
handlers.forEach(h -> h.beforeFlatrateTermReactivate(term));
}
@Override
public void afterSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor)
{
handlers.forEach(h -> h.afterSaveOfNextTermForPredecessor(next, predecessor));
}
@Override
public void afterFlatrateTermEnded(I_C_Flatrate_Term term)
{
handlers.forEach(h -> h.afterFlatrateTermEnded(term));
}
@Override
public void beforeSaveOfNextTermForPredecessor(I_C_Flatrate_Term next, I_C_Flatrate_Term predecessor)
{
handlers.forEach(h -> h.beforeSaveOfNextTermForPredecessor(next,predecessor));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\CompositeFlatrateTermEventListener.java
| 1
|
请完成以下Java代码
|
protected EvaluationContext createEvaluationContext(InstanceEvent event, Instance instance) {
Map<String, Object> root = new HashMap<>();
root.put("event", event);
root.put("instance", instance);
root.put("lastStatus", getLastStatus(event.getInstance()));
return SimpleEvaluationContext
.forPropertyAccessors(DataBindingPropertyAccessor.forReadOnlyAccess(), new MapAccessor())
.withRootObject(root)
.build();
}
@Nullable
public URI getWebhookUrl() {
return webhookUrl;
}
public void setWebhookUrl(@Nullable URI webhookUrl) {
this.webhookUrl = webhookUrl;
}
public String getThemeColor() {
return themeColor.getExpressionString();
}
public void setThemeColor(String themeColor) {
this.themeColor = parser.parseExpression(themeColor, ParserContext.TEMPLATE_EXPRESSION);
}
public String getDeregisterActivitySubtitle() {
return deregisterActivitySubtitle.getExpressionString();
}
public void setDeregisterActivitySubtitle(String deregisterActivitySubtitle) {
this.deregisterActivitySubtitle = parser.parseExpression(deregisterActivitySubtitle,
ParserContext.TEMPLATE_EXPRESSION);
}
public String getRegisterActivitySubtitle() {
return registerActivitySubtitle.getExpressionString();
}
public void setRegisterActivitySubtitle(String registerActivitySubtitle) {
this.registerActivitySubtitle = parser.parseExpression(registerActivitySubtitle,
ParserContext.TEMPLATE_EXPRESSION);
}
public String getStatusActivitySubtitle() {
return statusActivitySubtitle.getExpressionString();
}
|
public void setStatusActivitySubtitle(String statusActivitySubtitle) {
this.statusActivitySubtitle = parser.parseExpression(statusActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION);
}
@Data
@Builder
public static class Message {
private final String summary;
private final String themeColor;
private final String title;
@Builder.Default
private final List<Section> sections = new ArrayList<>();
}
@Data
@Builder
public static class Section {
private final String activityTitle;
private final String activitySubtitle;
@Builder.Default
private final List<Fact> facts = new ArrayList<>();
}
public record Fact(String name, @Nullable String value) {
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MicrosoftTeamsNotifier.java
| 1
|
请完成以下Java代码
|
public int getAD_Org_ID()
{
return AD_Org_ID;
}
@Override
public int getC_BPartner_ID()
{
return C_BPartner_ID;
}
@Override
public int getC_BPartner_Location_ID()
{
return C_BPatner_Location_ID;
}
@Override
public int getContact_ID()
{
return Contact_ID;
}
@Override
public int getC_Currency_ID()
{
return C_Currency_ID;
}
@Override
public BigDecimal getTotalAmt()
{
return totalAmt;
}
@Override
public BigDecimal getOpenAmt()
{
return openAmt;
}
@Override
public Date getDueDate()
{
return (Date)dueDate.clone();
}
@Override
public Date getGraceDate()
{
if (graceDate == null)
{
return null;
}
return (Date)graceDate.clone();
|
}
@Override
public int getDaysDue()
{
return daysDue;
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public int getRecordId()
{
return record_id;
}
@Override
public boolean isInDispute()
{
return inDispute;
}
@Override
public String toString()
{
return "DunnableDoc [tableName=" + tableName + ", record_id=" + record_id + ", C_BPartner_ID=" + C_BPartner_ID + ", C_BPatner_Location_ID=" + C_BPatner_Location_ID + ", Contact_ID="
+ Contact_ID + ", C_Currency_ID=" + C_Currency_ID + ", totalAmt=" + totalAmt + ", openAmt=" + openAmt + ", dueDate=" + dueDate + ", graceDate=" + graceDate + ", daysDue=" + daysDue
+ ", inDispute=" + inDispute + "]";
}
@Override
public String getDocumentNo()
{
return documentNo;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunnableDoc.java
| 1
|
请完成以下Java代码
|
protected Package definePackage(String name, Manifest man, URL url) throws IllegalArgumentException {
return (!this.exploded) ? super.definePackage(name, man, url) : definePackageForExploded(name, man, url);
}
private Package definePackageForExploded(String name, Manifest man, URL url) {
synchronized (this.definePackageLock) {
return definePackage(DefinePackageCallType.MANIFEST, () -> super.definePackage(name, man, url));
}
}
@Override
protected Package definePackage(String name, String specTitle, String specVersion, String specVendor,
String implTitle, String implVersion, String implVendor, URL sealBase) throws IllegalArgumentException {
if (!this.exploded) {
return super.definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor,
sealBase);
}
return definePackageForExploded(name, sealBase, () -> super.definePackage(name, specTitle, specVersion,
specVendor, implTitle, implVersion, implVendor, sealBase));
}
private Package definePackageForExploded(String name, URL sealBase, Supplier<Package> call) {
synchronized (this.definePackageLock) {
if (this.definePackageCallType == null) {
// We're not part of a call chain which means that the URLClassLoader
// is trying to define a package for our exploded JAR. We use the
// manifest version to ensure package attributes are set
Manifest manifest = getManifest(this.rootArchive);
if (manifest != null) {
return definePackage(name, manifest, sealBase);
}
}
return definePackage(DefinePackageCallType.ATTRIBUTES, call);
}
}
private <T> T definePackage(DefinePackageCallType type, Supplier<T> call) {
DefinePackageCallType existingType = this.definePackageCallType;
try {
this.definePackageCallType = type;
return call.get();
}
finally {
|
this.definePackageCallType = existingType;
}
}
private Manifest getManifest(Archive archive) {
try {
return (archive != null) ? archive.getManifest() : null;
}
catch (IOException ex) {
return null;
}
}
/**
* The different types of call made to define a package. We track these for exploded
* jars so that we can detect packages that should have manifest attributes applied.
*/
private enum DefinePackageCallType {
/**
* A define package call from a resource that has a manifest.
*/
MANIFEST,
/**
* A define package call with a direct set of attributes.
*/
ATTRIBUTES
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\LaunchedClassLoader.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void processCreateRequest(@NonNull final Exchange exchange)
{
final Object request = exchange.getIn().getBody();
if (!(request instanceof ExternalStatusCreateCamelRequest))
{
throw new RuntimeCamelException("The route " + ExternalSystemCamelConstants.MF_CREATE_EXTERNAL_SYSTEM_STATUS_V2_CAMEL_URI
+ " requires the body to be instanceof " + ExternalStatusCreateCamelRequest.class.getName()
+ " However, it is " + (request == null ? "null" : request.getClass().getName()));
}
final ExternalStatusCreateCamelRequest externalStatusRequest = (ExternalStatusCreateCamelRequest)request;
exchange.getIn().setHeader(HEADER_EXTERNAL_SYSTEM_CONFIG_TYPE, externalStatusRequest.getExternalSystemConfigType());
exchange.getIn().setHeader(HEADER_EXTERNAL_SYSTEM_CHILD_CONFIG_VALUE, externalStatusRequest.getExternalSystemChildConfigValue());
exchange.getIn().setHeader(HEADER_EXTERNAL_SERVICE_VALUE, externalStatusRequest.getServiceValue());
final JsonStatusRequest jsonStatusRequest = externalStatusRequest.getJsonStatusRequest();
exchange.getIn().setBody(jsonStatusRequest);
}
|
private void processRetrieveRequest(@NonNull final Exchange exchange)
{
final Object request = exchange.getIn().getBody();
if (!(request instanceof RetreiveServiceStatusCamelRequest))
{
throw new RuntimeCamelException("The route " + ExternalSystemCamelConstants.MF_GET_SERVICE_STATUS_V2_CAMEL_URI + " requires the body to be instanceof "
+ RetreiveServiceStatusCamelRequest.class.getName()
+ " However, it is " + (request == null ? "null" : request.getClass().getName()));
}
final RetreiveServiceStatusCamelRequest externalTypeCamelRequest = (RetreiveServiceStatusCamelRequest)request;
exchange.getIn().setHeader(HEADER_EXTERNAL_SYSTEM_CONFIG_TYPE, externalTypeCamelRequest.getType());
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\ExternalStatusRouteBuilder.java
| 2
|
请完成以下Java代码
|
public class MethodReference
{
public static final MethodReference of(@NonNull final Method method)
{
return new MethodReference(method);
}
private final AtomicReference<WeakReference<Method>> methodRef;
private final ClassReference<?> classRef;
private final String methodName;
private ImmutableList<ClassReference<?>> parameterTypeRefs;
private MethodReference(@NonNull final Method method)
{
methodRef = new AtomicReference<>(new WeakReference<>(method));
classRef = ClassReference.of(method.getDeclaringClass());
methodName = method.getName();
parameterTypeRefs = Stream.of(method.getParameterTypes())
.map(parameterType -> ClassReference.of(parameterType))
.collect(ImmutableList.toImmutableList());
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("class", classRef)
.add("methodName", methodName)
.add("parameters", parameterTypeRefs)
.toString();
}
public Method getMethod()
{
// Get if not expired
{
final WeakReference<Method> weakRef = methodRef.get();
final Method method = weakRef != null ? weakRef.get() : null;
if (method != null)
{
return method;
}
}
// Load the class
try
|
{
final Class<?> clazz = classRef.getReferencedClass();
final Class<?>[] parameterTypes = parameterTypeRefs.stream()
.map(parameterTypeRef -> parameterTypeRef.getReferencedClass())
.toArray(size -> new Class<?>[size]);
final Method methodNew = clazz.getDeclaredMethod(methodName, parameterTypes);
methodRef.set(new WeakReference<>(methodNew));
return methodNew;
}
catch (final Exception ex)
{
throw new IllegalStateException("Cannot load expired field: " + classRef + "/" + methodName + " (" + parameterTypeRefs + ")", ex);
}
}
@VisibleForTesting
void forget()
{
methodRef.set(null);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\MethodReference.java
| 1
|
请完成以下Java代码
|
private static void configureModel(String userName, Model model) {
model.setModelVersion("4.0.0");
model.setArtifactId("com." + userName.toLowerCase());
model.setGroupId("learning-project");
model.setVersion("0.0.1-SNAPSHOT");
}
private static String generateMainClass(String packageName) {
return packageName + ";\n" +
"\n" +
"public class Main {\n" +
" public static void main(String[] args){\n" +
" System.out.println(\"Hello World!\");\n" +
" }\n" +
"}\n";
}
private static Path generateFolders(Path sourceFolder, String packageName) throws IOException {
return Files.createDirectories(sourceFolder.resolve(packageName));
}
private Build configureJavaVersion() {
Plugin plugin = new Plugin();
plugin.setGroupId("org.apache.maven.plugins");
plugin.setArtifactId("maven-compiler-plugin");
plugin.setVersion("3.8.1");
|
Xpp3Dom configuration = new Xpp3Dom("configuration");
Xpp3Dom source = new Xpp3Dom("source");
source.setValue(javaVersion.getVersion());
Xpp3Dom target = new Xpp3Dom("target");
target.setValue(javaVersion.getVersion());
configuration.addChild(source);
configuration.addChild(target);
plugin.setConfiguration(configuration);
Build build = new Build();
build.addPlugin(plugin);
return build;
}
}
|
repos\tutorials-master\maven-modules\maven-exec-plugin\src\main\java\com\baeldung\learningplatform\ProjectBuilder.java
| 1
|
请完成以下Java代码
|
public void invalidPropertyValue(Exception e) {
logError("015", "Exception while reading configuration property: {}", e.getMessage());
}
/**
* Method for logging message when model TTL longer than global TTL.
*
* @param definitionKey the correlated definition key with which history TTL is related to.
* For processes related to httl, that is the processDefinitionKey, for cases the case definition key
* whereas for decisions is the decision definition key.
*/
public void logModelHTTLLongerThanGlobalConfiguration(String definitionKey) {
logWarn(
"017", "definitionKey: {}; "
+ "The specified Time To Live (TTL) in the model is longer than the global TTL configuration. "
+ "The historic data related to this model will be cleaned up at later point comparing to the other processes.",
definitionKey);
}
public NotValidException logErrorNoTTLConfigured() {
return new NotValidException(exceptionMessage("018",
"History Time To Live (TTL) cannot be null. "
+ "TTL is necessary for the History Cleanup to work. The following options are possible:\n"
+ "* Set historyTimeToLive in the model\n"
+ "* Set a default historyTimeToLive as a global process engine configuration\n"
+ "* (Not recommended) Deactivate the enforceTTL config to disable this check"));
}
public ProcessEngineException invalidTransactionIsolationLevel(String transactionIsolationLevel) {
|
return new ProcessEngineException(exceptionMessage("019",
"The transaction isolation level set for the database is '{}' which differs from the recommended value. "
+ "Please change the isolation level to 'READ_COMMITTED' or set property 'skipIsolationLevelCheck' to true. "
+ "Please keep in mind that some levels are known to cause deadlocks and other unexpected behaviours.",
transactionIsolationLevel));
}
public void logSkippedIsolationLevelCheck(String transactionIsolationLevel) {
logWarn("020", "The transaction isolation level set for the database is '{}' which differs from the recommended value "
+ "and property skipIsolationLevelCheck is enabled. "
+ "Please keep in mind that levels different from 'READ_COMMITTED' are known to cause deadlocks and other unexpected behaviours.",
transactionIsolationLevel);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ConfigurationLogger.java
| 1
|
请完成以下Java代码
|
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public UserSexEnum getUserSex() {
return userSex;
}
public void setUserSex(UserSexEnum userSex) {
this.userSex = userSex;
}
public String getNickName() {
return nickName;
}
|
public void setNickName(String nickName) {
this.nickName = nickName;
}
@Override
public String toString() {
return "UserEntity{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", userSex=" + userSex +
", nickName='" + nickName + '\'' +
'}';
}
}
|
repos\spring-boot-leaning-master\2.x_42_courses\第 3-2 课: 如何优雅的使用 MyBatis XML 配置版\spring-boot-mybatis-xml\src\main\java\com\neo\model\User.java
| 1
|
请完成以下Java代码
|
public void setBPartnerAddress(String address)
{
delegate.setBPartnerAddress_Override(address);
}
@Override
public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentLocationAdapter.super.setRenderedAddress(from);
}
@Override
public I_M_ShipmentSchedule getWrappedRecord()
{
return delegate;
|
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public OverrideLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OverrideLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_ShipmentSchedule.class));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\location\adapter\OverrideLocationAdapter.java
| 1
|
请完成以下Java代码
|
public class ScriptCalculatedFieldState extends BaseCalculatedFieldState {
protected CalculatedFieldScriptEngine tbelExpression;
public ScriptCalculatedFieldState(EntityId entityId) {
super(entityId);
}
@Override
public void setCtx(CalculatedFieldCtx ctx, TbActorRef actorCtx) {
super.setCtx(ctx, actorCtx);
this.tbelExpression = ctx.getTbelExpressions().get(ctx.getExpression());
}
@Override
public ListenableFuture<CalculatedFieldResult> performCalculation(Map<String, ArgumentEntry> updatedArgs, CalculatedFieldCtx ctx) {
ListenableFuture<Object> resultFuture = ctx.evaluateTbelExpression(tbelExpression, this);
Output output = ctx.getOutput();
return Futures.transform(resultFuture,
|
result -> TelemetryCalculatedFieldResult.builder()
.outputStrategy(output.getStrategy())
.type(output.getType())
.scope(output.getScope())
.result(JacksonUtil.valueToTree(result))
.build(),
MoreExecutors.directExecutor()
);
}
@Override
public CalculatedFieldType getType() {
return CalculatedFieldType.SCRIPT;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\cf\ctx\state\ScriptCalculatedFieldState.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DummyDiscoveryService implements DiscoveryService {
private final TbServiceInfoProvider serviceInfoProvider;
private final PartitionService partitionService;
public DummyDiscoveryService(TbServiceInfoProvider serviceInfoProvider, PartitionService partitionService) {
this.serviceInfoProvider = serviceInfoProvider;
this.partitionService = partitionService;
}
@AfterStartUp(order = AfterStartUp.DISCOVERY_SERVICE)
public void onApplicationEvent(ApplicationReadyEvent event) {
partitionService.recalculatePartitions(serviceInfoProvider.getServiceInfo(), Collections.emptyList());
}
@Override
public List<TransportProtos.ServiceInfo> getOtherServers() {
return Collections.emptyList();
|
}
@Override
public boolean isMonolith() {
return true;
}
@Override
public void setReady(boolean ready) {
boolean changed = serviceInfoProvider.setReady(ready);
if (changed) {
serviceInfoProvider.generateNewServiceInfoWithCurrentSystemInfo();
}
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\DummyDiscoveryService.java
| 2
|
请完成以下Java代码
|
public void setMandatory(boolean flag)
{
m_mandatory = flag;
}
/**
* Is lookup model mandatory
* @return boolean
*/
public boolean isMandatory()
{
return m_mandatory;
}
/**
* Is this lookup model populated
* @return boolean
*/
public boolean isLoaded()
{
return m_loaded;
}
/**
* Returns a list of parameters on which this lookup depends.
*
* Those parameters will be fetched from context on validation time.
*
* @return list of parameter names
*/
public Set<String> getParameters()
{
return ImmutableSet.of();
}
/**
*
* @return evaluation context
*/
public IValidationContext getValidationContext()
{
return IValidationContext.NULL;
}
|
/**
* Suggests a valid value for given value
*
* @param value
* @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned
*/
public NamePair suggestValidValue(final NamePair value)
{
return null;
}
/**
* Returns true if given <code>display</code> value was rendered for a not found item.
* To be used together with {@link #getDisplay} methods.
*
* @param display
* @return true if <code>display</code> contains not found markers
*/
public boolean isNotFoundDisplayValue(String display)
{
return false;
}
} // Lookup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
| 1
|
请完成以下Java代码
|
public void run(String... strings) throws Exception {
photoService.launchPhotoProcess("one", "two", "three");
}
};
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
@Transactional
class PhotoService {
private final RuntimeService runtimeService;
private final TaskService taskService;
private final PhotoRepository photoRepository;
@Autowired
public PhotoService(RuntimeService runtimeService, TaskService taskService, PhotoRepository photoRepository) {
this.runtimeService = runtimeService;
this.taskService = taskService;
this.photoRepository = photoRepository;
}
public void processPhoto(Long photoId) {
System.out.println("processing photo#" + photoId);
}
public void launchPhotoProcess(String... photoLabels) {
List<Photo> photos = new ArrayList<>();
for (String l : photoLabels) {
Photo x = this.photoRepository.save(new Photo(l));
photos.add(x);
}
Map<String, Object> procVars = new HashMap<>();
procVars.put("photos", photos);
ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("dogeProcess", procVars);
List<Execution> waitingExecutions = runtimeService.createExecutionQuery().activityId("wait").list();
System.out.println("--> # executions = " + waitingExecutions.size());
for (Execution execution : waitingExecutions) {
runtimeService.trigger(execution.getId());
}
Task reviewTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
|
taskService.complete(reviewTask.getId(), Collections.singletonMap("approved", (Object) true));
long count = runtimeService.createProcessInstanceQuery().count();
System.out.println("Proc count " + count);
}
}
interface PhotoRepository extends JpaRepository<Photo, Long> {
}
@Entity
class Photo {
@Id
@GeneratedValue
private Long id;
Photo() {
}
Photo(String username) {
this.username = username;
}
private String username;
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-jpa\src\main\java\flowable\Application.java
| 1
|
请完成以下Java代码
|
public UserOperationLogContextEntryBuilder propertyChanges(List<PropertyChange> propertyChanges) {
entry.setPropertyChanges(propertyChanges);
return this;
}
public UserOperationLogContextEntryBuilder propertyChanges(PropertyChange propertyChange) {
List<PropertyChange> propertyChanges = new ArrayList<PropertyChange>();
propertyChanges.add(propertyChange);
entry.setPropertyChanges(propertyChanges);
return this;
}
public UserOperationLogContextEntry create() {
return entry;
}
public UserOperationLogContextEntryBuilder jobId(String jobId) {
entry.setJobId(jobId);
return this;
}
public UserOperationLogContextEntryBuilder jobDefinitionId(String jobDefinitionId) {
entry.setJobDefinitionId(jobDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionId(String processDefinitionId) {
entry.setProcessDefinitionId(processDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder processDefinitionKey(String processDefinitionKey) {
entry.setProcessDefinitionKey(processDefinitionKey);
return this;
}
public UserOperationLogContextEntryBuilder processInstanceId(String processInstanceId) {
entry.setProcessInstanceId(processInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder caseDefinitionId(String caseDefinitionId) {
entry.setCaseDefinitionId(caseDefinitionId);
return this;
}
public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) {
entry.setDeploymentId(deploymentId);
return this;
}
public UserOperationLogContextEntryBuilder batchId(String batchId) {
entry.setBatchId(batchId);
|
return this;
}
public UserOperationLogContextEntryBuilder taskId(String taskId) {
entry.setTaskId(taskId);
return this;
}
public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) {
entry.setCaseInstanceId(caseInstanceId);
return this;
}
public UserOperationLogContextEntryBuilder category(String category) {
entry.setCategory(category);
return this;
}
public UserOperationLogContextEntryBuilder annotation(String annotation) {
entry.setAnnotation(annotation);
return this;
}
public UserOperationLogContextEntryBuilder tenantId(String tenantId) {
entry.setTenantId(tenantId);
return this;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProcessVariableHeaderMapper implements HeaderMapper<Map<String, Object>> {
private final Set<String> keysToPreserve = new ConcurrentSkipListSet<>();
public ProcessVariableHeaderMapper(Set<String> sync) {
this.keysToPreserve.addAll(sync);
}
@Override
public void fromHeaders(MessageHeaders headers, Map<String, Object> target) {
// inbound SI msg. take the headers and convert it to
sync(this.keysToPreserve, headers, target);
}
@Override
public Map<String, Object> toHeaders(Map<String, Object> source) {
Map<String, Object> matches = sync(
this.keysToPreserve,
|
source,
new HashMap<>());
return matches;
}
private static Map<String, Object> sync(
Set<String> keys,
Map<String, Object> in,
Map<String, Object> out) {
for (String k : keys)
if (in.containsKey(k))
out.put(k, in.get(k));
return out;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\integration\ProcessVariableHeaderMapper.java
| 2
|
请完成以下Java代码
|
private static class DefaultCacheKey {
private final Method method;
private final @Nullable Class<?> targetClass;
DefaultCacheKey(Method method, @Nullable Class<?> targetClass) {
this.method = method;
this.targetClass = targetClass;
}
@Override
public boolean equals(Object other) {
DefaultCacheKey otherKey = (DefaultCacheKey) other;
return (this.method.equals(otherKey.method)
&& ObjectUtils.nullSafeEquals(this.targetClass, otherKey.targetClass));
}
|
@Override
public int hashCode() {
return this.method.hashCode() * 21 + ((this.targetClass != null) ? this.targetClass.hashCode() : 0);
}
@Override
public String toString() {
String targetClassName = (this.targetClass != null) ? this.targetClass.getName() : "-";
return "CacheKey[" + targetClassName + "; " + this.method + "]";
}
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\method\DelegatingMethodSecurityMetadataSource.java
| 1
|
请完成以下Java代码
|
public long getMaxWait() {
return maxWait;
}
public void setMaxWait(long maxWait) {
this.maxWait = maxWait;
}
public long getMaxBackoff() {
return maxBackoff;
}
public void setMaxBackoff(long maxBackoff) {
this.maxBackoff = maxBackoff;
}
public int getBackoffDecreaseThreshold() {
return backoffDecreaseThreshold;
}
public void setBackoffDecreaseThreshold(int backoffDecreaseThreshold) {
this.backoffDecreaseThreshold = backoffDecreaseThreshold;
}
public String getName() {
return name;
}
public Command<AcquiredJobs> getAcquireJobsCmd(int numJobs) {
return acquireJobsCmdFactory.getCommand(numJobs);
}
public AcquireJobsCommandFactory getAcquireJobsCmdFactory() {
return acquireJobsCmdFactory;
}
public void setAcquireJobsCmdFactory(AcquireJobsCommandFactory acquireJobsCmdFactory) {
this.acquireJobsCmdFactory = acquireJobsCmdFactory;
}
public boolean isActive() {
return isActive;
}
public RejectedJobsHandler getRejectedJobsHandler() {
return rejectedJobsHandler;
}
public void setRejectedJobsHandler(RejectedJobsHandler rejectedJobsHandler) {
this.rejectedJobsHandler = rejectedJobsHandler;
}
protected void startJobAcquisitionThread() {
|
if (jobAcquisitionThread == null) {
jobAcquisitionThread = new Thread(acquireJobsRunnable, getName());
jobAcquisitionThread.start();
}
}
protected void stopJobAcquisitionThread() {
try {
jobAcquisitionThread.join();
}
catch (InterruptedException e) {
LOG.interruptedWhileShuttingDownjobExecutor(e);
}
jobAcquisitionThread = null;
}
public AcquireJobsRunnable getAcquireJobsRunnable() {
return acquireJobsRunnable;
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutor.java
| 1
|
请完成以下Java代码
|
public void setQtyReserved (BigDecimal QtyReserved)
{
set_Value (COLUMNNAME_QtyReserved, QtyReserved);
}
/** Get Reservierte Menge.
@return Reservierte Menge
*/
public BigDecimal getQtyReserved ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReserved);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Amt.
@param RRAmt
Revenue Recognition Amount
*/
public void setRRAmt (BigDecimal RRAmt)
{
set_Value (COLUMNNAME_RRAmt, RRAmt);
}
/** Get Revenue Recognition Amt.
@return Revenue Recognition Amount
*/
public BigDecimal getRRAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RRAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Revenue Recognition Start.
@param RRStartDate
Revenue Recognition Start Date
*/
public void setRRStartDate (Timestamp RRStartDate)
{
set_Value (COLUMNNAME_RRStartDate, RRStartDate);
}
/** Get Revenue Recognition Start.
@return Revenue Recognition Start Date
*/
public Timestamp getRRStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_RRStartDate);
}
public org.compiere.model.I_C_OrderLine getRef_OrderLine() throws RuntimeException
{
return (org.compiere.model.I_C_OrderLine)MTable.get(getCtx(), org.compiere.model.I_C_OrderLine.Table_Name)
.getPO(getRef_OrderLine_ID(), get_TrxName()); }
/** Set Referenced Order Line.
@param Ref_OrderLine_ID
Reference to corresponding Sales/Purchase Order
*/
|
public void setRef_OrderLine_ID (int Ref_OrderLine_ID)
{
if (Ref_OrderLine_ID < 1)
set_Value (COLUMNNAME_Ref_OrderLine_ID, null);
else
set_Value (COLUMNNAME_Ref_OrderLine_ID, Integer.valueOf(Ref_OrderLine_ID));
}
/** Get Referenced Order Line.
@return Reference to corresponding Sales/Purchase Order
*/
public int getRef_OrderLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ref_OrderLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ressourcenzuordnung.
@param S_ResourceAssignment_ID
Ressourcenzuordnung
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_Value (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_Value (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Ressourcenzuordnung.
@return Ressourcenzuordnung
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_OrderLine_Overview.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getDescription(ConnectionFactoryBeanCreationException cause) {
StringBuilder description = new StringBuilder();
description.append("Failed to configure a ConnectionFactory: ");
if (!StringUtils.hasText(cause.getUrl())) {
description.append("'url' attribute is not specified and ");
}
description.append(String.format("no embedded database could be configured.%n"));
description.append(String.format("%nReason: %s%n", cause.getMessage()));
return description.toString();
}
private String getAction(ConnectionFactoryBeanCreationException cause) {
StringBuilder action = new StringBuilder();
action.append(String.format("Consider the following:%n"));
if (EmbeddedDatabaseConnection.NONE == cause.getEmbeddedDatabaseConnection()) {
action.append(String.format("\tIf you want an embedded database (H2), please put it on the classpath.%n"));
}
else {
action.append(String.format("\tReview the configuration of %s%n.", cause.getEmbeddedDatabaseConnection()));
}
action
.append("\tIf you have database settings to be loaded from a particular "
+ "profile you may need to activate it")
.append(getActiveProfiles());
return action.toString();
|
}
private String getActiveProfiles() {
StringBuilder message = new StringBuilder();
String[] profiles = this.environment.getActiveProfiles();
if (ObjectUtils.isEmpty(profiles)) {
message.append(" (no profiles are currently active).");
}
else {
message.append(" (the profiles ");
message.append(StringUtils.arrayToCommaDelimitedString(profiles));
message.append(" are currently active).");
}
return message.toString();
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\ConnectionFactoryBeanCreationFailureAnalyzer.java
| 2
|
请完成以下Java代码
|
public abstract class BaseEntityViewProcessor extends BaseEdgeProcessor {
@Autowired
private DataValidator<EntityView> entityViewValidator;
protected Pair<Boolean, Boolean> saveOrUpdateEntityView(TenantId tenantId, EntityViewId entityViewId, EntityViewUpdateMsg entityViewUpdateMsg) {
boolean created = false;
boolean entityViewNameUpdated = false;
EntityView entityView = JacksonUtil.fromString(entityViewUpdateMsg.getEntity(), EntityView.class, true);
if (entityView == null) {
throw new RuntimeException("[{" + tenantId + "}] entityViewUpdateMsg {" + entityViewUpdateMsg + "} cannot be converted to entity view");
}
EntityView entityViewById = edgeCtx.getEntityViewService().findEntityViewById(tenantId, entityViewId);
if (entityViewById == null) {
created = true;
entityView.setId(null);
} else {
entityView.setId(entityViewId);
}
if (isSaveRequired(entityViewById, entityView)) {
entityViewNameUpdated = updateEntityViewNameIfDuplicateExists(tenantId, entityViewId, entityView);
setCustomerId(tenantId, created ? null : entityViewById.getCustomerId(), entityView, entityViewUpdateMsg);
entityViewValidator.validate(entityView, EntityView::getTenantId);
if (created) {
entityView.setId(entityViewId);
}
edgeCtx.getEntityViewService().saveEntityView(entityView, false);
|
}
return Pair.of(created, entityViewNameUpdated);
}
private boolean updateEntityViewNameIfDuplicateExists(TenantId tenantId, EntityViewId entityViewId, EntityView entityView) {
EntityView entityViewByName = edgeCtx.getEntityViewService().findEntityViewByTenantIdAndName(tenantId, entityView.getName());
return generateUniqueNameIfDuplicateExists(tenantId, entityViewId, entityView, entityViewByName).map(uniqueName -> {
entityView.setName(uniqueName);
return true;
}).orElse(false);
}
protected abstract void setCustomerId(TenantId tenantId, CustomerId customerId, EntityView entityView, EntityViewUpdateMsg entityViewUpdateMsg);
protected void deleteEntityView(TenantId tenantId, EntityViewId entityViewId) {
deleteEntityView(tenantId, null, entityViewId);
}
protected void deleteEntityView(TenantId tenantId, Edge edge, EntityViewId entityViewId) {
EntityView entityViewById = edgeCtx.getEntityViewService().findEntityViewById(tenantId, entityViewId);
if (entityViewById != null) {
edgeCtx.getEntityViewService().deleteEntityView(tenantId, entityViewId);
pushEntityEventToRuleEngine(tenantId, edge, entityViewById, TbMsgType.ENTITY_DELETED);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\entityview\BaseEntityViewProcessor.java
| 1
|
请完成以下Java代码
|
protected Iterator<I_M_HU> retrieveHUs()
{
final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder()
.setContext(getCtx(), ITrx.TRXNAME_None);
// Only top level HUs
huQueryBuilder.setOnlyTopLevelHUs();
// Only Active HUs
huQueryBuilder.addHUStatusToInclude(X_M_HU.HUSTATUS_Active);
// Only for preselected warehouse
if (p_M_Warehouse_ID > 0)
{
huQueryBuilder.addOnlyInWarehouseId(WarehouseId.ofRepoId(p_M_Warehouse_ID));
|
}
// Only for given SQL where clause
if (!Check.isEmpty(p_huWhereClause, true))
{
huQueryBuilder.addFilter(TypedSqlQueryFilter.of(p_huWhereClause));
}
// Fetch the HUs iterator
return huQueryBuilder
.createQuery()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true) // because we might change the hu's locator
.setOption(IQuery.OPTION_IteratorBufferSize, 1000)
.iterate(I_M_HU.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToDirectWarehouse_Mass.java
| 1
|
请完成以下Java代码
|
public int getC_Calendar_ID()
{
if (m_C_Calendar_ID == 0)
{
MYear year = (MYear) getC_Year();
if (year != null)
{
m_C_Calendar_ID = year.getC_Calendar_ID();
}
else
{
log.error("@NotFound@ C_Year_ID=" + getC_Year_ID());
}
}
return m_C_Calendar_ID;
} // getC_Calendar_ID
/**
* Get Calendar for Organization
* @param ctx Context
* @param orgRepoId Organization
*/
public static int getC_Calendar_ID(final Properties ctx, final int orgRepoId)
{
int C_Calendar_ID = 0;
final OrgId orgId = OrgId.ofRepoIdOrAny(orgRepoId);
if (orgId.isRegular())
|
{
OrgInfo info = Services.get(IOrgDAO.class).getOrgInfoById(orgId);
C_Calendar_ID = CalendarId.toRepoId(info.getCalendarId());
}
if (C_Calendar_ID <= 0)
{
I_AD_ClientInfo cInfo = Services.get(IClientDAO.class).retrieveClientInfo(ctx);
C_Calendar_ID = cInfo.getC_Calendar_ID();
}
return C_Calendar_ID;
} // getC_Calendar_ID
} // MPeriod
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MPeriod.java
| 1
|
请完成以下Java代码
|
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=541435
|
* Reference name: DD_OrderLine_Schedule_Status
*/
public static final int STATUS_AD_Reference_ID=541435;
/** NotStarted = NS */
public static final String STATUS_NotStarted = "NS";
/** InProgress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
| 1
|
请完成以下Java代码
|
public class Application {
private static final Logger LOG = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
new Application().run();
}
public void run() {
CassandraConnector connector = new CassandraConnector();
connector.connect("127.0.0.1", 9042, "datacenter1");
CqlSession session = connector.getSession();
KeyspaceRepository keyspaceRepository = new KeyspaceRepository(session);
keyspaceRepository.createKeyspace("testKeyspace", 1);
keyspaceRepository.useKeyspace("testKeyspace");
|
VideoRepository videoRepository = new VideoRepository(session);
ProductRepository productRepository = new ProductRepository(session);
videoRepository.createTable();
productRepository.createProductTableByName("testKeyspace");
videoRepository.insertVideo(new Video("Video Title 1", Instant.now()));
videoRepository.insertVideo(new Video("Video Title 2",
Instant.now().minus(1, ChronoUnit.DAYS)));
List<Video> videos = videoRepository.selectAll();
videos.forEach(x -> LOG.info(x.toString()));
connector.close();
}
}
|
repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\datastax\cassandra\Application.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.