instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public List<I_AD_UI_Section> getUISections(final AdTabId adTabId)
{
// Generate the UI elements if needed
if (!adTabId2sections.containsKey(adTabId))
{
final WindowUIElementsGenerator generator = WindowUIElementsGenerator.forConsumer(this);
final I_AD_Tab adTab = Services.get(IADWindowDAO.class).getTabByIdInTrx(adTabId);
final boolean primaryTab = adTab.getTabLevel() == 0;
if (primaryTab)
{
generator.migratePrimaryTab(adTab);
}
else
{
generator.migrateDetailTab(adTab);
}
}
return adTabId2sections.get(adTabId);
}
@Override
public void consume(final I_AD_UI_Column uiColumn, final I_AD_UI_Section parent)
{
logger.debug("Generated in memory {} for {}", uiColumn, parent);
section2columns.put(parent, uiColumn);
}
@Override
public List<I_AD_UI_Column> getUIColumns(final I_AD_UI_Section uiSection)
{
return section2columns.get(uiSection);
}
@Override
public void consume(final I_AD_UI_ElementGroup uiElementGroup, final I_AD_UI_Column parent)
{
logger.debug("Generated in memory {} for {}", uiElementGroup, parent);
column2elementGroups.put(parent, uiElementGroup);
}
@Override
public List<I_AD_UI_ElementGroup> getUIElementGroups(final I_AD_UI_Column uiColumn)
{
return column2elementGroups.get(uiColumn);
}
@Override
public void consume(final I_AD_UI_Element uiElement, final I_AD_UI_ElementGroup parent)
{
|
logger.debug("Generated in memory {} for {}", uiElement, parent);
elementGroup2elements.put(parent, uiElement);
}
@Override
public List<I_AD_UI_Element> getUIElements(final I_AD_UI_ElementGroup uiElementGroup)
{
return elementGroup2elements.get(uiElementGroup);
}
@Override
public List<I_AD_UI_Element> getUIElementsOfType(@NonNull final AdTabId adTabId, @NonNull final LayoutElementType layoutElementType)
{
return elementGroup2elements.values().stream()
.filter(uiElement -> layoutElementType.getCode().equals(uiElement.getAD_UI_ElementType()))
.collect(ImmutableList.toImmutableList());
}
@Override
public void consume(final I_AD_UI_ElementField uiElementField, final I_AD_UI_Element parent)
{
logger.debug("Generated in memory {} for {}", uiElementField, parent);
element2elementFields.put(parent, uiElementField);
}
@Override
public List<I_AD_UI_ElementField> getUIElementFields(final I_AD_UI_Element uiElement)
{
return element2elementFields.get(uiElement);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\InMemoryUIElementsProvider.java
| 1
|
请完成以下Java代码
|
private static MessageDigest getSha512Digest() {
try {
return MessageDigest.getInstance("SHA-512");
}
catch (NoSuchAlgorithmException ex) {
throw new RuntimeException(ex.getMessage());
}
}
/**
* Calculates the SHA digest and returns the value as a <code>byte[]</code>.
* @param data Data to digest
* @return SHA digest
*/
public static byte[] sha(byte[] data) {
return getSha512Digest().digest(data);
}
/**
* Calculates the SHA digest and returns the value as a <code>byte[]</code>.
* @param data Data to digest
* @return SHA digest
*/
public static byte[] sha(String data) {
return sha(data.getBytes());
}
/**
* Calculates the SHA digest and returns the value as a hex string.
|
* @param data Data to digest
* @return SHA digest as a hex string
*/
public static String shaHex(byte[] data) {
return new String(Hex.encode(sha(data)));
}
/**
* Calculates the SHA digest and returns the value as a hex string.
* @param data Data to digest
* @return SHA digest as a hex string
*/
public static String shaHex(String data) {
return new String(Hex.encode(sha(data)));
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\token\Sha512DigestUtils.java
| 1
|
请完成以下Java代码
|
public ServerResponse render(String name, Map<String, ?> model) {
return new GatewayRenderingResponseBuilder(name).status(this.statusCode)
.headers(headers -> headers.putAll(this.headers))
.cookies(cookies -> cookies.addAll(this.cookies))
.modelAttributes(model)
.build();
}
@Override
public ServerResponse stream(Consumer<ServerResponse.StreamBuilder> streamConsumer) {
return GatewayStreamingServerResponse.create(this.statusCode, this.headers, this.cookies, streamConsumer, null);
}
private static class WriteFunctionResponse extends AbstractGatewayServerResponse {
private final WriteFunction writeFunction;
|
WriteFunctionResponse(HttpStatusCode statusCode, HttpHeaders headers, MultiValueMap<String, Cookie> cookies,
WriteFunction writeFunction) {
super(statusCode, headers, cookies);
Objects.requireNonNull(writeFunction, "WriteFunction must not be null");
this.writeFunction = writeFunction;
}
@Override
protected @Nullable ModelAndView writeToInternal(HttpServletRequest request, HttpServletResponse response,
Context context) throws Exception {
return this.writeFunction.write(request, response);
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayServerResponseBuilder.java
| 1
|
请完成以下Java代码
|
public void setDataEntry_TargetWindow(final org.compiere.model.I_AD_Window DataEntry_TargetWindow)
{
set_ValueFromPO(COLUMNNAME_DataEntry_TargetWindow_ID, org.compiere.model.I_AD_Window.class, DataEntry_TargetWindow);
}
@Override
public void setDataEntry_TargetWindow_ID (final int DataEntry_TargetWindow_ID)
{
if (DataEntry_TargetWindow_ID < 1)
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, null);
else
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, DataEntry_TargetWindow_ID);
}
@Override
public int getDataEntry_TargetWindow_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_TargetWindow_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
|
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTabName (final java.lang.String TabName)
{
set_Value (COLUMNNAME_TabName, TabName);
}
@Override
public java.lang.String getTabName()
{
return get_ValueAsString(COLUMNNAME_TabName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Tab.java
| 1
|
请完成以下Java代码
|
public class MapDeserializer implements JsonDeserializer<Map<String, Object>> {
@Override
public Map<String, Object> deserialize(JsonElement elem, Type type, JsonDeserializationContext context) throws JsonParseException {
return elem.getAsJsonObject()
.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().isJsonPrimitive() ?
toPrimitive(e.getValue().getAsJsonPrimitive(), context)
: context.deserialize(e.getValue(), Employee.class)
));
}
private Object toPrimitive(JsonPrimitive jsonValue, JsonDeserializationContext context) {
if (jsonValue.isBoolean())
return jsonValue.getAsBoolean();
else if (jsonValue.isString())
return jsonValue.getAsString();
else {
BigDecimal bigDec = jsonValue.getAsBigDecimal();
Long l;
Integer i;
if ((i = toInteger(bigDec)) != null) {
|
return i;
} else if ((l = toLong(bigDec)) != null) {
return l;
} else {
return bigDec.doubleValue();
}
}
}
private Long toLong(BigDecimal val) {
try {
return val.toBigIntegerExact().longValue();
} catch (ArithmeticException e) {
return null;
}
}
private Integer toInteger(BigDecimal val) {
try {
return val.intValueExact();
} catch (ArithmeticException e) {
return null;
}
}
}
|
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\serialization\MapDeserializer.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) {
log.debug("REST request to update User : {}", userDTO);
Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
throw new EmailAlreadyUsedException();
}
existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase());
if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
throw new LoginAlreadyUsedException();
}
Optional<UserDTO> updatedUser = userService.updateUser(userDTO);
return ResponseUtil.wrapOrNotFound(updatedUser,
HeaderUtil.createAlert("A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin()));
}
/**
* GET /users : get all users.
*
* @param pageable the pagination information
* @return the ResponseEntity with status 200 (OK) and with body all users
*/
@GetMapping("/users")
public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* @return a string list of the all of the roles
*/
@GetMapping("/users/authorities")
@PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
public List<String> getAuthorities() {
return userService.getAuthorities();
}
/**
* GET /users/:login : get the "login" user.
*
* @param login the login of the user to find
* @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
*/
|
@GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
public ResponseEntity<UserDTO> getUser(@PathVariable String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(
userService.getUserWithAuthoritiesByLogin(login)
.map(UserDTO::new));
}
/**
* DELETE /users/:login : delete the "login" User.
*
* @param login the login of the user to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
@PreAuthorize("hasRole(\"" + AuthoritiesConstants.ADMIN + "\")")
public ResponseEntity<Void> deleteUser(@PathVariable String login) {
log.debug("REST request to delete User: {}", login);
userService.deleteUser(login);
return ResponseEntity.ok().headers(HeaderUtil.createAlert( "A user is deleted with identifier " + login, login)).build();
}
}
|
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\UserResource.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_C_BP_Group getC_BP_Group_Match()
{
return get_ValueAsPO(COLUMNNAME_C_BP_Group_Match_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setC_BP_Group_Match(final org.compiere.model.I_C_BP_Group C_BP_Group_Match)
{
set_ValueFromPO(COLUMNNAME_C_BP_Group_Match_ID, org.compiere.model.I_C_BP_Group.class, C_BP_Group_Match);
}
@Override
public void setC_BP_Group_Match_ID (final int C_BP_Group_Match_ID)
{
if (C_BP_Group_Match_ID < 1)
set_Value (COLUMNNAME_C_BP_Group_Match_ID, null);
else
set_Value (COLUMNNAME_C_BP_Group_Match_ID, C_BP_Group_Match_ID);
}
@Override
public int getC_BP_Group_Match_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_Group_Match_ID);
}
@Override
public de.metas.contracts.commission.model.I_C_LicenseFeeSettings getC_LicenseFeeSettings()
{
return get_ValueAsPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class);
}
@Override
public void setC_LicenseFeeSettings(final de.metas.contracts.commission.model.I_C_LicenseFeeSettings C_LicenseFeeSettings)
{
set_ValueFromPO(COLUMNNAME_C_LicenseFeeSettings_ID, de.metas.contracts.commission.model.I_C_LicenseFeeSettings.class, C_LicenseFeeSettings);
}
@Override
public void setC_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID)
{
if (C_LicenseFeeSettings_ID < 1)
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, null);
else
set_Value (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID);
}
@Override
public int getC_LicenseFeeSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID);
|
}
@Override
public void setC_LicenseFeeSettingsLine_ID (final int C_LicenseFeeSettingsLine_ID)
{
if (C_LicenseFeeSettingsLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettingsLine_ID, C_LicenseFeeSettingsLine_ID);
}
@Override
public int getC_LicenseFeeSettingsLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettingsLine_ID);
}
@Override
public void setPercentOfBasePoints (final BigDecimal PercentOfBasePoints)
{
set_Value (COLUMNNAME_PercentOfBasePoints, PercentOfBasePoints);
}
@Override
public BigDecimal getPercentOfBasePoints()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PercentOfBasePoints);
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.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettingsLine.java
| 1
|
请完成以下Java代码
|
public static LookupValuesPage ofValuesAndHasMoreFlag(@NonNull final List<LookupValue> values, boolean hasMoreRecords)
{
return ofValuesAndHasMoreFlag(LookupValuesList.fromCollection(values), hasMoreRecords);
}
public static LookupValuesPage ofValuesAndHasMoreFlag(@NonNull final LookupValuesList values, boolean hasMoreRecords)
{
return builder()
.totalRows(OptionalInt.empty()) // N/A
.firstRow(-1) // N/A
.values(values)
.hasMoreResults(OptionalBoolean.ofBoolean(hasMoreRecords))
.build();
}
public static LookupValuesPage allValues(@NonNull final LookupValuesList values)
{
return builder()
.totalRows(OptionalInt.of(values.size())) // N/A
.firstRow(0) // N/A
.values(values)
.hasMoreResults(OptionalBoolean.FALSE)
|
.build();
}
public static LookupValuesPage ofNullable(@Nullable final LookupValue lookupValue)
{
if (lookupValue == null)
{
return EMPTY;
}
return allValues(LookupValuesList.fromNullable(lookupValue));
}
public <T> T transform(@NonNull final Function<LookupValuesPage, T> transformation)
{
return transformation.apply(this);
}
public boolean isEmpty()
{
return values.isEmpty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValuesPage.java
| 1
|
请完成以下Java代码
|
public class RegistrationForm {
@NotBlank(groups = BasicInfo.class)
private String firstName;
@NotBlank(groups = BasicInfo.class)
private String lastName;
@Email(groups = BasicInfo.class)
private String email;
@NotBlank(groups = BasicInfo.class)
private String phone;
@NotBlank(groups = { BasicInfo.class, AdvanceInfo.class })
private String captcha;
@NotBlank(groups = AdvanceInfo.class)
private String street;
@NotBlank(groups = AdvanceInfo.class)
private String houseNumber;
@NotBlank(groups = AdvanceInfo.class)
private String zipCode;
@NotBlank(groups = AdvanceInfo.class)
private String city;
@NotBlank(groups = AdvanceInfo.class)
private String country;
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getCaptcha() {
return captcha;
}
public void setCaptcha(String captcha) {
this.captcha = captcha;
}
}
|
repos\tutorials-master\javaxval\src\main\java\com\baeldung\javaxval\validationgroup\RegistrationForm.java
| 1
|
请完成以下Java代码
|
public void beforeSave_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct)
{
updateItemProduct(itemProduct);
setUOMItemProduct(itemProduct);
Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct);
// Validate the item product only if is saved.
validateItemProduct(itemProduct);
}
@CalloutMethod(columnNames = {
I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_ID,
I_M_HU_PI_Item_Product.COLUMNNAME_Qty,
I_M_HU_PI_Item_Product.COLUMNNAME_IsInfiniteCapacity
})
public void onManualChange_M_HU_PI_Item_Product(final I_M_HU_PI_Item_Product itemProduct, final ICalloutField field)
{
updateItemProduct(itemProduct);
setUOMItemProduct(itemProduct);
Services.get(IHUPIItemProductBL.class).setNameAndDescription(itemProduct);
}
private void updateItemProduct(final I_M_HU_PI_Item_Product itemProduct)
{
if (itemProduct.isAllowAnyProduct())
{
|
itemProduct.setM_Product_ID(-1);
itemProduct.setIsInfiniteCapacity(true);
}
}
private void setUOMItemProduct(final I_M_HU_PI_Item_Product huPiItemProduct)
{
final ProductId productId = ProductId.ofRepoIdOrNull(huPiItemProduct.getM_Product_ID());
if (productId == null)
{
// nothing to do
return;
}
final UomId stockingUOMId = Services.get(IProductBL.class).getStockUOMId(productId);
huPiItemProduct.setC_UOM_ID(stockingUOMId.getRepoId());
}
private void validateItemProduct(final I_M_HU_PI_Item_Product itemProduct)
{
if (Services.get(IHUCapacityBL.class).isValidItemProduct(itemProduct))
{
return;
}
final String errorMsg = Services.get(IMsgBL.class).getMsg(InterfaceWrapperHelper.getCtx(itemProduct), M_HU_PI_Item_Product.MSG_QUANTITY_INVALID);
throw new AdempiereException(errorMsg);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\M_HU_PI_Item_Product.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the codeQualifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCodeQualifier() {
return codeQualifier;
}
/**
* Sets the value of the codeQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCodeQualifier(String value) {
this.codeQualifier = value;
}
/**
* Gets the value of the internalId property.
*
* @return
* possible object is
* {@link String }
*
|
*/
public String getInternalId() {
return internalId;
}
/**
* Sets the value of the internalId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInternalId(String value) {
this.internalId = value;
}
/**
* Gets the value of the internalSubId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInternalSubId() {
return internalSubId;
}
/**
* Sets the value of the internalSubId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInternalSubId(String value) {
this.internalSubId = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\SenderType.java
| 2
|
请完成以下Java代码
|
private static List<String> getColumnHeaders()
{
return ImmutableList.of(
I_M_HU_Trace.COLUMNNAME_LotNumber,
I_M_HU_Trace.COLUMNNAME_HUTraceType,
I_M_HU_Trace.COLUMNNAME_M_Product_ID,
I_M_HU_Trace.COLUMNNAME_M_InOut_ID,
I_M_HU_Trace.COLUMNNAME_PP_Order_ID,
I_M_HU_Trace.COLUMNNAME_M_Inventory_ID,
I_M_InOut.COLUMNNAME_MovementDate,
I_M_HU_Trace.COLUMNNAME_Qty,
I_M_Product.COLUMNNAME_C_UOM_ID,
"Detail_Type",
"Finished_Product_No",
"Finished_Product_Name",
"Finished_Product_Qty",
|
"Finished_Product_UOM",
"Finished_Product_Lot",
"Vendor_Lot",
"Finished_Product_Mhd",
"Finished_Product_Clearance",
"Customer_Vendor_No",
"Customer_Vendor",
"ShipmentQty",
"Shipment_Note",
"Shipment_Date",
"Prod_Stock",
"TraceId",
"ReportDate"
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\trace\process\M_HU_Trace_Report_Excel.java
| 1
|
请完成以下Java代码
|
private final void markSkipped(final I_PMM_QtyReport_Event event, final I_PMM_PurchaseCandidate candidate, final String errorMsg)
{
event.setErrorMsg(errorMsg);
InterfaceWrapperHelper.save(event);
if (errorMsg != null)
{
Loggables.addLog("Event " + event + " skipped: " + errorMsg);
}
countSkipped.incrementAndGet();
}
private boolean isProcessedByFutureEvent(final I_PMM_PurchaseCandidate candidate, final I_PMM_QtyReport_Event currentEvent)
{
if (candidate == null)
{
return false;
}
final int lastQtyReportEventId = candidate.getLast_QtyReport_Event_ID();
if (lastQtyReportEventId > currentEvent.getPMM_QtyReport_Event_ID())
{
return true;
}
return false;
}
public String getProcessSummary()
{
return "@Processed@ #" + countProcessed.get()
+ ", @IsError@ #" + countErrors.get()
+ ", @Skipped@ #" + countSkipped.get();
}
@VisibleForTesting
|
static PMMBalanceChangeEvent createPMMBalanceChangeEvent(final I_PMM_QtyReport_Event qtyReportEvent)
{
final BigDecimal qtyPromisedDiff = qtyReportEvent.getQtyPromised().subtract(qtyReportEvent.getQtyPromised_Old());
final BigDecimal qtyPromisedTUDiff = qtyReportEvent.getQtyPromised_TU().subtract(qtyReportEvent.getQtyPromised_TU_Old());
final PMMBalanceChangeEvent event = PMMBalanceChangeEvent.builder()
.setC_BPartner_ID(qtyReportEvent.getC_BPartner_ID())
.setM_Product_ID(qtyReportEvent.getM_Product_ID())
.setM_AttributeSetInstance_ID(qtyReportEvent.getM_AttributeSetInstance_ID())
.setM_HU_PI_Item_Product_ID(qtyReportEvent.getM_HU_PI_Item_Product_ID())
.setC_Flatrate_DataEntry_ID(qtyReportEvent.getC_Flatrate_DataEntry_ID())
//
.setDate(qtyReportEvent.getDatePromised())
//
.setQtyPromised(qtyPromisedDiff, qtyPromisedTUDiff)
//
.build();
logger.trace("Created event {} from {}", event, qtyReportEvent);
return event;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMQtyReportEventTrxItemProcessor.java
| 1
|
请完成以下Java代码
|
public File locatePom(File projectDirectory) {
File pomFile = new File(projectDirectory, JSON_POM);
if (!pomFile.exists()) {
pomFile = new File(projectDirectory, XML_POM);
}
return pomFile;
}
@Override
public Model read(InputStream input, Map<String, ?> options) throws IOException, ModelParseException {
try (final Reader in = ReaderFactory.newPlatformReader(input)) {
return read(in, options);
}
}
@Override
|
public Model read(Reader reader, Map<String, ?> options) throws IOException, ModelParseException {
FileModelSource source = (options != null) ? (FileModelSource) options.get(SOURCE) : null;
if (source != null && source.getLocation().endsWith(JSON_EXT)) {
Model model = objectMapper.readValue(reader, Model.class);
return model;
}
//It's a normal maven project with a pom.xml file
return modelReader.read(reader, options);
}
@Override
public Model read(File input, Map<String, ?> options) throws IOException, ModelParseException {
return null;
}
}
|
repos\tutorials-master\maven-modules\maven-polyglot\maven-polyglot-json-extension\src\main\java\com\demo\polyglot\CustomModelProcessor.java
| 1
|
请完成以下Java代码
|
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
@Override
public void setURL (java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
|
@Override
public java.lang.String getURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_URL);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_AD_InputDataSource.java
| 1
|
请完成以下Java代码
|
public class StatsActor extends ContextAwareActor {
public StatsActor(ActorSystemContext context) {
super(context);
}
@Override
protected boolean doProcess(TbActorMsg msg) {
log.debug("Received message: {}", msg);
if (msg.getMsgType().equals(MsgType.STATS_PERSIST_MSG)) {
onStatsPersistMsg((StatsPersistMsg) msg);
return true;
} else {
return false;
}
}
public void onStatsPersistMsg(StatsPersistMsg msg) {
if (msg.isEmpty()) {
return;
}
systemContext.getEventService().saveAsync(StatisticsEvent.builder()
.tenantId(msg.getTenantId())
.entityId(msg.getEntityId().getId())
.serviceId(systemContext.getServiceInfoProvider().getServiceId())
.messagesProcessed(msg.getMessagesProcessed())
.errorsOccurred(msg.getErrorsOccurred())
.build()
|
);
}
private JsonNode toBodyJson(String serviceId, long messagesProcessed, long errorsOccurred) {
return JacksonUtil.newObjectNode().put("server", serviceId).put("messagesProcessed", messagesProcessed).put("errorsOccurred", errorsOccurred);
}
public static class ActorCreator extends ContextBasedCreator {
private final String actorId;
public ActorCreator(ActorSystemContext context, String actorId) {
super(context);
this.actorId = actorId;
}
@Override
public TbActorId createActorId() {
return new TbStringActorId(actorId);
}
@Override
public TbActor createActor() {
return new StatsActor(context);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\stats\StatsActor.java
| 1
|
请完成以下Java代码
|
private void setIsExportedShipmentToCustomsInvoice(@NonNull final CustomsInvoice customsInvoice)
{
customsInvoice
.getLines()
.stream()
.forEach(line -> setIsExportedShipmentToCustomsInvoiceLine(line));
}
private void setIsExportedShipmentToCustomsInvoiceLine(@NonNull final CustomsInvoiceLine customsInvoiceLine)
{
final IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
customsInvoiceLine.getAllocations()
.stream()
.map(alloc -> alloc.getInoutAndLineId().getInOutId())
.forEach(shipment -> inOutDAO.setExportedInCustomsInvoice(shipment));
}
private CustomsInvoiceLine allocateShipmentLine(
@NonNull final CustomsInvoiceLine customsInvoiceLineForProduct,
@NonNull final InOutAndLineId inOutAndLineId,
@NonNull final CurrencyId currencyId)
{
final IUOMConversionBL uomConversionBL = Services.get(IUOMConversionBL.class);
final CustomsInvoiceLineAlloc existingAlloc = customsInvoiceLineForProduct.getAllocationByInOutLineId(inOutAndLineId).orElse(null);
Quantity qty = customsInvoiceLineForProduct.getQuantity();
Money lineNetAmt = customsInvoiceLineForProduct.getLineNetAmt();
if (existingAlloc != null)
{
final Quantity existingAllocQty = existingAlloc.getQuantityInPriceUOM();
final Money existingAllocNetAmt = existingAlloc.getNetAmt();
qty = Quantitys.subtract(UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), qty, existingAllocQty);
lineNetAmt = lineNetAmt.subtract(existingAllocNetAmt);
customsInvoiceLineForProduct.removeAllocation(existingAlloc);
}
final CustomsInvoiceLineAlloc newAlloc;
{
final Quantity inoutLineQty = getInOutLineQty(inOutAndLineId);
|
final ProductPrice inoutLinePrice = getInOutLinePriceConverted(inOutAndLineId, currencyId);
final Quantity inoutLineQtyInPriceUOM = uomConversionBL.convertQuantityTo(inoutLineQty, UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), inoutLinePrice.getUomId());
newAlloc = CustomsInvoiceLineAlloc.builder()
.inoutAndLineId(inOutAndLineId)
.price(inoutLinePrice.toMoney())
.quantityInPriceUOM(inoutLineQtyInPriceUOM)
.build();
customsInvoiceLineForProduct.addAllocation(newAlloc);
}
qty = Quantitys.add(UOMConversionContext.of(customsInvoiceLineForProduct.getProductId()), qty, newAlloc.getQuantityInPriceUOM());
lineNetAmt = lineNetAmt.add(newAlloc.getNetAmt());
return customsInvoiceLineForProduct.toBuilder()
.lineNetAmt(lineNetAmt)
.quantity(qty)
.build();
}
private Optional<CustomsInvoiceLine> findCustomsInvoiceLineForProductId(@NonNull final ProductId productId, @NonNull final Collection<CustomsInvoiceLine> existingLines)
{
return existingLines.stream()
.filter(line -> line.getProductId().equals(productId))
.findFirst();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\customs\CustomsInvoiceService.java
| 1
|
请完成以下Java代码
|
public class XmlIntrospectionUtil
{
private static final String SCHEMA_LOCATION = "schemaLocation";
public static String extractXsdValueOrNull(@NonNull final byte[] xmlInput)
{
return extractXsdValueOrNull(new ByteArrayInputStream(xmlInput));
}
/**
* Extracts the XSD schema name; For the sake of performance, only check the first element.
*/
public static String extractXsdValueOrNull(@NonNull final InputStream xmlInput)
{
final XMLInputFactory f = XMLInputFactory.newInstance();
try
{
final XMLStreamReader r = f.createXMLStreamReader(xmlInput);
while (r.hasNext())
{
final int eventType = r.next();
if (XMLStreamReader.START_ELEMENT == eventType)
{
for (int i = 0; i <= r.getAttributeCount(); i++)
{
final boolean foundSchemaNameSpace = XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(r.getAttributeNamespace(i));
final boolean foundLocationAttributeName = SCHEMA_LOCATION.equals(r.getAttributeLocalName(i));
if (foundSchemaNameSpace && foundLocationAttributeName)
{
return r.getAttributeValue(i);
}
|
}
return null; // only checked the first element
}
}
return null;
}
catch (final XMLStreamException e)
{
throw new XsdValueExtractionFailedException(e);
}
}
public static class XsdValueExtractionFailedException extends RuntimeException
{
private static final long serialVersionUID = 8456946625940728739L;
private XsdValueExtractionFailedException(@NonNull final XMLStreamException e)
{
super(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\xml\XmlIntrospectionUtil.java
| 1
|
请完成以下Java代码
|
public class TextEditorContextMenuAction extends AbstractContextMenuAction
{
private Boolean scriptEditor = null;
public boolean isScriptEditor()
{
if (scriptEditor != null)
{
return scriptEditor;
}
final VEditor editor = getEditor();
if (editor == null)
{
return false;
}
final GridField gridField = editor.getField();
final String columnName = gridField.getColumnName();
if (columnName == null)
{
return false;
}
if (columnName.equals("Script") || columnName.endsWith("_Script"))
{
scriptEditor = true;
}
else
{
scriptEditor = false;
}
return scriptEditor;
}
@Override
public String getName()
{
return isScriptEditor() ? "Script" : "Editor";
}
@Override
public String getIcon()
{
return isScriptEditor() ? "Script16" : "Editor16";
}
@Override
public boolean isAvailable()
{
final GridField gridField = getEditor().getField();
if (gridField == null)
{
return false;
}
final int displayType = gridField.getDisplayType();
if (displayType == DisplayType.Text || displayType == DisplayType.URL)
{
if (gridField.getFieldLength() > gridField.getDisplayLength())
{
return true;
}
else
{
return false;
}
}
else if (displayType == DisplayType.TextLong
|| displayType == DisplayType.Memo)
{
return true;
}
|
else
{
return false;
}
}
@Override
public boolean isRunnable()
{
return true;
}
@Override
public void run()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
final Object value = editor.getValue();
final String text = value == null ? null : value.toString();
final boolean editable = editor.isReadWrite();
final String textNew = startEditor(gridField, text, editable);
if (editable)
{
gridField.getGridTab().setValue(gridField, textNew);
}
// TODO: i think is handled above
// Data Binding
// try
// {
// fireVetoableChange(m_columnName, m_oldText, getText());
// }
// catch (PropertyVetoException pve)
// {
// }
}
protected String startEditor(final GridField gridField, final String text, final boolean editable)
{
final Properties ctx = Env.getCtx();
final String columnName = gridField.getColumnName();
final String title = Services.get(IMsgBL.class).translate(ctx, columnName);
final int windowNo = gridField.getWindowNo();
final Frame frame = Env.getWindow(windowNo);
final String textNew;
if (gridField.getDisplayType() == DisplayType.TextLong)
{
// Start it
HTMLEditor ed = new HTMLEditor (frame, title, text, editable);
textNew = ed.getHtmlText();
}
else
{
final Container comp = (Container)getEditor();
final int fieldLength = gridField.getFieldLength();
textNew = Editor.startEditor(comp, title, text, editable, fieldLength);
}
return textNew;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\menu\TextEditorContextMenuAction.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getNextServiceDate() {
return nextServiceDate;
}
public void setNextServiceDate(String nextServiceDate) {
this.nextServiceDate = nextServiceDate;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceToCreateMaintenances deviceToCreateMaintenances = (DeviceToCreateMaintenances) o;
return Objects.equals(this.maintenanceCode, deviceToCreateMaintenances.maintenanceCode) &&
Objects.equals(this.maintenanceInterval, deviceToCreateMaintenances.maintenanceInterval) &&
Objects.equals(this.lastServiceDate, deviceToCreateMaintenances.lastServiceDate) &&
Objects.equals(this.nextServiceDate, deviceToCreateMaintenances.nextServiceDate);
}
@Override
public int hashCode() {
return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate);
}
|
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceToCreateMaintenances {\n");
sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n");
sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n");
sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n");
sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java
| 2
|
请完成以下Java代码
|
public class UserDao {
SessionFactory sessionFactory;
public UserDao() {
this(null);
}
@Inject
public UserDao(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Object add(User user) {
Session session = sessionFactory.openSession();
session.beginTransaction();
Object Id = session.save(user);
|
session.getTransaction().commit();
return Id;
}
public User findByEmail(String email) {
Session session = sessionFactory.openSession();
session.beginTransaction();
Criteria criteria = session.createCriteria(User.class);
criteria.add(Restrictions.eq("email", email));
criteria.setMaxResults(1);
User u = (User) criteria.uniqueResult();
session.getTransaction().commit();
session.close();
return u;
}
}
|
repos\tutorials-master\web-modules\vraptor\src\main\java\com\baeldung\daos\UserDao.java
| 1
|
请完成以下Java代码
|
public String getModus() {
if (modus == null) {
return "production";
} else {
return modus;
}
}
/**
* Sets the value of the modus property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setModus(String value) {
this.modus = value;
}
/**
* Gets the value of the validationStatus property.
*
* @return
* possible object is
* {@link Long }
*
|
*/
public Long getValidationStatus() {
return validationStatus;
}
/**
* Sets the value of the validationStatus property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setValidationStatus(Long value) {
this.validationStatus = 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\RequestType.java
| 1
|
请完成以下Java代码
|
default String getNonce() {
return this.getClaimAsString(IdTokenClaimNames.NONCE);
}
/**
* Returns the Authentication Context Class Reference {@code (acr)}.
* @return the Authentication Context Class Reference
*/
default String getAuthenticationContextClass() {
return this.getClaimAsString(IdTokenClaimNames.ACR);
}
/**
* Returns the Authentication Methods References {@code (amr)}.
* @return the Authentication Methods References
*/
default List<String> getAuthenticationMethods() {
return this.getClaimAsStringList(IdTokenClaimNames.AMR);
}
/**
* Returns the Authorized party {@code (azp)} to which the ID Token was issued.
* @return the Authorized party to which the ID Token was issued
*/
default String getAuthorizedParty() {
return this.getClaimAsString(IdTokenClaimNames.AZP);
|
}
/**
* Returns the Access Token hash value {@code (at_hash)}.
* @return the Access Token hash value
*/
default String getAccessTokenHash() {
return this.getClaimAsString(IdTokenClaimNames.AT_HASH);
}
/**
* Returns the Authorization Code hash value {@code (c_hash)}.
* @return the Authorization Code hash value
*/
default String getAuthorizationCodeHash() {
return this.getClaimAsString(IdTokenClaimNames.C_HASH);
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\IdTokenClaimAccessor.java
| 1
|
请完成以下Java代码
|
private void logRequest(final MTLinkRequest request, final String msgSuffix)
{
logger.debug(request + msgSuffix); // log the request
Loggables.addLog(request.getModel() + msgSuffix); // don't be too verbose in the user/admin output; keep it readable.
}
@Override
public boolean unlinkModelFromMaterialTrackings(final Object model)
{
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model);
for (final I_M_Material_Tracking_Ref exitingRef : existingRefs)
{
unlinkModelFromMaterialTracking(model, exitingRef);
}
return true;
}
@Override
public boolean unlinkModelFromMaterialTrackings(final Object model, @NonNull final I_M_Material_Tracking materialTracking)
{
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
final List<I_M_Material_Tracking_Ref> existingRefs = materialTrackingDAO.retrieveMaterialTrackingRefsForModel(model);
if (existingRefs.isEmpty())
{
return false;
}
|
boolean atLeastOneUnlinked = false;
for (final I_M_Material_Tracking_Ref exitingRef : existingRefs)
{
if (exitingRef.getM_Material_Tracking_ID() != materialTracking.getM_Material_Tracking_ID())
{
continue;
}
unlinkModelFromMaterialTracking(model, exitingRef);
atLeastOneUnlinked = true;
}
return atLeastOneUnlinked;
}
private final void unlinkModelFromMaterialTracking(final Object model, final I_M_Material_Tracking_Ref ref)
{
final I_M_Material_Tracking materialTrackingOld = ref.getM_Material_Tracking();
InterfaceWrapperHelper.delete(ref);
listeners.afterModelUnlinked(model, materialTrackingOld);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingBL.java
| 1
|
请完成以下Java代码
|
public FacetCollectorRequestBuilder<ModelType> includeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.include(facetCategory);
return this;
}
/**
* Advice to NOT collect facets from given exclude facet categories, even if they were added to include list.
*
* @param facetCategory
*/
public FacetCollectorRequestBuilder<ModelType> excludeFacetCategory(final IFacetCategory facetCategory)
{
facetCategoryIncludesExcludes.exclude(facetCategory);
return this;
}
/**
*
* @param facetCategory
* @return true if given facet category shall be considered when collecting facets
*/
public boolean acceptFacetCategory(final IFacetCategory facetCategory)
{
// Don't accept it if is excluded by includes/excludes list
if (!facetCategoryIncludesExcludes.build().test(facetCategory))
|
{
return false;
}
// Only categories which have "eager refresh" set (if asked)
if (onlyEagerRefreshCategories && !facetCategory.isEagerRefresh())
{
return false;
}
// accept the facet category
return true;
}
/**
* Collect facets only for categories which have {@link IFacetCategory#isEagerRefresh()}.
*/
public FacetCollectorRequestBuilder<ModelType> setOnlyEagerRefreshCategories()
{
this.onlyEagerRefreshCategories = true;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\FacetCollectorRequestBuilder.java
| 1
|
请完成以下Java代码
|
public DmnTypeDefinition getTypeDefinition() {
return typeDefinition;
}
public void setTypeDefinition(DmnTypeDefinition typeDefinition) {
this.typeDefinition = typeDefinition;
}
public String getExpressionLanguage() {
return expressionLanguage;
}
public void setExpressionLanguage(String expressionLanguage) {
this.expressionLanguage = expressionLanguage;
}
public String getExpression() {
return expression;
}
public void setExpression(String expression) {
this.expression = expression;
}
@Override
public String toString() {
return "DmnExpressionImpl{" +
|
"id='" + id + '\'' +
", name='" + name + '\'' +
", typeDefinition=" + typeDefinition +
", expressionLanguage='" + expressionLanguage + '\'' +
", expression='" + expression + '\'' +
'}';
}
public void cacheCompiledScript(CompiledScript compiledScript) {
this.cachedCompiledScript = compiledScript;
}
public CompiledScript getCachedCompiledScript() {
return this.cachedCompiledScript;
}
public ElExpression getCachedExpression() {
return this.cachedExpression;
}
public void setCachedExpression(ElExpression expression) {
this.cachedExpression = expression;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnExpressionImpl.java
| 1
|
请完成以下Java代码
|
public void setProxyPort (int ProxyPort)
{
set_Value (COLUMNNAME_ProxyPort, Integer.valueOf(ProxyPort));
}
/** Get Proxy port.
@return Port of your proxy server
*/
@Override
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Require CreditCard Verification Code.
@param RequireVV
Require 3/4 digit Credit Verification Code
*/
@Override
public void setRequireVV (boolean RequireVV)
{
set_Value (COLUMNNAME_RequireVV, Boolean.valueOf(RequireVV));
}
/** Get Require CreditCard Verification Code.
@return Require 3/4 digit Credit Verification Code
*/
@Override
public boolean isRequireVV ()
{
Object oo = get_Value(COLUMNNAME_RequireVV);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
|
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/** Set Vendor ID.
@param VendorID
Vendor ID for the Payment Processor
*/
@Override
public void setVendorID (java.lang.String VendorID)
{
set_Value (COLUMNNAME_VendorID, VendorID);
}
/** Get Vendor ID.
@return Vendor ID for the Payment Processor
*/
@Override
public java.lang.String getVendorID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VendorID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java
| 1
|
请完成以下Java代码
|
static DataFetcherExceptionResolverAdapter forSingleError(
BiFunction<Throwable, DataFetchingEnvironment, GraphQLError> resolver) {
return new DataFetcherExceptionResolverAdapter() {
@Override
protected GraphQLError resolveToSingleError(Throwable ex, DataFetchingEnvironment env) {
return resolver.apply(ex, env);
}
};
}
/**
* Factory method to create a {@link DataFetcherExceptionHandler} from a
* list of {@link DataFetcherExceptionResolver}'s. This is used internally
* in {@link AbstractGraphQlSourceBuilder} to set the exception handler on
* {@link graphql.GraphQL.Builder}, which in turn is used to create
|
* {@link graphql.execution.ExecutionStrategy}'s. Applications may also use
* this method to create an exception handler when they to need to initialize
* a custom {@code ExecutionStrategy}.
* <p>Resolvers are invoked in turn until one resolves the exception by
* emitting a (possibly empty) {@code GraphQLError} list. If the exception
* remains unresolved, the handler creates a {@code GraphQLError} with
* {@link ErrorType#INTERNAL_ERROR} and a short message with the execution id.
* @param resolvers the list of resolvers to use
* @return the created {@link DataFetcherExceptionHandler} instance
* @since 1.1.1
*/
static DataFetcherExceptionHandler createExceptionHandler(List<DataFetcherExceptionResolver> resolvers) {
return new ExceptionResolversExceptionHandler(resolvers);
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DataFetcherExceptionResolver.java
| 1
|
请完成以下Java代码
|
public void setRecord (int AD_Table_ID, int Record_ID)
{
setAD_Table_ID(AD_Table_ID);
setRecord_ID(Record_ID);
} // setRecord
public void setRecord (final TableRecordReference record)
{
if(record != null)
{
setRecord(record.getAD_Table_ID(), record.getRecord_ID());
}
else
{
setRecord(-1, -1);
}
}
|
/**
* String Representation
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer ("MNote[")
.append(get_ID()).append(",AD_Message_ID=").append(getAD_Message_ID())
.append(",").append(getReference())
.append(",Processed=").append(isProcessed())
.append("]");
return sb.toString();
} // toString
} // MNote
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNote.java
| 1
|
请完成以下Java代码
|
public VPanelFormFieldBuilder setAutocomplete(boolean autocomplete)
{
this.autocomplete = autocomplete;
return this;
}
private int getAD_Column_ID()
{
// not set is allowed
return AD_Column_ID;
}
/**
* @param AD_Column_ID Column for lookups.
*/
public VPanelFormFieldBuilder setAD_Column_ID(int AD_Column_ID)
{
this.AD_Column_ID = AD_Column_ID;
return this;
}
public VPanelFormFieldBuilder setAD_Column_ID(final String tableName, final String columnName)
{
return setAD_Column_ID(Services.get(IADTableDAO.class).retrieveColumn(tableName, columnName).getAD_Column_ID());
}
private EventListener getEditorListener()
{
// null allowed
return editorListener;
}
/**
* @param listener VetoableChangeListener that gets called if the field is changed.
*/
public VPanelFormFieldBuilder setEditorListener(EventListener listener)
{
|
this.editorListener = listener;
return this;
}
public VPanelFormFieldBuilder setBindEditorToModel(boolean bindEditorToModel)
{
this.bindEditorToModel = bindEditorToModel;
return this;
}
public VPanelFormFieldBuilder setReadOnly(boolean readOnly)
{
this.readOnly = readOnly;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelFormFieldBuilder.java
| 1
|
请完成以下Java代码
|
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Exclusion From Sale Reason.
@param ExclusionFromSaleReason Exclusion From Sale Reason */
@Override
public void setExclusionFromSaleReason (java.lang.String ExclusionFromSaleReason)
{
set_Value (COLUMNNAME_ExclusionFromSaleReason, ExclusionFromSaleReason);
}
/** Get Exclusion From Sale Reason.
@return Exclusion From Sale Reason */
@Override
public java.lang.String getExclusionFromSaleReason ()
{
return (java.lang.String)get_Value(COLUMNNAME_ExclusionFromSaleReason);
}
/** Set Banned Manufacturer .
@param M_BannedManufacturer_ID Banned Manufacturer */
@Override
public void setM_BannedManufacturer_ID (int M_BannedManufacturer_ID)
{
if (M_BannedManufacturer_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_BannedManufacturer_ID, Integer.valueOf(M_BannedManufacturer_ID));
}
/** Get Banned Manufacturer .
@return Banned Manufacturer */
@Override
public int getM_BannedManufacturer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_BannedManufacturer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner getManufacturer() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class);
|
}
@Override
public void setManufacturer(org.compiere.model.I_C_BPartner Manufacturer)
{
set_ValueFromPO(COLUMNNAME_Manufacturer_ID, org.compiere.model.I_C_BPartner.class, Manufacturer);
}
/** Set Hersteller.
@param Manufacturer_ID
Hersteller des Produktes
*/
@Override
public void setManufacturer_ID (int Manufacturer_ID)
{
if (Manufacturer_ID < 1)
set_Value (COLUMNNAME_Manufacturer_ID, null);
else
set_Value (COLUMNNAME_Manufacturer_ID, Integer.valueOf(Manufacturer_ID));
}
/** Get Hersteller.
@return Hersteller des Produktes
*/
@Override
public int getManufacturer_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Manufacturer_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BannedManufacturer.java
| 1
|
请完成以下Java代码
|
public class WebLogAspect {
@Around("execution(public * com..controller.*.*(..))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
//获取当前请求对象
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//记录请求信息
StopWatch stopWatch = new StopWatch();
stopWatch.start();
Object result = pjp.proceed();
stopWatch.stop();
Signature signature = pjp.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
String urlStr = request.getRequestURL().toString();
log.info("===================================begin==================================================");
log.info("req path: {}", StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
log.info("req ip: {}", request.getRemoteUser());
log.info("req method: {}", request.getMethod());
log.info("req params: {}", getParameter(method, pjp.getArgs()));
log.info("req result: {}", JSONUtil.toJsonStr(result));
log.info("req uri: {}", request.getRequestURI());
log.info("req url: {}", request.getRequestURL().toString());
log.info("req cost: {}ms", stopWatch.getLastTaskTimeMillis());
log.info("===================================end===================================================");
return result;
}
/**
|
* 根据方法和传入的参数获取请求参数
*/
private Object getParameter(Method method, Object[] args) {
List<Object> argList = new ArrayList<>();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
//将RequestBody注解修饰的参数作为请求参数
RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
if (requestBody != null) {
argList.add(args[i]);
}
//将RequestParam注解修饰的参数作为请求参数
RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
if (requestParam != null) {
Map<String, Object> map = new HashMap<>();
String key = parameters[i].getName();
if (!StringUtils.isEmpty(requestParam.value())) {
key = requestParam.value();
}
map.put(key, args[i]);
argList.add(map);
}
}
if (argList.size() == 0) {
return null;
} else if (argList.size() == 1) {
return argList.get(0);
} else {
return argList;
}
}
}
|
repos\spring-boot-quick-master\quick-platform-component\src\main\java\com\quick\component\config\logAspect\WebLogAspect.java
| 1
|
请完成以下Java代码
|
public static Object convertToDisplayType(final String value, final String columnName, final int displayType)
{
// true NULL
if (value == null || value.isEmpty())
{
return null;
}
// see also MTable.readData
try
{
//
// Handle hardcoded cases
// IDs & Integer & CreatedBy/UpdatedBy
if (!Check.isEmpty(columnName))
{
if ("CreatedBy".equals(columnName)
|| "UpdatedBy".equals(columnName)
|| (columnName.endsWith("_ID") && DisplayType.isID(displayType))) // teo_sarca [ 1672725 ] Process parameter that ends with _ID but is boolean
{
try
// defaults -1 => null
{
final int ii = java.lang.Integer.parseInt(value);
if (ii < 0)
return null;
return ii;
}
catch (final Exception e)
{
s_log.warn("Cannot parse: " + value + " - ColumnName=" + columnName + ", DisplayType=" + displayType + ". Returning ZERO.", e);
}
return 0;
}
}
// Integer
if (displayType == DisplayType.Integer)
{
return new java.lang.Integer(value);
}
// Number
if (DisplayType.isNumeric(displayType))
{
return new BigDecimal(value);
}
// Timestamps
if (DisplayType.isDate(displayType))
{
// try timestamp format - then date format -- [ 1950305 ]
java.util.Date date = null;
try
{
date = DisplayType.getTimestampFormat_Default().parse(value);
}
catch (final java.text.ParseException e)
{
date = DisplayType.getDateFormat_JDBC().parse(value);
}
return new Timestamp(date.getTime());
}
// Boolean
if (displayType == DisplayType.YesNo)
{
return toBoolean(value);
}
// Default
return value;
}
catch (final Exception e)
{
s_log.error("Error while converting value '" + value + "', ColumnName=" + columnName + ", DisplayType=" + displayType, e);
|
}
return null;
}
/**
* Delegates to {@link StringUtils#toBoolean(Object, Boolean)}.
*/
@Nullable
public static Boolean toBoolean(@Nullable final Object value, @Nullable final Boolean defaultValue)
{
return StringUtils.toBoolean(value, defaultValue);
}
@NonNull
public static Boolean toBooleanNonNull(@Nullable final Object value, final boolean defaultValue)
{
return StringUtils.toBoolean(value, defaultValue);
}
/**
* Delegates to {@link StringUtils#toBoolean(Object, Boolean)}.
*/
public static boolean toBoolean(@Nullable final Object value)
{
return StringUtils.toBoolean(value);
}
/**
* Delegates to {@link StringUtils#ofBoolean(Boolean)}.
*/
@Nullable
public static String toBooleanString(@Nullable final Boolean value)
{
return StringUtils.ofBoolean(value);
}
} // DisplayType
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\DisplayType.java
| 1
|
请完成以下Java代码
|
public class Declarables {
private final Collection<Declarable> declarables;
public Declarables(Declarable... declarables) {
if (!ObjectUtils.isEmpty(declarables)) {
this.declarables = new ArrayList<>(declarables.length);
this.declarables.addAll(Arrays.asList(declarables));
}
else {
this.declarables = new ArrayList<>();
}
}
public Declarables(Collection<? extends Declarable> declarables) {
Assert.notNull(declarables, "declarables cannot be null");
this.declarables = new ArrayList<>(declarables.size());
this.declarables.addAll(declarables);
}
public Collection<Declarable> getDeclarables() {
return this.declarables;
}
|
/**
* Return the elements that are instances of the provided class.
* @param <T> The type.
* @param type the type's class.
* @return the filtered list.
* @since 2.2
*/
public <T extends Declarable> List<T> getDeclarablesByType(Class<? extends T> type) {
return this.declarables.stream()
.filter(type::isInstance)
.map(type::cast)
.collect(Collectors.toList());
}
@Override
public String toString() {
return "Declarables [declarables=" + this.declarables + "]";
}
}
|
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\Declarables.java
| 1
|
请完成以下Java代码
|
public static ContextPath ofJson(@NonNull String json)
{
return new ContextPath(
SPLITTER.splitToList(json)
.stream()
.map(ContextPathElement::ofJson)
.collect(ImmutableList.toImmutableList())
);
}
public static ContextPath root(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return new ContextPath(ImmutableList.of(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
entityDescriptor.getWindowId().toInt())
));
}
static String extractName(final @NonNull DocumentEntityDescriptor entityDescriptor)
{
final String tableName = entityDescriptor.getTableNameOrNull();
return tableName != null ? tableName : entityDescriptor.getInternalName();
}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson()
{
String json = this._json;
if (json == null)
{
json = this._json = computeJson();
}
return json;
}
private String computeJson()
{
return elements.stream()
.map(ContextPathElement::toJson)
.collect(Collectors.joining("."));
}
public ContextPath newChild(@NonNull final String name)
{
return newChild(ContextPathElement.ofName(name));
}
public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return newChild(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull())
));
}
private ContextPath newChild(@NonNull final ContextPathElement element)
{
return new ContextPath(ImmutableList.<ContextPathElement>builder()
.addAll(elements)
.add(element)
.build());
}
|
public AdWindowId getAdWindowId()
{
return AdWindowId.ofRepoId(elements.get(0).getId());
}
@Override
public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value
class ContextPathElement
{
@NonNull String name;
int id;
@JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1));
return new ContextPathElement(name, id);
}
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java
| 1
|
请完成以下Java代码
|
public void validate(ValidatingMigrationInstruction instruction, final ValidatingMigrationInstructions instructions,
MigrationInstructionValidationReportImpl report) {
ActivityImpl targetActivity = instruction.getTargetActivity();
FlowScopeWalker flowScopeWalker = new FlowScopeWalker(targetActivity.getFlowScope());
MiBodyCollector miBodyCollector = new MiBodyCollector();
flowScopeWalker.addPreVisitor(miBodyCollector);
// walk until a target scope is found that is mapped
flowScopeWalker.walkWhile(new WalkCondition<ScopeImpl>() {
@Override
public boolean isFulfilled(ScopeImpl element) {
return element == null || !instructions.getInstructionsByTargetScope(element).isEmpty();
}
});
if (miBodyCollector.firstMiBody != null) {
report.addFailure("Target activity '" + targetActivity.getId() + "' is a descendant of multi-instance body '" +
miBodyCollector.firstMiBody.getId() + "' that is not mapped from the source process definition.");
}
}
public static class MiBodyCollector implements TreeVisitor<ScopeImpl> {
|
protected ScopeImpl firstMiBody;
@Override
public void visit(ScopeImpl obj) {
if (firstMiBody == null && obj != null && isMiBody(obj)) {
firstMiBody = obj;
}
}
protected boolean isMiBody(ScopeImpl scope) {
return scope.getActivityBehavior() instanceof MultiInstanceActivityBehavior;
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instruction\CannotAddMultiInstanceBodyValidator.java
| 1
|
请完成以下Java代码
|
public static boolean checkContainment(Geometry point, Geometry polygon) {
boolean isInside = polygon.contains(point);
log.info("Is the point inside polygon? {}", isInside);
return isInside;
}
public static boolean checkIntersect(Geometry rectangle1, Geometry rectangle2) {
boolean intersect = rectangle1.intersects(rectangle2);
Geometry overlap = rectangle1.intersection(rectangle2);
log.info("Do both rectangle intersect? {}", intersect);
log.info("Overlapping Area: {}", overlap);
return intersect;
}
public static Geometry getBuffer(Geometry point, int intBuffer) {
Geometry buffer = point.buffer(intBuffer);
log.info("Buffer Geometry: {}", buffer);
return buffer;
}
public static double getDistance(Geometry point1, Geometry point2) {
double distance = point1.distance(point2);
log.info("Distance: {}",distance);
return distance;
}
public static Geometry getUnion(Geometry geometry1, Geometry geometry2) {
Geometry union = geometry1.union(geometry2);
|
log.info("Union Result: {}", union);
return union;
}
public static Geometry getDifference(Geometry base, Geometry cut) {
Geometry result = base.difference(cut);
log.info("Resulting Geometry: {}", result);
return result;
}
public static Geometry validateAndRepair(Geometry invalidGeo) throws Exception {
boolean valid = invalidGeo.isValid();
log.info("Is valid Geometry value? {}", valid);
Geometry repaired = invalidGeo.buffer(0);
log.info("Repaired Geometry: {}", repaired);
return repaired;
}
}
|
repos\tutorials-master\jts\src\main\java\com\baeldung\jts\operations\JTSOperationUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class RedisHttpSessionConfiguration extends AbstractRedisHttpSessionConfiguration<RedisSessionRepository>
implements EmbeddedValueResolverAware, ImportAware {
private StringValueResolver embeddedValueResolver;
private SessionIdGenerator sessionIdGenerator = UuidSessionIdGenerator.getInstance();
@Bean
@Override
public RedisSessionRepository sessionRepository() {
RedisTemplate<String, Object> redisTemplate = createRedisTemplate();
RedisSessionRepository sessionRepository = new RedisSessionRepository(redisTemplate);
sessionRepository.setDefaultMaxInactiveInterval(getMaxInactiveInterval());
if (StringUtils.hasText(getRedisNamespace())) {
sessionRepository.setRedisKeyNamespace(getRedisNamespace());
}
sessionRepository.setFlushMode(getFlushMode());
sessionRepository.setSaveMode(getSaveMode());
sessionRepository.setSessionIdGenerator(this.sessionIdGenerator);
getSessionRepositoryCustomizers()
.forEach((sessionRepositoryCustomizer) -> sessionRepositoryCustomizer.customize(sessionRepository));
return sessionRepository;
}
@Override
public void setEmbeddedValueResolver(StringValueResolver resolver) {
this.embeddedValueResolver = resolver;
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
|
Map<String, Object> attributeMap = importMetadata
.getAnnotationAttributes(EnableRedisHttpSession.class.getName());
AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap);
if (attributes == null) {
return;
}
setMaxInactiveInterval(Duration.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds")));
String redisNamespaceValue = attributes.getString("redisNamespace");
if (StringUtils.hasText(redisNamespaceValue)) {
setRedisNamespace(this.embeddedValueResolver.resolveStringValue(redisNamespaceValue));
}
setFlushMode(attributes.getEnum("flushMode"));
setSaveMode(attributes.getEnum("saveMode"));
}
@Autowired(required = false)
public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
this.sessionIdGenerator = sessionIdGenerator;
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\RedisHttpSessionConfiguration.java
| 2
|
请完成以下Java代码
|
public void sendError(int sc) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc, msg);
}
@Override
public void sendRedirect(String location) throws IOException {
appendSameSiteIfMissing();
super.sendRedirect(location);
}
@Override
public PrintWriter getWriter() throws IOException {
appendSameSiteIfMissing();
return super.getWriter();
}
@Override
|
public ServletOutputStream getOutputStream() throws IOException {
appendSameSiteIfMissing();
return super.getOutputStream();
}
protected void appendSameSiteIfMissing() {
Collection<String> cookieHeaders = response.getHeaders(CookieConstants.SET_COOKIE_HEADER_NAME);
boolean firstHeader = true;
String cookieHeaderStart = cookieConfigurator.getCookieName("JSESSIONID") + "=";
for (String cookieHeader : cookieHeaders) {
if (cookieHeader.startsWith(cookieHeaderStart)) {
cookieHeader = cookieConfigurator.getConfig(cookieHeader);
}
if (firstHeader) {
response.setHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
firstHeader = false;
} else {
response.addHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
}
}
}
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SessionCookieFilter.java
| 1
|
请完成以下Java代码
|
private void invoiceNew (MRequest request)
{
m_invoice = new MInvoice (getCtx(), 0, get_TrxName());
m_invoice.setIsSOTrx(true);
I_C_BPartner partner = Services.get(IBPartnerDAO.class).getById(request.getC_BPartner_ID());
m_invoice.setBPartner(partner);
m_invoice.save();
m_linecount = 0;
} // invoiceNew
/**
* Invoice Line
* @param request request
*/
private void invoiceLine (MRequest request)
{
MRequestUpdate[] updates = request.getUpdates(null);
for (int i = 0; i < updates.length; i++)
{
BigDecimal qty = updates[i].getQtyInvoiced();
if (qty == null || qty.signum() == 0)
continue;
|
// if (updates[i].getC_InvoiceLine_ID() > 0)
// continue;
MInvoiceLine il = new MInvoiceLine(m_invoice);
m_linecount++;
il.setLine(m_linecount*10);
//
il.setQty(qty);
// Product
int M_Product_ID = updates[i].getM_ProductSpent_ID();
if (M_Product_ID == 0)
M_Product_ID = p_M_Product_ID;
il.setM_Product_ID(M_Product_ID);
//
il.setPrice();
il.save();
// updates[i].setC_InvoiceLine_ID(il.getC_InvoiceLine_ID());
// updates[i].save();
}
} // invoiceLine
} // RequestInvoice
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\RequestInvoice.java
| 1
|
请完成以下Java代码
|
public String getDepartment() {
return department;
}
/**
* Sets the value of the department property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDepartment(String value) {
this.department = value;
}
/**
* Gets the value of the subaddressing property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSubaddressing() {
return subaddressing;
}
/**
* Sets the value of the subaddressing property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSubaddressing(String value) {
this.subaddressing = value;
}
/**
* Gets the value of the postal property.
*
* @return
* possible object is
* {@link PostalAddressType }
*
*/
public PostalAddressType getPostal() {
return postal;
}
/**
* Sets the value of the postal property.
*
* @param value
* allowed object is
* {@link PostalAddressType }
*
*/
public void setPostal(PostalAddressType value) {
this.postal = value;
}
|
/**
* Gets the value of the telecom property.
*
* @return
* possible object is
* {@link TelecomAddressType }
*
*/
public TelecomAddressType getTelecom() {
return telecom;
}
/**
* Sets the value of the telecom property.
*
* @param value
* allowed object is
* {@link TelecomAddressType }
*
*/
public void setTelecom(TelecomAddressType value) {
this.telecom = value;
}
/**
* Gets the value of the online property.
*
* @return
* possible object is
* {@link OnlineAddressType }
*
*/
public OnlineAddressType getOnline() {
return online;
}
/**
* Sets the value of the online property.
*
* @param value
* allowed object is
* {@link OnlineAddressType }
*
*/
public void setOnline(OnlineAddressType value) {
this.online = 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\CompanyType.java
| 1
|
请完成以下Java代码
|
public void setGreaterThanAlphabetic(boolean greaterThanAlphabetic) {
this.greaterThanAlphabetic = greaterThanAlphabetic;
}
public boolean isGreaterThanOrEqual() {
return greaterThanOrEqual;
}
public void setGreaterThanOrEqual(boolean greaterThanOrEqual) {
this.greaterThanOrEqual = greaterThanOrEqual;
}
public boolean isGreaterThanOrEqualAlphabetic() {
return greaterThanOrEqualAlphabetic;
}
public void setGreaterThanOrEqualAlphabetic(boolean greaterThanOrEqualAlphabetic) {
this.greaterThanOrEqualAlphabetic = greaterThanOrEqualAlphabetic;
}
public boolean isAnd() {
return and;
}
public void setAnd(boolean and) {
this.and = and;
}
public boolean isAndAlphabetic() {
return andAlphabetic;
}
public void setAndAlphabetic(boolean andAlphabetic) {
this.andAlphabetic = andAlphabetic;
}
public boolean isOr() {
return or;
}
public void setOr(boolean or) {
this.or = or;
}
public boolean isOrAlphabetic() {
return orAlphabetic;
}
public void setOrAlphabetic(boolean orAlphabetic) {
this.orAlphabetic = orAlphabetic;
}
public boolean isNot() {
return not;
}
public void setNot(boolean not) {
this.not = not;
}
public boolean isNotAlphabetic() {
return notAlphabetic;
|
}
public void setNotAlphabetic(boolean notAlphabetic) {
this.notAlphabetic = notAlphabetic;
}
@Override
public String toString() {
return "SpelRelational{" +
"equal=" + equal +
", equalAlphabetic=" + equalAlphabetic +
", notEqual=" + notEqual +
", notEqualAlphabetic=" + notEqualAlphabetic +
", lessThan=" + lessThan +
", lessThanAlphabetic=" + lessThanAlphabetic +
", lessThanOrEqual=" + lessThanOrEqual +
", lessThanOrEqualAlphabetic=" + lessThanOrEqualAlphabetic +
", greaterThan=" + greaterThan +
", greaterThanAlphabetic=" + greaterThanAlphabetic +
", greaterThanOrEqual=" + greaterThanOrEqual +
", greaterThanOrEqualAlphabetic=" + greaterThanOrEqualAlphabetic +
", and=" + and +
", andAlphabetic=" + andAlphabetic +
", or=" + or +
", orAlphabetic=" + orAlphabetic +
", not=" + not +
", notAlphabetic=" + notAlphabetic +
'}';
}
}
|
repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelRelational.java
| 1
|
请完成以下Java代码
|
public void setDefault()
{
} // setDefault
// -----------------------------------------------------
@Override
public ColorUIResource getFocusColor()
{
return getPrimary2();
}
@Override
public ColorUIResource getPrimaryControlShadow()
{
return getPrimary3();
}
@Override
public ColorUIResource getMenuSelectedBackground()
{
return getPrimary1();
}
@Override
public ColorUIResource getMenuSelectedForeground()
{
return WHITE;
}
@Override
public ColorUIResource getMenuItemBackground()
{
return WHITE;
}
@Override
public ColorUIResource getToggleButtonCheckColor()
|
{
return new ColorUIResource(220, 241, 203);
}
@Override
public void addCustomEntriesToTable(final UIDefaults table)
{
super.addCustomEntriesToTable(table);
final Object[] uiDefaults =
{
"ScrollBar.thumbHighlight", getPrimaryControlHighlight(),
PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(22),
PlasticScrollBarUI.MAX_BUMPS_WIDTH_KEY, new Integer(30),
// TabbedPane
// "TabbedPane.selected", getWhite(),
"TabbedPane.selectHighlight", new ColorUIResource(231, 218, 188),
"TabbedPane.unselectedBackground", null, // let AdempiereTabbedPaneUI calculate it
AdempiereLookAndFeel.ERROR_BG_KEY, error,
AdempiereLookAndFeel.ERROR_FG_KEY, txt_error,
AdempiereLookAndFeel.INACTIVE_BG_KEY, inactive,
AdempiereLookAndFeel.INFO_BG_KEY, info,
AdempiereLookAndFeel.MANDATORY_BG_KEY, mandatory
};
table.putDefaults(uiDefaults);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereTheme.java
| 1
|
请完成以下Java代码
|
protected String getCleanVersion(String versionString) {
Matcher matcher = CLEAN_VERSION_REGEX.matcher(versionString);
if (!matcher.find()) {
throw new FlowableException("Illegal format for version: " + versionString);
}
String cleanString = matcher.group();
try {
Double.parseDouble(cleanString); // try to parse it, to see if it is
// really a number
return cleanString;
} catch (NumberFormatException nfe) {
throw new FlowableException("Illegal format for version: " + versionString, nfe);
}
}
|
protected ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return CommandContextUtil.getProcessEngineConfiguration();
}
@Override
protected String getResourcesRootDirectory() {
return "org/flowable/db/";
}
@Override
public String getContext() {
return "bpmn";
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\db\ProcessDbSchemaManager.java
| 1
|
请完成以下Java代码
|
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return prepareNewContext()
.requiresParameters(dependsOnContextVariables)
.requiresFilterAndLimit();
}
private LookupDataSourceContext.Builder prepareNewContext()
{
return LookupDataSourceContext.builder(CONTEXT_LookupTableName);
}
@Override
public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
final LookupValueFilterPredicate filter = evalCtx.getFilterPredicate();
final int limit = evalCtx.getLimit(Integer.MAX_VALUE);
final int offset = evalCtx.getOffset(0);
return attributeValuesProvider.getAvailableValues(evalCtx)
.stream()
.map(namePair -> StringLookupValue.of(
namePair.getID(),
TranslatableStrings.constant(namePair.getName()),
TranslatableStrings.constant(namePair.getDescription())))
.filter(filter)
.collect(LookupValuesList.collect())
.pageByOffsetAndLimit(offset, limit);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
|
}
@Override
public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
if (attributeValuesProvider instanceof DefaultAttributeValuesProvider)
{
final DefaultAttributeValuesProvider defaultAttributeValuesProvider = (DefaultAttributeValuesProvider)attributeValuesProvider;
final AttributeId attributeId = defaultAttributeValuesProvider.getAttributeId();
return SqlForFetchingLookupById.builder()
.keyColumnNameFQ(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_Value))
.numericKey(false)
.displayColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Name))
.descriptionColumn(ConstantStringExpression.of(I_M_AttributeValue.COLUMNNAME_Description))
.activeColumn(ColumnNameFQ.ofTableAndColumnName(I_M_AttributeValue.Table_Name, I_M_AttributeValue.COLUMNNAME_IsActive))
.sqlFrom(ConstantStringExpression.of(I_M_AttributeValue.Table_Name))
.additionalWhereClause(I_M_AttributeValue.Table_Name + "." + I_M_AttributeValue.COLUMNNAME_M_Attribute_ID + "=" + attributeId.getRepoId())
.build();
}
else
{
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pattribute\ASILookupDescriptor.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCreate_datetime() {
return create_datetime;
}
public void setCreate_datetime(String create_datetime) {
this.create_datetime = create_datetime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
|
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
}
|
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\entities\Persons.java
| 1
|
请完成以下Java代码
|
protected mxRectangle apply(TreeNode node, mxRectangle bounds) {
mxRectangle g = graph.getModel().getGeometry(node.cell);
if (node.cell != null && g != null) {
if (isVertexMovable(node.cell)) {
g = setVertexLocation(node.cell, node.x, node.y);
}
if (bounds == null) {
bounds = new mxRectangle(g.getX(), g.getY(), g.getWidth(), g.getHeight());
} else {
bounds = new mxRectangle(
Math.min(bounds.getX(), g.getX()),
Math.min(bounds.getY(), g.getY()),
Math.max(bounds.getX() + bounds.getWidth(), g.getX() + g.getWidth()),
Math.max(bounds.getY() + bounds.getHeight(), g.getY() + g.getHeight())
);
}
}
return bounds;
}
/**
*
*/
protected Polyline createLine(double dx, double dy, Polyline next) {
return new Polyline(dx, dy, next);
}
/**
*
*/
protected static class TreeNode {
/**
*
*/
protected Object cell;
/**
*
*/
protected double x, y, width, height, offsetX, offsetY;
/**
*
*/
protected TreeNode child, next; // parent, sibling
/**
*
|
*/
protected Polygon contour = new Polygon();
/**
*
*/
public TreeNode(Object cell) {
this.cell = cell;
}
}
/**
*
*/
protected static class Polygon {
/**
*
*/
protected Polyline lowerHead, lowerTail, upperHead, upperTail;
}
/**
*
*/
protected static class Polyline {
/**
*
*/
protected double dx, dy;
/**
*
*/
protected Polyline next;
/**
*
*/
protected Polyline(double dx, double dy, Polyline next) {
this.dx = dx;
this.dy = dy;
this.next = next;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-layout\src\main\java\org\activiti\bpmn\BPMNLayout.java
| 1
|
请完成以下Java代码
|
public void addReview(Review review) {
this.reviews.add(review);
review.setBook(this);
}
public void removeReview(Review review) {
review.setBook(null);
this.reviews.remove(review);
}
public void removeReviews() {
Iterator<Review> iterator = this.reviews.iterator();
while (iterator.hasNext()) {
Review review = iterator.next();
review.setBook(null);
iterator.remove();
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public List<Review> getReviews() {
return reviews;
}
|
public void setReviews(List<Review> reviews) {
this.reviews = reviews;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootPropertyExpressions\src\main\java\com\bookstore\entity\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getMessageAcknowledgementCode() {
return messageAcknowledgementCode;
}
/**
* Sets the value of the messageAcknowledgementCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMessageAcknowledgementCode(String value) {
this.messageAcknowledgementCode = value;
}
/**
* Gets the value of the functionalGroupAcknowledgementCode property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getFunctionalGroupAcknowledgementCode() {
return functionalGroupAcknowledgementCode;
}
/**
* Sets the value of the functionalGroupAcknowledgementCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFunctionalGroupAcknowledgementCode(String value) {
this.functionalGroupAcknowledgementCode = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\CONTRLExtensionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SyncProduct createSyncProduct(final String name, final String packingInfo)
{
final SyncProduct.SyncProductBuilder product = SyncProduct.builder()
.uuid(randomUUID())
.name(name)
.packingInfo(packingInfo)
.shared(true);
for (final String language : languages)
{
product.nameTrl(language, name + " " + language);
}
return product.build();
}
private static String randomUUID()
{
return UUID.randomUUID().toString();
}
@Transactional
void createDummyProductSupplies()
{
for (final BPartner bpartner : bpartnersRepo.findAll())
{
for (final Contract contract : contractsRepo.findByBpartnerAndDeletedFalse(bpartner))
{
final List<ContractLine> contractLines = contract.getContractLines();
if (contractLines.isEmpty())
|
{
continue;
}
final ContractLine contractLine = contractLines.get(0);
final Product product = contractLine.getProduct();
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now()) // today
.qty(new BigDecimal("10"))
.qtyConfirmedByUser(true)
.build());
productSuppliesService.reportSupply(IProductSuppliesService.ReportDailySupplyRequest.builder()
.bpartner(bpartner)
.contractLine(contractLine)
.productId(product.getId())
.date(LocalDate.now().plusDays(1)) // tomorrow
.qty(new BigDecimal("3"))
.qtyConfirmedByUser(true)
.build());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\util\DummyDataProducer.java
| 2
|
请完成以下Java代码
|
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing to do
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
// nothing to do
return null;
}
@Override
public String modelChange(final PO po, int type)
{
if (type != TYPE_BEFORE_CHANGE && type != TYPE_BEFORE_NEW)
{
return null;
}
if (!po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_QtyReserved))
{
return null;
}
|
if (po instanceof MStorage)
{
final MStorage st = (MStorage)po;
if (st.getQtyReserved().signum() < 0)
{
st.setQtyReserved(BigDecimal.ZERO);
// no need for the warning & stacktrace for now.
// final AdempiereException ex = new AdempiereException("@" + C_OrderLine.ERR_NEGATIVE_QTY_RESERVED + "@. Setting QtyReserved to ZERO."
// + "\nStorage: " + st);
// logger.warn(ex.getLocalizedMessage(), ex);
logger.info(Services.get(IMsgBL.class).getMsg(po.getCtx(), C_OrderLine.ERR_NEGATIVE_QTY_RESERVED.toAD_MessageWithMarkers() + ". Setting QtyReserved to ZERO." + "\nStorage: " + st));
return null;
}
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\ProhibitNegativeQtyReserved.java
| 1
|
请完成以下Java代码
|
public List<ExecutionListener> getExecutionListeners(String eventName) {
return (List) super.getListeners(eventName);
}
@Deprecated
public void addExecutionListener(String eventName, ExecutionListener executionListener) {
super.addListener(eventName, executionListener);
}
@Deprecated
public void addExecutionListener(String eventName, ExecutionListener executionListener, int index) {
super.addListener(eventName, executionListener, index);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Deprecated
public Map<String, List<ExecutionListener>> getExecutionListeners() {
return (Map) super.getListeners();
}
// getters and setters //////////////////////////////////////////////////////
public List<ActivityImpl> getActivities() {
return flowActivities;
}
public Set<ActivityImpl> getEventActivities() {
return eventActivities;
}
|
public boolean isSubProcessScope() {
return isSubProcessScope;
}
public void setSubProcessScope(boolean isSubProcessScope) {
this.isSubProcessScope = isSubProcessScope;
}
@Override
public ProcessDefinitionImpl getProcessDefinition() {
return processDefinition;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ScopeImpl.java
| 1
|
请完成以下Java代码
|
public PickingJobLine withNewStep(@NonNull final PickingJob.AddStepRequest request)
{
final PickingJobStep newStep = PickingJobStep.builder()
.id(request.getNewStepId())
.isGeneratedOnFly(request.isGeneratedOnFly())
.salesOrderAndLineId(salesOrderAndLineId)
.scheduleId(scheduleId)
.productId(productId)
.productName(productName)
.qtyToPick(request.getQtyToPick())
.pickFroms(PickingJobStepPickFromMap.ofList(ImmutableList.of(
PickingJobStepPickFrom.builder()
.pickFromKey(PickingJobStepPickFromKey.MAIN)
.pickFromLocator(request.getPickFromLocator())
.pickFromHU(request.getPickFromHU())
.build()
)))
.packToSpec(request.getPackToSpec())
.build();
return toBuilder()
.steps(ImmutableList.<PickingJobStep>builder()
.addAll(this.steps)
.add(newStep)
.build())
.build();
}
public PickingJobLine withManuallyClosed(final boolean isManuallyClosed)
{
return this.isManuallyClosed != isManuallyClosed
? toBuilder().isManuallyClosed(isManuallyClosed).build()
: this;
}
@NonNull
public ImmutableSet<HuId> getPickedHUIds()
{
return steps.stream()
.map(PickingJobStep::getPickedHUIds)
.flatMap(List::stream)
.collect(ImmutableSet.toImmutableSet());
}
public Optional<HuId> getLastPickedHUId()
{
return steps.stream()
.map(PickingJobStep::getLastPickedHU)
.filter(Optional::isPresent)
.map(Optional::get)
.max(Comparator.comparing(PickingJobStepPickedToHU::getCreatedAt))
.map(PickingJobStepPickedToHU::getActualPickedHU)
.map(HUInfo::getId);
}
PickingJobLine withCurrentPickingTarget(@NonNull final CurrentPickingTarget currentPickingTarget)
|
{
return !CurrentPickingTarget.equals(this.currentPickingTarget, currentPickingTarget)
? toBuilder().currentPickingTarget(currentPickingTarget).build()
: this;
}
PickingJobLine withCurrentPickingTarget(@NonNull final UnaryOperator<CurrentPickingTarget> currentPickingTargetMapper)
{
final CurrentPickingTarget changedCurrentPickingTarget = currentPickingTargetMapper.apply(this.currentPickingTarget);
return !CurrentPickingTarget.equals(this.currentPickingTarget, changedCurrentPickingTarget)
? toBuilder().currentPickingTarget(changedCurrentPickingTarget).build()
: this;
}
public boolean isPickingSlotSet() {return currentPickingTarget.isPickingSlotSet();}
public Optional<PickingSlotId> getPickingSlotId() {return currentPickingTarget.getPickingSlotId();}
public PickingJobLine withPickingSlot(@Nullable final PickingSlotIdAndCaption pickingSlot)
{
return withCurrentPickingTarget(currentPickingTarget.withPickingSlot(pickingSlot));
}
public boolean isFullyPicked() {return qtyRemainingToPick.signum() <= 0;}
public boolean isFullyPickedExcludingRejectedQty()
{
return qtyToPick.subtract(qtyPicked).signum() <= 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void run(Integer id) {
var process = lookup(id);
if (!State.CREATED.equals(process.state())) {
return;
}
start(process);
verify(process);
finish(process);
}
private void finish(Process process) {
template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.DONE).inc("transitionCount", 1)).first();
|
}
void start(Process process) {
template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.ACTIVE).inc("transitionCount", 1)).first();
}
Process lookup(Integer id) {
return repository.findById(id).get();
}
void verify(Process process) {
Assert.state(process.id() % 3 != 0, "We're sorry but we needed to drop that one");
}
}
|
repos\spring-data-examples-main\mongodb\transactions\src\main\java\example\springdata\mongodb\imperative\TransitionService.java
| 2
|
请完成以下Java代码
|
public final class HUQRCodeUniqueId
{
@NonNull String idBase;
@Getter
@NonNull String displayableSuffix;
private HUQRCodeUniqueId(@NonNull final String idBase, @NonNull final String displayableSuffix)
{
this.idBase = idBase;
this.displayableSuffix = displayableSuffix;
}
public static HUQRCodeUniqueId random()
{
return ofUUID(UUID.randomUUID());
}
public static HUQRCodeUniqueId ofUUID(@NonNull final UUID uuid)
{
final String uuidStr = uuid.toString().replace("-", ""); // expect 32 chars
final StringBuilder uuidFirstPart = new StringBuilder(32);
final StringBuilder uuidLastPart = new StringBuilder();
// TO reduce the change of having duplicate displayable suffix,
// we cannot just take the last 4 chars but we will pick some of them from the middle
// See https://www.ietf.org/rfc/rfc4122.txt section 3, to understand the UUID v4 format.
for (int i = 0; i < uuidStr.length(); i++)
{
final char ch = uuidStr.charAt(i);
if (// from time_low (0-7):
i == 5
// from: time_mid (8-11):
|| i == 8
|| i == 11
// from: time_hi_and_version (12-15)
|| i == 13
// from: clock_seq_hi_and_reserved (16-17)
// from: clock_seq_low (18-19)
// from: node (20-31)
)
{
uuidLastPart.append(ch);
}
else
{
uuidFirstPart.append(ch);
}
}
final String uuidLastPartNorm = Strings.padStart(
String.valueOf(Integer.parseInt(uuidLastPart.toString(), 16)),
5, // because 4 hex digits can lead to 5 decimal digits (i.e. FFFF -> 65535)
'0');
return new HUQRCodeUniqueId(uuidFirstPart.toString(), uuidLastPartNorm);
}
|
@JsonCreator
public static HUQRCodeUniqueId ofJson(@NonNull final String json)
{
final int idx = json.indexOf('-');
if (idx <= 0)
{
throw new AdempiereException("Invalid ID: `" + json + "`");
}
final String idBase = json.substring(0, idx);
final String displayableSuffix = json.substring(idx + 1);
return new HUQRCodeUniqueId(idBase, displayableSuffix);
}
@Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return idBase + "-" + displayableSuffix;
}
public static boolean equals(@Nullable final HUQRCodeUniqueId id1, @Nullable final HUQRCodeUniqueId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeUniqueId.java
| 1
|
请完成以下Java代码
|
public void dispose()
{
} // dispose
// private int m_fieldLength;
private String m_columnName;
private String m_oldText;
private String m_initialText;
private volatile boolean m_setting = false;
private GridField m_mField;
/**
* Set Editor to value
* @param value value
*/
@Override
public void setValue(Object value)
{
if (value == null)
m_oldText = "";
else
m_oldText = value.toString();
if (m_setting)
return;
super.setValue(m_oldText);
m_initialText = m_oldText;
// Always position Top
setCaretPosition(0);
} // setValue
/**
* Property Change Listener
* @param evt event
*/
@Override
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
/**
* Action Listener Interface - NOP
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
} // addActionListener
/**************************************************************************
* Key Listener Interface
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Key Released
* if Escape restore old Text.
* @param e event
*/
@Override
public void keyReleased(KeyEvent e)
|
{
// ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
setText(m_initialText);
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField field model
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: begin
@Override
public boolean isAutoCommit()
{
return true;
}
// metas: end
} // VText
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VText.java
| 1
|
请完成以下Java代码
|
public class User {
@NotBlank(message = "User name must be present")
@Size(min = 3, max = 50, message = "User name size not valid")
private String name;
@NotBlank(message = "User email must be present")
@Email(message = "User email format is incorrect")
private String email;
public User() {
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
repos\tutorials-master\javaxval-2\src\main\java\com\baeldung\javaxval\childvalidation\User.java
| 1
|
请完成以下Java代码
|
protected class SameSiteResponseProxy extends HttpServletResponseWrapper {
protected HttpServletResponse response;
public SameSiteResponseProxy(HttpServletResponse resp) {
super(resp);
response = resp;
}
@Override
public void sendError(int sc) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc);
}
@Override
public void sendError(int sc, String msg) throws IOException {
appendSameSiteIfMissing();
super.sendError(sc, msg);
}
@Override
public void sendRedirect(String location) throws IOException {
appendSameSiteIfMissing();
super.sendRedirect(location);
}
@Override
|
public PrintWriter getWriter() throws IOException {
appendSameSiteIfMissing();
return super.getWriter();
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
appendSameSiteIfMissing();
return super.getOutputStream();
}
protected void appendSameSiteIfMissing() {
Collection<String> cookieHeaders = response.getHeaders(CookieConstants.SET_COOKIE_HEADER_NAME);
boolean firstHeader = true;
String cookieHeaderStart = cookieConfigurator.getCookieName("JSESSIONID") + "=";
for (String cookieHeader : cookieHeaders) {
if (cookieHeader.startsWith(cookieHeaderStart)) {
cookieHeader = cookieConfigurator.getConfig(cookieHeader);
}
if (firstHeader) {
response.setHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
firstHeader = false;
} else {
response.addHeader(CookieConstants.SET_COOKIE_HEADER_NAME, cookieHeader);
}
}
}
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\SessionCookieFilter.java
| 1
|
请完成以下Java代码
|
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public List<String> getHobbies() {
return hobbies;
}
public void setHobbies(List<String> hobbies) {
this.hobbies = hobbies;
}
public Map<String, String> getClothes() {
return clothes;
}
public void setClothes(Map<String, String> clothes) {
this.clothes = clothes;
}
public List<Person> getFriends() {
return friends;
}
public void setFriends(List<Person> friends) {
this.friends = friends;
|
}
@Override
public String toString() {
StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age="
+ age + ", birthday=" + birthday + ", hobbies=" + hobbies
+ ", clothes=" + clothes + "]\n");
if (friends != null) {
str.append("Friends:\n");
for (Person f : friends) {
str.append("\t").append(f);
}
}
return str.toString();
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\model\Person.java
| 1
|
请完成以下Java代码
|
private Optional<I_EDI_DesadvLine_InOutLine> getRecordByInOutLineIdIfExists(@NonNull final InOutLineId shipmentLineId)
{
return queryBL.createQueryBuilder(I_EDI_DesadvLine_InOutLine.class)
.addEqualsFilter(I_EDI_DesadvLine_InOutLine.COLUMNNAME_M_InOutLine_ID, shipmentLineId)
.create()
.firstOnlyOptional(I_EDI_DesadvLine_InOutLine.class);
}
@NonNull
private static DesadvInOutLine ofRecord(@NonNull final I_EDI_DesadvLine_InOutLine record)
{
final ProductId productId = ProductId.ofRepoId(record.getM_Product_ID());
return DesadvInOutLine.builder()
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.desadvLineId(EDIDesadvLineId.ofRepoId(record.getEDI_DesadvLine_ID()))
.shipmentLineId(InOutLineId.ofRepoId(record.getM_InOutLine_ID()))
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.qtyEnteredInBPartnerUOM(Optional.of(record.getC_UOM_BPartner_ID())
|
.map(UomId::ofRepoIdOrNull)
.map(bpartnerUOMId -> Quantitys.of(record.getQtyEnteredInBPartnerUOM(), bpartnerUOMId))
.orElse(null))
.qtyDeliveredInStockingUOM(StockQtyAndUOMQtys
.ofQtyInStockUOM(record.getQtyDeliveredInStockingUOM(), productId)
.getStockQty())
.qtyDeliveredInUOM(Quantitys.of(record.getQtyDeliveredInUOM(), UomId.ofRepoId(record.getC_UOM_ID())))
.qtyDeliveredInInvoiceUOM(Optional.of(record.getC_UOM_Invoice_ID())
.map(UomId::ofRepoIdOrNull)
.map(invoiceUOMId -> Quantitys.of(record.getQtyDeliveredInInvoiceUOM(), invoiceUOMId))
.orElse(null))
.desadvTotalQtyDeliveredInStockingUOM(StockQtyAndUOMQtys
.ofQtyInStockUOM(record.getDesadvLineTotalQtyDelivered(), productId)
.getStockQty())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\EDIDesadvInOutLineDAO.java
| 1
|
请完成以下Java代码
|
public class ApplicationServerImpl implements ApplicationServer {
protected String vendor;
protected String version;
public ApplicationServerImpl(String vendor, String version) {
this.vendor = vendor;
this.version = version;
}
public ApplicationServerImpl(String version) {
this.vendor = parseServerVendor(version);
this.version = version;
}
public String getVendor() {
return vendor;
|
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\telemetry\dto\ApplicationServerImpl.java
| 1
|
请完成以下Java代码
|
public static Optional<ShippingWeightSourceTypes> ofCommaSeparatedString(@Nullable final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
if (stringNorm == null)
{
return Optional.empty();
}
final ImmutableList<ShippingWeightSourceType> result = SPLITTER.splitToList(stringNorm)
.stream()
.map(ShippingWeightSourceType::valueOf)
.distinct()
.collect(ImmutableList.toImmutableList());
return !result.isEmpty()
? Optional.of(new ShippingWeightSourceTypes(result))
: Optional.empty();
}
@Override
public @NotNull Iterator<ShippingWeightSourceType> iterator()
|
{
return list.iterator();
}
public Optional<Quantity> calculateWeight(final Function<ShippingWeightSourceType, Optional<Quantity>> calculateWeightFunc)
{
for (final ShippingWeightSourceType weightSourceType : list)
{
final Optional<Quantity> weight = calculateWeightFunc.apply(weightSourceType);
if (weight.isPresent())
{
return weight;
}
}
return Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\weighting\ShippingWeightSourceTypes.java
| 1
|
请完成以下Java代码
|
public void setDebugClosedTransactions(boolean enabled)
{
getTrxManager().setDebugClosedTransactions(enabled);
}
@Override
public boolean isDebugClosedTransactions()
{
return getTrxManager().isDebugClosedTransactions();
}
@Override
public String[] getActiveTransactionInfos()
{
final List<ITrx> trxs = getTrxManager().getActiveTransactionsList();
return toStringArray(trxs);
}
@Override
public String[] getDebugClosedTransactionInfos()
{
final List<ITrx> trxs = getTrxManager().getDebugClosedTransactions();
return toStringArray(trxs);
}
private final String[] toStringArray(final List<ITrx> trxs)
{
if (trxs == null || trxs.isEmpty())
{
return new String[] {};
}
final String[] arr = new String[trxs.size()];
for (int i = 0; i < trxs.size(); i++)
{
final ITrx trx = trxs.get(0);
if (trx == null)
{
arr[i] = "null";
}
else
{
arr[i] = trx.toString();
}
}
return arr;
}
@Override
public void rollbackAndCloseActiveTrx(final String trxName)
{
final ITrxManager trxManager = getTrxManager();
if (trxManager.isNull(trxName))
{
throw new IllegalArgumentException("Only not null transactions are allowed: " + trxName);
}
|
final ITrx trx = trxManager.getTrx(trxName);
if (trxManager.isNull(trx))
{
// shall not happen because getTrx is already throwning an exception
throw new IllegalArgumentException("No transaction was found for: " + trxName);
}
boolean rollbackOk = false;
try
{
rollbackOk = trx.rollback(true);
}
catch (SQLException e)
{
throw new RuntimeException("Could not rollback '" + trx + "' because: " + e.getLocalizedMessage(), e);
}
if (!rollbackOk)
{
throw new RuntimeException("Could not rollback '" + trx + "' for unknown reason");
}
}
@Override
public void setDebugConnectionBackendId(boolean debugConnectionBackendId)
{
getTrxManager().setDebugConnectionBackendId(debugConnectionBackendId);
}
@Override
public boolean isDebugConnectionBackendId()
{
return getTrxManager().isDebugConnectionBackendId();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\jmx\JMXTrxManager.java
| 1
|
请完成以下Java代码
|
public BusinessRulesCollection getRules()
{
return ruleRepository.getAll();
}
public void addRulesChangedListener(final BusinessRulesChangedListener listener)
{
ruleRepository.addCacheResetListener(listener);
}
public void fireTriggersForSourceModel(@NonNull final Object sourceModel, @NonNull final TriggerTiming timing)
{
BusinessRuleFireTriggersCommand.builder()
.eventRepository(eventRepository)
.logger(logger)
.recordMatcher(recordMatcher)
//
.rules(ruleRepository.getAll())
.sourceModel(sourceModel)
|
.timing(timing)
//
.build().execute();
}
public void processEvents(@NonNull final QueryLimit limit)
{
BusinessRuleEventProcessorCommand.builder()
.ruleRepository(ruleRepository)
.eventRepository(eventRepository)
.recordWarningRepository(recordWarningRepository)
.logger(logger)
.recordMatcher(recordMatcher)
//
.limit(limit)
//
.build().execute();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\BusinessRuleService.java
| 1
|
请完成以下Java代码
|
public int getAD_Tab_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tab_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Window getAD_Window() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setAD_Window(org.compiere.model.I_AD_Window AD_Window)
{
set_ValueFromPO(COLUMNNAME_AD_Window_ID, org.compiere.model.I_AD_Window.class, AD_Window);
}
/** Set Fenster.
@param AD_Window_ID
Eingabe- oder Anzeige-Fenster
|
*/
@Override
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 Fenster.
@return Eingabe- oder Anzeige-Fenster
*/
@Override
public int getAD_Window_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element_Link.java
| 1
|
请完成以下Java代码
|
public static final HUItemsLocalCache getCreate(final I_M_HU hu)
{
HUItemsLocalCache cache = InterfaceWrapperHelper.getDynAttribute(hu, DYNATTR_Instance);
if (cache == null)
{
cache = new HUItemsLocalCache(hu);
cache.setCacheDisabled(HUConstants.DEBUG_07504_Disable_HUItemsLocalCache);
InterfaceWrapperHelper.setDynAttribute(hu, DYNATTR_Instance, cache);
}
return cache;
}
private HUItemsLocalCache(final I_M_HU hu)
{
super(hu);
}
@Override
protected final Comparator<I_M_HU_Item> createItemsComparator()
{
return IHandlingUnitsDAO.HU_ITEMS_COMPARATOR;
}
/**
* Retrieves a list of {@link I_M_HU_Item}s with ordering according to {@link #ITEM_TYPE_ORDERING}.
*/
@Override
protected final List<I_M_HU_Item> retrieveItems(final IContextAware ctx, final I_M_HU hu)
{
final IQueryBuilder<I_M_HU_Item> queryBuilder = queryBL.createQueryBuilder(I_M_HU_Item.class, ctx)
.addEqualsFilter(I_M_HU_Item.COLUMN_M_HU_ID, hu.getM_HU_ID())
.addOnlyActiveRecordsFilter();
|
final List<I_M_HU_Item> items = queryBuilder
.create()
.list()
.stream()
.peek(item -> item.setM_HU(hu)) // Make sure item.getM_HU() will return our HU
.sorted(createItemsComparator())
.collect(Collectors.toList());
return items;
}
@Override
protected Object mkKey(final I_M_HU_Item item)
{
return item.getM_HU_Item_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUItemsLocalCache.java
| 1
|
请完成以下Java代码
|
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_K_IndexLog[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Index Query.
@param IndexQuery
Text Search Query
*/
public void setIndexQuery (String IndexQuery)
{
set_ValueNoCheck (COLUMNNAME_IndexQuery, IndexQuery);
}
/** Get Index Query.
@return Text Search Query
*/
public String getIndexQuery ()
{
return (String)get_Value(COLUMNNAME_IndexQuery);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getIndexQuery());
}
/** Set Query Result.
@param IndexQueryResult
Result of the text query
*/
public void setIndexQueryResult (int IndexQueryResult)
{
set_ValueNoCheck (COLUMNNAME_IndexQueryResult, Integer.valueOf(IndexQueryResult));
}
/** Get Query Result.
@return Result of the text query
*/
public int getIndexQueryResult ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IndexQueryResult);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Index Log.
@param K_IndexLog_ID
Text search log
*/
public void setK_IndexLog_ID (int K_IndexLog_ID)
{
|
if (K_IndexLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexLog_ID, Integer.valueOf(K_IndexLog_ID));
}
/** Get Index Log.
@return Text search log
*/
public int getK_IndexLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** QuerySource AD_Reference_ID=391 */
public static final int QUERYSOURCE_AD_Reference_ID=391;
/** Collaboration Management = C */
public static final String QUERYSOURCE_CollaborationManagement = "C";
/** Java Client = J */
public static final String QUERYSOURCE_JavaClient = "J";
/** HTML Client = H */
public static final String QUERYSOURCE_HTMLClient = "H";
/** Self Service = W */
public static final String QUERYSOURCE_SelfService = "W";
/** Set Query Source.
@param QuerySource
Source of the Query
*/
public void setQuerySource (String QuerySource)
{
set_Value (COLUMNNAME_QuerySource, QuerySource);
}
/** Get Query Source.
@return Source of the Query
*/
public String getQuerySource ()
{
return (String)get_Value(COLUMNNAME_QuerySource);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexLog.java
| 1
|
请完成以下Java代码
|
public int getCM_WebProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_WebProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Manual.
@param IsManual
This is a manual process
*/
public void setIsManual (boolean IsManual)
{
set_Value (COLUMNNAME_IsManual, Boolean.valueOf(IsManual));
}
/** Get Manual.
@return This is a manual process
*/
public boolean isManual ()
{
Object oo = get_Value(COLUMNNAME_IsManual);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Keyword.
@param Keyword
Case insensitive keyword
*/
public void setKeyword (String Keyword)
{
set_Value (COLUMNNAME_Keyword, Keyword);
}
/** Get Keyword.
@return Case insensitive keyword
*/
public String getKeyword ()
{
return (String)get_Value(COLUMNNAME_Keyword);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getKeyword());
}
/** Set Index Stop.
@param K_IndexStop_ID
Keyword not to be indexed
*/
|
public void setK_IndexStop_ID (int K_IndexStop_ID)
{
if (K_IndexStop_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_IndexStop_ID, Integer.valueOf(K_IndexStop_ID));
}
/** Get Index Stop.
@return Keyword not to be indexed
*/
public int getK_IndexStop_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_IndexStop_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name)
.getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_Value (COLUMNNAME_R_RequestType_ID, null);
else
set_Value (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_IndexStop.java
| 1
|
请完成以下Java代码
|
public void setTU_HU_PI_Item_Product_ID(final int tu_HU_PI_Item_Product_ID)
{
this.tu_HU_PI_Item_Product_ID = tu_HU_PI_Item_Product_ID;
}
public BigDecimal getQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public void setQtyCUsPerTU(final BigDecimal qtyCU)
{
this.qtyCUsPerTU = qtyCU;
}
/**
* Called from the process class to set the TU qty from the process parameter.
*/
public void setQtyTU(final BigDecimal qtyTU)
{
this.qtyTU = qtyTU;
}
public void setQtyLU(final BigDecimal qtyLU)
{
this.qtyLU = qtyLU;
}
private boolean getIsReceiveIndividualCUs()
|
{
if (isReceiveIndividualCUs == null)
{
isReceiveIndividualCUs = computeIsReceiveIndividualCUs();
}
return isReceiveIndividualCUs;
}
private boolean computeIsReceiveIndividualCUs()
{
if (selectedRow.getType() != PPOrderLineType.MainProduct
|| selectedRow.getUomId() == null
|| !selectedRow.getUomId().isEach())
{
return false;
}
return Optional.ofNullable(selectedRow.getOrderId())
.flatMap(ppOrderBOMBL::getSerialNoSequenceId)
.isPresent();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\PackingInfoProcessParams.java
| 1
|
请完成以下Java代码
|
public void setMessageQueueMode(boolean isMessageQueueMode) {
this.messageQueueMode = isMessageQueueMode;
}
public int getMaxTimerJobsPerAcquisition() {
return maxTimerJobsPerAcquisition;
}
public void setMaxTimerJobsPerAcquisition(int maxTimerJobsPerAcquisition) {
this.maxTimerJobsPerAcquisition = maxTimerJobsPerAcquisition;
}
public int getMaxAsyncJobsDuePerAcquisition() {
return maxAsyncJobsDuePerAcquisition;
}
public void setMaxAsyncJobsDuePerAcquisition(int maxAsyncJobsDuePerAcquisition) {
this.maxAsyncJobsDuePerAcquisition = maxAsyncJobsDuePerAcquisition;
}
public int getDefaultTimerJobAcquireWaitTimeInMillis() {
return defaultTimerJobAcquireWaitTimeInMillis;
}
public void setDefaultTimerJobAcquireWaitTimeInMillis(int defaultTimerJobAcquireWaitTimeInMillis) {
this.defaultTimerJobAcquireWaitTimeInMillis = defaultTimerJobAcquireWaitTimeInMillis;
}
public int getDefaultAsyncJobAcquireWaitTimeInMillis() {
return defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setDefaultAsyncJobAcquireWaitTimeInMillis(int defaultAsyncJobAcquireWaitTimeInMillis) {
this.defaultAsyncJobAcquireWaitTimeInMillis = defaultAsyncJobAcquireWaitTimeInMillis;
}
public int getDefaultQueueSizeFullWaitTime() {
return defaultQueueSizeFullWaitTime;
}
public void setDefaultQueueSizeFullWaitTime(int defaultQueueSizeFullWaitTime) {
this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime;
}
public int getTimerLockTimeInMillis() {
return timerLockTimeInMillis;
}
public void setTimerLockTimeInMillis(int timerLockTimeInMillis) {
this.timerLockTimeInMillis = timerLockTimeInMillis;
}
public int getAsyncJobLockTimeInMillis() {
return asyncJobLockTimeInMillis;
|
}
public void setAsyncJobLockTimeInMillis(int asyncJobLockTimeInMillis) {
this.asyncJobLockTimeInMillis = asyncJobLockTimeInMillis;
}
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis;
}
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis;
}
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public int getNumberOfRetries() {
return numberOfRetries;
}
public void setNumberOfRetries(int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AsyncExecutorProperties.java
| 1
|
请完成以下Java代码
|
public Long getOrder_id() {
return order_id;
}
public void setOrder_id(Long order_id) {
this.order_id = order_id;
}
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public String getProductName() {
|
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getProductPrice() {
return productPrice;
}
public void setProductPrice(Double productPrice) {
this.productPrice = productPrice;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\DTO\ResultDTO.java
| 1
|
请完成以下Java代码
|
public Resource performGet(@NonNull final GetRequest getRequest)
{
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(getRequest.getBaseURL());
Loggables.withLogger(log, Level.DEBUG).addLog("*** performGet(): for request {}", getRequest);
if (!Check.isEmpty(getRequest.getPathVariables()))
{
builder.pathSegment(getRequest.getPathVariables().toArray(new String[0]));
}
if (!Check.isEmpty(getRequest.getQueryParameters()))
{
builder.queryParams(getRequest.getQueryParameters());
}
final HttpEntity<String> request = new HttpEntity<>(buildHttpHeaders(getRequest));
final URI uri = builder.build().encode().toUri();
final ResponseEntity<Resource> responseEntity = restTemplate().exchange(uri, HttpMethod.GET, request, Resource.class);
final boolean responseWithErrors = !responseEntity.getStatusCode().is2xxSuccessful();
if (responseWithErrors)
{
throw new AdempiereException("Something went wrong when retrieving from postgREST!, response body:" + responseEntity.getBody());
}
log.debug("*** PostgRESTClient.performGet(), response: {}", responseEntity.getBody());
return responseEntity.getBody();
}
private HttpHeaders buildHttpHeaders(@NonNull final GetRequest request)
{
final PostgRESTResponseFormat responseFormat = request.getResponseFormat();
final List<MediaType> acceptableMediaTypes = new ArrayList<>();
request.getAdditionalAccepts().forEach(a -> acceptableMediaTypes.add(MediaType.valueOf(a)));
|
acceptableMediaTypes.add(MediaType.valueOf(responseFormat.getContentType()));
final HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
return headers;
}
private RestTemplate restTemplate()
{
final OrgId orgId = Env.getOrgId();
final PostgRESTConfig config = configRepository.getConfigFor(orgId);
return new RestTemplateBuilder()
.setConnectTimeout(config.getConnectionTimeout())
.setReadTimeout(config.getReadTimeout())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\client\PostgRESTClient.java
| 1
|
请完成以下Java代码
|
public void deletePicture(User user) {
UserEntity userEntity = (UserEntity) user;
if (userEntity.getPictureByteArrayRef() != null) {
userEntity.getPictureByteArrayRef().delete();
}
}
@Override
public void delete(String userId) {
UserEntity user = findById(userId);
if (user != null) {
List<IdentityInfoEntity> identityInfos = getIdentityInfoEntityManager().findIdentityInfoByUserId(userId);
for (IdentityInfoEntity identityInfo : identityInfos) {
getIdentityInfoEntityManager().delete(identityInfo);
}
getMembershipEntityManager().deleteMembershipByUserId(userId);
delete(user);
}
}
@Override
public List<User> findUserByQueryCriteria(UserQueryImpl query) {
return dataManager.findUserByQueryCriteria(query);
}
@Override
public long findUserCountByQueryCriteria(UserQueryImpl query) {
return dataManager.findUserCountByQueryCriteria(query);
}
@Override
public UserQuery createNewUserQuery() {
return new UserQueryImpl(getCommandExecutor());
}
@Override
public Boolean checkPassword(String userId, String password, PasswordEncoder passwordEncoder, PasswordSalt salt) {
User user = null;
if (userId != null) {
user = findById(userId);
}
return (user != null) && (password != null) && passwordEncoder.isMatches(password, user.getPassword(), salt);
}
@Override
public List<User> findUsersByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findUsersByNativeQuery(parameterMap);
}
@Override
public long findUserCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findUserCountByNativeQuery(parameterMap);
}
@Override
public boolean isNewUser(User user) {
return ((UserEntity) user).getRevision() == 0;
}
@Override
public Picture getUserPicture(User user) {
|
UserEntity userEntity = (UserEntity) user;
return userEntity.getPicture();
}
@Override
public void setUserPicture(User user, Picture picture) {
UserEntity userEntity = (UserEntity) user;
userEntity.setPicture(picture);
dataManager.update(userEntity);
}
@Override
public List<User> findUsersByPrivilegeId(String name) {
return dataManager.findUsersByPrivilegeId(name);
}
public UserDataManager getUserDataManager() {
return dataManager;
}
public void setUserDataManager(UserDataManager userDataManager) {
this.dataManager = userDataManager;
}
protected IdentityInfoEntityManager getIdentityInfoEntityManager() {
return engineConfiguration.getIdentityInfoEntityManager();
}
protected MembershipEntityManager getMembershipEntityManager() {
return engineConfiguration.getMembershipEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
ManagedConnection result = null;
Iterator it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = (ManagedConnection) it.next();
if (mc instanceof JcaExecutorServiceManagedConnection) {
result = mc;
}
}
return result;
}
public PrintWriter getLogWriter() throws ResourceException {
return logwriter;
}
public void setLogWriter(PrintWriter out) throws ResourceException {
logwriter = out;
}
public ResourceAdapter getResourceAdapter() {
return ra;
}
|
public void setResourceAdapter(ResourceAdapter ra) {
this.ra = ra;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof JcaExecutorServiceManagedConnectionFactory))
return false;
return true;
}
}
|
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnectionFactory.java
| 1
|
请完成以下Java代码
|
public String getCanonicalName() {
return "activity-stack-init";
}
public void execute(PvmExecutionImpl execution) {
ScopeInstantiationContext executionStartContext = execution.getScopeInstantiationContext();
InstantiationStack instantiationStack = executionStartContext.getInstantiationStack();
List<PvmActivity> activityStack = instantiationStack.getActivities();
PvmActivity currentActivity = activityStack.remove(0);
PvmExecutionImpl propagatingExecution = execution;
if (currentActivity.isScope()) {
propagatingExecution = execution.createExecution();
execution.setActive(false);
propagatingExecution.setActivity(currentActivity);
propagatingExecution.initialize();
}
else {
propagatingExecution.setActivity(currentActivity);
}
// notify listeners for the instantiated activity
|
propagatingExecution.performOperation(operationOnScopeInitialization);
}
public boolean isAsync(PvmExecutionImpl instance) {
return false;
}
public PvmExecutionImpl getStartContextExecution(PvmExecutionImpl execution) {
return execution;
}
public boolean isAsyncCapable() {
return false;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationActivityInitStack.java
| 1
|
请完成以下Java代码
|
public class TaxCharges2 {
@XmlElement(name = "Id")
protected String id;
@XmlElement(name = "Rate")
protected BigDecimal rate;
@XmlElement(name = "Amt")
protected ActiveOrHistoricCurrencyAndAmount amt;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the rate property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getRate() {
return rate;
}
/**
* Sets the value of the rate property.
*
|
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setRate(BigDecimal value) {
this.rate = value;
}
/**
* Gets the value of the amt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.amt = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxCharges2.java
| 1
|
请完成以下Java代码
|
private GrantedAuthority mapAuthority(String name) {
if (this.convertToUpperCase) {
name = name.toUpperCase(Locale.ROOT);
}
else if (this.convertToLowerCase) {
name = name.toLowerCase(Locale.ROOT);
}
if (this.prefix.length() > 0 && !name.startsWith(this.prefix)) {
name = this.prefix + name;
}
return new SimpleGrantedAuthority(name);
}
/**
* Sets the prefix which should be added to the authority name (if it doesn't already
* exist)
* @param prefix the prefix, typically to satisfy the behaviour of an
* {@code AccessDecisionVoter}.
*/
public void setPrefix(String prefix) {
Assert.notNull(prefix, "prefix cannot be null");
this.prefix = prefix;
}
/**
|
* Whether to convert the authority value to upper case in the mapping.
* @param convertToUpperCase defaults to {@code false}
*/
public void setConvertToUpperCase(boolean convertToUpperCase) {
this.convertToUpperCase = convertToUpperCase;
}
/**
* Whether to convert the authority value to lower case in the mapping.
* @param convertToLowerCase defaults to {@code false}
*/
public void setConvertToLowerCase(boolean convertToLowerCase) {
this.convertToLowerCase = convertToLowerCase;
}
/**
* Sets a default authority to be assigned to all users
* @param authority the name of the authority to be assigned to all users.
*/
public void setDefaultAuthority(String authority) {
Assert.hasText(authority, "The authority name cannot be set to an empty value");
this.defaultAuthority = new SimpleGrantedAuthority(authority);
}
}
|
repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAuthorityMapper.java
| 1
|
请完成以下Java代码
|
public static JSONJavaException ofNullable(@Nullable final Exception exception, @NonNull final JSONOptions jsonOpts)
{
return exception != null ? of(exception, jsonOpts) : null;
}
@NonNull
public static JSONJavaException of(@NonNull final Exception exception, @NonNull final JSONOptions jsonOpts)
{
return builder()
.message(AdempiereException.extractMessageTrl(exception).translate(jsonOpts.getAdLanguage()))
.userFriendlyError(AdempiereException.isUserValidationError(exception))
.stackTrace(Trace.toOneLineStackTraceString(exception))
.attributes(extractAttributes(exception, jsonOpts))
.adIssueId(IssueReportableExceptions.getAdIssueIdOrNull(exception))
.build();
}
@Nullable
private static Map<String, Object> extractAttributes(@NonNull final Exception exception, @NonNull final JSONOptions jsonOpts)
{
|
if (exception instanceof AdempiereException)
{
final Map<String, Object> exceptionAttributes = ((AdempiereException)exception).getParameters();
if (exceptionAttributes == null || exceptionAttributes.isEmpty())
{
return null;
}
return exceptionAttributes.entrySet()
.stream()
.map(entry -> GuavaCollectors.entry(entry.getKey(), Values.valueToJsonObject(entry.getValue(), jsonOpts, String::valueOf)))
.collect(GuavaCollectors.toImmutableMap());
}
else
{
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONJavaException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<JsonRequestUOMConversionUpsert> getUOMConversionUpsertRequest(@NonNull final ProductRow productRow)
{
if (productRow.getQty() == null)
{
return Optional.empty();
}
final String toUomCode = UOMCodeEnum.getX12DE355CodeByPCMCode(productRow.getUomCode())
.orElse(productRow.getUomCode());
if (DEFAULT_UOM_X12DE355_CODE.equals(toUomCode))
{
return Optional.empty();
}
final JsonRequestUOMConversionUpsert request = new JsonRequestUOMConversionUpsert();
request.setFromUomCode(DEFAULT_UOM_X12DE355_CODE);
request.setToUomCode(toUomCode);
request.setFromToMultiplier(productRow.getQty());
return Optional.of(request);
}
@NonNull
private String getTaxCategory(@NonNull final BigDecimal taxRate)
{
return taxCategory2TaxRates
.entrySet()
.stream()
.filter(entry -> entry.getValue().stream().anyMatch(rate -> rate.compareTo(taxRate) == 0))
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new RuntimeException("No Tax Category found for Tax Rate = " + taxRate));
}
@NonNull
private static ImmutableMap<String, List<BigDecimal>> getTaxCategoryMappingRules(@NonNull final JsonExternalSystemRequest externalSystemRequest)
|
{
final String taxCategoryMappings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_TAX_CATEGORY_MAPPINGS);
if (Check.isBlank(taxCategoryMappings))
{
return ImmutableMap.of();
}
final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return mapper.readValue(taxCategoryMappings, JsonTaxCategoryMappings.class)
.getJsonTaxCategoryMappingList()
.stream()
.collect(ImmutableMap.toImmutableMap(JsonTaxCategoryMapping::getTaxCategory, JsonTaxCategoryMapping::getTaxRates));
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
private static boolean hasMissingFields(@NonNull final ProductRow productRow)
{
return Check.isBlank(productRow.getProductIdentifier())
|| Check.isBlank(productRow.getName())
|| Check.isBlank(productRow.getValue());
}
@NonNull
private static JsonRequestProductUpsert wrapUpsertItem(@NonNull final JsonRequestProductUpsertItem upsertItem)
{
return JsonRequestProductUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\ProductUpsertProcessor.java
| 2
|
请完成以下Java代码
|
public class DBRes_fr extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "CConnectionDialog", "Connexion Server" },
{ "Name", "Nom" },
{ "AppsHost", "Hote d'Application" },
{ "AppsPort", "Port de l'Application" },
{ "TestApps", "Application de Test" },
{ "DBHost", "Hote Base de Donn\u00E9es" },
{ "DBPort", "Port Base de Donn\u00E9es" },
{ "DBName", "Nom Base de Donn\u00E9es" },
{ "DBUidPwd", "Utilisateur / Mot de Passe" },
{ "ViaFirewall", "via Firewall" },
{ "FWHost", "Hote Firewall" },
{ "FWPort", "Port Firewall" },
{ "TestConnection", "Test Base de Donn\u00E9es" },
{ "Type", "Type Base de Donn\u00E9es" },
{ "BequeathConnection", "Connexion d\u00E9di\u00E9e" },
{ "Overwrite", "Ecraser" },
{ "ConnectionProfile", "Connection" },
{ "LAN", "LAN" },
|
{ "TerminalServer", "Terminal Server" },
{ "VPN", "VPN" },
{ "WAN", "WAN" },
{ "ConnectionError", "Erreur Connexion" },
{ "ServerNotActive", "Serveur Non Actif" }
};
/**
* Get Contsnts
* @return contents
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // DBRes_fr
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_fr.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HULabelConfigRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, HULabelConfigMap> cache = CCache.<Integer, HULabelConfigMap>builder()
.tableName(I_M_HU_Label_Config.Table_Name)
.initialCapacity(1)
.build();
public ExplainedOptional<HULabelConfig> getFirstMatching(HULabelConfigQuery query)
{
return getMap().getFirstMatching(query);
}
private HULabelConfigMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private HULabelConfigMap retrieveMap()
{
ImmutableList<HULabelConfigRoute> list = queryBL.createQueryBuilder(I_M_HU_Label_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(HULabelConfigRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new HULabelConfigMap(list);
}
public static HULabelConfigRoute fromRecord(final I_M_HU_Label_Config record)
{
return HULabelConfigRoute.builder()
.seqNo(SeqNo.ofInt(record.getSeqNo()))
.sourceDocType(HULabelSourceDocType.ofNullableCode(record.getHU_SourceDocType()))
.acceptHUUnitTypes(extractAcceptedHuUnitTypes(record))
.bpartnerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_ID()))
.config(HULabelConfig.builder()
.printFormatProcessId(AdProcessId.ofRepoId(record.getLabelReport_Process_ID()))
.autoPrint(record.isAutoPrint())
.autoPrintCopies(PrintCopies.ofIntOrOne(record.getAutoPrintCopies()))
.build())
.build();
}
public static ImmutableSet<HuUnitType> extractAcceptedHuUnitTypes(final I_M_HU_Label_Config record)
{
final ImmutableSet.Builder<HuUnitType> builder = ImmutableSet.builder();
if (record.isApplyToLUs())
{
builder.add(HuUnitType.LU);
}
if (record.isApplyToTUs())
{
builder.add(HuUnitType.TU);
}
if (record.isApplyToCUs())
{
builder.add(HuUnitType.VHU);
}
return builder.build();
}
|
//
//
//
//
//
private static class HULabelConfigMap
{
private final ImmutableList<HULabelConfigRoute> orderedList;
public HULabelConfigMap(final ImmutableList<HULabelConfigRoute> list)
{
this.orderedList = list.stream()
.sorted(Comparator.comparing(HULabelConfigRoute::getSeqNo))
.collect(ImmutableList.toImmutableList());
}
public ExplainedOptional<HULabelConfig> getFirstMatching(@NonNull final HULabelConfigQuery query)
{
return orderedList.stream()
.filter(route -> route.isMatching(query))
.map(HULabelConfigRoute::getConfig)
.findFirst()
.map(ExplainedOptional::of)
.orElseGet(() -> ExplainedOptional.emptyBecause("No HU Label Config found for " + query));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\report\labels\HULabelConfigRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public JsonExternalSystemLeichMehlPluFileConfigs getPluFileConfigs(@NonNull final Map<String, String> params)
{
final String pluFileConfigs = params.get(ExternalSystemConstants.PARAM_PLU_FILE_CONFIG);
if (Check.isBlank(pluFileConfigs))
{
throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_PLU_FILE_CONFIG);
}
final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return mapper.readValue(pluFileConfigs, JsonExternalSystemLeichMehlPluFileConfigs.class);
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
}
@NonNull
public Predicate isStoreFileOnDisk()
{
return exchange -> {
final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class);
return context.getDestinationDetails().isStoreFileOnDisk();
};
}
@NonNull
public Predicate isPluFileExportAuditEnabled()
{
|
return exchange -> {
final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class);
return context.isPluFileExportAuditEnabled();
};
}
public static Integer getPPOrderMetasfreshId(@NonNull final Map<String, String> parameters)
{
final String ppOrderStr = parameters.get(ExternalSystemConstants.PARAM_PP_ORDER_ID);
if (Check.isBlank(ppOrderStr))
{
throw new RuntimeException("Missing mandatory param: " + ExternalSystemConstants.PARAM_PP_ORDER_ID);
}
try
{
return Integer.parseInt(ppOrderStr);
}
catch (final NumberFormatException e)
{
throw new RuntimeException("Unable to parse PP_Order_ID from string=" + ppOrderStr);
}
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\ExportPPOrderHelper.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Money getPriceStdAsMoney()
{
return Money.of(getPriceStd(), getCurrencyId());
}
/**
* @return discount, never {@code null}
*/
@Override
@NonNull
public Percent getDiscount()
{
return CoalesceUtil.coalesceNotNull(discount, Percent.ZERO);
}
@Override
public void setDiscount(@NonNull final Percent discount)
{
if (isDisallowDiscount())
{
throw new AdempiereException("Attempt to set the discount although isDisallowDiscount()==true")
.appendParametersToMessage()
.setParameter("this", this);
}
if (isDontOverrideDiscountAdvice())
{
return;
}
this.discount = discount;
this.isDiscountCalculated = true;
}
@Override
public void addPricingRuleApplied(@NonNull final IPricingRule rule)
{
rulesApplied.add(rule);
}
@Override
public List<IPricingAttribute> getPricingAttributes()
{
return pricingAttributes;
}
@Override
public void addPricingAttributes(final Collection<IPricingAttribute> pricingAttributesToAdd)
{
if (pricingAttributesToAdd == null || pricingAttributesToAdd.isEmpty())
{
return;
}
pricingAttributes.addAll(pricingAttributesToAdd);
}
/**
* Supposed to be called by the pricing engine.
* <p>
* task https://github.com/metasfresh/metasfresh/issues/4376
*/
public void updatePriceScales()
{
|
priceStd = scaleToPrecision(priceStd);
priceLimit = scaleToPrecision(priceLimit);
priceList = scaleToPrecision(priceList);
}
@Nullable
private BigDecimal scaleToPrecision(@Nullable final BigDecimal priceToRound)
{
if (priceToRound == null || precision == null)
{
return priceToRound;
}
return precision.round(priceToRound);
}
@Override
public boolean isCampaignPrice()
{
return campaignPrice;
}
@Override
public IPricingResult setLoggableMessages(@NonNull final ImmutableList<String> loggableMessages)
{
this.loggableMessages = loggableMessages;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PricingResult.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class M_ShipmentSchedule
{
@NonNull private final ShipmentScheduleService shipmentScheduleService;
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = {
I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver,
I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override,
I_M_ShipmentSchedule.COLUMNNAME_DeliveryDate,
I_M_ShipmentSchedule.COLUMNNAME_DeliveryDate_Override,
I_M_ShipmentSchedule.COLUMNNAME_M_Shipper_ID })
public void markAsCarrierAdviceRequested(final I_M_ShipmentSchedule shipmentSchedule)
{
if(InterfaceWrapperHelper.isValueChanged(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_M_Shipper_ID))
{
shipmentSchedule.setCarrier_Product_ID(CarrierProductId.toRepoId(null));
shipmentSchedule.setCarrier_Goods_Type_ID(CarrierGoodsTypeId.toRepoId(null));
shipmentSchedule.setCarrier_Advising_Status(CarrierAdviseStatus.NotRequested.getCode());
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentSchedule.getM_ShipmentSchedule_ID());
if(shipmentScheduleId != null)
{
shipmentScheduleService.removeAssignedServiceIdsByShipmentScheduleIds(ImmutableSet.of(shipmentScheduleId));
}
}
if (!shipmentScheduleService.isEligibleForAutoCarrierAdvise(shipmentSchedule))
{
return;
}
shipmentSchedule.setCarrier_Advising_Status(CarrierAdviseStatus.Requested.getCode());
shipmentSchedule.setCarrier_Product_ID(CarrierProductId.toRepoId(null));
}
@ModelChange(timings = {
ModelValidator.TYPE_AFTER_NEW,
|
ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = {
I_M_ShipmentSchedule.COLUMNNAME_Carrier_Advising_Status })
public void requestCarrierAdvice(final I_M_ShipmentSchedule shipmentSchedule)
{
if (!isMarkedAsCarrierAdviceRequested(shipmentSchedule))
{
return;
}
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(shipmentSchedule.getC_Async_Batch_ID());
AdviseDeliveryOrderWorkpackageProcessor.enqueueOnTrxCommit(shipmentScheduleId, asyncBatchId);
}
private boolean isMarkedAsCarrierAdviceRequested(final I_M_ShipmentSchedule shipmentSchedule)
{
final CarrierAdviseStatus carrierAdviseStatus = CarrierAdviseStatus.ofNullableCode(shipmentSchedule.getCarrier_Advising_Status());
return carrierAdviseStatus != null && carrierAdviseStatus.isRequested();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\interceptor\M_ShipmentSchedule.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Pharmacy getPharmacyOrNull(
@NonNull final PharmacyApi pharmacyApi,
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final String pharmacyId) throws ApiException
{
if (EmptyUtil.isBlank(pharmacyId))
{
return null;
}
final Pharmacy pharmacy = pharmacyApi.getPharmacy(albertaConnectionDetails.getApiKey(), pharmacyId);
if (pharmacy == null)
{
throw new RuntimeException("No info returned for pharmacy: " + pharmacyId);
}
return pharmacy;
}
@Nullable
private Users getUserOrNull(
@NonNull final UserApi userApi,
|
@NonNull final AlbertaConnectionDetails albertaConnectionDetails,
@Nullable final String userId) throws ApiException
{
if (EmptyUtil.isBlank(userId))
{
return null;
}
final Users user = userApi.getUser(albertaConnectionDetails.getApiKey(), userId);
if (user == null)
{
throw new RuntimeException("No info returned for user: " + userId);
}
return user;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\CreateBPartnerReqProcessor.java
| 2
|
请完成以下Java代码
|
public void onMessage(@NonNull final Message message)
{
String text = null;
final String messageReference = "onMessage-startAt-millis-" + SystemTime.millis();
try (final IAutoCloseable ignored = setupLoggable(messageReference))
{
text = extractMessageBodyAsString(message);
Loggables.withLogger(logger, Level.TRACE)
.addLog("Received message(text): \n{}", text);
importXMLDocument(text);
log("Imported Document", text, null, null); // loggable can't store the message-text for us
// not sending reply
if (StringUtils.isNotEmpty(message.getMessageProperties().getReplyTo()))
{
Loggables.withLogger(logger, Level.WARN)
.addLog("Sending reply currently not supported with RabbitMQ");
}
}
catch (final RuntimeException e)
{
logException(e, text);
}
}
private String extractMessageBodyAsString(@NonNull final Message message)
{
|
final String encoding = message.getMessageProperties().getContentEncoding();
if (Check.isEmpty(encoding))
{
Loggables.withLogger(logger, Level.WARN)
.addLog("Incoming RabbitMQ message lacks content encoding info; assuming UTF-8; messageId={}", message.getMessageProperties().getMessageId());
return new String(message.getBody(), StandardCharsets.UTF_8);
}
try
{
return new String(message.getBody(), encoding);
}
catch (final UnsupportedEncodingException e)
{
throw new AdempiereException("Incoming RabbitMQ message has unsupportred encoding='" + encoding + "'; messageId=" + message.getMessageProperties().getMessageId(), e);
}
}
private IAutoCloseable setupLoggable(@NonNull final String reference)
{
final IIMPProcessorBL impProcessorBL = Services.get(IIMPProcessorBL.class);
final I_IMP_Processor importProcessor = replicationProcessor.getMImportProcessor();
return impProcessorBL.setupTemporaryLoggable(importProcessor, reference);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\imp\RabbitMqListener.java
| 1
|
请完成以下Java代码
|
private static List prepareData() {
List data = new ArrayList();
data.add(new Question("Can I have a bonus?", -5));
return data;
}
private static void checkResults(List results) {
Iterator itr = results.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
if (obj instanceof Answer) {
log.info(obj.toString());
}
}
}
|
private static void registerRules(String rulesFile, String rulesURI, RuleServiceProvider serviceProvider) throws ConfigurationException, RuleExecutionSetCreateException, IOException, RuleExecutionSetRegisterException {
// Get the rule administrator.
RuleAdministrator ruleAdministrator = serviceProvider.getRuleAdministrator();
// load the rules
InputStream ruleInput = JessWithJsr94.class.getResourceAsStream(rulesFile);
HashMap vendorProperties = new HashMap();
// Create the RuleExecutionSet
RuleExecutionSet ruleExecutionSet = ruleAdministrator
.getLocalRuleExecutionSetProvider(vendorProperties)
.createRuleExecutionSet(ruleInput, vendorProperties);
// Register the rule execution set.
ruleAdministrator.registerRuleExecutionSet(rulesURI, ruleExecutionSet, vendorProperties);
}
}
|
repos\tutorials-master\rule-engines-modules\jess\src\main\java\com\baeldung\rules\jess\JessWithJsr94.java
| 1
|
请完成以下Java代码
|
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public boolean isInitialVariables() {
return initialVariables;
}
public void setInitialVariables(boolean initialVariables) {
this.initialVariables = initialVariables;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
|
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isWithoutBusinessKey() {
return withoutBusinessKey;
}
public void setWithoutBusinessKey(boolean withoutBusinessKey) {
this.withoutBusinessKey = withoutBusinessKey;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesBatchConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getApplicationRef() {
return applicationRef;
}
/**
* Sets the value of the applicationRef property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setApplicationRef(String value) {
this.applicationRef = value;
}
/**
* Gets the value of the processingPriorityCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getProcessingPriorityCode() {
return processingPriorityCode;
}
/**
* Sets the value of the processingPriorityCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setProcessingPriorityCode(String value) {
this.processingPriorityCode = value;
}
/**
* Gets the value of the ackRequest property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAckRequest() {
return ackRequest;
}
/**
* Sets the value of the ackRequest property.
*
* @param value
|
* allowed object is
* {@link String }
*
*/
public void setAckRequest(String value) {
this.ackRequest = value;
}
/**
* Gets the value of the agreementId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAgreementId() {
return agreementId;
}
/**
* Sets the value of the agreementId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAgreementId(String value) {
this.agreementId = 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_ecosio_remadv\at\erpel\schemas\_1p0\messaging\header\InterchangeHeaderType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Collection<GrantedAuthority> convert(Jwt jwt) {
Collection<String> tokenScopes = parseScopesClaim(jwt);
if ( tokenScopes.isEmpty()) {
return Collections.emptyList();
}
return tokenScopes.stream()
.map(s -> scopes.getOrDefault(s, s))
.map(s -> this.authorityPrefix + s)
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toCollection(HashSet::new));
}
protected Collection<String> parseScopesClaim(Jwt jwt) {
String scopeClaim;
if ( this.authoritiesClaimName == null ) {
scopeClaim = WELL_KNOWN_AUTHORITIES_CLAIM_NAMES.stream()
.filter(jwt::hasClaim)
.findFirst()
.orElse(null);
if ( scopeClaim == null ) {
return Collections.emptyList();
}
}
else {
scopeClaim = this.authoritiesClaimName;
}
Object v = jwt.getClaim(scopeClaim);
|
if ( v == null ) {
return Collections.emptyList();
}
if ( v instanceof String) {
return Arrays.asList(v.toString().split(" "));
}
else if ( v instanceof Collection ) {
return ((Collection<?>)v).stream()
.map(Object::toString)
.collect(Collectors.toCollection(HashSet::new));
}
return Collections.emptyList();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-oidc\src\main\java\com\baeldung\openid\oidc\jwtauthorities\config\MappingJwtGrantedAuthoritiesConverter.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class RuleController {
public static final Logger logger = LoggerFactory.getLogger(RuleController.class);
@Autowired
RuleService ruleService;
@ResponseBody
@RequestMapping("address")
public Object test(int num) {
AddressCheckResult result = new AddressCheckResult();
Address address = new Address();
address.setPostcode(generateRandom(num));
String ruleKey = "score";
KieSession kieSession = ruleService.getKieSessionByName(ruleKey);
int ruleFiredCount = 0;
try {
kieSession.insert(address);
kieSession.insert(result);
ruleFiredCount = kieSession.fireAllRules();
} catch (Exception e) {
logger.warn(e.getMessage(), e);
} finally {
if (kieSession != null) {
kieSession.destroy();
}
}
System.out.println("触发了" + ruleFiredCount + "条规则");
if (result.isPostCodeResult()) {
System.out.println("规则校验通过");
}
return "ok";
}
/**
* 从数据加载最新规则
*
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping("/reloadRule")
public String reloadRule() throws IOException {
ruleService.reloadRule();
return "ok";
}
/**
* 查询规则
*
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping("query")
public List<Rule> query() throws IOException {
return ruleService.findAll();
}
|
/**
* 修改规则
*
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping("update")
public Rule update(Rule rule) throws IOException {
return ruleService.update(rule);
}
/**
* 新增规则
*
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping("add")
public Rule add(Rule rule) throws IOException {
return ruleService.insert(rule);
}
/**
* 生成随机数
*
* @param num
* @return
*/
public String generateRandom(int num) {
String chars = "0123456789";
StringBuffer number = new StringBuffer();
for (int i = 0; i < num; i++) {
int rand = (int) (Math.random() * 10);
number = number.append(chars.charAt(rand));
}
return number.toString();
}
}
|
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\controller\RuleController.java
| 2
|
请完成以下Java代码
|
public class WorkflowLaunchersList implements Iterable<WorkflowLauncher>
{
@NonNull private final ImmutableList<WorkflowLauncher> launchers;
@NonNull @Getter private final ImmutableList<OrderBy> orderByFields;
@Nullable @Getter private final PrintableScannedCode filterByQRCode;
@Nullable @Getter private final ImmutableSet<String> actions;
@NonNull @Getter private final Instant timestamp;
@Builder
private WorkflowLaunchersList(
@NonNull final List<WorkflowLauncher> launchers,
@NonNull @Singular final ImmutableList<OrderBy> orderByFields,
@Nullable final PrintableScannedCode filterByQRCode,
@Nullable final Set<String> actions,
@Nullable final Instant timestamp)
{
this.launchers = ImmutableList.copyOf(launchers);
this.orderByFields = orderByFields;
this.filterByQRCode = filterByQRCode;
this.actions = actions != null ? ImmutableSet.copyOf(actions) : null;
this.timestamp = timestamp != null ? timestamp : SystemTime.asInstant();
}
public int size() {return launchers.size();}
@Override
@NonNull
public Iterator<WorkflowLauncher> iterator() {return launchers.iterator();}
|
public Stream<WorkflowLauncher> stream() {return launchers.stream();}
public boolean isEmpty() {return launchers.isEmpty();}
public boolean isStaled(@NonNull final Duration maxStaleAccepted)
{
return maxStaleAccepted.compareTo(Duration.ZERO) <= 0 // explicitly asked for a fresh value
|| SystemTime.asInstant().isAfter(timestamp.plus(maxStaleAccepted));
}
public boolean equalsIgnoringTimestamp(@NonNull final WorkflowLaunchersList other)
{
return Objects.equals(this.launchers, other.launchers)
&& Objects.equals(this.filterByQRCode, other.filterByQRCode);
}
public ImmutableList<WorkflowLauncher> toList() {return launchers;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WorkflowLaunchersList.java
| 1
|
请完成以下Java代码
|
public void setRecord_Source_ID (int Record_Source_ID)
{
if (Record_Source_ID < 1)
set_Value (COLUMNNAME_Record_Source_ID, null);
else
set_Value (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID));
}
/** Get Quell-Datensatz-ID.
@return Quell-Datensatz-ID */
public int getRecord_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ziel-Datensatz-ID.
@param Record_Target_ID Ziel-Datensatz-ID */
public void setRecord_Target_ID (int Record_Target_ID)
{
if (Record_Target_ID < 1)
set_Value (COLUMNNAME_Record_Target_ID, null);
else
set_Value (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID));
}
/** Get Ziel-Datensatz-ID.
@return Ziel-Datensatz-ID */
public int getRecord_Target_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_ID);
if (ii == null)
return 0;
|
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
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_Relation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CommonResult login(@RequestParam String username,
@RequestParam String password) {
String token = memberService.login(username, password);
if (token == null) {
return CommonResult.validateFailed("用户名或密码错误");
}
Map<String, String> tokenMap = new HashMap<>();
tokenMap.put("token", token);
tokenMap.put("tokenHead", tokenHead);
return CommonResult.success(tokenMap);
}
@ApiOperation("获取会员信息")
@RequestMapping(value = "/info", method = RequestMethod.GET)
@ResponseBody
public CommonResult info(Principal principal) {
if(principal==null){
return CommonResult.unauthorized(null);
}
UmsMember member = memberService.getCurrentMember();
return CommonResult.success(member);
}
@ApiOperation("获取验证码")
@RequestMapping(value = "/getAuthCode", method = RequestMethod.GET)
@ResponseBody
public CommonResult getAuthCode(@RequestParam String telephone) {
String authCode = memberService.generateAuthCode(telephone);
return CommonResult.success(authCode,"获取验证码成功");
}
@ApiOperation("会员修改密码")
|
@RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
@ResponseBody
public CommonResult updatePassword(@RequestParam String telephone,
@RequestParam String password,
@RequestParam String authCode) {
memberService.updatePassword(telephone,password,authCode);
return CommonResult.success(null,"密码修改成功");
}
@ApiOperation(value = "刷新token")
@RequestMapping(value = "/refreshToken", method = RequestMethod.GET)
@ResponseBody
public CommonResult refreshToken(HttpServletRequest request) {
String token = request.getHeader(tokenHeader);
String refreshToken = memberService.refreshToken(token);
if (refreshToken == null) {
return CommonResult.failed("token已经过期!");
}
Map<String, String> tokenMap = new HashMap<>();
tokenMap.put("token", refreshToken);
tokenMap.put("tokenHead", tokenHead);
return CommonResult.success(tokenMap);
}
}
|
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\UmsMemberController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id
private int id;
@Column(name = "first_name")
private String firstName;
// switch these two lines to reproduce the exception
// @Column(name = "first_name")
@Column(name = "last_name")
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
|
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-exceptions-2\src\main\java\com\baeldung\hibernate\columnduplicatedmapping\Person.java
| 2
|
请完成以下Java代码
|
public void afterModelUnlinked(final Object model, final I_M_Material_Tracking materialTrackingOld)
{
final I_M_InOutLine receiptLine = InterfaceWrapperHelper.create(model, I_M_InOutLine.class);
if (!isEligible(receiptLine, materialTrackingOld))
{
return;
}
final BigDecimal qtyReceivedToRemove = receiptLine.getMovementQty();
final BigDecimal qtyReceived = materialTrackingOld.getQtyReceived();
final BigDecimal qtyReceivedNew = qtyReceived.subtract(qtyReceivedToRemove);
materialTrackingOld.setQtyReceived(qtyReceivedNew);
InterfaceWrapperHelper.save(materialTrackingOld);
}
private final boolean isEligible(final I_M_InOutLine inoutLine, final I_M_Material_Tracking materialTracking)
{
|
// check if the inoutLine's product is our tracked product.
if (materialTracking.getM_Product_ID() != inoutLine.getM_Product_ID())
{
return false;
}
final I_M_InOut inout = inoutLine.getM_InOut();
// Shipments are not eligible (just in case)
if (inout.isSOTrx())
{
return false;
}
return true;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\spi\impl\listeners\InOutLineMaterialTrackingListener.java
| 1
|
请完成以下Java代码
|
public String getF_ALLOWADD() {
return F_ALLOWADD;
}
public void setF_ALLOWADD(String f_ALLOWADD) {
F_ALLOWADD = f_ALLOWADD;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_LEVEL() {
return F_LEVEL;
}
public void setF_LEVEL(String f_LEVEL) {
F_LEVEL = f_LEVEL;
}
public String getF_END() {
return F_END;
}
public void setF_END(String f_END) {
F_END = f_END;
}
public String getF_SHAREDIREC() {
return F_SHAREDIREC;
}
public void setF_SHAREDIREC(String f_SHAREDIREC) {
F_SHAREDIREC = f_SHAREDIREC;
}
public String getF_HISTORYID() {
return F_HISTORYID;
}
public void setF_HISTORYID(String f_HISTORYID) {
F_HISTORYID = f_HISTORYID;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_VERSION() {
return F_VERSION;
}
public void setF_VERSION(String f_VERSION) {
F_VERSION = f_VERSION;
}
public String getF_ISSTD() {
return F_ISSTD;
}
|
public void setF_ISSTD(String f_ISSTD) {
F_ISSTD = f_ISSTD;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public String getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(String f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISENTERPRISES() {
return F_ISENTERPRISES;
}
public void setF_ISENTERPRISES(String f_ISENTERPRISES) {
F_ISENTERPRISES = f_ISENTERPRISES;
}
public String getF_ISCLEAR() {
return F_ISCLEAR;
}
public void setF_ISCLEAR(String f_ISCLEAR) {
F_ISCLEAR = f_ISCLEAR;
}
public String getF_PARENTID() {
return F_PARENTID;
}
public void setF_PARENTID(String f_PARENTID) {
F_PARENTID = f_PARENTID;
}
}
|
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java
| 1
|
请完成以下Java代码
|
public String getActivityInstanceId() {
return activityInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseExecutionId() {
return caseExecutionId;
}
public String getTaskId() {
return taskId;
}
public String getTenantId() {
return tenantId;
}
public String getUserOperationId() {
return userOperationId;
}
public Date getTime() {
return time;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) {
|
HistoricDetailDto dto = null;
if (historicDetail instanceof HistoricFormField) {
HistoricFormField historicFormField = (HistoricFormField) historicDetail;
dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField);
} else if (historicDetail instanceof HistoricVariableUpdate) {
HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate);
}
fromHistoricDetail(historicDetail, dto);
return dto;
}
protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) {
dto.id = historicDetail.getId();
dto.processDefinitionKey = historicDetail.getProcessDefinitionKey();
dto.processDefinitionId = historicDetail.getProcessDefinitionId();
dto.processInstanceId = historicDetail.getProcessInstanceId();
dto.activityInstanceId = historicDetail.getActivityInstanceId();
dto.executionId = historicDetail.getExecutionId();
dto.taskId = historicDetail.getTaskId();
dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey();
dto.caseDefinitionId = historicDetail.getCaseDefinitionId();
dto.caseInstanceId = historicDetail.getCaseInstanceId();
dto.caseExecutionId = historicDetail.getCaseExecutionId();
dto.tenantId = historicDetail.getTenantId();
dto.userOperationId = historicDetail.getUserOperationId();
dto.time = historicDetail.getTime();
dto.removalTime = historicDetail.getRemovalTime();
dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDetailDto.java
| 1
|
请完成以下Java代码
|
public class JuelExpression implements Expression {
protected String expressionText;
protected ValueExpression valueExpression;
public JuelExpression(ValueExpression valueExpression, String expressionText) {
this.valueExpression = valueExpression;
this.expressionText = expressionText;
}
@Override
public Object getValue(VariableContainer variableContainer) {
ELContext elContext = Context.getProcessEngineConfiguration().getExpressionManager().getElContext((VariableScope) variableContainer);
try {
ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
return invocation.getInvocationResult();
} catch (PropertyNotFoundException pnfe) {
throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe);
} catch (MethodNotFoundException mnfe) {
throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe);
} catch (ELException ele) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, ele);
} catch (Exception e) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, e);
}
}
|
@Override
public void setValue(Object value, VariableContainer variableContainer) {
ELContext elContext = Context.getProcessEngineConfiguration().getExpressionManager().getElContext((VariableScope) variableContainer);
try {
ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (Exception e) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, e);
}
}
@Override
public String toString() {
if (valueExpression != null) {
return valueExpression.getExpressionString();
}
return super.toString();
}
@Override
public String getExpressionText() {
return expressionText;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AcquireJobsCmd implements Command<List<? extends JobInfoEntity>> {
protected AsyncExecutor asyncExecutor;
protected int remainingCapacity;
protected JobInfoEntityManager<? extends JobInfoEntity> jobEntityManager;
public AcquireJobsCmd(AsyncExecutor asyncExecutor) {
this(asyncExecutor, Integer.MAX_VALUE, asyncExecutor.getJobServiceConfiguration().getJobEntityManager());
}
public AcquireJobsCmd(AsyncExecutor asyncExecutor, int remainingCapacity, JobInfoEntityManager<? extends JobInfoEntity> jobEntityManager) {
this.asyncExecutor = asyncExecutor;
this.remainingCapacity = remainingCapacity;
this.jobEntityManager = jobEntityManager;
}
@Override
public List<? extends JobInfoEntity> execute(CommandContext commandContext) {
int maxResults = Math.min(remainingCapacity, asyncExecutor.getMaxAsyncJobsDuePerAcquisition());
List<String> enabledCategories = asyncExecutor.getJobServiceConfiguration().getEnabledJobCategories();
List<? extends JobInfoEntity> jobs = jobEntityManager.findJobsToExecute(enabledCategories, new Page(0, maxResults));
for (JobInfoEntity job : jobs) {
lockJob(job, asyncExecutor.getAsyncJobLockTimeInMillis(), asyncExecutor.getJobServiceConfiguration());
}
|
return jobs;
}
protected void lockJob(JobInfoEntity job, int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) {
GregorianCalendar gregorianCalendar = calculateLockExpirationTime(lockTimeInMillis, jobServiceConfiguration);
job.setLockOwner(asyncExecutor.getLockOwner());
job.setLockExpirationTime(gregorianCalendar.getTime());
}
protected GregorianCalendar calculateLockExpirationTime(int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime());
gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
return gregorianCalendar;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AcquireJobsCmd.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.