instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Car getDriver1Car() {
return driver1Car;
}
public void setDriver1Car(Car driver1Car) {
this.driver1Car = driver1Car;
}
public Car getDriver2Car() {
return driver2Car;
}
public void setDriver2Car(Car driver2Car) {
this.driver2Car = driver2Car;
}
public Car getFirstCarInPark() {
return firstCarInPark;
}
public void setFirstCarInPark(Car firstCarInPark) { | this.firstCarInPark = firstCarInPark;
}
public Integer getNumberOfCarsInPark() {
return numberOfCarsInPark;
}
public void setNumberOfCarsInPark(Integer numberOfCarsInPark) {
this.numberOfCarsInPark = numberOfCarsInPark;
}
@Override
public String toString() {
return "[" +
"driver1Car=" + driver1Car +
", driver2Car=" + driver2Car +
", firstCarInPark=" + firstCarInPark +
", numberOfCarsInPark=" + numberOfCarsInPark +
']';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelCollections.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Boolean save(User user) {
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
return userDao.insert(user) > 0;
}
/**
* 删除用户
*
* @param id 主键id
* @return 删除成功 {@code true} 删除失败 {@code false}
*/
@Override
public Boolean delete(Long id) {
return userDao.delete(id) > 0;
}
/**
* 更新用户
*
* @param user 用户实体
* @param id 主键id
* @return 更新成功 {@code true} 更新失败 {@code false}
*/
@Override
public Boolean update(User user, Long id) {
User exist = getUser(id);
if (StrUtil.isNotBlank(user.getPassword())) {
String rawPass = user.getPassword();
String salt = IdUtil.simpleUUID();
String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
user.setPassword(pass);
user.setSalt(salt);
}
BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true));
exist.setLastUpdateTime(new DateTime()); | return userDao.update(exist, id) > 0;
}
/**
* 获取单个用户
*
* @param id 主键id
* @return 单个用户对象
*/
@Override
public User getUser(Long id) {
return userDao.findOneById(id);
}
/**
* 获取用户列表
*
* @param user 用户实体
* @return 用户列表
*/
@Override
public List<User> getUser(User user) {
return userDao.findByExample(user);
}
} | repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\service\impl\UserServiceImpl.java | 2 |
请完成以下Java代码 | public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto,
HistoricActivityInstance historicActivityInstance) {
dto.id = historicActivityInstance.getId();
dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId();
dto.activityId = historicActivityInstance.getActivityId();
dto.activityName = historicActivityInstance.getActivityName();
dto.activityType = historicActivityInstance.getActivityType();
dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey(); | dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId();
dto.processInstanceId = historicActivityInstance.getProcessInstanceId();
dto.executionId = historicActivityInstance.getExecutionId();
dto.taskId = historicActivityInstance.getTaskId();
dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId();
dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId();
dto.assignee = historicActivityInstance.getAssignee();
dto.startTime = historicActivityInstance.getStartTime();
dto.endTime = historicActivityInstance.getEndTime();
dto.durationInMillis = historicActivityInstance.getDurationInMillis();
dto.canceled = historicActivityInstance.isCanceled();
dto.completeScope = historicActivityInstance.isCompleteScope();
dto.tenantId = historicActivityInstance.getTenantId();
dto.removalTime = historicActivityInstance.getRemovalTime();
dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricActivityInstanceDto.java | 1 |
请完成以下Java代码 | public void setM_HU_Storage(final de.metas.handlingunits.model.I_M_HU_Storage M_HU_Storage)
{
set_ValueFromPO(COLUMNNAME_M_HU_Storage_ID, de.metas.handlingunits.model.I_M_HU_Storage.class, M_HU_Storage);
}
@Override
public void setM_HU_Storage_ID (final int M_HU_Storage_ID)
{
if (M_HU_Storage_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_Storage_ID, M_HU_Storage_ID);
}
@Override
public int getM_HU_Storage_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_Storage_ID);
}
@Override
public void setM_Locator_ID (final int M_Locator_ID)
{
if (M_Locator_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Locator_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Locator_ID, M_Locator_ID);
}
@Override
public int getM_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Locator_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); | else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_ValueNoCheck (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_M_HU_Stock_Detail_V.java | 1 |
请完成以下Java代码 | public double getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = itemPrice;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
@Override | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Item item = (Item) o;
return id == item.id &&
Double.compare(item.itemPrice, itemPrice) == 0 &&
Objects.equals(itemName, item.itemName) &&
itemType == item.itemType &&
Objects.equals(createdOn, item.createdOn);
}
@Override
public int hashCode() {
return Objects.hash(id, itemName, itemPrice, itemType, createdOn);
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkey\Item.java | 1 |
请完成以下Java代码 | public String getErrorMessage() {
return errorMessage;
}
public Map<String, Object> getValueInfo() {
return valueInfo;
}
public static HistoricVariableUpdateDto fromHistoricVariableUpdate(HistoricVariableUpdate historicVariableUpdate) {
HistoricVariableUpdateDto dto = new HistoricVariableUpdateDto();
fromHistoricVariableUpdate(dto, historicVariableUpdate);
return dto;
}
protected static void fromHistoricVariableUpdate(HistoricVariableUpdateDto dto,
HistoricVariableUpdate historicVariableUpdate) {
dto.revision = historicVariableUpdate.getRevision();
dto.variableName = historicVariableUpdate.getVariableName();
dto.variableInstanceId = historicVariableUpdate.getVariableInstanceId();
dto.initial = historicVariableUpdate.isInitial();
if (historicVariableUpdate.getErrorMessage() == null) {
try {
VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(historicVariableUpdate.getTypedValue()); | dto.value = variableValueDto.getValue();
dto.variableType = variableValueDto.getType();
dto.valueInfo = variableValueDto.getValueInfo();
} catch (RuntimeException e) {
dto.errorMessage = e.getMessage();
dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName());
}
}
else {
dto.errorMessage = historicVariableUpdate.getErrorMessage();
dto.variableType = VariableValueDto.toRestApiTypeName(historicVariableUpdate.getTypeName());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableUpdateDto.java | 1 |
请完成以下Java代码 | public void setUnlockAccount (final @Nullable java.lang.String UnlockAccount)
{
set_Value (COLUMNNAME_UnlockAccount, UnlockAccount);
}
@Override
public java.lang.String getUnlockAccount()
{
return get_ValueAsString(COLUMNNAME_UnlockAccount);
}
@Override
public void setUserPIN (final @Nullable java.lang.String UserPIN)
{
set_Value (COLUMNNAME_UserPIN, UserPIN);
}
@Override
public java.lang.String getUserPIN()
{ | return get_ValueAsString(COLUMNNAME_UserPIN);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User.java | 1 |
请完成以下Java代码 | public class DateFormType extends AbstractFormFieldType {
public final static String TYPE_NAME = "date";
protected String datePattern;
protected DateFormat dateFormat;
public DateFormType(String datePattern) {
this.datePattern = datePattern;
this.dateFormat = new SimpleDateFormat(datePattern);
}
public String getName() {
return TYPE_NAME;
}
public Object getInformation(String key) {
if ("datePattern".equals(key)) {
return datePattern;
}
return null;
}
public TypedValue convertToModelValue(TypedValue propertyValue) {
Object value = propertyValue.getValue();
if(value == null) {
return Variables.dateValue(null, propertyValue.isTransient());
}
else if(value instanceof Date) {
return Variables.dateValue((Date) value, propertyValue.isTransient());
}
else if(value instanceof String) {
String strValue = ((String) value).trim();
if (strValue.isEmpty()) {
return Variables.dateValue(null, propertyValue.isTransient());
}
try {
return Variables.dateValue((Date) dateFormat.parseObject(strValue), propertyValue.isTransient());
} catch (ParseException e) {
throw new ProcessEngineException("Could not parse value '"+value+"' as date using date format '"+datePattern+"'.");
}
}
else {
throw new ProcessEngineException("Value '"+value+"' cannot be transformed into a Date.");
}
}
public TypedValue convertToFormValue(TypedValue modelValue) {
if(modelValue.getValue() == null) {
return Variables.stringValue("", modelValue.isTransient());
} else if(modelValue.getType() == ValueType.DATE) {
return Variables.stringValue(dateFormat.format(modelValue.getValue()), modelValue.isTransient());
} | else {
throw new ProcessEngineException("Expected value to be of type '"+ValueType.DATE+"' but got '"+modelValue.getType()+"'.");
}
}
// deprecated //////////////////////////////////////////////////////////
public Object convertFormValueToModelValue(Object propertyValue) {
if (propertyValue==null || "".equals(propertyValue)) {
return null;
}
try {
return dateFormat.parseObject(propertyValue.toString());
} catch (ParseException e) {
throw new ProcessEngineException("invalid date value "+propertyValue);
}
}
public String convertModelValueToFormValue(Object modelValue) {
if (modelValue==null) {
return null;
}
return dateFormat.format(modelValue);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\DateFormType.java | 1 |
请完成以下Java代码 | public String toString()
{
final StringBuilder sb = new StringBuilder("SimpleMDAGNode{");
sb.append("letter=").append(letter);
sb.append(", isAcceptNode=").append(isAcceptNode);
sb.append(", transitionSetSize=").append(transitionSetSize);
sb.append(", transitionSetBeginIndex=").append(transitionSetBeginIndex);
sb.append('}');
return sb.toString();
}
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeChar(letter); | out.writeByte(isAcceptNode ? 1 : 0);
out.writeInt(transitionSetBeginIndex);
out.writeInt(transitionSetSize);
}
@Override
public boolean load(ByteArray byteArray)
{
letter = byteArray.nextChar();
isAcceptNode = byteArray.nextByte() == 1;
transitionSetBeginIndex = byteArray.nextInt();
transitionSetSize = byteArray.nextInt();
return true;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\SimpleMDAGNode.java | 1 |
请完成以下Java代码 | public void updatePaymentById(@NonNull POSPaymentId posPaymentId, @NonNull final UnaryOperator<POSPayment> updater)
{
final int paymentIdx = getPaymentIndexById(posPaymentId);
updatePaymentByIndex(paymentIdx, updater);
}
private void updatePaymentByIndex(final int paymentIndex, @NonNull final UnaryOperator<POSPayment> updater)
{
final POSPayment payment = paymentIndex >= 0 ? payments.get(paymentIndex) : null;
final POSPayment paymentChanged = updater.apply(payment);
if (paymentIndex >= 0)
{
payments.set(paymentIndex, paymentChanged);
}
else
{
payments.add(paymentChanged);
}
updateTotals();
}
private int getPaymentIndexById(final @NonNull POSPaymentId posPaymentId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentId.equals(payments.get(i).getLocalId(), posPaymentId))
{
return i;
}
}
throw new AdempiereException("No payment found for " + posPaymentId + " in " + payments);
}
private OptionalInt getPaymentIndexByExternalId(final @NonNull POSPaymentExternalId externalId)
{
for (int i = 0; i < payments.size(); i++)
{
if (POSPaymentExternalId.equals(payments.get(i).getExternalId(), externalId))
{
return OptionalInt.of(i);
} | }
return OptionalInt.empty();
}
public void removePaymentsIf(@NonNull final Predicate<POSPayment> predicate)
{
updateAllPayments(payment -> {
// skip payments marked as DELETED
if (payment.isDeleted())
{
return payment;
}
if (!predicate.test(payment))
{
return payment;
}
if (payment.isAllowDeleteFromDB())
{
payment.assertAllowDelete();
return null;
}
else
{
return payment.changingStatusToDeleted();
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrder.java | 1 |
请完成以下Java代码 | public String getInitiatorFunctionNameFQ()
{
for (final PerformanceMonitoringService.Metadata metadata : calledBy)
{
if (!metadata.isGroupingPlaceholder())
{
return metadata.getFunctionNameFQ();
}
}
return !calledBy.isEmpty() ? calledBy.get(0).getFunctionNameFQ() : "";
}
@Nullable
public String getLastCalledFunctionNameFQ()
{
if (calledBy.isEmpty())
{
return null;
}
else
{
return calledBy.get(calledBy.size() - 1).getFunctionNameFQ();
}
}
public String getInitiatorWindow()
{
final String windowName = !calledBy.isEmpty() ? calledBy.get(0).getWindowNameAndId() : "";
return windowName != null ? windowName : "NONE";
}
public boolean isInitiator() {return calledBy.isEmpty();}
public PerformanceMonitoringService.Type getEffectiveType(final PerformanceMonitoringService.Metadata metadata)
{
return !calledBy.isEmpty() ? calledBy.get(0).getType() : metadata.getType(); | }
public int getDepth() {return calledBy.size();}
public IAutoCloseable addCalledByIfNotNull(@Nullable final PerformanceMonitoringService.Metadata metadata)
{
if (metadata == null)
{
return () -> {};
}
final int sizeBeforeAdd = calledBy.size();
calledBy.add(metadata);
return () -> {
while (calledBy.size() > sizeBeforeAdd)
{
calledBy.remove(calledBy.size() - 1);
}
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\PerformanceMonitoringData.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UnapdatableBook {
@Id
@GeneratedValue
private Long id;
@Column(updatable = false)
private String title;
private String author;
public UnapdatableBook() {
}
public UnapdatableBook(String title, String author) {
this.title = title;
this.author = author;
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
} | public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo-4\src\main\java\com\baeldung\spring\insertableonly\unpadatable\UnapdatableBook.java | 2 |
请完成以下Java代码 | public void deleteForItem(final I_M_HU_PI_Item packingInstructionsItem)
{
final List<I_M_HU_PI_Item_Product> products = huPIItemProductDAO.retrievePIMaterialItemProducts(packingInstructionsItem);
for (final I_M_HU_PI_Item_Product product : products)
{
InterfaceWrapperHelper.delete(product);
}
}
@Override
public void setNameAndDescription(final I_M_HU_PI_Item_Product itemProduct)
{
//
// Build itemProduct's name from scratch
final String nameBuilt = buildDisplayName()
.setM_HU_PI_Item_Product(itemProduct)
.buildItemProductDisplayName(); // build it from scratch
// Set it as Name and Description
itemProduct.setName(nameBuilt);
itemProduct.setDescription(nameBuilt);
}
@Override
public IHUPIItemProductDisplayNameBuilder buildDisplayName()
{
return new HUPIItemProductDisplayNameBuilder();
}
@Override
public ITranslatableString getDisplayName(@NonNull final HUPIItemProductId piItemProductId)
{
return huPIItemProductDAO.getById(piItemProductId).getName();
}
@Nullable
public I_M_HU_PI_Item_Product getDefaultForProduct(@NonNull final ProductId productId, @NonNull final ZonedDateTime dateTime)
{
return huPIItemProductDAO.retrieveDefaultForProduct(productId, dateTime);
}
@NonNull
public I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine) | {
final HUPIItemProductId hupiItemProductId = HUPIItemProductId.ofRepoIdOrNull(orderLine.getM_HU_PI_Item_Product_ID());
if (hupiItemProductId != null)
{
return huPIItemProductDAO.getRecordById(hupiItemProductId);
}
else
{
final ProductId productId = ProductId.ofRepoId(orderLine.getM_Product_ID());
final BPartnerId buyerBPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
return huPIItemProductDAO.retrieveMaterialItemProduct(
productId,
buyerBPartnerId,
TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone),
X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true/* allowInfiniteCapacity */);
}
}
@Override
public int getRequiredLUCount(final @NonNull Quantity qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM)
{
if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
return 1;
}
else
{
// Note need to use the StockQty because lutuConfigurationInStockUOM is also in stock-UOM.
// And in the case of catchweight, it's very important to *not* make metasfresh convert quantites using the UOM-conversion
return lutuConfigurationFactory.calculateQtyLUForTotalQtyCUs(
lutuConfigurationInStockUOM,
qty);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductBL.java | 1 |
请完成以下Java代码 | public static <T> boolean elementIsContainedInArray(T element, T... values) {
if (element != null && values != null) {
return elementIsContainedInList(element, Arrays.asList(values));
}
else {
return false;
}
}
/**
* Returns any element if obj1.compareTo(obj2) == 0
*/
public static <T extends Comparable<T>> T min(T obj1, T obj2) {
return obj1.compareTo(obj2) <= 0 ? obj1 : obj2;
} | /**
* Returns any element if obj1.compareTo(obj2) == 0
*/
public static <T extends Comparable<T>> T max(T obj1, T obj2) {
return obj1.compareTo(obj2) >= 0 ? obj1 : obj2;
}
public static <T> boolean elementsAreContainedInArray(Collection<T> subset, T[] superset) {
if (subset != null && !subset.isEmpty() && superset != null && superset.length > 0 && superset.length >= subset.size()) {
return new HashSet<>(Arrays.asList(superset)).containsAll(subset);
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CompareUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getSenderID() {
return senderID;
}
/**
* Sets the value of the senderID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSenderID(String value) {
this.senderID = value;
}
/**
* Gets the value of the recipientID property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRecipientID() {
return recipientID;
}
/**
* Sets the value of the recipientID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRecipientID(String value) {
this.recipientID = value;
}
/**
* Gets the value of the interchangeRef property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInterchangeRef() {
return interchangeRef;
}
/**
* Sets the value of the interchangeRef property.
*
* @param value
* allowed object is
* {@link String } | *
*/
public void setInterchangeRef(String value) {
this.interchangeRef = value;
}
/**
* Gets the value of the dateTime property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateTime() {
return dateTime;
}
/**
* Sets the value of the dateTime property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateTime(XMLGregorianCalendar value) {
this.dateTime = value;
}
/**
* Gets the value of the testIndicator property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTestIndicator() {
return testIndicator;
}
/**
* Sets the value of the testIndicator property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTestIndicator(String value) {
this.testIndicator = value;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIMessage.java | 2 |
请完成以下Java代码 | public static InvoiceCandidateIdsSelection ofIdsSet(@NonNull final Set<InvoiceCandidateId> ids)
{
return !ids.isEmpty()
? new InvoiceCandidateIdsSelection(null, ImmutableSet.copyOf(ids))
: EMPTY;
}
public static InvoiceCandidateIdsSelection extractFixedIdsSet(@NonNull final Iterable<? extends I_C_Invoice_Candidate> invoiceCandidates)
{
final ImmutableSet.Builder<InvoiceCandidateId> ids = ImmutableSet.builder();
for (final I_C_Invoice_Candidate ic : invoiceCandidates)
{
final InvoiceCandidateId id = InvoiceCandidateId.ofRepoIdOrNull(ic.getC_Invoice_Candidate_ID());
if (id != null)
{
ids.add(id);
}
}
return ofIdsSet(ids.build());
}
@Nullable private final PInstanceId selectionId;
@Nullable private final ImmutableSet<InvoiceCandidateId> ids;
private InvoiceCandidateIdsSelection(
@Nullable final PInstanceId selectionId,
@Nullable final ImmutableSet<InvoiceCandidateId> ids)
{
if (CoalesceUtil.countNotNulls(selectionId, ids) != 1)
{
throw new AdempiereException("Only `selectionId` or only `ids` can be set, but not both")
.appendParametersToMessage()
.setParameter("selectionId", selectionId)
.setParameter("ids", ids);
} | this.selectionId = selectionId;
this.ids = ids;
}
public boolean isEmpty() {return selectionId == null && (ids == null || ids.isEmpty());}
public boolean isDatabaseSelection()
{
return selectionId != null;
}
public interface CaseMapper
{
void empty();
void fixedSet(@NonNull ImmutableSet<InvoiceCandidateId> ids);
void selectionId(@NonNull PInstanceId selectionId);
}
public void apply(@NonNull final CaseMapper mapper)
{
if (selectionId != null)
{
mapper.selectionId(selectionId);
}
else if (ids != null && !ids.isEmpty())
{
mapper.fixedSet(ids);
}
else
{
mapper.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\InvoiceCandidateIdsSelection.java | 1 |
请完成以下Java代码 | public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM)
{
set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM);
}
@Override
public BigDecimal getQtyEnteredInPriceUOM()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JobDetailFactoryBean executeJobDetail() {
return createJobDetail(InvokingJobDetailFactory.class, GROUP_NAME, "executeJob");
}
/**
* 执行规则job工厂
*
* 配置job 类中需要定时执行的 方法 execute
* @param jobClass
* @param groupName
* @param targetObject
* @return
*/
private static JobDetailFactoryBean createJobDetail(Class<? extends Job> jobClass, | String groupName,
String targetObject) {
JobDetailFactoryBean factoryBean = new JobDetailFactoryBean();
factoryBean.setJobClass(jobClass);
factoryBean.setDurability(true);
factoryBean.setRequestsRecovery(true);
factoryBean.setGroup(groupName);
Map<String, String> map = new HashMap<>();
map.put("targetMethod", "execute");
map.put("targetObject", targetObject);
factoryBean.setJobDataAsMap(map);
return factoryBean;
}
} | repos\springBoot-master\springboot-Quartz\src\main\java\com\abel\quartz\config\QuartzConfig.java | 2 |
请完成以下Java代码 | public class FlowableChangeTenantIdEventImpl extends FlowableEventImpl implements FlowableChangeTenantIdEvent {
protected String engineScopeType;
protected String sourceTenantId;
protected String targetTenantId;
protected String definitionTenantId;
public FlowableChangeTenantIdEventImpl(String engineScopeType, String sourceTenantId, String targetTenantId, String definitionTenantId) {
super(FlowableEngineEventType.CHANGE_TENANT_ID);
this.engineScopeType = engineScopeType;
this.sourceTenantId = sourceTenantId;
this.targetTenantId = targetTenantId;
this.definitionTenantId = definitionTenantId;
}
@Override
public String getEngineScopeType() {
return engineScopeType;
} | @Override
public String getSourceTenantId() {
return sourceTenantId;
}
@Override
public String getTargetTenantId() {
return targetTenantId;
}
@Override
public String getDefinitionTenantId() {
return definitionTenantId;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableChangeTenantIdEventImpl.java | 1 |
请完成以下Java代码 | public IStringExpression getExpressionBaseLang()
{
return expressionBaseLang;
}
public IStringExpression getExpressionTrl()
{
return expressionTrl;
}
public String getAD_LanguageParamName()
{
return adLanguageParam.getName();
}
@Override
public String getExpressionString()
{
return expressionBaseLang.getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return expressionBaseLang.getFormatedExpressionString();
}
@Override
public Set<CtxName> getParameters()
{
return parameters;
}
@Override
public String evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
try
{
//
// Evaluate the adLanguage parameter
final OnVariableNotFound adLanguageOnVariableNoFound = getOnVariableNotFoundForInternalParameter(onVariableNotFound);
final String adLanguage = StringExpressionsHelper.evaluateParam(adLanguageParam, ctx, adLanguageOnVariableNoFound);
if (adLanguage == null || adLanguage == IStringExpression.EMPTY_RESULT)
{
return IStringExpression.EMPTY_RESULT;
}
else if (adLanguage.isEmpty() && onVariableNotFound == OnVariableNotFound.Empty)
{
return "";
}
final IStringExpression expressionEffective;
if (Language.isBaseLanguage(adLanguage))
{
expressionEffective = expressionBaseLang;
}
else
{
expressionEffective = expressionTrl;
}
return expressionEffective.evaluate(ctx, onVariableNotFound);
} | catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
private static final OnVariableNotFound getOnVariableNotFoundForInternalParameter(final OnVariableNotFound onVariableNotFound)
{
switch (onVariableNotFound)
{
case Preserve:
// Preserve is not supported because we don't know which expression to pick if the deciding parameter is not determined
return OnVariableNotFound.Fail;
default:
return onVariableNotFound;
}
}
@Override
public IStringExpression resolvePartial(final Evaluatee ctx)
{
try
{
boolean changed = false;
final IStringExpression expressionBaseLangNew = expressionBaseLang.resolvePartial(ctx);
if (!expressionBaseLang.equals(expressionBaseLangNew))
{
changed = true;
}
final IStringExpression expressionTrlNew = expressionTrl.resolvePartial(Evaluatees.excludingVariables(ctx, adLanguageParam.getName()));
if (!changed && !expressionTrl.equals(expressionTrlNew))
{
changed = true;
}
if (!changed)
{
return this;
}
return new TranslatableParameterizedStringExpression(adLanguageParam, expressionBaseLangNew, expressionTrlNew);
}
catch (final Exception e)
{
throw ExpressionEvaluationException.wrapIfNeeded(e)
.addExpression(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\TranslatableParameterizedStringExpression.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Map<String, Boolean> getCommunicationPreferences() {
return communicationPreferences;
}
public void setCommunicationPreferences(Map<String, Boolean> communicationPreferences) {
this.communicationPreferences = communicationPreferences;
}
public List<String> getFavorites() {
return favorites;
}
public void setFavorites(List<String> favorites) {
this.favorites = favorites;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Customer)) {
return false;
}
Customer customer = (Customer) o;
return Objects.equals(id, customer.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\model\Customer.java | 1 |
请完成以下Java代码 | public void applyTo(final Fact fact)
{
if (!hasChangesToApply())
{
return;
}
applyUpdatesTo(fact);
addLinesTo(fact);
}
public void applyUpdatesTo(final Fact fact)
{
fact.mapEachLine(this::applyTo);
}
private FactLine applyTo(@NonNull final FactLine factLine)
{
final FactLineMatchKey matchKey = FactLineMatchKey.ofFactLine(factLine);
//
// Remove line
final FactAcctChanges remove = linesToRemoveByKey.remove(matchKey);
if (remove != null)
{
return null; // consider line removed
}
//
// Change line
else
{
final FactAcctChanges change = linesToChangeByKey.remove(matchKey);
if (change != null)
{
factLine.updateFrom(change);
}
return factLine;
}
} | private void addLinesTo(@NonNull final Fact fact)
{
final AcctSchemaId acctSchemaId = fact.getAcctSchemaId();
final List<FactAcctChanges> additions = linesToAddGroupedByAcctSchemaId.removeAll(acctSchemaId);
additions.forEach(addition -> addLine(fact, addition));
}
public void addLine(@NonNull final Fact fact, @NonNull final FactAcctChanges changesToAdd)
{
if (!changesToAdd.getType().isAdd())
{
throw new AdempiereException("Expected type `Add` but it was " + changesToAdd);
}
final FactLine factLine = fact.createLine()
.alsoAddZeroLine()
.setAccount(changesToAdd.getAccountIdNotNull())
.setAmtSource(changesToAdd.getAmtSourceDr(), changesToAdd.getAmtSourceCr())
.setAmtAcct(changesToAdd.getAmtAcctDr(), changesToAdd.getAmtAcctCr())
.setC_Tax_ID(changesToAdd.getTaxId())
.description(changesToAdd.getDescription())
.productId(changesToAdd.getProductId())
.userElementString1(changesToAdd.getUserElementString1())
.salesOrderId(changesToAdd.getSalesOrderId())
.activityId(changesToAdd.getActivityId())
.buildAndAdd();
if (factLine != null)
{
factLine.updateFrom(changesToAdd); // just to have appliedUserChanges set
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChangesApplier.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((accountNumber == null) ? 0 : accountNumber.hashCode());
result = prime * result + ((accountType == null) ? 0 : accountType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass()) | return false;
AccountId other = (AccountId) obj;
if (accountNumber == null) {
if (other.accountNumber != null)
return false;
} else if (!accountNumber.equals(other.accountNumber))
return false;
if (accountType == null) {
if (other.accountType != null)
return false;
} else if (!accountType.equals(other.accountType))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\primarykeys\AccountId.java | 1 |
请完成以下Java代码 | public static PemContent load(Path path) throws IOException {
Assert.notNull(path, "'path' must not be null");
try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ)) {
return load(in);
}
}
/**
* Load {@link PemContent} from the given {@link InputStream}.
* @param in an input stream to load the content from
* @return the loaded PEM content
* @throws IOException on IO error
*/
public static PemContent load(InputStream in) throws IOException {
return of(StreamUtils.copyToString(in, StandardCharsets.UTF_8));
}
/** | * Return a new {@link PemContent} instance containing the given text.
* @param text the text containing PEM encoded content
* @return a new {@link PemContent} instance
*/
@Contract("!null -> !null")
public static @Nullable PemContent of(@Nullable String text) {
return (text != null) ? new PemContent(text) : null;
}
/**
* Return if PEM content is present in the given text.
* @param text the text to check
* @return if the text includes PEM encoded content.
*/
public static boolean isPresentInText(@Nullable String text) {
return text != null && PEM_HEADER.matcher(text).find() && PEM_FOOTER.matcher(text).find();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\pem\PemContent.java | 1 |
请完成以下Java代码 | public class ReferredDocumentInformation7 {
@XmlElement(name = "Tp")
protected ReferredDocumentType4 tp;
@XmlElement(name = "Nb")
protected String nb;
@XmlElement(name = "RltdDt")
@XmlSchemaType(name = "date")
protected XMLGregorianCalendar rltdDt;
@XmlElement(name = "LineDtls")
protected List<DocumentLineInformation1> lineDtls;
/**
* Gets the value of the tp property.
*
* @return
* possible object is
* {@link ReferredDocumentType4 }
*
*/
public ReferredDocumentType4 getTp() {
return tp;
}
/**
* Sets the value of the tp property.
*
* @param value
* allowed object is
* {@link ReferredDocumentType4 }
*
*/
public void setTp(ReferredDocumentType4 value) {
this.tp = value;
}
/**
* Gets the value of the nb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNb() {
return nb;
}
/**
* Sets the value of the nb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNb(String value) {
this.nb = value;
}
/**
* Gets the value of the rltdDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getRltdDt() {
return rltdDt;
} | /**
* Sets the value of the rltdDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setRltdDt(XMLGregorianCalendar value) {
this.rltdDt = value;
}
/**
* Gets the value of the lineDtls property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineDtls property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineDtls().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentLineInformation1 }
*
*
*/
public List<DocumentLineInformation1> getLineDtls() {
if (lineDtls == null) {
lineDtls = new ArrayList<DocumentLineInformation1>();
}
return this.lineDtls;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\ReferredDocumentInformation7.java | 1 |
请完成以下Java代码 | private @NonNull I_C_OrderLine fromOrderLineCandidate(final @NonNull OrderLineCandidate candidate, @NonNull final I_C_OrderLine bomSalesOrderLine)
{
final I_C_OrderLine newOrderLine = InterfaceWrapperHelper.newInstance(I_C_OrderLine.class, bomSalesOrderLine);
PO.copyValues((X_C_OrderLine)bomSalesOrderLine, (X_C_OrderLine)newOrderLine);
newOrderLine.setM_Product_ID(candidate.getProductId().getRepoId());
newOrderLine.setC_UOM_ID(candidate.getQty().getUomId().getRepoId());
newOrderLine.setQtyOrdered(candidate.getQty().toBigDecimal());
newOrderLine.setQtyReserved(candidate.getQty().toBigDecimal());
if (candidate.getBestBeforePolicy() != null)
{
newOrderLine.setShipmentAllocation_BestBefore_Policy(candidate.getBestBeforePolicy().getCode());
}
newOrderLine.setM_AttributeSetInstance_ID(AttributeSetInstanceId.NONE.getRepoId());
newOrderLine.setExplodedFrom_BOMLine_ID(candidate.getExplodedFromBOMLineId().getRepoId());
final GroupId compensationGroupId = candidate.getCompensationGroupId(); | if (compensationGroupId != null)
{
final Group group = orderGroupsRepo.retrieveGroupIfExists(compensationGroupId);
final ActivityId groupActivityId = group == null ? null : group.getActivityId();
newOrderLine.setC_Order_CompensationGroup_ID(compensationGroupId.getOrderCompensationGroupId());
newOrderLine.setC_Activity_ID(ActivityId.toRepoId(groupActivityId));
}
//needed to know to what SO line the resulting PO Lines should be allocated to
newOrderLine.setC_OrderLine_ID(bomSalesOrderLine.getC_OrderLine_ID());
return newOrderLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreatePOFromSOs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserResourceRepository implements ResourceRepositoryV2<User, Long> {
@Autowired
private UserRepository userRepository;
@Override
public User findOne(Long id, QuerySpec querySpec) {
Optional<User> user = userRepository.findById(id);
return user.isPresent()? user.get() : null;
}
@Override
public ResourceList<User> findAll(QuerySpec querySpec) {
return querySpec.apply(userRepository.findAll());
}
@Override
public ResourceList<User> findAll(Iterable<Long> ids, QuerySpec querySpec) {
return querySpec.apply(userRepository.findAllById(ids));
}
@Override
public <S extends User> S save(S entity) {
return userRepository.save(entity);
} | @Override
public void delete(Long id) {
userRepository.deleteById(id);
}
@Override
public Class<User> getResourceClass() {
return User.class;
}
@Override
public <S extends User> S create(S entity) {
return save(entity);
}
} | repos\tutorials-master\spring-katharsis\src\main\java\com\baeldung\persistence\katharsis\UserResourceRepository.java | 2 |
请完成以下Java代码 | public final class FilterWarehouseByDocTypeValidationRule extends AbstractJavaValidationRule
{
public static final transient FilterWarehouseByDocTypeValidationRule instance = new FilterWarehouseByDocTypeValidationRule();
private static final String COLUMNNAME_C_DocType_ID = "C_DocType_ID";
private static final String COLUMNNAME_C_DocTypeTarget_ID = "C_DocTypeTarget_ID";
private static final Set<String> PARAMS = ImmutableSet.of(COLUMNNAME_C_DocType_ID, COLUMNNAME_C_DocTypeTarget_ID);
private FilterWarehouseByDocTypeValidationRule()
{
}
@Override
public boolean accept(
@NonNull final IValidationContext evalCtx,
final NamePair item)
{
if (null == item)
{
// Should never happen.
return false;
}
final String docType = evalCtx.get_ValueAsString(COLUMNNAME_C_DocType_ID);
final String docTypeTarget = evalCtx.get_ValueAsString(COLUMNNAME_C_DocTypeTarget_ID);
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(StringUtils.toIntegerOrZero(docType));
final DocTypeId docTypeTargetId = DocTypeId.ofRepoIdOrNull(StringUtils.toIntegerOrZero(docTypeTarget));
if (docTypeId == null && docTypeTargetId == null)
{
// Not a document. All warehouses available.
return true;
}
final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(NumberUtils.asInt(item.getID(), -1));
Check.assumeNotNull(warehouseId, "Invalid warehouse {}", item.getID());
// Check if we have any available doc types assigned to our warehouse.
// If not, we shall accept this warehouse right away (task 09301).
// As soon as there is assigned at least on doc type, we will enforce the restrictions. | final IWarehouseDAO warehousesRepo = Services.get(IWarehouseDAO.class);
if (warehousesRepo.isAllowAnyDocType(warehouseId))
{
return true; // no restrictions defined => accept this warehouse
}
// First check for doc type.
if (docTypeId != null)
{
final String docBaseType = Services.get(IDocTypeDAO.class).getById(docTypeId).getDocBaseType();
return warehousesRepo.isDocTypeAllowed(warehouseId, docBaseType);
}
// For orders, also check doc type target
if (docTypeTargetId != null)
{
final String docBaseType = Services.get(IDocTypeDAO.class).getById(docTypeTargetId).getDocBaseType();
return warehousesRepo.isDocTypeAllowed(warehouseId, docBaseType);
}
return false;
}
@Override
public Set<String> getParameters(@Nullable final String contextTableName)
{
return PARAMS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\validationrule\FilterWarehouseByDocTypeValidationRule.java | 1 |
请完成以下Java代码 | public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
Object delegate = resolveDelegateExpression(expression, execution, fieldExtensions);
if (delegate instanceof HttpResponseHandler) {
((HttpResponseHandler) delegate).handleHttpResponse(execution, httpResponse);
} else {
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpResponseHandler.class);
}
}
/**
* returns the expression text for this execution listener. Comes in handy if you want to check which listeners you already have.
*/
public String getExpressionText() {
return expression.getExpressionText();
}
public static Object resolveDelegateExpression(Expression expression,
VariableContainer variableScope, List<FieldExtension> fieldExtensions) {
// Note: we can't cache the result of the expression, because the
// execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
Object delegate = expression.getValue(variableScope); | if (fieldExtensions != null && fieldExtensions.size() > 0) {
DelegateExpressionFieldInjectionMode injectionMode = CommandContextUtil.getCmmnEngineConfiguration().getDelegateExpressionFieldInjectionMode();
if (injectionMode == DelegateExpressionFieldInjectionMode.COMPATIBILITY) {
CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, true);
} else if (injectionMode == DelegateExpressionFieldInjectionMode.MIXED) {
CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, false);
}
}
return delegate;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\http\handler\DelegateExpressionHttpHandler.java | 1 |
请完成以下Java代码 | public final class ETag
{
public static final ETag of(final int version)
{
return new ETag(version, ImmutableMap.of());
}
public static final ETag of(final long version, final Map<String, String> attributes)
{
return new ETag(version, ImmutableMap.copyOf(attributes));
}
private final long version;
private final ImmutableMap<String, String> attributes;
private transient volatile String _etagString = null; // lazy
private ETag(final long version, final ImmutableMap<String, String> attributes)
{
this.version = version;
this.attributes = attributes;
}
@Override
public String toString()
{
return toETagString();
}
public String toETagString()
{
String etagString = _etagString;
if (etagString == null)
{
_etagString = etagString = buildETagString();
}
return etagString;
}
private String buildETagString()
{
final StringBuilder etagString = new StringBuilder();
etagString.append("v=").append(version);
if (!attributes.isEmpty())
{ | final String attributesStr = attributes.entrySet()
.stream()
.sorted(Comparator.comparing(entry -> entry.getKey()))
.map(entry -> entry.getKey() + "=" + entry.getValue())
.collect(Collectors.joining("#"));
etagString.append("#").append(attributesStr);
}
return etagString.toString();
}
public final ETag overridingAttributes(final Map<String, String> overridingAttributes)
{
if (overridingAttributes.isEmpty())
{
return this;
}
if (attributes.isEmpty())
{
return new ETag(version, ImmutableMap.copyOf(overridingAttributes));
}
final Map<String, String> newAttributes = new HashMap<>(attributes);
newAttributes.putAll(overridingAttributes);
return new ETag(version, ImmutableMap.copyOf(newAttributes));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\cache\ETag.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
}
public void setModificationBuilder(ProcessInstanceModificationBuilderImpl modificationBuilder) {
this.modificationBuilder = modificationBuilder;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId){
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
public String getRestartedProcessInstanceId(){ | return restartedProcessInstanceId;
}
public static ProcessInstantiationBuilder createProcessInstanceById(CommandExecutor commandExecutor, String processDefinitionId) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionId = processDefinitionId;
return builder;
}
public static ProcessInstantiationBuilder createProcessInstanceByKey(CommandExecutor commandExecutor, String processDefinitionKey) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionKey = processDefinitionKey;
return builder;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstantiationBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EcommerceWebSecurityConfig {
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("spring")
.password(passwordEncoder.encode("secret"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http.addFilterAfter(new AuditInterceptor(), AnonymousAuthenticationFilter.class)
.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/private/**")) | .authenticated())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/public/showProducts"))
.permitAll())
.authorizeHttpRequests(request -> request.requestMatchers(new AntPathRequestMatcher("/public/registerUser"))
.anonymous())
.build();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-security-2\src\main\java\com\baeldung\permitallanonymous\security\EcommerceWebSecurityConfig.java | 2 |
请完成以下Java代码 | public String toString()
{
return getSQL(null);
}
public boolean isJoinAnd()
{
return joinAnd;
}
public String getColumnName()
{
return columnName;
}
/* package */void setColumnName(final String columnName)
{
this.columnName = columnName;
}
/**
* Get Info Name
*
* @return Info Name
*/
public String getInfoName()
{
return infoName;
} // getInfoName
public Operator getOperator()
{
return operator;
}
/**
* Get Info Operator
*
* @return info Operator
*/
public String getInfoOperator()
{
return operator == null ? null : operator.getCaption();
} // getInfoOperator
/**
* Get Display with optional To
* | * @return info display
*/
public String getInfoDisplayAll()
{
if (infoDisplayTo == null)
{
return infoDisplay;
}
StringBuilder sb = new StringBuilder(infoDisplay);
sb.append(" - ").append(infoDisplayTo);
return sb.toString();
} // getInfoDisplay
public Object getCode()
{
return code;
}
public String getInfoDisplay()
{
return infoDisplay;
}
public Object getCodeTo()
{
return codeTo;
}
public String getInfoDisplayTo()
{
return infoDisplayTo;
}
} // Restriction | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MQuery.java | 1 |
请完成以下Java代码 | public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Java Class.
@param JavaClass Java Class */
public void setJavaClass (String JavaClass)
{
set_Value (COLUMNNAME_JavaClass, JavaClass);
}
/** Get Java Class.
@return Java Class */
public String getJavaClass ()
{
return (String)get_Value(COLUMNNAME_JavaClass);
}
/** 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);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_Processor_Type.java | 1 |
请完成以下Java代码 | public class ExtensionElement extends BaseElement {
protected String name;
protected String namespacePrefix;
protected String namespace;
protected String elementText;
protected Map<String, List<ExtensionElement>> childElements = new LinkedHashMap<>();
public String getElementText() {
return elementText;
}
public void setElementText(String elementText) {
this.elementText = elementText;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNamespacePrefix() {
return namespacePrefix;
}
public void setNamespacePrefix(String namespacePrefix) {
this.namespacePrefix = namespacePrefix;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public Map<String, List<ExtensionElement>> getChildElements() {
return childElements;
}
public void addChildElement(ExtensionElement childElement) {
if (childElement != null && StringUtils.isNotEmpty(childElement.getName())) {
List<ExtensionElement> elementList = null;
if (!this.childElements.containsKey(childElement.getName())) {
elementList = new ArrayList<>();
this.childElements.put(childElement.getName(), elementList);
}
this.childElements.get(childElement.getName()).add(childElement); | }
}
public void setChildElements(Map<String, List<ExtensionElement>> childElements) {
this.childElements = childElements;
}
@Override
public ExtensionElement clone() {
ExtensionElement clone = new ExtensionElement();
clone.setValues(this);
return clone;
}
public void setValues(ExtensionElement otherElement) {
super.setValues(otherElement);
setName(otherElement.getName());
setNamespacePrefix(otherElement.getNamespacePrefix());
setNamespace(otherElement.getNamespace());
setElementText(otherElement.getElementText());
childElements = new LinkedHashMap<>();
if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) {
for (String key : otherElement.getChildElements().keySet()) {
List<ExtensionElement> otherElementList = otherElement.getChildElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<ExtensionElement> elementList = new ArrayList<>();
for (ExtensionElement extensionElement : otherElementList) {
elementList.add(extensionElement.clone());
}
childElements.put(key, elementList);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ExtensionElement.java | 1 |
请完成以下Java代码 | public Message<?> changeMessageToUserName(Message<?> message) {
return buildNewMessage(getUsername(), message);
}
@Bean(name = "finalPSResult")
public DirectChannel finalPSResult() {
return new DirectChannel();
}
@Bean
@GlobalChannelInterceptor(patterns = { "startPSChannel", "endDirectChannel" })
public ChannelInterceptor securityContextPropagationInterceptor() {
return new SecurityContextPropagationChannelInterceptor();
}
@Bean
public ThreadPoolTaskExecutor executor() {
ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
pool.setCorePoolSize(10);
pool.setMaxPoolSize(10);
pool.setWaitForTasksToCompleteOnShutdown(true);
return pool;
}
public String getRoles() { | SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(","));
}
public String getUsername() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return securityContext.getAuthentication().getName();
}
public Message<String> buildNewMessage(String content, Message<?> message) {
DefaultMessageBuilderFactory builderFactory = new DefaultMessageBuilderFactory();
MessageBuilder<String> messageBuilder = builderFactory.withPayload(content);
messageBuilder.copyHeaders(message.getHeaders());
return messageBuilder.build();
}
} | repos\tutorials-master\spring-integration\src\main\java\com\baeldung\si\security\SecurityPubSubChannel.java | 1 |
请完成以下Java代码 | class MySqlJdbcDockerComposeConnectionDetailsFactory
extends DockerComposeConnectionDetailsFactory<JdbcConnectionDetails> {
protected MySqlJdbcDockerComposeConnectionDetailsFactory() {
super("mysql");
}
@Override
protected JdbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) {
return new MySqlJdbcDockerComposeConnectionDetails(source.getRunningService());
}
/**
* {@link JdbcConnectionDetails} backed by a {@code mysql} {@link RunningService}.
*/
static class MySqlJdbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements JdbcConnectionDetails {
private static final JdbcUrlBuilder jdbcUrlBuilder = new JdbcUrlBuilder("mysql", 3306);
private final MySqlEnvironment environment;
private final String jdbcUrl;
MySqlJdbcDockerComposeConnectionDetails(RunningService service) {
super(service);
this.environment = new MySqlEnvironment(service.env());
this.jdbcUrl = jdbcUrlBuilder.build(service, this.environment.getDatabase());
} | @Override
public String getUsername() {
return this.environment.getUsername();
}
@Override
public String getPassword() {
return this.environment.getPassword();
}
@Override
public String getJdbcUrl() {
return this.jdbcUrl;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\docker\compose\MySqlJdbcDockerComposeConnectionDetailsFactory.java | 1 |
请完成以下Java代码 | public void setPeriodStatus (String PeriodStatus)
{
set_Value (COLUMNNAME_PeriodStatus, PeriodStatus);
}
/** Get Period Status.
@return Current state of this period
*/
public String getPeriodStatus ()
{
return (String)get_Value(COLUMNNAME_PeriodStatus);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Period.java | 1 |
请完成以下Java代码 | public class CommentGenerator {
private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
private static final Random RANDOM = new Random(System.currentTimeMillis());
private static final List<String> COMMENT_AUTHOR =
Arrays.asList(
"Mkyong", "Oliver", "Jack", "Harry", "Jacob",
"Isla", "Emily", "Poppy", "Ava", "Isabella");
private static final List<String> COMMENT_MESSAGE =
Arrays.asList(
"I Love this!",
"Me too!",
"Wow",
"True!", | "Hello everyone here?",
"Good!");
public static String randomAuthor() {
return COMMENT_AUTHOR.get(RANDOM.nextInt(COMMENT_AUTHOR.size()));
}
public static String randomMessage() {
return COMMENT_MESSAGE.get(RANDOM.nextInt(COMMENT_MESSAGE.size()));
}
public static String getCurrentTimeStamp() {
return dtf.format(LocalDateTime.now());
}
} | repos\spring-boot-master\webflux-thymeleaf-serversentevent\src\main\java\com\mkyong\reactive\utils\CommentGenerator.java | 1 |
请完成以下Java代码 | public class CustomCollector<T, R> {
private final List<R> results = new ArrayList<>();
private final List<Throwable> exceptions = new ArrayList<>();
public static <T, R> Collector<T, ?, CustomCollector<T, R>> of(Function<T, R> mapper) {
return Collector.of(
CustomCollector::new,
(collector, item) -> {
try {
R result = mapper.apply(item);
collector.results.add(result);
} catch (Exception e) {
collector.exceptions.add(e);
}
}, | (left, right) -> {
left.results.addAll(right.results);
left.exceptions.addAll(right.exceptions);
return left;
}
);
}
public List<R> getResults() {
return results;
}
public List<Throwable> getExceptions() {
return exceptions;
}
} | repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\aggregateexception\CustomCollector.java | 1 |
请完成以下Java代码 | public String getMessagingSid() {
return messagingSid;
}
public void setMessagingSid(String messagingSid) {
this.messagingSid = messagingSid;
}
public NewArticleNotification getNewArticleNotification() {
return newArticleNotification;
}
public void setNewArticleNotification(NewArticleNotification newArticleNotification) {
this.newArticleNotification = newArticleNotification;
}
public class NewArticleNotification { | @NotBlank(message = "Content SID must be configured")
@Pattern(regexp = "^HX[0-9a-fA-F]{32}$", message = "Invalid content SID format")
private String contentSid;
public String getContentSid() {
return contentSid;
}
public void setContentSid(String contentSid) {
this.contentSid = contentSid;
}
}
} | repos\tutorials-master\saas-modules\twilio-whatsapp\src\main\java\com\baeldung\twilio\whatsapp\TwilioConfigurationProperties.java | 1 |
请完成以下Java代码 | public void setIncluded_Role_ID (int Included_Role_ID)
{
if (Included_Role_ID < 1)
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Included_Role_ID, Integer.valueOf(Included_Role_ID));
}
/** Get Included Role.
@return Included Role */
@Override
public int getIncluded_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/ | @Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Role_Included.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private DataBuffer rewritedBodyToDataBuffer() {
if (isZippedResponse()) {
byte[] zippedBody = zipContent(rewritedBody);
originalResponse.getHeaders().setContentLength(zippedBody.length);
return bufferFactory.wrap(zippedBody);
}
originalResponse.getHeaders().setContentLength(rewritedBody.getBytes().length);
return bufferFactory.wrap(rewritedBody.getBytes());
}
private String contentToString(byte[] content) {
if (isZippedResponse()) {
byte[] unzippedContent = unzipContent(content);
return new String(unzippedContent, StandardCharsets.UTF_8);
}
return new String(content, StandardCharsets.UTF_8);
}
private boolean isZippedResponse() {
return (
!originalResponse.getHeaders().isEmpty() &&
originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING) != null &&
Objects.requireNonNull(originalResponse.getHeaders().get(HttpHeaders.CONTENT_ENCODING)).contains("gzip")
);
}
private byte[] unzipContent(byte[] content) {
try {
GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(content));
byte[] unzippedContent = gzipInputStream.readAllBytes();
gzipInputStream.close();
return unzippedContent;
} catch (IOException e) {
log.error("Error when unzip content during modify servers from api-doc of {}: {}", path, e.getMessage()); | }
return content;
}
private byte[] zipContent(String content) {
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(content.length());
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(content.getBytes(StandardCharsets.UTF_8));
gzipOutputStream.flush();
gzipOutputStream.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
log.error("Error when zip content during modify servers from api-doc of {}: {}", path, e.getMessage());
}
return content.getBytes();
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\filter\ModifyServersOpenApiFilter.java | 2 |
请完成以下Java代码 | public CallOrderSummary update(@NonNull final CallOrderSummary callOrderSummary)
{
final I_C_CallOrderSummary record = InterfaceWrapperHelper.load(callOrderSummary.getSummaryId(), I_C_CallOrderSummary.class);
setSummaryDataToRecord(record, callOrderSummary.getSummaryData());
save(record);
return ofRecord(record);
}
private static void setSummaryDataToRecord(@NonNull final I_C_CallOrderSummary record, @NonNull final CallOrderSummaryData callOrderSummaryData)
{
record.setC_Order_ID(callOrderSummaryData.getOrderId().getRepoId());
record.setC_OrderLine_ID(callOrderSummaryData.getOrderLineId().getRepoId());
record.setC_Flatrate_Term_ID(callOrderSummaryData.getFlatrateTermId().getRepoId());
record.setM_Product_ID(callOrderSummaryData.getProductId().getRepoId());
record.setC_UOM_ID(callOrderSummaryData.getUomId().getRepoId());
record.setQtyEntered(callOrderSummaryData.getQtyEntered());
record.setQtyDeliveredInUOM(callOrderSummaryData.getQtyDelivered());
record.setQtyInvoicedInUOM(callOrderSummaryData.getQtyInvoiced());
record.setPOReference(callOrderSummaryData.getPoReference());
record.setIsSOTrx(callOrderSummaryData.getSoTrx().toBoolean());
if (callOrderSummaryData.getAttributeSetInstanceId() != null)
{
record.setM_AttributeSetInstance_ID(callOrderSummaryData.getAttributeSetInstanceId().getRepoId());
}
}
@NonNull | private static CallOrderSummary ofRecord(@NonNull final I_C_CallOrderSummary record)
{
return CallOrderSummary.builder()
.summaryId(CallOrderSummaryId.ofRepoId(record.getC_CallOrderSummary_ID()))
.summaryData(ofRecordData(record))
.build();
}
@NonNull
private static CallOrderSummaryData ofRecordData(@NonNull final I_C_CallOrderSummary record)
{
return CallOrderSummaryData.builder()
.orderId(OrderId.ofRepoId(record.getC_Order_ID()))
.orderLineId(OrderLineId.ofRepoId(record.getC_OrderLine_ID()))
.flatrateTermId(FlatrateTermId.ofRepoId(record.getC_Flatrate_Term_ID()))
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.uomId(UomId.ofRepoId(record.getC_UOM_ID()))
.qtyEntered(record.getQtyEntered())
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNull(record.getM_AttributeSetInstance_ID()))
.qtyDelivered(record.getQtyDeliveredInUOM())
.qtyInvoiced(record.getQtyInvoicedInUOM())
.poReference(record.getPOReference())
.isActive(record.isActive())
.soTrx(SOTrx.ofBoolean(record.isSOTrx()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\summary\CallOrderSummaryRepo.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
initialize(getSnapshotFilePath());
while (true) {
Collection<MonitoringEvent> events = monitoringEventAPI.getAllMonitoringEvent();
processEvents(events);
sleep(POLL_INTERVAL_MILLISECONDS);
}
}
private static void processEvents(Collection<MonitoringEvent> events) {
logger.info("Processing {} events", events.size());
events.forEach(evt -> {
logger.info("Event ID: {}, Name: {}, Type: {}, Status: {}, Device ID: {}, Creation Date: {}",
evt.getEventId(),
evt.getEventName().getValue(),
evt.getEventType().getValue(),
evt.getStatus().getValue(),
evt.getDeviceId().getValue(),
evt.getCreationDate().getValue());
});
}
private static void initialize(final Path snapshotPath) {
announcementWatcher = new HollowFilesystemAnnouncementWatcher(snapshotPath);
blobRetriever = new HollowFilesystemBlobRetriever(snapshotPath);
logger.info("snapshot data file location: {}", snapshotPath.toString());
consumer = new HollowConsumer.Builder<>()
.withAnnouncementWatcher(announcementWatcher)
.withBlobRetriever(blobRetriever)
.withGeneratedAPIClass(MonitoringEventAPI.class)
.build(); | consumer.triggerRefresh();
monitoringEventAPI = consumer.getAPI(MonitoringEventAPI.class);
}
private static void sleep(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
private static Path getSnapshotFilePath() {
String moduleDir = System.getProperty("user.dir");
String snapshotPath = moduleDir + "/.hollow/snapshots";
logger.info("snapshot data directory: {}", snapshotPath);
Path path = Paths.get(snapshotPath);
return path;
}
} | repos\tutorials-master\netflix-modules\hollow\src\main\java\com\baeldung\hollow\consumer\MonitoringEventConsumer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ApplicationConfiguration {
static final String SYSTEM_PROFILE_DB = "system.profile";
@Autowired MongoOperations operations;
/**
* Initialize db instance with defaults.
*/
@PostConstruct
public void initializeWithDefaults() {
// Enable profiling
setProfilingLevel(2);
}
/** | * Clean up resources on shutdown
*/
@PreDestroy
public void cleanUpWhenShuttingDown() {
// Disable profiling
setProfilingLevel(0);
if (operations.collectionExists(SYSTEM_PROFILE_DB)) {
operations.dropCollection(SYSTEM_PROFILE_DB);
}
}
private void setProfilingLevel(int level) {
operations.executeCommand(new Document("profile", level));
}
} | repos\spring-data-examples-main\mongodb\example\src\main\java\example\springdata\mongodb\advanced\ApplicationConfiguration.java | 2 |
请完成以下Java代码 | public String sync() {
logger.info("sync method start");
String result = this.execute();
logger.info("sync method end");
return result;
}
@GetMapping("async/mono")
public Mono<String> asyncMono() {
logger.info("async method start");
Mono<String> result = Mono.fromSupplier(this::execute);
logger.info("async method end");
return result;
}
// SSE(Server Sent Event)
// https://developer.mozilla.org/zh-CN/docs/Server-sent_events/Using_server-sent_events
// http://www.ruanyifeng.com/blog/2017/05/server-sent_events.html
@GetMapping(value = "async/flux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> asyncFlux() {
logger.info("async method start");
Flux<String> result = Flux.fromStream(IntStream.range(1, 5).mapToObj(i -> {
try {
TimeUnit.SECONDS.sleep(1); | } catch (InterruptedException e) {
e.printStackTrace();
}
return "int value:" + i;
}));
logger.info("async method end");
return result;
}
private String execute() {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "hello";
}
} | repos\SpringAll-master\57.Spring-Boot-WebFlux\webflux\src\main\java\com\example\webflux\TestController.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("elementGroups", elementGroups.isEmpty() ? null : elementGroups)
.toString();
}
public boolean hasElementGroups()
{
return !elementGroups.isEmpty();
}
public static final class Builder
{
private static final Logger logger = LogManager.getLogger(DocumentLayoutColumnDescriptor.Builder.class);
private String internalName;
private final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupsBuilders = new ArrayList<>();
private Builder()
{
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("internalName", internalName)
.add("elementGroups-count", elementGroupsBuilders.size())
.toString();
}
public DocumentLayoutColumnDescriptor build()
{
final DocumentLayoutColumnDescriptor result = new DocumentLayoutColumnDescriptor(this);
logger.trace("Built {} for {}", result, this);
return result;
}
private List<DocumentLayoutElementGroupDescriptor> buildElementGroups()
{
return elementGroupsBuilders
.stream()
.map(DocumentLayoutElementGroupDescriptor.Builder::build)
.filter(this::checkValid)
.collect(GuavaCollectors.toImmutableList());
}
private boolean checkValid(final DocumentLayoutElementGroupDescriptor elementGroup)
{
if(!elementGroup.hasElementLines())
{ | logger.trace("Skip adding {} to {} because it does not have element line", elementGroup, this);
return false;
}
return true;
}
public Builder setInternalName(String internalName)
{
this.internalName = internalName;
return this;
}
public Builder addElementGroups(@NonNull final List<DocumentLayoutElementGroupDescriptor.Builder> elementGroupBuilders)
{
elementGroupsBuilders.addAll(elementGroupBuilders);
return this;
}
public Builder addElementGroup(@NonNull final DocumentLayoutElementGroupDescriptor.Builder elementGroupBuilder)
{
elementGroupsBuilders.add(elementGroupBuilder);
return this;
}
public Stream<DocumentLayoutElementDescriptor.Builder> streamElementBuilders()
{
return elementGroupsBuilders.stream().flatMap(DocumentLayoutElementGroupDescriptor.Builder::streamElementBuilders);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutColumnDescriptor.java | 1 |
请完成以下Java代码 | public class TenantAwareDataSource implements DataSource {
protected TenantInfoHolder tenantInfoHolder;
protected Map<Object, DataSource> dataSources = new ConcurrentHashMap<>();
public TenantAwareDataSource(TenantInfoHolder tenantInfoHolder) {
this.tenantInfoHolder = tenantInfoHolder;
}
public void addDataSource(Object key, DataSource dataSource) {
dataSources.put(key, dataSource);
}
public void removeDataSource(Object key) {
dataSources.remove(key);
}
@Override
public Connection getConnection() throws SQLException {
return getCurrentDataSource().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return getCurrentDataSource().getConnection(username, password);
}
protected DataSource getCurrentDataSource() {
String tenantId = tenantInfoHolder.getCurrentTenantId();
DataSource dataSource = dataSources.get(tenantId);
if (dataSource == null) {
throw new FlowableException("Could not find a dataSource for tenant " + tenantId);
}
return dataSource;
}
@Override
public int getLoginTimeout() throws SQLException {
return 0; // Default
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
}
@SuppressWarnings("unchecked")
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
if (iface.isInstance(this)) {
return (T) this;
}
throw new SQLException("Cannot unwrap " + getClass().getName() + " as an instance of " + iface.getName());
}
@Override | public boolean isWrapperFor(Class<?> iface) throws SQLException {
return iface.isInstance(this);
}
public Map<Object, DataSource> getDataSources() {
return dataSources;
}
public void setDataSources(Map<Object, DataSource> dataSources) {
this.dataSources = dataSources;
}
// Unsupported //////////////////////////////////////////////////////////
@Override
public PrintWriter getLogWriter() throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
throw new UnsupportedOperationException();
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
throw new UnsupportedOperationException();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\multitenant\TenantAwareDataSource.java | 1 |
请完成以下Java代码 | public WFNode getNodeById(@NonNull final WFNodeId nodeId)
{
for (final WFNode node : getNodes())
{
if (node.getId().equals(nodeId))
{
return node;
}
}
throw new AdempiereException("Node " + nodeId + " not found");
}
/**
* @return Nodes in sequence
*/
public List<WFNode> getNodesInOrder(@NonNull final ClientId clientId)
{
final ArrayList<WFNode> list = new ArrayList<>();
addNodesSF(list, firstNodeId, clientId); // start with first
// Remaining Nodes
if (getNodes().size() != list.size())
{
// Add Stand alone
for (final WFNode node : getNodes())
{
if (!node.isActive())
{
continue;
}
final ClientId nodeClientId = node.getClientId();
if (nodeClientId.isSystem()
|| ClientId.equals(nodeClientId, clientId))
{
boolean found = false;
for (final WFNode existing : list)
{
if (existing.getId().equals(node.getId()))
{
found = true;
break;
}
}
if (!found)
{
log.warn("Added Node w/o transition: {}", node);
list.add(node);
}
}
}
}
return list;
} // getNodesInOrder
/**
* Add Nodes recursively (sibling first) to Ordered List
*/
private void addNodesSF(
final ArrayList<WFNode> list,
@NonNull final WFNodeId nodeId,
@NonNull final ClientId clientId)
{
final ArrayList<WFNode> tmplist = new ArrayList<>();
final WFNode node = getNodeById(nodeId);
final ClientId nodeClientId = node.getClientId();
if (nodeClientId.isSystem() || ClientId.equals(nodeClientId, clientId))
{
if (!list.contains(node))
{
list.add(node);
}
for (final WFNodeTransition transition : node.getTransitions(clientId))
{
final WFNode child = getNodeById(transition.getNextNodeId());
if (child == null)
{
continue;
} | if (!child.isActive())
{
continue;
}
final ClientId childClientId = child.getClientId();
if (childClientId.isSystem() || ClientId.equals(childClientId, clientId))
{
if (!list.contains(child))
{
list.add(child);
tmplist.add(child);
}
}
}
// Remainder Nodes not connected
for (final WFNode mwfNode : tmplist)
{
addNodesSF(list, mwfNode.getId(), clientId);
}
}
}
public ImmutableList<WFNodeTransition> getTransitionsFromNode(
@NonNull final WFNodeId nodeId,
@NonNull final ClientId clientId)
{
for (final WFNode node : getNodesInOrder(clientId))
{
if (node.getId().equals(nodeId))
{
return node.getTransitions(clientId);
}
}
return ImmutableList.of();
} // getNext
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\Workflow.java | 1 |
请完成以下Java代码 | public void validateEvent(PickingRequestedEvent event)
{
event.assertValid();
}
@Override
public void handleEvent(@NonNull final PickingRequestedEvent event)
{
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(event.getShipmentScheduleId());
final PickingSlotId pickingSlotId;
if (event.getPickingSlotId() > 0)
{
pickingSlotId = PickingSlotId.ofRepoId(event.getPickingSlotId());
}
else
{
pickingSlotId = allocatePickingSlot(shipmentScheduleId);
}
final Set<HuId> huIds = HuId.ofRepoIds(event.getTopLevelHuIdsToPick());
for (final HuId huIdToPick : HuId.ofRepoIds(event.getTopLevelHuIdsToPick()))
{
// NOTE: we are not moving the HU to shipment schedule's locator.
pickingCandidateService.pickHU(PickRequest.builder()
.shipmentScheduleId(shipmentScheduleId)
.pickFrom(PickFrom.ofHuId(huIdToPick))
.pickingSlotId(pickingSlotId)
.build());
}
pickingCandidateService.processForHUIds(huIds, shipmentScheduleId);
}
private PickingSlotId allocatePickingSlot(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = Services.get(IShipmentSchedulePA.class).getById(shipmentScheduleId);
final BPartnerLocationId bpLocationId = Services.get(IShipmentScheduleEffectiveBL.class).getBPartnerLocationId(shipmentSchedule);
final PickingSlotQuery pickingSlotQuery = PickingSlotQuery.builder()
.availableForBPartnerLocationId(bpLocationId)
.build(); | final List<I_M_PickingSlot> pickingSlots = Services.get(IPickingSlotDAO.class).retrievePickingSlots(pickingSlotQuery);
Check.errorIf(pickingSlots.isEmpty(),
"Found no picking slot for C_BP_Location_ID={}; C_BPartner_ID={}; shipmentSchedule={}",
bpLocationId,
(Supplier<Object>)() -> loadOutOfTrx(bpLocationId, I_C_BPartner_Location.class).getC_BPartner_ID(),
shipmentSchedule);
final I_M_PickingSlot firstPickingSlot = pickingSlots.get(0);
Loggables.withLogger(logger, Level.DEBUG).addLog(
"Retrieved an available picking slot, because none was set in the event; pickingSlot={}",
firstPickingSlot);
return PickingSlotId.ofRepoId(firstPickingSlot.getM_PickingSlot_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\handler\PickingRequestedHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JXlsExporter setAD_Language(final String adLanguage)
{
this._adLanguage = adLanguage;
return this;
}
private Language getLanguage()
{
if (!Check.isEmpty(_adLanguage, true))
{
return Language.getLanguage(_adLanguage);
}
return Env.getLanguage(getContext());
}
public Locale getLocale()
{
final Language language = getLanguage();
if (language != null)
{
return language.getLocale();
}
return Locale.getDefault();
}
public JXlsExporter setTemplateResourceName(final String templateResourceName)
{
this._templateResourceName = templateResourceName;
return this;
}
private InputStream getTemplate()
{
if (_template != null)
{
return _template;
}
if (!Check.isEmpty(_templateResourceName, true))
{
final ClassLoader loader = getLoader();
final InputStream template = loader.getResourceAsStream(_templateResourceName);
if (template == null)
{
throw new JXlsExporterException("Could not find template for name: " + _templateResourceName + " using " + loader);
}
return template;
}
throw new JXlsExporterException("Template is not configured");
}
public JXlsExporter setTemplate(final InputStream template)
{
this._template = template;
return this;
}
private IXlsDataSource getDataSource()
{
Check.assumeNotNull(_dataSource, "dataSource not null");
return _dataSource; | }
public JXlsExporter setDataSource(final IXlsDataSource dataSource)
{
this._dataSource = dataSource;
return this;
}
public JXlsExporter setResourceBundle(final ResourceBundle resourceBundle)
{
this._resourceBundle = resourceBundle;
return this;
}
private ResourceBundle getResourceBundle()
{
if (_resourceBundle != null)
{
return _resourceBundle;
}
if (!Check.isEmpty(_templateResourceName, true))
{
String baseName = null;
try
{
final int dotIndex = _templateResourceName.lastIndexOf('.');
baseName = dotIndex <= 0 ? _templateResourceName : _templateResourceName.substring(0, dotIndex);
return ResourceBundle.getBundle(baseName, getLocale(), getLoader());
}
catch (final MissingResourceException e)
{
logger.debug("No resource found for {}", baseName);
}
}
return null;
}
public Map<String, String> getResourceBundleAsMap()
{
final ResourceBundle bundle = getResourceBundle();
if (bundle == null)
{
return ImmutableMap.of();
}
return ResourceBundleMapWrapper.of(bundle);
}
public JXlsExporter setProperty(@NonNull final String name, @NonNull final Object value)
{
Check.assumeNotEmpty(name, "name not empty");
_properties.put(name, value);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\JXlsExporter.java | 2 |
请完成以下Java代码 | public String getByteArrayId() {
return byteArrayId;
}
public void setByteArrayId(String byteArrayId) {
this.byteArrayId = byteArrayId;
this.byteArrayValue = null;
}
public byte[] getByteArrayValue() {
getByteArrayEntity();
if (byteArrayValue != null) {
return byteArrayValue.getBytes();
}
else {
return null;
}
}
protected ByteArrayEntity getByteArrayEntity() {
if (byteArrayValue == null) {
if (byteArrayId != null) {
// no lazy fetching outside of command context
if (Context.getCommandContext() != null) {
return byteArrayValue = Context
.getCommandContext()
.getDbEntityManager()
.selectById(ByteArrayEntity.class, byteArrayId);
}
}
}
return byteArrayValue;
}
public void setByteArrayValue(byte[] bytes) {
setByteArrayValue(bytes, false);
}
public void setByteArrayValue(byte[] bytes, boolean isTransient) {
if (bytes != null) {
// note: there can be cases where byteArrayId is not null
// but the corresponding byte array entity has been removed in parallel;
// thus we also need to check if the actual byte array entity still exists
if (this.byteArrayId != null && getByteArrayEntity() != null) {
byteArrayValue.setBytes(bytes);
}
else {
deleteByteArrayValue();
byteArrayValue = new ByteArrayEntity(nameProvider.getName(), bytes, type, rootProcessInstanceId, removalTime);
// avoid insert of byte array value for a transient variable
if (!isTransient) {
Context. | getCommandContext()
.getByteArrayManager()
.insertByteArray(byteArrayValue);
byteArrayId = byteArrayValue.getId();
}
}
}
else {
deleteByteArrayValue();
}
}
public void deleteByteArrayValue() {
if (byteArrayId != null) {
// the next apparently useless line is probably to ensure consistency in the DbSqlSession cache,
// but should be checked and docked here (or removed if it turns out to be unnecessary)
getByteArrayEntity();
if (byteArrayValue != null) {
Context.getCommandContext()
.getDbEntityManager()
.delete(byteArrayValue);
}
byteArrayId = null;
}
}
public void setByteArrayValue(ByteArrayEntity byteArrayValue) {
this.byteArrayValue = byteArrayValue;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\util\ByteArrayField.java | 1 |
请完成以下Java代码 | public Optional<User> findByEmail(String email) {
return userJpaRepository.findByEmail(email);
}
@Override
public Optional<User> findByUsername(String username) {
return userJpaRepository.findByUsername(username);
}
@Override
public boolean existsByEmail(String email) {
return userJpaRepository.existsByEmail(email);
}
@Override
public boolean existsByUsername(String username) {
return userJpaRepository.existsByUsername(username);
}
@Override
public boolean existsBy(String email, String username) {
return userJpaRepository.existsByEmailOrUsername(email, username);
}
@Override
@Transactional
public User updateUserDetails(
UUID userId,
PasswordEncoder passwordEncoder,
String email,
String username,
String password,
String bio,
String imageUrl) { | return this.findById(userId)
.map(user -> {
if (!user.equalsEmail(email) && this.existsByEmail(email)) {
throw new IllegalArgumentException("email is already exists.");
}
if (!user.equalsUsername(username) && this.existsByUsername(username)) {
throw new IllegalArgumentException("username is already exists.");
}
user.setEmail(email);
user.setUsername(username);
user.encryptPassword(passwordEncoder, password);
user.setBio(bio);
user.setImageUrl(imageUrl);
return userJpaRepository.save(user);
})
.orElseThrow(() -> new IllegalArgumentException("user not found."));
}
} | repos\realworld-java21-springboot3-main\module\persistence\src\main\java\io\zhc1\realworld\persistence\UserRepositoryAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JpaTest {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "add_time")
private Date addTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id; | }
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getAddTime() {
return addTime;
}
public void setAddTime(Date addTime) {
this.addTime = addTime;
}
} | repos\spring-boot-quick-master\quick-jpa\src\main\java\com\quick\jpa\entity\JpaTest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | final class MetasJRXlsExporterNature extends JRXlsExporterNature
{
public MetasJRXlsExporterNature(
final JasperReportsContext jasperReportsContext,
final ExporterFilter filter,
final boolean isIgnoreGraphics,
final boolean isIgnorePageMargins)
{
super(jasperReportsContext, filter, isIgnoreGraphics, isIgnorePageMargins);
}
@Override
public void setXProperties(final Map<String, Object> xCutsProperties, final JRPrintElement element)
{
super.setXProperties(xCutsProperties, element);
}
/**
* First calls the parent's {@link JRXlsExporterNature#setXProperties(CutsInfo, JRPrintElement, int, int, int, int) setXProperties} method.<br>
* Then, "forwards" the {@value MetasJRXlsExporter#PROPERTY_COLUMN_HIDDEN} property from the given <code>element</code> to the {@link Cut} of the given <code>xCuts</code> (of the given <code>row1</code>).
*/
@Override
public void setXProperties(CutsInfo xCuts, JRPrintElement element, int row1, int col1, int row2, int col2)
{
super.setXProperties(xCuts, element, row1, col1, row2, col2);
// Mark the xCut (i.e. the column) as hidden if any element from it required a hidden column. | if (isColumnHidden(element))
{
final Cut cut = xCuts.getCut(col1);
cut.setProperty(MetasJRXlsExporter.PROPERTY_COLUMN_HIDDEN, true);
}
}
/**
* Evaluates the given <code>element</code> and check if it has the property {@value MetasJRXlsExporter#PROPERTY_COLUMN_HIDDEN} set to <code>true</code>.
* If that's the case, then it returns <code>true</code>.
*
* @return <code>true</code> if the element was annotated to require a hidden column
*/
private boolean isColumnHidden(final JRPrintElement element)
{
if (element.hasProperties()
&& element.getPropertiesMap().containsProperty(MetasJRXlsExporter.PROPERTY_COLUMN_HIDDEN))
{
final boolean defaultValue = false; // not hidden by default
// we make this test to avoid reaching the global default value of the property directly
// and thus skipping the report level one, if present
return getPropertiesUtil().getBooleanProperty(element, MetasJRXlsExporter.PROPERTY_COLUMN_HIDDEN, defaultValue);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\exporter\MetasJRXlsExporterNature.java | 2 |
请完成以下Java代码 | public I_AD_Window getAD_Window() throws RuntimeException
{
return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name)
.getPO(getAD_Window_ID(), get_TrxName()); }
/** Set Window.
@param AD_Window_ID
Data entry or display window
*/
public void setAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID < 1)
set_Value (COLUMNNAME_AD_Window_ID, null);
else
set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID));
}
/** Get Window.
@return Data entry or display window
*/
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Attribute.
@param Attribute Attribute */
public void setAttribute (String Attribute)
{
set_Value (COLUMNNAME_Attribute, Attribute);
}
/** Get Attribute.
@return Attribute */
public String getAttribute ()
{
return (String)get_Value(COLUMNNAME_Attribute);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), getAttribute());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Preference.java | 1 |
请完成以下Java代码 | public static void replaceOneOperations() {
UpdateOptions options = new UpdateOptions().upsert(true);
Document replaceDocument = new Document();
replaceDocument.append("modelName", "GTPP")
.append("companyName", "Hero Honda")
.append("launchYear", 2022)
.append("type", "Bike")
.append("registeredNo", "EPS 5562");
UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options);
System.out.println("updateReplaceResult:- " + updateReplaceResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Update with upsert operation
//
updateOperations();
//
// Update with upsert operation using setOnInsert | //
updateSetOnInsertOperations();
//
// Update with upsert operation using findOneAndUpdate
//
findOneAndUpdateOperations();
//
// Update with upsert operation using replaceOneOperations
//
replaceOneOperations();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Builder setDLM_Partition_Config_ID(final int dlm_Partition_Config_ID)
{
DLM_Partition_Config_ID = dlm_Partition_Config_ID;
return this;
}
public Builder setChanged(final boolean changed)
{
this.changed = changed;
return this;
}
private PartitionerConfigLine.LineBuilder newLine()
{
assertLineTableNamesUnique();
final PartitionerConfigLine.LineBuilder lineBuilder = new PartitionerConfigLine.LineBuilder(this);
lineBuilders.add(lineBuilder);
return lineBuilder;
}
/**
*
* @param tableName
* @return the already existing line builder for the given <code>tableName</code>, or a new one, if none existed yet.
*/
public LineBuilder line(final String tableName)
{
final Optional<LineBuilder> existingLineBuilder = lineBuilders
.stream()
.filter(b -> tableName.equals(b.getTableName()))
.findFirst();
if (existingLineBuilder.isPresent())
{
return existingLineBuilder.get();
}
setChanged(true); | return newLine().setTableName(tableName);
}
private void assertLineTableNamesUnique()
{
final List<LineBuilder> nonUniqueLines = lineBuilders.stream()
.collect(Collectors.groupingBy(r -> r.getTableName())) // group them by tableName; this returns a map
.entrySet().stream() // now stream the map's entries
.filter(e -> e.getValue().size() > 1) // now remove from the stream those that are OK
.flatMap(e -> e.getValue().stream()) // now get a stream with those that are not OK
.collect(Collectors.toList());
Check.errorUnless(nonUniqueLines.isEmpty(), "Found LineBuilders with duplicate tableNames: {}", nonUniqueLines);
}
public PartitionConfig build()
{
assertLineTableNamesUnique();
final PartitionConfig partitionerConfig = new PartitionConfig(name, changed);
partitionerConfig.setDLM_Partition_Config_ID(DLM_Partition_Config_ID);
// first build the lines
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
final PartitionerConfigLine line = lineBuilder.buildLine(partitionerConfig);
partitionerConfig.lines.add(line);
}
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
lineBuilder.buildRefs();
}
return partitionerConfig;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionConfig.java | 2 |
请完成以下Java代码 | protected final void setValue(final Object value)
{
Object valueToSet;
boolean forwardValue = true;
try
{
// Checkbox
if (displayType == DisplayType.YesNo)
{
compCheckbox.setSelected(DisplayType.toBooleanNonNull(value, false));
valueToSet = null;
forwardValue = false;
}
else if (value == null)
{
valueToSet = null;
}
// Number
else if (DisplayType.isNumeric(displayType))
{
valueToSet = numberFormat.format(value);
}
// Date
else if (DisplayType.isDate(displayType))
{
valueToSet = dateFormat.format(value);
}
// Row ID
else if (displayType == DisplayType.RowID)
{
valueToSet = "";
}
// Password (fixed string)
else if (isPassword)
{
valueToSet = "**********";
}
// other (String ...)
else
{
valueToSet = value;
}
}
catch (Exception e)
{
logger.error("(" + value + ") " + value.getClass().getName(), e);
valueToSet = value.toString();
}
//
// Forward the value to super
if (forwardValue)
{
super.setValue(valueToSet);
}
} // setValue | /**
* to String
*
* @return String representation
*/
@Override
public String toString()
{
return getClass().getSimpleName() + "[DisplayType=" + displayType + "]";
} // toString
/**
* Sets precision to be used in case we are dealing with a number.
*
* If not set, default displayType's precision will be used.
*
* @param precision
*/
public void setPrecision(final int precision)
{
if (numberFormat != null)
{
numberFormat.setMinimumFractionDigits(precision);
numberFormat.setMaximumFractionDigits(precision);
}
}
} // VCellRenderer | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableCellRenderer.java | 1 |
请完成以下Java代码 | public Iterator<String> iterator()
{
return getAllStrings().iterator();
}
@Override
public Object[] toArray()
{
return getAllStrings().toArray();
}
@Override
public <T> T[] toArray(T[] a)
{
return getAllStrings().toArray(a);
}
@Override
public boolean add(String s)
{
addString(s);
return true;
}
@Override
public boolean remove(Object o)
{
if (o.getClass() == String.class)
{
removeString((String) o);
}
else
{
removeString(o.toString());
}
return true;
}
@Override
public boolean containsAll(Collection<?> c)
{
for (Object e : c)
if (!contains(e))
return false;
return true;
}
@Override
public boolean addAll(Collection<? extends String> c)
{
boolean modified = false;
for (String e : c)
if (add(e)) | modified = true;
return modified;
}
@Override
public boolean retainAll(Collection<?> c)
{
boolean modified = false;
Iterator<String> it = iterator();
while (it.hasNext())
{
if (!c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public boolean removeAll(Collection<?> c)
{
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext())
{
if (c.contains(it.next()))
{
it.remove();
modified = true;
}
}
return modified;
}
@Override
public void clear()
{
sourceNode = new MDAGNode(false);
simplifiedSourceNode = null;
if (equivalenceClassMDAGNodeHashMap != null)
equivalenceClassMDAGNodeHashMap.clear();
mdagDataArray = null;
charTreeSet.clear();
transitionCount = 0;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGSet.java | 1 |
请完成以下Java代码 | public final class OrgResource implements Resource
{
/**
* Any Org
*/
public static final OrgResource ANY = new OrgResource();
public static OrgResource of(
@NonNull final ClientId adClientId,
@NonNull final OrgId adOrgId,
final boolean isGroupingOrg)
{
return new OrgResource(ClientAndOrgId.ofClientAndOrg(adClientId, adOrgId), isGroupingOrg);
}
public static OrgResource anyOrg(@NonNull final ClientId adClientId)
{
return new OrgResource(ClientAndOrgId.ofClientAndOrg(adClientId, OrgId.ANY), false);
}
@Nullable private final ClientAndOrgId clientAndOrgId;
@Getter
private final boolean isGroupingOrg;
private OrgResource(
@NonNull final ClientAndOrgId clientAndOrgId,
final boolean isGroupingOrg)
{
this.clientAndOrgId = clientAndOrgId;
this.isGroupingOrg = isGroupingOrg;
}
/**
* Any Org constructor
*/ | private OrgResource()
{
clientAndOrgId = null;
isGroupingOrg = false;
}
public boolean isRegularOrg() {return clientAndOrgId != null && clientAndOrgId.getOrgId().isRegular();}
@Nullable
public ClientId getClientId() {return clientAndOrgId != null ? clientAndOrgId.getClientId() : null;}
@Nullable
public OrgId getOrgId() {return clientAndOrgId != null ? clientAndOrgId.getOrgId() : null;}
@Nullable
public OrgId getOrgIdOrAny() {return clientAndOrgId != null ? clientAndOrgId.getOrgId() : OrgId.ANY;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgResource.java | 1 |
请完成以下Java代码 | public class InfoProperties implements Iterable<InfoProperties.Entry> {
private final Properties entries;
/**
* Create an instance with the specified entries.
* @param entries the information to expose
*/
public InfoProperties(Properties entries) {
Assert.notNull(entries, "'entries' must not be null");
this.entries = copy(entries);
}
/**
* Return the value of the specified property or {@code null}.
* @param key the key of the property
* @return the property value
*/
public @Nullable String get(String key) {
return this.entries.getProperty(key);
}
/**
* Return the value of the specified property as an {@link Instant} or {@code null} if
* the value is not a valid {@link Long} representation of an epoch time.
* @param key the key of the property
* @return the property value
*/
public @Nullable Instant getInstant(String key) {
String s = get(key);
if (s != null) {
try {
return Instant.ofEpochMilli(Long.parseLong(s));
}
catch (NumberFormatException ex) {
// Not valid epoch time
}
}
return null;
}
@Override
public Iterator<Entry> iterator() {
return new PropertiesIterator(this.entries);
}
/**
* Return a {@link PropertySource} of this instance.
* @return a {@link PropertySource}
*/
public PropertySource<?> toPropertySource() {
return new PropertiesPropertySource(getClass().getSimpleName(), copy(this.entries));
}
private Properties copy(Properties properties) {
Properties copy = new Properties();
copy.putAll(properties);
return copy;
}
private static final class PropertiesIterator implements Iterator<Entry> {
private final Iterator<Map.Entry<Object, Object>> iterator;
private PropertiesIterator(Properties properties) {
this.iterator = properties.entrySet().iterator(); | }
@Override
public boolean hasNext() {
return this.iterator.hasNext();
}
@Override
public Entry next() {
Map.Entry<Object, Object> entry = this.iterator.next();
return new Entry((String) entry.getKey(), (String) entry.getValue());
}
@Override
public void remove() {
throw new UnsupportedOperationException("InfoProperties are immutable.");
}
}
/**
* Property entry.
*/
public static final class Entry {
private final String key;
private final String value;
private Entry(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return this.key;
}
public String getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\info\InfoProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPrinterLanguage() {
return printerLanguage;
}
/**
* Sets the value of the printerLanguage property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrinterLanguage(String value) {
this.printerLanguage = value;
}
/**
* Gets the value of the paperFormat property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPaperFormat() {
return paperFormat;
}
/**
* Sets the value of the paperFormat property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPaperFormat(String value) {
this.paperFormat = value;
}
/**
* Gets the value of the printer property.
*
* @return
* possible object is
* {@link Printer }
*
*/ | public Printer getPrinter() {
return printer;
}
/**
* Sets the value of the printer property.
*
* @param value
* allowed object is
* {@link Printer }
*
*/
public void setPrinter(Printer value) {
this.printer = value;
}
/**
* Gets the value of the startPosition property.
*
* @return
* possible object is
* {@link StartPosition }
*
*/
public StartPosition getStartPosition() {
return startPosition;
}
/**
* Sets the value of the startPosition property.
*
* @param value
* allowed object is
* {@link StartPosition }
*
*/
public void setStartPosition(StartPosition value) {
this.startPosition = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\PrintOptions.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ConnectionFactory secondConnectionFactory(
@Value("${spring.rabbitmq.second.host}") String host,
@Value("${spring.rabbitmq.second.port}") int port,
@Value("${spring.rabbitmq.second.username}") String username,
@Value("${spring.rabbitmq.second.password}") String password,
@Value("${spring.rabbitmq.second.virtual-host}") String virtualHost) {
return getCachingConnectionFactory(host, port, username, password, virtualHost);
}
@Bean(name = "secondRabbitTemplate")
@Primary
public RabbitTemplate secondRabbitTemplate(
@Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory) {
RabbitTemplate secondRabbitTemplate = new RabbitTemplate(connectionFactory);
//使用外部事物
//lpzRabbitTemplate.setChannelTransacted(true);
return secondRabbitTemplate;
}
@Bean(name = "secondContainerFactory")
public SimpleRabbitListenerContainerFactory secondFactory( | SimpleRabbitListenerContainerFactoryConfigurer configurer,
@Qualifier("secondConnectionFactory") ConnectionFactory connectionFactory) {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
}
private CachingConnectionFactory getCachingConnectionFactory(String host,
int port,
String username,
String password,
String virtualHost) {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setHost(host);
connectionFactory.setPort(port);
connectionFactory.setUsername(username);
connectionFactory.setPassword(password);
connectionFactory.setVirtualHost(virtualHost);
return connectionFactory;
}
} | repos\spring-boot-quick-master\quick-multi-rabbitmq\src\main\java\com\multi\rabbitmq\config\RabbitMqConfiguration.java | 2 |
请完成以下Java代码 | public void deleteUIElementsByFieldId(@NonNull final AdFieldId adFieldId)
{
queryBL.createQueryBuilder(I_AD_UI_Element.class)
.addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Field_ID, adFieldId)
.create()
.delete();
}
@Override
public void deleteUISectionsByTabId(@NonNull final AdTabId adTabId)
{
queryBL.createQueryBuilder(I_AD_UI_Section.class)
.addEqualsFilter(I_AD_UI_Section.COLUMN_AD_Tab_ID, adTabId)
.create()
.delete();
}
@Override
public AdWindowId getAdWindowId(
@NonNull final String tableName,
@NonNull final SOTrx soTrx,
@NonNull final AdWindowId defaultValue)
{
final I_AD_Table adTableRecord = adTableDAO.retrieveTable(tableName);
switch (soTrx)
{
case SALES:
return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getAD_Window_ID()), defaultValue);
case PURCHASE:
return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getPO_Window_ID()), defaultValue);
default:
throw new AdempiereException("Param 'soTrx' has an unspupported value; soTrx=" + soTrx);
}
} | @Override
public ImmutableSet<AdWindowId> retrieveAllAdWindowIdsByTableId(final AdTableId adTableId)
{
final List<AdWindowId> adWindowIds = queryBL.createQueryBuilder(I_AD_Tab.class)
.addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId)
.create()
.listDistinct(I_AD_Tab.COLUMNNAME_AD_Window_ID, AdWindowId.class);
return ImmutableSet.copyOf(adWindowIds);
}
@Override
public ImmutableSet<AdWindowId> retrieveAllActiveAdWindowIds()
{
return queryBL.createQueryBuilder(I_AD_Window.class)
.addOnlyActiveRecordsFilter()
.orderBy(I_AD_Window.COLUMNNAME_AD_Window_ID)
.create()
.idsAsSet(AdWindowId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\api\impl\ADWindowDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_Invoice_Candidate
{
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, //
ifColumnsChanged = { I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID })
public void setIsEDIInvoicRecipient(final I_C_Invoice_Candidate invoiceCandidate)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final I_C_BPartner ediBPartner = bpartnerDAO.getById(BPartnerId.ofRepoId(invoiceCandidate.getBill_BPartner_ID()), I_C_BPartner.class);
if (ediBPartner == null || ediBPartner.getC_BPartner_ID() <= 0)
{
// nothing to do
return;
} | // Make sure the IsEDIRecipient flag is up to date in the invoice candidate
// It shall always be the same as in the bill BPartner
final boolean isEDIRecipient = ediBPartner.isEdiInvoicRecipient();
invoiceCandidate.setIsEdiInvoicRecipient(isEDIRecipient);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW }, //
ifColumnsChanged = { I_C_Invoice_Candidate.COLUMNNAME_C_Order_ID, I_C_Invoice_Candidate.COLUMNNAME_M_InOut_ID })
public void setIsEDIEnabled(final I_C_Invoice_Candidate invoiceCandidate)
{
Services.get(IEDIInvoiceCandBL.class).setEdiEnabled(invoiceCandidate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\C_Invoice_Candidate.java | 2 |
请完成以下Java代码 | public class M_PriceList_Create extends JavaProcess implements IProcessPrecondition
{
// Services
private final transient ISessionBL sessionBL = Services.get(ISessionBL.class);
private final transient IAttributeSetInstanceBL asiBL = Services.get(IAttributeSetInstanceBL.class);
private final transient IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
final I_M_PriceList_Version plv = priceListDAO.getPriceListVersionById(priceListVersionId);
if(plv.getM_DiscountSchema_ID() <= 0)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No Pricing Schema Selected");
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
// Disabling change log creation because we might create and then update a huge amount of records.
// To avoid this huge performance issue we are disabling for this thread (08125)
sessionBL.setDisableChangeLogsForThread(true);
try
{
DB.executeFunctionCallEx( //
ITrx.TRXNAME_ThreadInherited //
, "select M_PriceList_Version_CopyFromBase(p_M_PriceList_Version_ID:=?, p_AD_User_ID:=?)" //
, new Object[] { getTargetPriceListVersion_ID(), getAD_User_ID() } //
);
cloneASIs();
}
finally
{ | sessionBL.setDisableChangeLogsForThread(false);
}
return MSG_OK;
}
private void cloneASIs()
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_M_ProductPrice.class, getCtx(), ITrx.TRXNAME_ThreadInherited)
.addEqualsFilter(I_M_ProductPrice.COLUMNNAME_M_PriceList_Version_ID, getTargetPriceListVersion_ID())
.addEqualsFilter(I_M_ProductPrice.COLUMN_IsAttributeDependant, true)
.create()
.iterateAndStream()
.forEach(this::cloneASI);
}
private void cloneASI(final I_M_ProductPrice productPrice)
{
if (!productPrice.isAttributeDependant())
{
return;
}
// NOTE: we assume the ASI was set when the initial copy function was executed
final I_M_AttributeSetInstance sourceASI = productPrice.getM_AttributeSetInstance();
final I_M_AttributeSetInstance targetASI = sourceASI == null ? null : asiBL.copy(sourceASI);
productPrice.setM_AttributeSetInstance(targetASI);
InterfaceWrapperHelper.save(productPrice);
}
private int getTargetPriceListVersion_ID()
{
return getRecord_ID();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\M_PriceList_Create.java | 1 |
请完成以下Java代码 | public void setName(final String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
} | public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("User [name=").append(name).append(", id=").append(id).append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\persistence\multiple\model\user\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private HttpHeaders getHttpHeaders()
{
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(ImmutableList.of(MediaType.APPLICATION_JSON));
if (authToken.getBearer() != null)
{
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + authToken.getBearerNotNull());
}
return headers;
}
private RestTemplate restTemplate()
{
return new RestTemplateBuilder()
.errorHandler(new ShopwareApiErrorHandler())
.setConnectTimeout(Duration.of(CONNECTION_TIMEOUT_SECONDS, SECONDS))
.setReadTimeout(Duration.of(READ_TIMEOUT_SECONDS, SECONDS))
.build();
}
@NonNull
private static Optional<JsonNode> readDataJsonNode(@NonNull final ResponseEntity<String> response)
{
try
{
final JsonNode rootJsonNode = objectMapper.readValue(response.getBody(), JsonNode.class);
return Optional.ofNullable(rootJsonNode.get(JSON_NODE_DATA));
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
@Builder
private static class AuthToken
{
@NonNull
private final String clientId;
@NonNull
private final String clientSecret;
@NonNull
private Instant validUntil;
@Nullable
@Getter
private String bearer;
public GetBearerRequest toGetBearerRequest()
{
return GetBearerRequest.builder()
.grantType("client_credentials")
.clientId(clientId) | .clientSecret(clientSecret)
.build();
}
public void updateBearer(@NonNull final String bearer, @NonNull final Instant validUntil)
{
this.bearer = bearer;
this.validUntil = validUntil;
}
public boolean isExpired()
{
return bearer == null || Instant.now().isAfter(validUntil);
}
@NonNull
public String getBearerNotNull()
{
if (bearer == null)
{
throw new RuntimeException("AuthToken.bearer is null!");
}
return bearer;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\ShopwareClient.java | 2 |
请完成以下Java代码 | public final class ServerWebExchangeDelegatingServerHttpHeadersWriter implements ServerHttpHeadersWriter {
private final ServerWebExchangeMatcherEntry<ServerHttpHeadersWriter> headersWriter;
/**
* Creates a new instance
* @param headersWriter the {@link ServerWebExchangeMatcherEntry} holding a
* {@link ServerWebExchangeMatcher} and the {@link ServerHttpHeadersWriter} to invoke
* if the matcher returns a match.
*/
public ServerWebExchangeDelegatingServerHttpHeadersWriter(
ServerWebExchangeMatcherEntry<ServerHttpHeadersWriter> headersWriter) {
Assert.notNull(headersWriter, "headersWriter cannot be null");
Assert.notNull(headersWriter.getMatcher(), "webExchangeMatcher cannot be null");
Assert.notNull(headersWriter.getEntry(), "delegateHeadersWriter cannot be null");
this.headersWriter = headersWriter;
}
/**
* Creates a new instance
* @param webExchangeMatcher the {@link ServerWebExchangeMatcher} to use. If it | * returns a match, the delegateHeadersWriter is invoked.
* @param delegateHeadersWriter the {@link ServerHttpHeadersWriter} to invoke if the
* {@link ServerWebExchangeMatcher} returns a match.
*/
public ServerWebExchangeDelegatingServerHttpHeadersWriter(ServerWebExchangeMatcher webExchangeMatcher,
ServerHttpHeadersWriter delegateHeadersWriter) {
this(new ServerWebExchangeMatcherEntry<>(webExchangeMatcher, delegateHeadersWriter));
}
@Override
public Mono<Void> writeHttpHeaders(ServerWebExchange exchange) {
return this.headersWriter.getMatcher()
.matches(exchange)
.filter(ServerWebExchangeMatcher.MatchResult::isMatch)
.flatMap((matchResult) -> this.headersWriter.getEntry().writeHttpHeaders(exchange));
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\ServerWebExchangeDelegatingServerHttpHeadersWriter.java | 1 |
请完成以下Java代码 | public void putInCache(MutableAcl acl) {
Assert.notNull(acl, "Acl required");
Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required");
Assert.notNull(acl.getId(), "ID required");
if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) {
putInCache((MutableAcl) acl.getParentAcl());
}
this.cache.put(acl.getObjectIdentity(), acl);
this.cache.put(acl.getId(), acl);
}
private MutableAcl getFromCache(Object key) {
Cache.ValueWrapper element = this.cache.get(key);
if (element == null) {
return null;
}
return initializeTransientFields((MutableAcl) element.get());
}
private MutableAcl initializeTransientFields(MutableAcl value) {
if (value instanceof AclImpl) { | FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy);
}
if (value.getParentAcl() != null) {
initializeTransientFields((MutableAcl) value.getParentAcl());
}
return value;
}
@Override
public void clearCache() {
this.cache.clear();
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\SpringCacheBasedAclCache.java | 1 |
请完成以下Java代码 | public void setC_Payment_Reservation_ID (int C_Payment_Reservation_ID)
{
if (C_Payment_Reservation_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Payment_Reservation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Payment_Reservation_ID, Integer.valueOf(C_Payment_Reservation_ID));
}
/** Get Payment Reservation.
@return Payment Reservation */
@Override
public int getC_Payment_Reservation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_Reservation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Status. | @param Status Status */
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status */
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment_Reservation_Capture.java | 1 |
请完成以下Java代码 | public static SecurityConfig securityConfig() {
return new SecurityConfig();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeRequests()
.requestMatchers("/css/**", "/index")
.permitAll()
.requestMatchers("/user/**")
.authenticated()
.and()
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login"))
.logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/logout"))
.authenticationProvider(authProvider())
.with(securityConfig(), Customizer.withDefaults());
return http.build();
} | public CustomAuthenticationFilter authenticationFilter(AuthenticationManager authenticationManager) {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
filter.setAuthenticationManager(authenticationManager);
filter.setAuthenticationFailureHandler(failureHandler());
filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler());
filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository());
return filter;
}
public AuthenticationProvider authProvider() {
return new CustomUserDetailsAuthenticationProvider(passwordEncoder, userDetailsService);
}
public SimpleUrlAuthenticationFailureHandler failureHandler() {
return new SimpleUrlAuthenticationFailureHandler("/login?error=true");
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\SecurityConfig.java | 1 |
请完成以下Java代码 | private static NonBusinessDay toNonBusinessDay(final I_C_NonBusinessDay record)
{
if (record.isRepeat())
{
final String frequency = record.getFrequency();
if (Check.isEmpty(frequency, true))
{
throw new FillMandatoryException(I_C_NonBusinessDay.COLUMNNAME_Frequency);
}
return RecurrentNonBusinessDay.builder()
.frequency(RecurrentNonBusinessDayFrequency.forCode(frequency))
.startDate(TimeUtil.asLocalDate(record.getDate1()))
.endDate(TimeUtil.asLocalDate(record.getEndDate()))
.name(record.getName())
.build();
}
else
{
return FixedNonBusinessDay.builder()
.fixedDate(TimeUtil.asLocalDate(record.getDate1()))
.name(record.getName())
.build();
}
}
@Override
public void validate(@NonNull final I_C_NonBusinessDay record)
{
if (!record.isActive())
{
return;
}
toNonBusinessDay(record);
}
@Override
@NonNull
public I_C_Calendar getDefaultCalendar(@NonNull final OrgId orgId)
{
final I_C_Calendar calendar = queryBL.createQueryBuilder(I_C_Calendar.class)
.addEqualsFilter(I_C_Calendar.COLUMNNAME_IsDefault, true)
.addInArrayFilter(I_C_Calendar.COLUMNNAME_AD_Org_ID, ImmutableList.of(orgId, OrgId.ANY)) | .orderByDescending(I_C_Calendar.COLUMNNAME_AD_Org_ID)
.create()
.first();
if (calendar == null)
{
throw new AdempiereException(CalendarBL.MSG_SET_DEFAULT_OR_ORG_CALENDAR);
}
return calendar;
}
@Nullable
@Override
public String getName(final CalendarId calendarId)
{
final List<String> calendarNames = queryBL.createQueryBuilder(I_C_Calendar.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Calendar.COLUMNNAME_C_Calendar_ID, calendarId)
.create()
.listDistinct(I_C_Calendar.COLUMNNAME_Name, String.class);
if (calendarNames.isEmpty())
{
return null;
}
return calendarNames.get(0);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\AbstractCalendarDAO.java | 1 |
请完成以下Java代码 | public static final String evaluateParam(final CtxName name, final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
final String value = name.getValueAsString(ctx);
if (value != null && value != CtxNames.VALUE_NULL)
{
return value;
}
return evaluateMissingParameter(name, onVariableNotFound);
}
public static final String evaluateMissingParameter(final CtxName token, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
if (onVariableNotFound == OnVariableNotFound.ReturnNoResult)
{
return IStringExpression.EMPTY_RESULT;
}
else if (onVariableNotFound == OnVariableNotFound.Preserve)
{
return token.toStringWithMarkers();
}
else if (onVariableNotFound == OnVariableNotFound.Empty)
{
return ""; | }
else if (onVariableNotFound == OnVariableNotFound.Fail)
{
throw ExpressionEvaluationException.newWithTranslatableMessage("@NotFound@: " + token);
}
else
{
throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound);
}
}
private StringExpressionsHelper()
{
throw new AssertionError();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionsHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailService {
private final JavaMailSender javaMailSender;
public void sendEmail(EmailDto email) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
var message = new MimeMessageHelper(mimeMessage, true, StandardCharsets.UTF_8.name());
message.setTo(toInetArray(email.to()));
message.setCc(toInetArray(email.cc()));
message.setBcc(toInetArray(email.bcc()));
message.setFrom(email.fromEmail(), email.fromName()); | message.setSubject(email.subject());
message.setText(email.content(), email.isHtml());
for (var file : email.files()) {
message.addAttachment(file.filename(), new ByteArrayResource(file.data()));
}
javaMailSender.send(mimeMessage);
log.debug("Email Sent subject: {}", email.subject());
} catch (IOException | MessagingException e) {
throw new RuntimeException("Failed to send email", e);
}
}
} | repos\spring-boot-web-application-sample-master\email\email-service\src\main\java\gt\mail\modules\email\EmailService.java | 2 |
请完成以下Java代码 | public List<HistoricActivityInstanceDto> queryHistoricActivityInstances(HistoricActivityInstanceQueryDto queryDto, Integer firstResult, Integer maxResults) {
queryDto.setObjectMapper(objectMapper);
HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine);
List<HistoricActivityInstance> matchingHistoricActivityInstances = QueryUtil.list(query, firstResult, maxResults);
List<HistoricActivityInstanceDto> historicActivityInstanceResults = new ArrayList<HistoricActivityInstanceDto>();
for (HistoricActivityInstance historicActivityInstance : matchingHistoricActivityInstances) {
HistoricActivityInstanceDto resultHistoricActivityInstance = new HistoricActivityInstanceDto();
HistoricActivityInstanceDto.fromHistoricActivityInstance(resultHistoricActivityInstance, historicActivityInstance);
historicActivityInstanceResults.add(resultHistoricActivityInstance);
}
return historicActivityInstanceResults;
}
@Override
public CountResultDto getHistoricActivityInstancesCount(UriInfo uriInfo) { | HistoricActivityInstanceQueryDto queryDto = new HistoricActivityInstanceQueryDto(objectMapper, uriInfo.getQueryParameters());
return queryHistoricActivityInstancesCount(queryDto);
}
@Override
public CountResultDto queryHistoricActivityInstancesCount(HistoricActivityInstanceQueryDto queryDto) {
queryDto.setObjectMapper(objectMapper);
HistoricActivityInstanceQuery query = queryDto.toQuery(processEngine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricActivityInstanceRestServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private OrderService self() {
return (OrderService) AopContext.currentProxy();
}
public void method01() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
public void method02() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
public void method03() {
// 查询订单
self().method031();
// 查询用户
self().method032();
}
@Transactional // 报错,因为此时获取的是 primary 对应的 DataSource ,即 users 。
public void method031() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
}
@Transactional
public void method032() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
public void method04() {
// 查询订单
self().method041();
// 查询用户
self().method042();
}
@Transactional | @DS(DBConstants.DATASOURCE_ORDERS)
public void method041() {
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
}
@Transactional
@DS(DBConstants.DATASOURCE_USERS)
public void method042() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
@Transactional
@DS(DBConstants.DATASOURCE_ORDERS)
public void method05() {
// 查询订单
OrderDO order = orderMapper.selectById(1);
System.out.println(order);
// 查询用户
self().method052();
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
@DS(DBConstants.DATASOURCE_USERS)
public void method052() {
UserDO user = userMapper.selectById(1);
System.out.println(user);
}
} | repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\service\OrderService.java | 2 |
请完成以下Java代码 | public int getC_Queue_PackageProcessor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_PackageProcessor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Java-Klasse.
@param Classname Java-Klasse */
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Java-Klasse.
@return Java-Klasse */
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
} | /** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Interner Name.
@param InternalName
Generally used to give records a name that can be safely referenced from code.
*/
@Override
public void setInternalName (java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
/** Get Interner Name.
@return Generally used to give records a name that can be safely referenced from code.
*/
@Override
public java.lang.String getInternalName ()
{
return (java.lang.String)get_Value(COLUMNNAME_InternalName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_PackageProcessor.java | 1 |
请完成以下Spring Boot application配置 | # dubbo 配置项,对应 DubboConfigurationProperties 配置类
dubbo:
# Dubbo 应用配置
application:
name: user-service-provider # 应用名
# Dubbo 注册中心配
registry:
address: zookeeper://127.0.0.1:2181 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。
# Dubbo 服务提供者协议配置
protocol:
port: -1 # 协议端口。使用 -1 表示随机端口。
name: dubbo # 使用 `dubbo://` 协议。更多协议,可见 http://dubbo.apache.org/zh-cn/docs/user/references/protocol/in | troduction.html 文档
# Dubbo 服务提供者配置
provider:
timeout: 1000 # 【重要】远程服务调用超时时间,单位:毫秒。默认为 1000 毫秒,胖友可以根据自己业务修改
filter: -exception # 去掉 ExceptionFilter
UserRpcService:
version: 1.0.0 | repos\SpringBoot-Labs-master\lab-30\lab-30-dubbo-xml-demo\user-rpc-service-provider\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | private int getProcessedTimeOffsetMillis()
{
return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_PROCESSED_OFFSET_MILLIS, 1);
}
private void save(final I_C_Async_Batch asyncBatch)
{
Services.get(IQueueDAO.class).save(asyncBatch);
}
private int setAsyncBatchCountEnqueued(@NonNull final I_C_Queue_WorkPackage workPackage, final int offset)
{
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID());
if (asyncBatchId == null)
{
return 0;
}
lock.lock();
try
{
final I_C_Async_Batch asyncBatch = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(asyncBatchId); | final Timestamp enqueued = SystemTime.asTimestamp();
if (asyncBatch.getFirstEnqueued() == null)
{
asyncBatch.setFirstEnqueued(enqueued);
}
asyncBatch.setLastEnqueued(enqueued);
final int countEnqueued = asyncBatch.getCountEnqueued() + offset;
asyncBatch.setCountEnqueued(countEnqueued);
// we just enqueued something, so we are clearly not done yet
asyncBatch.setIsProcessing(true);
asyncBatch.setProcessed(false);
save(asyncBatch);
return countEnqueued;
}
finally
{
lock.unlock();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
} | @Override
public boolean isEnabled() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
} | repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\userservice\UserDetailsImpl.java | 2 |
请完成以下Java代码 | protected void loadDocumentDetails()
{
// nothing
}
private PPOrderId getPPOrderId()
{
return PPOrderId.ofRepoId(get_ID());
}
private I_PP_Order getPPOrder()
{
return getModel(I_PP_Order.class);
}
@Override
public BigDecimal getBalance()
{
return BigDecimal.ZERO;
}
@Override
public List<Fact> createFacts(final AcctSchema as)
{
final DocStatus docStatus = getDocStatus(); | if (docStatus.isCompletedOrClosed())
{
createOrderCosts();
}
else if (DocStatus.Voided.equals(docStatus))
{
logger.debug("Skip creating costs for voided documents");
}
else
{
throw newPostingException()
.setPreserveDocumentPostedStatus()
.setDetailMessage("Invalid document status: " + docStatus);
}
return ImmutableList.of();
}
private void createOrderCosts()
{
if (!orderCostBL.hasPPOrderCosts(getPPOrderId()))
{
orderCostBL.createOrderCosts(getPPOrder());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\acct\Doc_PPOrder.java | 1 |
请完成以下Java代码 | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
resp.setContentType("text/plain");
// 1. Direct Access From the Servlet
ServletContext contextFromServlet = this.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET + contextFromServlet);
resp.getWriter()
.println();
// 2. Accessing Through the ServletConfig
ServletConfig config = this.getServletConfig();
ServletContext contextFromConfig = config.getServletContext();
resp.getWriter()
.println(LABEL_FROM_SERVLET_CONFIG + contextFromConfig);
resp.getWriter()
.println(); | // 3. Getting the Context From the HttpServletRequest (Servlet 3.0+)
ServletContext contextFromRequest = req.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SERVLET_REQUEST + contextFromRequest);
resp.getWriter()
.println();
// 4. Retrieving Through the Session Object
ServletContext contextFromSession = req.getSession()
.getServletContext();
resp.getWriter()
.println(LABEL_FROM_HTTP_SESSION + contextFromSession);
}
} | repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\context\ContextServlet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init() {
LOG.info("init ...");
}
@Bean(name="stdOut")
@Primary
public PrintService createOutPrintService() {
LOG.info("creating PrintService stdOut");
return superService;
}
@Bean(name="stdErr")
public PrintService createErrPrintService() {
LOG.info("creating PrintService stdErr");
return printServiceStdErr;
}
@Bean
public DataService createSuperService() { | LOG.info("creating DataService");
return superService;
}
@Bean(name="prototype")
@Scope("prototype")
public DataService createSuperServicePrototype() {
LOG.info("creating DataService prototype");
return new SuperService();
}
@PreDestroy
public void shutdown() {
LOG.info("##destroy.");
}
} | repos\spring-examples-java-17\spring-di\src\main\java\itx\examples\springboot\di\config\AppConfig.java | 2 |
请完成以下Java代码 | public class Table
{
/**
* 真实值,请不要直接读取
*/
public String[][] v;
static final String HEAD = "_B";
@Override
public String toString()
{
if (v == null) return "null";
final StringBuilder sb = new StringBuilder(v.length * v[0].length * 2);
for (String[] line : v)
{
for (String element : line)
{
sb.append(element).append('\t');
}
sb.append('\n');
}
return sb.toString();
}
/**
* 获取表中某一个元素 | * @param x
* @param y
* @return
*/
public String get(int x, int y)
{
if (x < 0) return HEAD + x;
if (x >= v.length) return HEAD + "+" + (x - v.length + 1);
return v[x][y];
}
public void setLast(int x, String t)
{
v[x][v[x].length - 1] = t;
}
public int size()
{
return v.length;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\Table.java | 1 |
请完成以下Java代码 | public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
throw new IllegalArgumentException ("MKTG_Platform_ID is virtual column"); }
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
throw new IllegalArgumentException ("Name is virtual column"); }
/** Get Name.
@return Alphanumeric identifier of the entity
*/ | @Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Externe Datensatz-ID.
@param RemoteRecordId Externe Datensatz-ID */
@Override
public void setRemoteRecordId (java.lang.String RemoteRecordId)
{
throw new IllegalArgumentException ("RemoteRecordId is virtual column"); }
/** Get Externe Datensatz-ID.
@return Externe Datensatz-ID */
@Override
public java.lang.String getRemoteRecordId ()
{
return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Campaign_ContactPerson.java | 1 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_Product_ID()));
}
/** 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);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Lot.java | 1 |
请完成以下Java代码 | public int getReversal_ID()
{
return get_ValueAsInt(COLUMNNAME_Reversal_ID);
}
@Override
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 |
请在Spring Boot框架中完成以下Java代码 | public PersistentTokenRepository persistentTokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
jdbcTokenRepository.setCreateTableOnStartup(false);
return jdbcTokenRepository;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) // 添加验证码校验过滤器
.formLogin() // 表单登录
// http.httpBasic() // HTTP Basic
.loginPage("/authentication/require") // 登录跳转 URL
.loginProcessingUrl("/login") // 处理表单登录 URL
.successHandler(authenticationSucessHandler) // 处理登录成功
.failureHandler(authenticationFailureHandler) // 处理登录失败
.and() | .rememberMe()
.tokenRepository(persistentTokenRepository()) // 配置 token 持久化仓库
.tokenValiditySeconds(3600) // remember 过期时间,单为秒
.userDetailsService(userDetailService) // 处理自动登录逻辑
.and()
.authorizeRequests() // 授权配置
.antMatchers("/authentication/require",
"/login.html",
"/code/image").permitAll() // 无需认证的请求路径
.anyRequest() // 所有请求
.authenticated() // 都需要认证
.and()
.csrf().disable();
}
} | repos\SpringAll-master\37.Spring-Security-RememberMe\src\main\java\cc\mrbird\security\browser\BrowserSecurityConfig.java | 2 |
请完成以下Java代码 | public String getRoleTitle() {
return roleTitle;
}
/**
* Sets the value of the roleTitle property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRoleTitle(String value) {
this.roleTitle = value;
}
/**
* Gets the value of the role property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRole() {
return role;
}
/**
* Sets the value of the role property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRole(String value) {
this.role = value;
}
/**
* Gets the value of the place property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getPlace() {
return place;
}
/**
* Sets the value of the place property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPlace(String value) {
this.place = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BodyType.java | 1 |
请完成以下Java代码 | public LocalDate getDocumentDate()
{
return TimeUtil.asLocalDate(getMovementDate());
}
/**
* Get Process Message
*
* @return clear text error message
*/
@Override
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Currency
*
* @return C_Currency_ID
*/
@Override
public int getC_Currency_ID()
{
// MPriceList pl = MPriceList.get(getCtx(), getM_PriceList_ID());
// return pl.getC_Currency_ID();
return 0; | } // getC_Currency_ID
/**
* Is Reversal
*
* @return true if this movement is a reversal of an original movement
*/
private boolean isReversal()
{
return Services.get(IMovementBL.class).isReversal(this);
} // isReversal
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
public boolean isComplete()
{
String ds = getDocStatus();
return DOCSTATUS_Completed.equals(ds)
|| DOCSTATUS_Closed.equals(ds)
|| DOCSTATUS_Reversed.equals(ds);
} // isComplete
} // MMovement | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovement.java | 1 |
请完成以下Java代码 | private Mono<OAuth2AuthorizeRequest> authorizeRequest(String registrationId, ServerWebExchange exchange) {
Mono<Authentication> defaultedAuthentication = currentAuthentication();
Mono<String> defaultedRegistrationId = Mono.justOrEmpty(registrationId)
.switchIfEmpty(clientRegistrationId(defaultedAuthentication))
.switchIfEmpty(Mono.error(() -> new IllegalArgumentException(
"The clientRegistrationId could not be resolved. Please provide one")));
Mono<ServerWebExchange> defaultedExchange = Mono.justOrEmpty(exchange)
.switchIfEmpty(currentServerWebExchange());
return Mono.zip(defaultedRegistrationId, defaultedAuthentication, defaultedExchange)
.map((zipped) -> OAuth2AuthorizeRequest.withClientRegistrationId(zipped.getT1())
.principal(zipped.getT2())
.attribute(ServerWebExchange.class.getName(), zipped.getT3())
.build());
}
private Mono<Authentication> currentAuthentication() {
// @formatter:off
return ReactiveSecurityContextHolder.getContext()
.map(SecurityContext::getAuthentication) | .defaultIfEmpty(ANONYMOUS_USER_TOKEN);
// @formatter:on
}
private Mono<String> clientRegistrationId(Mono<Authentication> authentication) {
return authentication.filter((t) -> t instanceof OAuth2AuthenticationToken)
.cast(OAuth2AuthenticationToken.class)
.map(OAuth2AuthenticationToken::getAuthorizedClientRegistrationId);
}
private Mono<ServerWebExchange> currentServerWebExchange() {
// @formatter:off
return Mono.deferContextual(Mono::just)
.filter((c) -> c.hasKey(ServerWebExchange.class))
.map((c) -> c.get(ServerWebExchange.class));
// @formatter:on
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\reactive\result\method\annotation\OAuth2AuthorizedClientArgumentResolver.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FlipService {
private final List<Foo> foos;
public FlipService() {
foos = new ArrayList<>();
foos.add(new Foo("Foo1", 1));
foos.add(new Foo("Foo2", 2));
foos.add(new Foo("Foo3", 3));
foos.add(new Foo("Foo4", 4));
foos.add(new Foo("Foo5", 5));
foos.add(new Foo("Foo6", 6));
}
public List<Foo> getAllFoos() {
return foos;
}
public Optional<Foo> getFooById(int id) {
return foos.stream().filter(foo -> (foo.getId() == id)).findFirst();
} | @FlipBean(with = NewFlipService.class)
@FlipOnSpringExpression(expression = "(2 + 2) == 4")
public Foo getNewFoo() {
return new Foo("New Foo!", 99);
}
public Foo getLastFoo() {
return foos.get(foos.size() - 1);
}
public Foo getFirstFoo() {
return foos.get(0);
}
} | repos\tutorials-master\spring-4\src\main\java\com\baeldung\flips\service\FlipService.java | 2 |
请完成以下Java代码 | void starting(ConfigurableBootstrapContext bootstrapContext, @Nullable Class<?> mainApplicationClass) {
doWithListeners("spring.boot.application.starting", (listener) -> listener.starting(bootstrapContext),
(step) -> {
if (mainApplicationClass != null) {
step.tag("mainApplicationClass", mainApplicationClass.getName());
}
});
}
void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
doWithListeners("spring.boot.application.environment-prepared",
(listener) -> listener.environmentPrepared(bootstrapContext, environment));
}
void contextPrepared(ConfigurableApplicationContext context) {
doWithListeners("spring.boot.application.context-prepared", (listener) -> listener.contextPrepared(context));
}
void contextLoaded(ConfigurableApplicationContext context) {
doWithListeners("spring.boot.application.context-loaded", (listener) -> listener.contextLoaded(context));
}
void started(ConfigurableApplicationContext context, Duration timeTaken) {
doWithListeners("spring.boot.application.started", (listener) -> listener.started(context, timeTaken));
}
void ready(ConfigurableApplicationContext context, Duration timeTaken) {
doWithListeners("spring.boot.application.ready", (listener) -> listener.ready(context, timeTaken));
}
void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) {
doWithListeners("spring.boot.application.failed",
(listener) -> callFailedListener(listener, context, exception), (step) -> {
step.tag("exception", exception.getClass().toString());
String message = exception.getMessage();
if (message != null) {
step.tag("message", message);
}
});
} | private void callFailedListener(SpringApplicationRunListener listener,
@Nullable ConfigurableApplicationContext context, Throwable exception) {
try {
listener.failed(context, exception);
}
catch (Throwable ex) {
if (exception == null) {
ReflectionUtils.rethrowRuntimeException(ex);
}
if (this.log.isDebugEnabled()) {
this.log.error("Error handling failed", ex);
}
else {
String message = ex.getMessage();
message = (message != null) ? message : "no error message";
this.log.warn("Error handling failed (" + message + ")");
}
}
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction) {
doWithListeners(stepName, listenerAction, null);
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction,
@Nullable Consumer<StartupStep> stepAction) {
StartupStep step = this.applicationStartup.start(stepName);
this.listeners.forEach(listenerAction);
if (stepAction != null) {
stepAction.accept(step);
}
step.end();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationRunListeners.java | 1 |
请完成以下Java代码 | private I_M_HU extractHU(final ViewRowAttributesKey key)
{
final HuId huId = HuId.ofRepoId(key.getHuId().toInt());
final I_M_HU hu = handlingUnitsRepo.getByIdOutOfTrx(huId);
if (hu == null)
{
throw new IllegalArgumentException("No HU found for M_HU_ID=" + huId);
}
return hu;
}
private static DocumentPath toDocumentPath(final ViewRowAttributesKey key)
{
final DocumentId documentTypeId = key.getHuId();
final DocumentId huEditorRowId = key.getHuEditorRowId();
return DocumentPath.rootDocumentPath(DocumentType.ViewRecordAttributes, documentTypeId, huEditorRowId);
}
private IAttributeStorageFactory getAttributeStorageFactory()
{ | return _attributeStorageFactory.get();
}
private IAttributeStorageFactory createAttributeStorageFactory()
{
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return attributeStorageFactoryService.createHUAttributeStorageFactory(storageFactory);
}
@Override
public void invalidateAll()
{
//
// Destroy AttributeStorageFactory
_attributeStorageFactory.forget();
//
// Destroy attribute documents
rowAttributesByKey.clear();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesProvider.java | 1 |
请完成以下Java代码 | private JsonProductInfo createProduct(
@NonNull final String productCode,
@NonNull final String productName,
@NonNull final XmlToOLCandsService.HighLevelContext context)
{
return JsonProductInfo.builder()
.syncAdvise(context.getProductsSyncAdvise())
.code(productCode)
.name(productName)
.type(JsonProductInfo.Type.SERVICE)
.uomCode(UOM_CODE)
.build();
}
private BigDecimal createPrice(@NonNull final RecordOtherType recordOtherType)
{
return createPrice(
recordOtherType.getUnit(),
recordOtherType.getUnitFactor(), | recordOtherType.getExternalFactor());
}
private BigDecimal createPrice(
@Nullable final BigDecimal unit,
@Nullable final BigDecimal unitFactor,
@Nullable final BigDecimal externalFactor)
{
final BigDecimal unitToUse = coalesce(unit, ONE); // tax point (TP) of the applied service
final BigDecimal unitFactorToUse = coalesce(unitFactor, ONE); // tax point value (TPV) of the applied service
final BigDecimal externalFactorToUse = coalesce(externalFactor, ONE);
return unitToUse.multiply(unitFactorToUse).multiply(externalFactorToUse);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_rest-api\src\main\java\de\metas\vertical\healthcare\forum_datenaustausch_ch\rest\xml_to_olcands\XmlServiceRecordUtil.java | 1 |
请完成以下Java代码 | public class CmmnDiEdgeXmlConverter extends BaseCmmnXmlConverter {
@Override
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_DI_EDGE;
}
@Override
public boolean hasChildElements() {
return false;
}
@Override
protected BaseElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
CmmnDiEdge diEdge = new CmmnDiEdge(); | diEdge.setId(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_ID));
diEdge.setCmmnElementRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_CMMN_ELEMENT_REF));
diEdge.setTargetCmmnElementRef(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_DI_TARGET_CMMN_ELEMENT_REF));
conversionHelper.addDiEdge(diEdge);
return diEdge;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
conversionHelper.setCurrentDiEdge(null);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\CmmnDiEdgeXmlConverter.java | 1 |
请完成以下Java代码 | public List<T> fetchByMultipleIds(List<ID> ids) {
Session session = entityManager.unwrap(Session.class);
MultiIdentifierLoadAccess<T> multiLoadAccess
= session.byMultipleIds(entityClass);
List<T> result = multiLoadAccess.multiLoad(ids);
return result;
}
@Override
public List<T> fetchInBatchesByMultipleIds(List<ID> ids, int batchSize) {
List<T> result = getMultiLoadAccess().withBatchSize(batchSize).multiLoad(ids);
return result;
}
@Override
public List<T> fetchBySessionCheckMultipleIds(List<ID> ids) {
List<T> result = getMultiLoadAccess().enableSessionCheck(true).multiLoad(ids);
return result;
}
@Override
public List<T> fetchInBatchesBySessionCheckMultipleIds(List<ID> ids, int batchSize) { | List<T> result = getMultiLoadAccess().enableSessionCheck(true)
.withBatchSize(batchSize).multiLoad(ids);
return result;
}
private MultiIdentifierLoadAccess<T> getMultiLoadAccess() {
Session session = entityManager.unwrap(Session.class);
return session.byMultipleIds(entityClass);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootLoadMultipleIds\src\main\java\com\bookstore\multipleids\MultipleIdsRepositoryImpl.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.