instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class PickingJobCreateRepoRequest
{
@NonNull PickingJobAggregationType aggregationType;
@NonNull OrgId orgId;
@Nullable OrderId salesOrderId;
@Nullable InstantAndOrgId preparationDate;
@Nullable InstantAndOrgId deliveryDate;
@Nullable BPartnerLocationId deliveryBPLocationId;
@Nullable String deliveryRenderedAddress;
@NonNull UserId pickerId;
@Nullable BPartnerLocationId handoverLocationId;
boolean isAllowPickingAnyHU;
@Singular @NonNull ImmutableList<Line> lines;
//
// -------------------------------------------
//
@Value
@Builder
public static class Line
{
@NonNull ProductId productId;
@NonNull HUPIItemProductId huPIItemProductId;
@NonNull Quantity qtyToPick;
@NonNull OrderAndLineId salesOrderAndLineId;
@NonNull BPartnerLocationId deliveryBPLocationId;
@Nullable ShipmentScheduleAndJobScheduleId scheduleId;
@Nullable UomId catchWeightUomId;
@Nullable PPOrderId pickFromManufacturingOrderId;
@Singular @NonNull ImmutableList<Step> steps;
@Builder.Default
@NonNull ImmutableSet<PickFromAlternative> pickFromAlternatives = ImmutableSet.of();
}
@Value(staticConstructor = "of")
public static class PickFromAlternative
{
@NonNull LocatorId pickFromLocatorId;
@NonNull HuId pickFromHUId;
@NonNull Quantity qtyAvailable;
}
|
@Value
@Builder
public static class Step
{
@NonNull ShipmentScheduleAndJobScheduleId scheduleId;
@NonNull OrderAndLineId salesOrderLineId;
//
// What?
@NonNull ProductId productId;
@NonNull Quantity qtyToPick;
//
// From where?
@NonNull StepPickFrom mainPickFrom;
@Builder.Default
@NonNull ImmutableSet<StepPickFrom> pickFromAlternatives = ImmutableSet.of();
@NonNull PackToSpec packToSpec;
}
@Value
@Builder
public static class StepPickFrom
{
@NonNull LocatorId pickFromLocatorId;
@NonNull HuId pickFromHUId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobCreateRepoRequest.java
| 2
|
请完成以下Java代码
|
public class ReportResultToCsvConverter {
protected static String DELIMITER = ",";
protected static String NEW_LINE_SEPARATOR = "\n";
public static String DURATION_HEADER = "PERIOD"
+ DELIMITER + "PERIOD_UNIT"
+ DELIMITER + "MINIMUM"
+ DELIMITER + "MAXIMUM"
+ DELIMITER + "AVERAGE";
public static String convertReportResult(List<ReportResult> reports, String reportType) {
if (HistoricProcessInstanceReportDto.REPORT_TYPE_DURATION.equals(reportType)) {
return convertDurationReportResult(reports);
}
throw new InvalidRequestException(Status.BAD_REQUEST, "Unkown report type " + reportType);
}
protected static String convertDurationReportResult(List<ReportResult> reports) {
StringBuilder buffer = new StringBuilder();
buffer.append(DURATION_HEADER);
for (ReportResult report : reports) {
DurationReportResult durationReport = (DurationReportResult) report;
|
buffer.append(NEW_LINE_SEPARATOR);
buffer.append(durationReport.getPeriod());
buffer.append(DELIMITER);
buffer.append(durationReport.getPeriodUnit().toString());
buffer.append(DELIMITER);
buffer.append(durationReport.getMinimum());
buffer.append(DELIMITER);
buffer.append(durationReport.getMaximum());
buffer.append(DELIMITER);
buffer.append(durationReport.getAverage());
}
return buffer.toString();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\converter\ReportResultToCsvConverter.java
| 1
|
请完成以下Java代码
|
private void syncPackageAllocationRecords(
@NonNull final I_DerKurier_DeliveryOrderLine lineRecord,
@NonNull final ImmutableSet<PackageId> packageIds)
{
final List<I_DerKurier_DeliveryOrderLine_Package> preExistingRecords = Services.get(IQueryBL.class)
.createQueryBuilder(I_DerKurier_DeliveryOrderLine_Package.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_DerKurier_DeliveryOrderLine_Package.COLUMN_DerKurier_DeliveryOrderLine_ID, lineRecord.getDerKurier_DeliveryOrderLine_ID())
.create()
.list();
final ImmutableListMultimap<Integer, I_DerKurier_DeliveryOrderLine_Package> packageId2preExistingRecord = //
Multimaps.index(preExistingRecords, I_DerKurier_DeliveryOrderLine_Package::getM_Package_ID);
// create missing records
for (final PackageId packageIdRepo : packageIds)
{
final int packageId = packageIdRepo.getRepoId();
final boolean recordForPackageIdExists = packageId2preExistingRecord.containsKey(packageId);
if (recordForPackageIdExists)
{
continue;
}
final I_DerKurier_DeliveryOrderLine_Package newRecord = newInstance(I_DerKurier_DeliveryOrderLine_Package.class);
newRecord.setDerKurier_DeliveryOrderLine(lineRecord);
newRecord.setM_Package_ID(packageId);
InterfaceWrapperHelper.save(newRecord);
}
// delete surplus records
for (final int preExistingRecordPackageId : packageId2preExistingRecord.keySet())
{
final boolean preExistingRecordCanBeKept = packageIds.contains(preExistingRecordPackageId);
if (preExistingRecordCanBeKept)
{
continue;
}
packageId2preExistingRecord
.get(preExistingRecordPackageId)
.forEach(InterfaceWrapperHelper::delete);
}
}
|
private I_DerKurier_DeliveryOrderLine loadOrNewInstance(final int deliveryOrderLineRepoId)
{
if (deliveryOrderLineRepoId <= 0)
{
return newInstance(I_DerKurier_DeliveryOrderLine.class);
}
return loadAssumeRecordExists(deliveryOrderLineRepoId, I_DerKurier_DeliveryOrderLine.class);
}
private <T> T loadAssumeRecordExists(
final int repoId,
@NonNull final Class<T> modelClass)
{
Check.assume(repoId > 0, "deliveryOrderRepoId > 0");
final T orderPO = InterfaceWrapperHelper.load(repoId, modelClass);
Check.assumeNotNull(orderPO, "A data recordfor modelClass={} and ID={}", modelClass.getSimpleName(), repoId);
return orderPO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\DerKurierDeliveryOrderRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SmsFlashPromotionController {
@Autowired
private SmsFlashPromotionService flashPromotionService;
@ApiOperation("添加活动")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody SmsFlashPromotion flashPromotion) {
int count = flashPromotionService.create(flashPromotion);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("编辑活动")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody SmsFlashPromotion flashPromotion) {
int count = flashPromotionService.update(id, flashPromotion);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("删除活动")
@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@PathVariable Long id) {
int count = flashPromotionService.delete(id);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
|
@ApiOperation("修改上下线状态")
@RequestMapping(value = "/update/status/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, Integer status) {
int count = flashPromotionService.updateStatus(id, status);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取活动详情")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<SmsFlashPromotion> getItem(@PathVariable Long id) {
SmsFlashPromotion flashPromotion = flashPromotionService.getItem(id);
return CommonResult.success(flashPromotion);
}
@ApiOperation("根据活动名称分页查询")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsFlashPromotion>> getItem(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsFlashPromotion> flashPromotionList = flashPromotionService.list(keyword, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(flashPromotionList));
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsFlashPromotionController.java
| 2
|
请完成以下Java代码
|
public ImmutableSet<PaymentId> retrievePaymentIds(@NonNull final PaymentQuery query)
{
final IQueryBuilder<I_C_Payment> queryBuilder = queryBL.createQueryBuilder(I_C_Payment.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Payment.COLUMNNAME_DocStatus, query.getDocStatus());
if (query.getReconciled() != null)
{
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReconciled, query.getReconciled());
}
if (query.getDirection() != null)
{
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReceipt, query.getDirection().isReceipt());
}
if (query.getBpartnerId() != null)
{
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_C_BPartner_ID, query.getBpartnerId());
}
if (query.getPayAmt() != null)
{
queryBuilder
.addEqualsFilter(I_C_Payment.COLUMNNAME_PayAmt, query.getPayAmt().toBigDecimal())
.addEqualsFilter(I_C_Payment.COLUMNNAME_C_Currency_ID, query.getPayAmt().getCurrencyId());
}
if (!query.getExcludePaymentIds().isEmpty())
{
queryBuilder.addNotInArrayFilter(I_C_Payment.COLUMNNAME_C_Payment_ID, query.getExcludePaymentIds());
}
if(query.getDateTrx() != null)
{
queryBuilder.addEqualsFilter(I_C_Payment.COLUMNNAME_DateTrx, query.getDateTrx());
}
return queryBuilder
.setLimit(query.getLimit())
.create()
.idsAsSet(PaymentId::ofRepoId);
}
@Override
public void save(final @NonNull I_C_Payment payment)
{
InterfaceWrapperHelper.save(payment);
}
|
@Override
public Iterator<I_C_Payment> retrieveEmployeePaymentsForTimeframe(
@NonNull final OrgId orgId,
@NonNull final BankAccountId bankAccountId,
@NonNull final Instant startDate,
@NonNull final Instant endDate)
{
final IQuery<I_C_BPartner> employeePartnerQuery = queryBL.createQueryBuilder(I_C_BPartner.class)
.addEqualsFilter(I_C_BPartner.COLUMNNAME_IsEmployee, true)
.create();
final Iterator<I_C_Payment> paymentsForEmployees = queryBL.createQueryBuilder(I_C_Payment.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Payment.COLUMNNAME_AD_Org_ID, orgId)
.addInArrayFilter(I_C_Payment.COLUMNNAME_DocStatus, DocStatus.completedOrClosedStatuses())
.addEqualsFilter(I_C_Payment.COLUMNNAME_IsAllocated, false)
.addEqualsFilter(I_C_Payment.COLUMNNAME_C_BP_BankAccount_ID, bankAccountId)
.addBetweenFilter(I_C_Payment.COLUMNNAME_DateTrx, startDate, endDate)
.addEqualsFilter(I_C_Payment.COLUMNNAME_IsReceipt, true)
.addInSubQueryFilter(I_C_Payment.COLUMNNAME_C_BPartner_ID,
I_C_BPartner.COLUMNNAME_C_BPartner_ID,
employeePartnerQuery)
.create()
.iterate(I_C_Payment.class);
return paymentsForEmployees;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\payment\api\impl\AbstractPaymentDAO.java
| 1
|
请完成以下Java代码
|
public static ImmutableAttributeSet toImmutableAttributeSet(@NonNull final AttributesKey attributesKey)
{
try
{
final ImmutableAttributeSet.Builder builder = ImmutableAttributeSet.builder();
final HashSet<AttributeValueId> attributeValueIds = new HashSet<>();
for (final AttributesKeyPart part : attributesKey.getParts())
{
if (part.getType() == AttributeKeyPartType.AttributeIdAndValue)
{
final AttributeId attributeId = part.getAttributeId();
final Object value = part.getValue();
final AttributeValueId attributeValueId = null;
builder.attributeValue(attributeId, value, attributeValueId);
}
else if (part.getType() == AttributeKeyPartType.AttributeValueId)
{
attributeValueIds.add(part.getAttributeValueId());
}
}
for (final AttributeListValue attributeValueRecord : attributesRepo().retrieveAttributeValuesByIds(attributeValueIds))
{
builder.attributeValue(attributeValueRecord);
}
return builder.build();
}
catch (final RuntimeException ex)
|
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("attributesKey", attributesKey);
}
}
public static AttributesKey pruneEmptyParts(@NonNull final AttributesKey attributesKey)
{
final ImmutableList<AttributesKeyPart> notBlankParts = attributesKey.getParts().stream()
.filter(p -> Check.isNotBlank(p.getValue()))
.collect(ImmutableList.toImmutableList());
return AttributesKey.ofParts(notBlankParts);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeys.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(rootDocumentPath)
.add("detailId", detailId)
.add("quickInputId", quickInputId)
.toString();
}
@Override
public int hashCode()
{
if (_hashCode == null)
{
_hashCode = Objects.hash(rootDocumentPath, detailId, quickInputId);
}
return _hashCode;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
else if (obj instanceof QuickInputPath)
{
final QuickInputPath other = (QuickInputPath)obj;
return Objects.equals(rootDocumentPath, other.rootDocumentPath)
&& Objects.equals(detailId, other.detailId)
&& Objects.equals(quickInputId, other.quickInputId);
|
}
else
{
return false;
}
}
public DocumentPath getRootDocumentPath()
{
return rootDocumentPath;
}
public DetailId getDetailId()
{
return detailId;
}
public DocumentId getQuickInputId()
{
return quickInputId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputPath.java
| 1
|
请完成以下Java代码
|
public void onParentResume(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("parentResume", execution);
}
// re-activation ////////////////////////////////////////////////////////
public void onReactivation(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("reactivate", execution);
}
// sentry ///////////////////////////////////////////////////////////////
protected boolean isAtLeastOneExitCriterionSatisfied(CmmnActivityExecution execution) {
return false;
}
|
public void fireExitCriteria(CmmnActivityExecution execution) {
throw LOG.criteriaNotAllowedForEventListenerOrMilestonesException("exit", execution.getId());
}
// helper ////////////////////////////////////////////////////////////////
protected CaseIllegalStateTransitionException createIllegalStateTransitionException(String transition, CmmnActivityExecution execution) {
String id = execution.getId();
return LOG.illegalStateTransitionException(transition, id, getTypeName());
}
protected abstract String getTypeName();
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerOrMilestoneActivityBehavior.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final OrgId orgId = OrgId.ofRepoId(toOrgId);
final PInstanceId pinstanceId = getPinstanceId();
final ImmutableList<I_C_DocType> docTypes = docTypeBL.retrieveForSelection(pinstanceId);
for (final I_C_DocType docType : docTypes)
{
docTypeBL.cloneToOrg(docType, orgId);
}
return "@Copied@=" + docTypes.size();
}
@Override
@RunOutOfTrx
protected void prepare()
{
if (createSelection() <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
private int createSelection()
|
{
final IQueryBuilder<I_C_DocType> queryBuilder = createDocTypesQueryBuilder();
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null");
DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
return queryBuilder
.create()
.createSelection(adPInstanceId);
}
@NonNull
private IQueryBuilder<I_C_DocType> createDocTypesQueryBuilder()
{
final IQueryFilter<I_C_DocType> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_C_DocType.class, getCtx(), ITrx.TRXNAME_None)
.filter(userSelectionFilter);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\process\C_DocType_Clone_Selection.java
| 1
|
请完成以下Java代码
|
/* package */ class BPartnerPrintFormatImportHelper
{
@NonNull private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
@NonNull private final IADTableDAO tableDAO = Services.get(IADTableDAO.class);
@NonNull private final BPartnerPrintFormatRepository bPartnerPrintFormatRepository;
@Builder
private BPartnerPrintFormatImportHelper(
@NonNull final BPartnerPrintFormatRepository bPartnerPrintFormatRepository)
{
this.bPartnerPrintFormatRepository = bPartnerPrintFormatRepository;
}
public void importRecord(@NonNull final BPartnerImportContext context)
{
final I_I_BPartner importRecord = context.getCurrentImportRecord();
if (importRecord.getAD_PrintFormat_ID() <= 0 && Check.isBlank(importRecord.getPrintFormat_DocBaseType()))
{
return;
}
final PrintFormatId printFormatId = PrintFormatId.ofRepoIdOrNull(importRecord.getAD_PrintFormat_ID());
final DocBaseType docBaseType;
if(!Check.isBlank(importRecord.getPrintFormat_DocBaseType()))
{
docBaseType = DocBaseType.ofCode(importRecord.getPrintFormat_DocBaseType());
}
// for vendors we have print format for purchase order
else if (importRecord.isVendor())
{
docBaseType = DocBaseType.PurchaseOrder;
}
// for customer we have print format for delivery
else
{
docBaseType = DocBaseType.Shipment;
}
final DocTypeId docTypeId = docTypeDAO.getDocTypeId(DocTypeQuery.builder()
|
.docBaseType(docBaseType)
.adClientId(importRecord.getAD_Client_ID())
.adOrgId(importRecord.getAD_Org_ID())
.build());
final AdTableId adTableId = AdTableId.ofRepoId(tableDAO.retrieveTableId(docBaseType.getTableName()));
final BPartnerId bPartnerId = BPartnerId.ofRepoId(importRecord.getC_BPartner_ID());
final BPartnerLocationId bPartnerLocationId = importRecord.isSetPrintFormat_C_BPartner_Location()
? BPartnerLocationId.ofRepoIdOrNull(bPartnerId, importRecord.getC_BPartner_Location_ID())
: null;
final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder()
.printFormatId(printFormatId)
.docTypeId(docTypeId)
.adTableId(adTableId)
.bPartnerLocationId(bPartnerLocationId)
.bpartnerId(bPartnerId)
.isExactMatch(true)
.build();
BPPrintFormat bpPrintFormat = bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery);
if (bpPrintFormat == null)
{
bpPrintFormat = BPPrintFormat.builder()
.adTableId(adTableId)
.docTypeId(docTypeId)
.printFormatId(printFormatId)
.bpartnerId(BPartnerId.ofRepoId(importRecord.getC_BPartner_ID()))
.bPartnerLocationId(bPartnerLocationId)
.printCopies(PrintCopies.ofInt(importRecord.getPrintFormat_DocumentCopies_Override()))
.build();
}
bpPrintFormat = bPartnerPrintFormatRepository.save(bpPrintFormat);
importRecord.setC_BP_PrintFormat_ID(bpPrintFormat.getBpPrintFormatId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerPrintFormatImportHelper.java
| 1
|
请完成以下Java代码
|
public class AddIdentityLinkForProcessInstanceCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
protected String userId;
protected String groupId;
protected String type;
protected byte[] details;
public AddIdentityLinkForProcessInstanceCmd(String processInstanceId, String userId, String groupId, String type) {
this(processInstanceId, userId, groupId, type, null);
}
public AddIdentityLinkForProcessInstanceCmd(
String processInstanceId,
String userId,
String groupId,
String type,
byte[] details
) {
validateParams(processInstanceId, userId, groupId, type);
this.processInstanceId = processInstanceId;
this.userId = userId;
this.groupId = groupId;
this.type = type;
this.details = details;
}
protected void validateParams(String processInstanceId, String userId, String groupId, String type) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
if (type == null) {
throw new ActivitiIllegalArgumentException(
"type is required when adding a new process instance identity link"
);
|
}
if (userId == null && groupId == null) {
throw new ActivitiIllegalArgumentException("userId and groupId cannot both be null");
}
}
public Void execute(CommandContext commandContext) {
ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
ExecutionEntity processInstance = executionEntityManager.findById(processInstanceId);
if (processInstance == null) {
throw new ActivitiObjectNotFoundException(
"Cannot find process instance with id " + processInstanceId,
ExecutionEntity.class
);
}
executeInternal(commandContext, processInstance);
return null;
}
protected void executeInternal(CommandContext commandContext, ExecutionEntity processInstance) {
IdentityLinkEntityManager identityLinkEntityManager = commandContext.getIdentityLinkEntityManager();
identityLinkEntityManager.addIdentityLink(processInstance, userId, groupId, type, details);
commandContext
.getHistoryManager()
.createProcessInstanceIdentityLinkComment(processInstanceId, userId, groupId, type, true);
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkForProcessInstanceCmd.java
| 1
|
请完成以下Java代码
|
public class PropertiesListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
private final CamundaBpmVersion version;
/**
* Default constructor, used when initializing via spring.factories.
*
* @see PropertiesListener#PropertiesListener(CamundaBpmVersion)
*/
public PropertiesListener() {
this(new CamundaBpmVersion());
}
/**
* Initialize with version.
|
*
* @param version the current camundaBpmVersion instance.
*/
PropertiesListener(CamundaBpmVersion version) {
this.version = version;
}
@Override
public void onApplicationEvent(final ApplicationEnvironmentPreparedEvent event) {
event.getEnvironment()
.getPropertySources()
.addFirst(version.getPropertiesPropertySource());
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\runlistener\PropertiesListener.java
| 1
|
请完成以下Java代码
|
public ImmutableList<HUReservationEntry> getEntriesByVHUIds(@NonNull final Collection<HuId> vhuIds)
{
return huReservationRepository.getEntriesByVHUIds(vhuIds);
}
public boolean isAnyOfVHUIdsReserved(@NonNull final Collection<HuId> vhuIds)
{
return !huReservationRepository.getEntriesByVHUIds(vhuIds).isEmpty();
}
@Builder(builderMethodName = "prepareHUQuery", builderClassName = "AvailableHUQueryBuilder")
private IHUQueryBuilder createHUQuery(
@NonNull final WarehouseId warehouseId,
@NonNull final ProductId productId,
@NonNull final BPartnerId bpartnerId,
@Nullable final AttributeSetInstanceId asiId,
@Nullable final HUReservationDocRef reservedToDocumentOrNotReservedAtAll)
{
final Set<WarehouseId> pickingWarehouseIds = warehousesRepo.getWarehouseIdsOfSamePickingGroup(warehouseId);
final IHUQueryBuilder huQuery = handlingUnitsDAO
.createHUQueryBuilder()
.addOnlyInWarehouseIds(pickingWarehouseIds)
.addOnlyWithProductId(productId)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active);
// ASI
if (asiId != null)
{
final ImmutableAttributeSet attributeSet = asiBL.getImmutableAttributeSetById(asiId);
huQuery.addOnlyWithAttributeValuesMatchingPartnerAndProduct(bpartnerId, productId, attributeSet);
huQuery.allowSqlWhenFilteringAttributes(isAllowSqlWhenFilteringHUAttributes());
}
// Reservation
if (reservedToDocumentOrNotReservedAtAll == null)
{
huQuery.setExcludeReserved();
}
else
{
huQuery.setExcludeReservedToOtherThan(reservedToDocumentOrNotReservedAtAll);
}
return huQuery;
}
|
// FIXME: move it to AttributeDAO
@Deprecated
public boolean isAllowSqlWhenFilteringHUAttributes()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_AllowSqlWhenFilteringHUAttributes, true);
}
public void transferReservation(
@NonNull final HUReservationDocRef from,
@NonNull final HUReservationDocRef to,
@NonNull final Set<HuId> vhuIds)
{
huReservationRepository.transferReservation(ImmutableSet.of(from), to, vhuIds);
}
public void transferReservation(
@NonNull final Collection<HUReservationDocRef> from,
@NonNull final HUReservationDocRef to)
{
final Set<HuId> vhuIds = ImmutableSet.of();
huReservationRepository.transferReservation(from, to, vhuIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\HUReservationService.java
| 1
|
请完成以下Java代码
|
public boolean isUseClassForNameClassLoading() {
return useClassForNameClassLoading;
}
public void setUseClassForNameClassLoading(boolean useClassForNameClassLoading) {
this.useClassForNameClassLoading = useClassForNameClassLoading;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
// getters and setters
// //////////////////////////////////////////////////////
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
|
public Throwable getException() {
return exception;
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public long getStartTime() {
return startTime;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\interceptor\CommandContext.java
| 1
|
请完成以下Java代码
|
public Wallet loadEncryptedWallet() throws IOException, UnreadableWalletException {
File walletFile = new File("baeldungencrypted.dat");
Wallet wallet = Wallet.loadFromFile(walletFile);
logger.info("Address: " + wallet.currentReceiveAddress().toString());
logger.info("Seed Phrase: " + wallet.getKeyChainSeed().getMnemonicString());
logger.info("Balance: " + wallet.getBalance().toFriendlyString());
logger.info("Public Key: " + wallet.findKeyFromAddress(wallet.currentReceiveAddress()).getPublicKeyAsHex());
return wallet;
}
public Wallet loadDecryptedWallet() throws IOException, UnreadableWalletException {
File walletFile = new File("baeldungencrypted.dat");
Wallet wallet = Wallet.loadFromFile(walletFile);
wallet.decrypt("password");
return wallet;
}
public Wallet loadWallet() throws IOException, UnreadableWalletException {
File walletFile = new File("baeldung.dat");
Wallet wallet = Wallet.loadFromFile(walletFile);
logger.info("Address: " + wallet.currentReceiveAddress().toString());
logger.info("Seed Phrase: " + wallet.getKeyChainSeed().getMnemonicString());
logger.info("Balance: " + wallet.getBalance().toFriendlyString());
logger.info("Public Key: " + wallet.findKeyFromAddress(wallet.currentReceiveAddress()).getPublicKeyAsHex());
logger.info("Private Key: " + wallet.findKeyFromAddress(wallet.currentReceiveAddress()).getPrivateKeyAsHex());
return wallet;
}
public Wallet loadUsingSeed(String seedWord) throws UnreadableWalletException {
DeterministicSeed seed = new DeterministicSeed(seedWord, null, "", Utils.currentTimeSeconds());
return Wallet.fromSeed(params, seed);
}
public void connectWalletToPeer() throws BlockStoreException, UnreadableWalletException, IOException {
|
Wallet wallet = loadWallet();
BlockStore blockStore = new MemoryBlockStore(params);
BlockChain chain = new BlockChain(params, wallet, blockStore);
PeerGroup peerGroup = new PeerGroup(params, chain);
peerGroup.addPeerDiscovery(new DnsDiscovery(params));
peerGroup.addWallet(wallet);
wallet.addCoinsReceivedEventListener((Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) -> {
logger.info("Received tx for " + tx.getValueSentToMe(wallet));
logger.info("New balance: " + newBalance.toFriendlyString());
});
peerGroup.start();
peerGroup.downloadBlockChain();
wallet.saveToFile(new File("baeldung.dat"));
logger.info("Wallet balance: " + wallet.getBalance()
.toFriendlyString());
}
}
|
repos\tutorials-master\java-blockchain\src\main\java\com\baeldung\bitcoinj\CreateWallet.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AppConfiguration
{
private static final Logger logger = LogManager.getLogger(AppConfiguration.class);
private final ApplicationContext context;
private final CamelContext camelContext;
public AppConfiguration(
final ApplicationContext context,
final CamelContext camelContext)
{
this.context = context;
this.camelContext = camelContext;
}
@Bean
public ProducerTemplate producerTemplate()
{
return camelContext.createProducerTemplate();
}
@Bean
public CustomRouteController customRouteController()
{
return new CustomRouteController(this.camelContext);
}
@Bean
CamelContextConfiguration contextConfiguration(
@NonNull final MetasfreshAuthProvider metasfreshAuthProvider,
@NonNull final CustomRouteController customRouteController,
@NonNull final ProducerTemplate producerTemplate
)
{
return new CamelContextConfiguration()
{
@Override
public void beforeApplicationStart(final CamelContext camelContext)
{
camelContext.setAutoStartup(false);
|
final Environment env = context.getEnvironment();
logger.log(Level.INFO, "Configured RabbitMQ hostname:port is {}:{}", env.getProperty("camel.component.rabbitmq.hostname"), env.getProperty("camel.component.rabbitmq.port-number"));
final String metasfreshAPIBaseURL = context.getEnvironment().getProperty(ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
if (Check.isBlank(metasfreshAPIBaseURL))
{
throw new RuntimeException("Missing mandatory property! property = " + ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
}
camelContext.getManagementStrategy()
.addEventNotifier(new MetasfreshAuthorizationTokenNotifier(metasfreshAuthProvider, metasfreshAPIBaseURL, customRouteController, producerTemplate));
camelContext.getManagementStrategy()
.addEventNotifier(new AuditEventNotifier(producerTemplate));
}
@Override
public void afterApplicationStart(final CamelContext camelContext)
{
customRouteController().startAlwaysRunningRoutes();
producerTemplate
.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication!");
}
};
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AppConfiguration.java
| 2
|
请完成以下Java代码
|
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Person [id=");
builder.append(id);
builder.append(", name=");
builder.append(name);
builder.append(", email=");
builder.append(email);
builder.append(", age=");
builder.append(age);
builder.append(", registeredDate=");
builder.append(registeredDate);
builder.append(", salary=");
builder.append(salary);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
|
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (id != other.id)
return false;
return true;
}
}
|
repos\tutorials-master\json-modules\json-2\src\main\java\com\baeldung\jsonb\Person.java
| 1
|
请完成以下Java代码
|
private void updateCustomerRetentionAfterInvoiceId(@NonNull final CustomerRetentionId customerRetentionId,
@NonNull final InvoiceId invoiceId,
@NonNull final LocalDate firstContractStartDate)
{
final InvoiceId predecessorSalesContractInvoiceId = contractInvoiceService.retrievePredecessorSalesContractInvoiceId(invoiceId);
if (Check.isEmpty(predecessorSalesContractInvoiceId))
{
setNewCustomer(customerRetentionId);
}
else
{
final I_C_Invoice predecessorInvoice = invoiceDAO.getByIdInTrx(predecessorSalesContractInvoiceId);
final I_C_Invoice lastInvoice = invoiceDAO.getByIdInTrx(invoiceId);
final LocalDate predecessorInvoiceDate = TimeUtil.asLocalDate(predecessorInvoice.getDateInvoiced());
final LocalDate lastInvoiceDate = TimeUtil.asLocalDate(lastInvoice.getDateInvoiced());
final LocalDate predecessorInvoiceContractEndDate = contractInvoiceService.retrieveContractEndDateForInvoiceIdOrNull(predecessorSalesContractInvoiceId);
final LocalDate dateToCompareThreshold;
if (predecessorInvoiceContractEndDate == null)
{
dateToCompareThreshold = predecessorInvoiceDate;
}
else
{
dateToCompareThreshold = predecessorInvoiceContractEndDate.isAfter(predecessorInvoiceDate) ? predecessorInvoiceContractEndDate
: predecessorInvoiceDate;
}
if (dateExceedsRegularThreshold(dateToCompareThreshold, lastInvoiceDate))
{
setNewCustomer(customerRetentionId);
}
else if (dateIsBeforeInitialThreshold(lastInvoiceDate, firstContractStartDate))
{
setNewCustomer(customerRetentionId);
}
else
{
setRegularCustomer(customerRetentionId);
}
}
}
public void deleteCustomerRetention(@NonNull final BPartnerId bpartnerId)
{
queryBL.createQueryBuilder(I_C_Customer_Retention.class)
.addEqualsFilter(I_C_Customer_Retention.COLUMNNAME_C_BPartner_ID, bpartnerId) // don't care if active or no
.create()
.delete();
|
}
public void updateCustomerRetentionOnOrderComplete(@NonNull final OrderId orderId)
{
final ContractOrderService contractOrderService = SpringContextHolder.instance.getBean(ContractOrderService.class);
final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
if (!contractOrderService.isContractSalesOrder(orderId))
{
// nothing to do
return;
}
final I_C_Order order = orderDAO.getById(orderId);
final BPartnerId bpartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final CustomerRetentionId customerRetentionId = retrieveOrCreateCustomerRetention(bpartnerId);
final I_C_Customer_Retention customerRetentionRecord = getById(customerRetentionId);
if (Check.isEmpty(customerRetentionRecord.getCustomerRetention()))
{
setNewCustomer(customerRetentionId);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\CustomerRetentionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProjectTypeId implements RepoIdAware
{
@JsonCreator
public static ProjectTypeId ofRepoId(final int repoId)
{
return new ProjectTypeId(repoId);
}
public static ProjectTypeId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ProjectTypeId(repoId) : null;
}
public static ProjectTypeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new ProjectTypeId(repoId) : null;
}
public static int toRepoId(final ProjectTypeId id)
{
return id != null ? id.getRepoId() : -1;
}
|
int repoId;
private ProjectTypeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_ProjectType_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(final ProjectTypeId id1, final ProjectTypeId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\ProjectTypeId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Long getLongValue() {
return null;
}
@Override
public void setLongValue(Long longValue) {
}
@Override
public Double getDoubleValue() {
return null;
}
@Override
public void setDoubleValue(Double doubleValue) {
}
@Override
public byte[] getBytes() {
return null;
}
|
@Override
public void setBytes(byte[] bytes) {
}
@Override
public Object getCachedValue() {
return null;
}
@Override
public void setCachedValue(Object cachedValue) {
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
@ApiModelProperty(example = "12")
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@ApiModelProperty(example = "14")
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@ApiModelProperty(example = "15")
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@ApiModelProperty(example = "cmmn")
public String getScopeType() {
return scopeType;
}
|
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@ApiModelProperty(example = "16")
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@ApiModelProperty(example = "someTenantId")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\task\TaskResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void persistTwoBooks() {
Book ar = new Book();
ar.setIsbn("001-AR");
ar.setTitle("Ancient Rome");
ar.setPrice(25);
Book rh = new Book();
rh.setIsbn("001-RH");
rh.setTitle("Rush Hour");
rh.setPrice(31);
bookRepository.save(ar);
bookRepository.save(rh);
}
public Book fetchFirstBookByNaturalId() {
// find the first book by a single natural id, transaction 1
|
// - the natural id, 001-AR, is fetched from Second Level Cache
// - the Book entity is fetched from database and place in Second Level Cache
Optional<Book> foundArBook
= bookRepository.findBySimpleNaturalId("001-AR");
return foundArBook.orElseThrow();
}
public Book fetchFirstBookByNaturalIdAgain() {
// find the first book by a single natural id, transaction 2
// - the natural id, 001-AR, is fetched from Second Level Cache
// - the Book entity is fetched from the Second Level Cache as well
Optional<Book> foundArBook
= bookRepository.findBySimpleNaturalId("001-AR");
return foundArBook.orElseThrow();
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalIdCache\src\main\java\com\bookstore\service\BookstoreService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UserService implements UserFindService {
private final PasswordEncoder passwordEncoder;
private final UserRepository userRepository;
public UserService(PasswordEncoder passwordEncoder, UserRepository userRepository) {
this.passwordEncoder = passwordEncoder;
this.userRepository = userRepository;
}
@Transactional
public User signUp(UserSignUpRequest request) {
final var encodedPassword = Password.of(request.getRawPassword(), passwordEncoder);
return userRepository.save(User.of(request.getEmail(),
request.getUserName(),
encodedPassword));
}
@Transactional(readOnly = true)
public Optional<User> login(Email email, String rawPassword) {
return userRepository.findFirstByEmail(email)
.filter(user -> user.matchesPassword(rawPassword, passwordEncoder));
}
@Override
@Transactional(readOnly = true)
|
public Optional<User> findById(long id) {
return userRepository.findById(id);
}
@Override
public Optional<User> findByUsername(UserName userName) {
return userRepository.findFirstByProfileUserName(userName);
}
@Transactional
public User updateUser(long id, UserUpdateRequest request) {
final var user = userRepository.findById(id).orElseThrow(NoSuchElementException::new);
request.getEmailToUpdate()
.ifPresent(user::changeEmail);
request.getUserNameToUpdate()
.ifPresent(user::changeName);
request.getPasswordToUpdate()
.map(rawPassword -> Password.of(rawPassword, passwordEncoder))
.ifPresent(user::changePassword);
request.getImageToUpdate()
.ifPresent(user::changeImage);
request.getBioToUpdate()
.ifPresent(user::changeBio);
return userRepository.save(user);
}
}
|
repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\user\UserService.java
| 2
|
请完成以下Java代码
|
public String getXMLElementName() {
return CmmnXmlConstants.ELEMENT_PLAN_FRAGMENT;
}
@Override
protected CmmnElement convert(XMLStreamReader xtr, ConversionHelper conversionHelper) {
/*
* A plan fragment does NOT have a runtime state, even though it has an associated plan item.
*
* From the CMMN spec: "Unlike other PlanItemDefinitions, a PlanFragment does not have a representation in run-time,
* i.e., there is no notion of lifecycle tracking of a PlanFragment (not being a Stage) in the context of a Case instance.
* Just the PlanItems that are contained in it are instantiated and have their lifecyles that are tracked.
*
* Do note that a Stage is a subclass of a PlanFragment (but this is only for plan item / sentry containment).
*/
PlanFragment planFragment = new PlanFragment();
planFragment.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));
planFragment.setCase(conversionHelper.getCurrentCase());
|
planFragment.setParent(conversionHelper.getCurrentPlanFragment());
conversionHelper.setCurrentPlanFragment(planFragment);
conversionHelper.addPlanFragment(planFragment);
return planFragment;
}
@Override
protected void elementEnd(XMLStreamReader xtr, ConversionHelper conversionHelper) {
super.elementEnd(xtr, conversionHelper);
conversionHelper.removeCurrentPlanFragment();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\PlanFragmentXmlConverter.java
| 1
|
请完成以下Java代码
|
private RESTApiTableInfoMap retrieveMap()
{
final String sql = "SELECT "
+ " t." + I_AD_Table.COLUMNNAME_TableName
+ ", c." + I_AD_Column.COLUMNNAME_ColumnName
+ " FROM " + I_AD_Column.Table_Name + " c "
+ " INNER JOIN " + I_AD_Table.Table_Name + " t ON (t.AD_Table_ID=c.AD_Table_ID)"
+ " WHERE c." + I_AD_Column.COLUMNNAME_IsRestAPICustomColumn + "='Y'"
+ " AND c.IsActive='Y' AND t.IsActive='Y'"
+ " ORDER BY t." + I_AD_Table.COLUMNNAME_TableName + ", c." + I_AD_Column.COLUMNNAME_ColumnName;
final HashMap<String, RESTApiTableInfoBuilder> builders = new HashMap<>();
DB.forEachRow(sql, null, rs -> {
final String tableName = rs.getString(I_AD_Table.COLUMNNAME_TableName);
final String columnName = rs.getString(I_AD_Column.COLUMNNAME_ColumnName);
builders.computeIfAbsent(tableName, RESTApiTableInfo::newBuilderForTableName)
.customRestAPIColumnName(columnName);
});
return builders.values().stream()
.map(RESTApiTableInfoBuilder::build)
.collect(RESTApiTableInfoMap.collect());
}
@EqualsAndHashCode
@ToString
private static class RESTApiTableInfoMap
{
|
private final ImmutableMap<String, RESTApiTableInfo> byTableName;
private RESTApiTableInfoMap(final List<RESTApiTableInfo> list)
{
this.byTableName = Maps.uniqueIndex(list, RESTApiTableInfo::getTableName);
}
public static Collector<RESTApiTableInfo, ?, RESTApiTableInfoMap> collect()
{
return GuavaCollectors.collectUsingListAccumulator(RESTApiTableInfoMap::new);
}
@Nullable
private RESTApiTableInfo getByTableNameOrNull(final String tableName)
{
return this.byTableName.get(tableName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\custom_columns\CustomColumnRepository.java
| 1
|
请完成以下Java代码
|
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Organization [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + ((id == null) ? 0 : id.hashCode());
result = (prime * result) + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Organization other = (Organization) obj;
if (id == null) {
if (other.id != null) {
return false;
|
}
} else if (!id.equals(other.id)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\persistence\model\Organization.java
| 1
|
请完成以下Java代码
|
public PublicKeyCredentialCreationOptionsBuilder timeout(Duration timeout) {
this.timeout = timeout;
return this;
}
/**
* Sets the {@link #getExcludeCredentials()} property.
* @param excludeCredentials the excluded credentials.
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder excludeCredentials(
List<PublicKeyCredentialDescriptor> excludeCredentials) {
this.excludeCredentials = excludeCredentials;
return this;
}
/**
* Sets the {@link #getAuthenticatorSelection()} property.
* @param authenticatorSelection the authenticator selection
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder authenticatorSelection(
AuthenticatorSelectionCriteria authenticatorSelection) {
this.authenticatorSelection = authenticatorSelection;
return this;
}
/**
* Sets the {@link #getAttestation()} property.
* @param attestation the attestation
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder attestation(AttestationConveyancePreference attestation) {
this.attestation = attestation;
return this;
}
/**
* Sets the {@link #getExtensions()} property.
* @param extensions the extensions
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder extensions(AuthenticationExtensionsClientInputs extensions) {
this.extensions = extensions;
|
return this;
}
/**
* Allows customizing the builder using the {@link Consumer} that is passed in.
* @param customizer the {@link Consumer} that can be used to customize the
* {@link PublicKeyCredentialCreationOptionsBuilder}
* @return the PublicKeyCredentialCreationOptionsBuilder
*/
public PublicKeyCredentialCreationOptionsBuilder customize(
Consumer<PublicKeyCredentialCreationOptionsBuilder> customizer) {
customizer.accept(this);
return this;
}
/**
* Builds a new {@link PublicKeyCredentialCreationOptions}
* @return the new {@link PublicKeyCredentialCreationOptions}
*/
public PublicKeyCredentialCreationOptions build() {
return new PublicKeyCredentialCreationOptions(this.rp, this.user, this.challenge, this.pubKeyCredParams,
this.timeout, this.excludeCredentials, this.authenticatorSelection, this.attestation,
this.extensions);
}
}
}
|
repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\PublicKeyCredentialCreationOptions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Person {
@Id
private Long id;
private String firstName;
private String lastName;
public Person() {
}
public Person(Long id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public Long getId() {
return id;
}
public void setId(Long 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\spring-data-jpa-crud\src\main\java\com\baeldung\boot\domain\Person.java
| 2
|
请完成以下Java代码
|
public Method getMethodFor(Object payload) {
if (this.invokerHandlerMethod != null) {
return this.invokerHandlerMethod.getMethod();
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getMethodFor(payload);
}
}
/**
* Return the return type for the method that will be chosen for this payload.
* @param payload the payload.
* @return the return type, or null if no handler found.
* @since 2.2.3
*/
public Type getReturnTypeFor(Object payload) {
if (this.invokerHandlerMethod != null) {
return this.invokerHandlerMethod.getMethod().getReturnType();
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getMethodFor(payload).getReturnType();
}
}
/**
* Get the bean from the handler method.
* @return the bean.
*/
public Object getBean() {
if (this.invokerHandlerMethod != null) {
return this.invokerHandlerMethod.getBean();
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getBean();
}
}
/**
* Return true if any handler method has an async reply type.
* @return the asyncReply.
|
* @since 2.2.21
*/
public boolean isAsyncReplies() {
return this.asyncReplies;
}
/**
* Build an {@link InvocationResult} for the result and inbound payload.
* @param result the result.
* @param inboundPayload the payload.
* @return the invocation result.
* @since 2.1.7
*/
public @Nullable InvocationResult getInvocationResultFor(Object result, Object inboundPayload) {
if (this.invokerHandlerMethod != null) {
return new InvocationResult(result, null, this.invokerHandlerMethod.getMethod().getGenericReturnType(),
this.invokerHandlerMethod.getBean(), this.invokerHandlerMethod.getMethod());
}
else {
Assert.notNull(this.delegatingHandler, "'delegatingHandler' or 'invokerHandlerMethod' is required");
return this.delegatingHandler.getInvocationResultFor(result, inboundPayload);
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\HandlerAdapter.java
| 1
|
请完成以下Java代码
|
public class Document extends BagOfWordsDocument
{
/**
* 文档所属类目
*/
public int category;
/**
* 一般用在训练集构造文档时
* @param catalog
* @param lexicon
* @param category
* @param tokenArray
*/
public Document(Catalog catalog, Lexicon lexicon, String category, String[] tokenArray)
{
super();
assert catalog != null;
assert lexicon != null;
// this.catalog = catalog;
// this.lexicon = lexicon;
// 将其转为数组类型,方便处理
this.category = catalog.addCategory(category);
// 统计词频
for (int i = 0; i < tokenArray.length; i++)
{
tfMap.add(lexicon.addWord(tokenArray[i]));
}
}
/**
* 一般用在预测时构造文档用
* @param wordIdTrie
* @param tokenArray
*/
public Document(ITrie<Integer> wordIdTrie, String[] tokenArray)
{
super();
for (int i = 0; i < tokenArray.length; i++)
{
Integer id = wordIdTrie.get(tokenArray[i].toCharArray());
if (id == null) continue;
tfMap.add(id);
}
}
/**
* 一般用在测试集构造文档时使用
* @param categoryId
|
* @param wordId
* @param category
* @param tokenArray
*/
public Document(Map<String, Integer> categoryId, BinTrie<Integer> wordId, String category, String[] tokenArray)
{
this(wordId, tokenArray);
Integer id = categoryId.get(category);
if (id == null) id = -1;
this.category = id;
}
public Document(DataInputStream in) throws IOException
{
category = in.readInt();
int size = in.readInt();
tfMap = new FrequencyMap<Integer>();
for (int i = 0; i < size; i++)
{
tfMap.put(in.readInt(), new int[]{in.readInt()});
}
}
// @Override
// public String toString()
// {
// final StringBuilder sb = new StringBuilder(tfMap.size() * 5);
// sb.append('《').append(super.toString()).append('》').append('\t');
// sb.append(catalog.getCategory(category));
// sb.append('\n');
// for (Map.Entry<Integer, int[]> entry : tfMap.entrySet())
// {
// sb.append(lexicon.getWord(entry.getKey()));
// sb.append('\t');
// sb.append(entry.getValue()[0]);
// sb.append('\n');
// }
// return sb.toString();
// }
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\Document.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ArticleController {
@Autowired
private ArticleService articleService;
/**
* 查询文章列表
*/
@RequiresPermissions("article:list")
@GetMapping("/listArticle")
public JSONObject listArticle(HttpServletRequest request) {
return articleService.listArticle(CommonUtil.request2Json(request));
}
/**
* 新增文章
*/
@RequiresPermissions("article:add")
@PostMapping("/addArticle")
|
public JSONObject addArticle(@RequestBody JSONObject requestJson) {
CommonUtil.hasAllRequired(requestJson, "content");
return articleService.addArticle(requestJson);
}
/**
* 修改文章
*/
@RequiresPermissions("article:update")
@PostMapping("/updateArticle")
public JSONObject updateArticle(@RequestBody JSONObject requestJson) {
CommonUtil.hasAllRequired(requestJson, "id,content");
return articleService.updateArticle(requestJson);
}
}
|
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\controller\ArticleController.java
| 2
|
请完成以下Java代码
|
static private String convert(char[]... keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.length * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeInt(total);
Integer[] valueArray = d.getValueArray(new Integer[0]);
out.writeInt(valueArray.length);
for (Integer v : valueArray)
{
out.writeInt(v);
|
}
d.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
total = byteArray.nextInt();
int size = byteArray.nextInt();
Integer[] valueArray = new Integer[size];
for (int i = 0; i < valueArray.length; ++i)
{
valueArray[i] = byteArray.nextInt();
}
d.load(byteArray, valueArray);
return true;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java
| 1
|
请完成以下Java代码
|
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "JSON object with Device Profile Id.")
public DeviceProfileId getDeviceProfileId() {
return deviceProfileId;
}
public void setDeviceProfileId(DeviceProfileId deviceProfileId) {
this.deviceProfileId = deviceProfileId;
}
@Schema(description = "JSON object with content specific to type of transport in the device profile.")
public DeviceData getDeviceData() {
if (deviceData != null) {
return deviceData;
} else {
if (deviceDataBytes != null) {
try {
deviceData = mapper.readValue(new ByteArrayInputStream(deviceDataBytes), DeviceData.class);
} catch (IOException e) {
log.warn("Can't deserialize device data: ", e);
return null;
}
return deviceData;
} else {
return null;
}
}
}
|
public void setDeviceData(DeviceData data) {
this.deviceData = data;
try {
this.deviceDataBytes = data != null ? mapper.writeValueAsBytes(data) : null;
} catch (JsonProcessingException e) {
log.warn("Can't serialize device data: ", e);
}
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getFirmwareId() {
return firmwareId;
}
public void setFirmwareId(OtaPackageId firmwareId) {
this.firmwareId = firmwareId;
}
@Schema(description = "JSON object with Ota Package Id.")
public OtaPackageId getSoftwareId() {
return softwareId;
}
public void setSoftwareId(OtaPackageId softwareId) {
this.softwareId = softwareId;
}
@Schema(description = "Additional parameters of the device",implementation = com.fasterxml.jackson.databind.JsonNode.class)
@Override
public JsonNode getAdditionalInfo() {
return super.getAdditionalInfo();
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Device.java
| 1
|
请完成以下Java代码
|
public java.sql.Timestamp getLastStartTime()
{
return get_ValueAsTimestamp(COLUMNNAME_LastStartTime);
}
@Override
public void setLockedAt (final @Nullable java.sql.Timestamp LockedAt)
{
set_Value (COLUMNNAME_LockedAt, LockedAt);
}
@Override
public java.sql.Timestamp getLockedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_LockedAt);
}
/**
* Priority AD_Reference_ID=154
* Reference name: _PriorityRule
*/
public static final int PRIORITY_AD_Reference_ID=154;
/** High = 3 */
public static final String PRIORITY_High = "3";
/** Medium = 5 */
public static final String PRIORITY_Medium = "5";
/** Low = 7 */
public static final String PRIORITY_Low = "7";
/** Urgent = 1 */
public static final String PRIORITY_Urgent = "1";
/** Minor = 9 */
public static final String PRIORITY_Minor = "9";
@Override
public void setPriority (final java.lang.String Priority)
{
set_Value (COLUMNNAME_Priority, Priority);
}
@Override
public java.lang.String getPriority()
{
return get_ValueAsString(COLUMNNAME_Priority);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setSkippedAt (final @Nullable java.sql.Timestamp SkippedAt)
{
set_Value (COLUMNNAME_SkippedAt, SkippedAt);
}
@Override
public java.sql.Timestamp getSkippedAt()
{
return get_ValueAsTimestamp(COLUMNNAME_SkippedAt);
}
@Override
public void setSkipped_Count (final int Skipped_Count)
{
set_Value (COLUMNNAME_Skipped_Count, Skipped_Count);
}
@Override
|
public int getSkipped_Count()
{
return get_ValueAsInt(COLUMNNAME_Skipped_Count);
}
@Override
public void setSkipped_First_Time (final @Nullable java.sql.Timestamp Skipped_First_Time)
{
set_Value (COLUMNNAME_Skipped_First_Time, Skipped_First_Time);
}
@Override
public java.sql.Timestamp getSkipped_First_Time()
{
return get_ValueAsTimestamp(COLUMNNAME_Skipped_First_Time);
}
@Override
public void setSkipped_Last_Reason (final @Nullable java.lang.String Skipped_Last_Reason)
{
set_Value (COLUMNNAME_Skipped_Last_Reason, Skipped_Last_Reason);
}
@Override
public java.lang.String getSkipped_Last_Reason()
{
return get_ValueAsString(COLUMNNAME_Skipped_Last_Reason);
}
@Override
public void setSkipTimeoutMillis (final int SkipTimeoutMillis)
{
set_Value (COLUMNNAME_SkipTimeoutMillis, SkipTimeoutMillis);
}
@Override
public int getSkipTimeoutMillis()
{
return get_ValueAsInt(COLUMNNAME_SkipTimeoutMillis);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ExportBPartnerRequestBuilder
{
public void prepareRetrieveBPartnerProductRequest(@NonNull final Exchange exchange)
{
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
final BPProductCamelRequest bpProductCamelRequest = BPProductCamelRequest.builder()
.orgCode(routeContext.getOrgCode())
.bPartnerIdentifier(String.valueOf(routeContext.getJsonResponseComposite().getBpartner().getMetasfreshId().getValue()))
.build();
exchange.getIn().setBody(bpProductCamelRequest);
}
public void prepareExternalReferenceLookupRequest(@NonNull final Exchange exchange)
{
final ExportBPartnerRouteContext routeContext = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_EXPORT_BPARTNER_CONTEXT, ExportBPartnerRouteContext.class);
final JsonResponseProductBPartner jsonResponseProductBPartner = exchange.getIn().getBody(JsonResponseProductBPartner.class);
if (Check.isEmpty(jsonResponseProductBPartner.getBPartnerProducts()))
{
exchange.getIn().setBody(null);
return;
}
final ImmutableSet<JsonMetasfreshId> productIds = jsonResponseProductBPartner.getBPartnerProducts()
.stream()
.map(JsonProductBPartner::getProductId)
.collect(ImmutableSet.toImmutableSet());
|
final List<JsonExternalReferenceLookupItem> items = productIds.stream()
.map(productId -> JsonExternalReferenceLookupItem.builder()
.metasfreshId(productId)
.type(EXTERNAL_REF_TYPE_PRODUCT)
.build())
.collect(ImmutableList.toImmutableList());
final JsonExternalReferenceLookupRequest jsonExternalReferenceLookupRequest = JsonExternalReferenceLookupRequest.builder()
.systemName(JsonExternalSystemName.of(GRSSIGNUM_SYSTEM_NAME))
.items(items)
.build();
final ExternalReferenceLookupCamelRequest externalReferenceSearchCamelRequest = ExternalReferenceLookupCamelRequest.builder()
.externalSystemConfigId(routeContext.getExternalSystemConfigId())
.adPInstanceId(JsonMetasfreshId.ofOrNull(routeContext.getPinstanceId()))
.orgCode(routeContext.getOrgCode())
.jsonExternalReferenceLookupRequest(jsonExternalReferenceLookupRequest)
.build();
exchange.getIn().setBody(externalReferenceSearchCamelRequest);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\bpartner\processor\ExportBPartnerRequestBuilder.java
| 2
|
请完成以下Java代码
|
public static List<String> searchtweets() throws TwitterException {
Twitter twitter = getTwitterinstance();
Query query = new Query("source:twitter4j baeldung");
QueryResult result = twitter.search(query);
List<Status> statuses = result.getTweets();
return statuses.stream().map(
item -> item.getText()).collect(
Collectors.toList());
}
public static void streamFeed() {
StatusListener listener = new StatusListener(){
@Override
public void onException(Exception e) {
e.printStackTrace();
}
@Override
public void onDeletionNotice(StatusDeletionNotice arg) {
System.out.println("Got a status deletion notice id:" + arg.getStatusId());
}
@Override
public void onScrubGeo(long userId, long upToStatusId) {
System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
}
@Override
public void onStallWarning(StallWarning warning) {
System.out.println("Got stall warning:" + warning);
|
}
@Override
public void onStatus(Status status) {
System.out.println(status.getUser().getName() + " : " + status.getText());
}
@Override
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
}
};
TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
twitterStream.addListener(listener);
twitterStream.sample();
}
}
|
repos\tutorials-master\saas-modules\twitter4j\src\main\java\com\baeldung\Application.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernat
|
e.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=false
|
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\resources\application.properties
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class UrlFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
@Autowired
private FilterInvocationSecurityMetadataSource securityMetadataSource;
@Autowired
public void setUrlAccessDecisionManager(UrlAccessDecisionManager urlAccessDecisionManager) {
super.setAccessDecisionManager(urlAccessDecisionManager);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
FilterInvocation fi = new FilterInvocation(request, response, chain);
invoke(fi);
}
public void invoke(FilterInvocation fi) throws IOException, ServletException {
//fi里面有一个被拦截的url
//里面调用UrlMetadataSource的getAttributes(Object object)这个方法获取fi对应的所有权限
//再调用UrlAccessDecisionManager的decide方法来校验用户的权限是否足够
InterceptorStatusToken token = super.beforeInvocation(fi);
try {
//执行下一个拦截器
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
|
} finally {
super.afterInvocation(token, null);
}
}
@Override
public void destroy() {
}
@Override
public Class<?> getSecureObjectClass() {
return FilterInvocation.class;
}
@Override
public SecurityMetadataSource obtainSecurityMetadataSource() {
return this.securityMetadataSource;
}
}
|
repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\security\UrlFilterSecurityInterceptor.java
| 2
|
请完成以下Java代码
|
class JsonMembersCustomizerBuilder implements StructuredLoggingJsonMembersCustomizer.Builder<E> {
private final @Nullable StructuredLoggingJsonProperties properties;
private boolean nested;
JsonMembersCustomizerBuilder(@Nullable StructuredLoggingJsonProperties properties) {
this.properties = properties;
}
@Override
public JsonMembersCustomizerBuilder nested(boolean nested) {
this.nested = nested;
return this;
}
@Override
public StructuredLoggingJsonMembersCustomizer<E> build() {
return (members) -> {
List<StructuredLoggingJsonMembersCustomizer<?>> customizers = new ArrayList<>();
if (this.properties != null) {
customizers.add(new StructuredLoggingJsonPropertiesJsonMembersCustomizer(
StructuredLogFormatterFactory.this.instantiator, this.properties, this.nested));
|
}
customizers.addAll(loadStructuredLoggingJsonMembersCustomizers());
invokeCustomizers(members, customizers);
};
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private List<StructuredLoggingJsonMembersCustomizer<?>> loadStructuredLoggingJsonMembersCustomizers() {
return (List) StructuredLogFormatterFactory.this.factoriesLoader.load(
StructuredLoggingJsonMembersCustomizer.class,
ArgumentResolver.from(StructuredLogFormatterFactory.this.instantiator::getArg));
}
@SuppressWarnings("unchecked")
private void invokeCustomizers(Members<E> members,
List<StructuredLoggingJsonMembersCustomizer<?>> customizers) {
LambdaSafe.callbacks(StructuredLoggingJsonMembersCustomizer.class, customizers, members)
.withFilter(LambdaSafe.Filter.allowAll())
.invoke((customizer) -> customizer.customize(members));
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLogFormatterFactory.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_ImpFormat getAD_ImpFormat()
{
return get_ValueAsPO(COLUMNNAME_AD_ImpFormat_ID, org.compiere.model.I_AD_ImpFormat.class);
}
@Override
public void setAD_ImpFormat(final org.compiere.model.I_AD_ImpFormat AD_ImpFormat)
{
set_ValueFromPO(COLUMNNAME_AD_ImpFormat_ID, org.compiere.model.I_AD_ImpFormat.class, AD_ImpFormat);
}
@Override
public void setAD_ImpFormat_ID (final int AD_ImpFormat_ID)
{
if (AD_ImpFormat_ID < 1)
set_Value (COLUMNNAME_AD_ImpFormat_ID, null);
else
set_Value (COLUMNNAME_AD_ImpFormat_ID, AD_ImpFormat_ID);
}
@Override
public int getAD_ImpFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ImpFormat_ID);
}
@Override
public void setC_DataImport_ID (final int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_DataImport_ID, C_DataImport_ID);
}
@Override
public int getC_DataImport_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DataImport_ID);
}
/**
* DataImport_ConfigType AD_Reference_ID=541535
* Reference name: C_DataImport_ConfigType
*/
|
public static final int DATAIMPORT_CONFIGTYPE_AD_Reference_ID=541535;
/** Standard = S */
public static final String DATAIMPORT_CONFIGTYPE_Standard = "S";
/** Bank Statement Import = BSI */
public static final String DATAIMPORT_CONFIGTYPE_BankStatementImport = "BSI";
@Override
public void setDataImport_ConfigType (final java.lang.String DataImport_ConfigType)
{
set_Value (COLUMNNAME_DataImport_ConfigType, DataImport_ConfigType);
}
@Override
public java.lang.String getDataImport_ConfigType()
{
return get_ValueAsString(COLUMNNAME_DataImport_ConfigType);
}
@Override
public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DataImport.java
| 1
|
请完成以下Java代码
|
public ActiveCurrencyAndAmount getNoteDnmtn() {
return noteDnmtn;
}
/**
* Sets the value of the noteDnmtn property.
*
* @param value
* allowed object is
* {@link ActiveCurrencyAndAmount }
*
*/
public void setNoteDnmtn(ActiveCurrencyAndAmount value) {
this.noteDnmtn = value;
}
/**
* Gets the value of the nbOfNotes property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfNotes() {
return nbOfNotes;
}
/**
* Sets the value of the nbOfNotes property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfNotes(String value) {
this.nbOfNotes = value;
}
/**
* Gets the value of the amt property.
*
* @return
* possible object is
|
* {@link ActiveCurrencyAndAmount }
*
*/
public ActiveCurrencyAndAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveCurrencyAndAmount }
*
*/
public void setAmt(ActiveCurrencyAndAmount 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_04\CashDeposit1.java
| 1
|
请完成以下Java代码
|
protected void postProcessJob(ModificationBatchConfiguration configuration, JobEntity job, ModificationBatchConfiguration jobConfiguration) {
if (job.getDeploymentId() == null) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessEngineConfiguration().getDeploymentCache()
.findDeployedProcessDefinitionById(configuration.getProcessDefinitionId());
job.setDeploymentId(processDefinitionEntity.getDeploymentId());
}
}
@Override
public void executeHandler(ModificationBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
ModificationBuilderImpl executionBuilder = (ModificationBuilderImpl) commandContext.getProcessEngineConfiguration()
.getRuntimeService()
.createModification(batchConfiguration.getProcessDefinitionId())
.processInstanceIds(batchConfiguration.getIds());
executionBuilder.setInstructions(batchConfiguration.getInstructions());
if (batchConfiguration.isSkipCustomListeners()) {
executionBuilder.skipCustomListeners();
}
if (batchConfiguration.isSkipIoMappings()) {
executionBuilder.skipIoMappings();
}
executionBuilder.execute(false);
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
|
@Override
protected ModificationBatchConfiguration createJobConfiguration(ModificationBatchConfiguration configuration, List<String> processIdsForJob) {
return new ModificationBatchConfiguration(
processIdsForJob,
configuration.getProcessDefinitionId(),
configuration.getInstructions(),
configuration.isSkipCustomListeners(),
configuration.isSkipIoMappings()
);
}
@Override
protected ModificationBatchConfigurationJsonConverter getJsonConverterInstance() {
return ModificationBatchConfigurationJsonConverter.INSTANCE;
}
protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) {
return commandContext.getProcessEngineConfiguration()
.getDeploymentCache()
.findDeployedProcessDefinitionById(processDefinitionId);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBatchJobHandler.java
| 1
|
请完成以下Java代码
|
public class User {
@JMap(classes = {UserDto1.class, UserDto2.class})
private long id;
@JMap(attributes = {"username", "email"}, classes = {UserDto1.class, UserDto2.class})
private String email;
// constructors
public User() {
super();
}
public User(long id, String email) {
super();
this.id = id;
this.email = email;
}
// getters and setters
public long getId() {
return id;
}
|
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", email=" + email + "]";
}
}
|
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\jmapper\relational\User.java
| 1
|
请完成以下Java代码
|
protected List<I_C_AllocationLine> retrieveDocumentLines(final I_C_AllocationHdr document)
{
return Services.get(IAllocationDAO.class).retrieveLines(document);
}
@Override
protected AttributeSetInstanceId getM_AttributeSetInstance(final I_C_AllocationLine documentLine)
{
// shall not be called because we implement "getMaterialTrackingFromDocumentLineASI"
throw new IllegalStateException("shall not be called");
}
/**
* Loads and returns the material tracking of the invoice referenced by the given {@code documentLine}, if there is any. If there is none, it returns {@code null}.
* Analog to {@link C_Invoice#isEligibleForMaterialTracking(I_C_Invoice)}, if the invoice is a sales invoice or if it is reversed, then we don't bother trying to get its material tracking and directly return {@code null}.
*/
@Override
protected I_M_Material_Tracking getMaterialTrackingFromDocumentLineASI(final I_C_AllocationLine documentLine)
{
if (documentLine.getC_Invoice_ID() <= 0)
{
return null;
}
final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class);
|
final I_C_Invoice invoice = documentLine.getC_Invoice();
// please keep in sync with the isEligible method mentioned in the javadoc.
if (Services.get(IInvoiceBL.class).isReversal(invoice))
{
return null;
}
if (invoice.isSOTrx())
{
return null;
}
final I_M_Material_Tracking materialTracking = materialTrackingDAO.retrieveSingleMaterialTrackingForModel(invoice);
return materialTracking;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\model\validator\C_AllocationHdr.java
| 1
|
请完成以下Java代码
|
public Builder onErrorThrowException()
{
this.onErrorThrowException = true;
return this;
}
public Builder onErrorThrowException(final boolean onErrorThrowException)
{
this.onErrorThrowException = onErrorThrowException;
return this;
}
/**
* Advice the executor to switch current context with process info's context.
*
* @see ProcessInfo#getCtx()
* @see Env#switchContext(Properties)
*/
|
public Builder switchContextWhenRunning()
{
this.switchContextWhenRunning = true;
return this;
}
/**
* Sets the callback to be executed after AD_PInstance is created but before the actual process is started.
* If the callback fails, the exception is propagated, so the process will not be started.
* <p>
* A common use case of <code>beforeCallback</code> is to create to selections which are linked to this process instance.
*/
public Builder callBefore(final Consumer<ProcessInfo> beforeCallback)
{
this.beforeCallback = beforeCallback;
return this;
}
}
} // ProcessCtl
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutor.java
| 1
|
请完成以下Java代码
|
public int getIncluded_Aggregation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Aggregation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Include Logic.
@param IncludeLogic
If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded.
*/
@Override
public void setIncludeLogic (java.lang.String IncludeLogic)
{
set_Value (COLUMNNAME_IncludeLogic, IncludeLogic);
}
/** Get Include Logic.
@return If expression is evaluated as true, the item will be included. If evaluated as false, the item will be excluded.
*/
@Override
public java.lang.String getIncludeLogic ()
{
return (java.lang.String)get_Value(COLUMNNAME_IncludeLogic);
}
/**
* Type AD_Reference_ID=540532
|
* Reference name: C_AggregationItem_Type
*/
public static final int TYPE_AD_Reference_ID=540532;
/** Column = COL */
public static final String TYPE_Column = "COL";
/** IncludedAggregation = INC */
public static final String TYPE_IncludedAggregation = "INC";
/** Attribute = ATR */
public static final String TYPE_Attribute = "ATR";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java-gen\de\metas\aggregation\model\X_C_AggregationItem.java
| 1
|
请完成以下Java代码
|
public static <T> PageData<T> emptyPageData() {
return (PageData<T>) EMPTY_PAGE_DATA;
}
@Schema(description = "Array of the entities", accessMode = Schema.AccessMode.READ_ONLY)
public List<T> getData() {
return data;
}
@Schema(description = "Total number of available pages. Calculated based on the 'pageSize' request parameter and total number of entities that match search criteria", accessMode = Schema.AccessMode.READ_ONLY)
public int getTotalPages() {
return totalPages;
}
@Schema(description = "Total number of elements in all available pages", accessMode = Schema.AccessMode.READ_ONLY)
|
public long getTotalElements() {
return totalElements;
}
@Schema(description = "'false' value indicates the end of the result set", accessMode = Schema.AccessMode.READ_ONLY)
@JsonProperty("hasNext")
public boolean hasNext() {
return hasNext;
}
public <D> PageData<D> mapData(Function<T, D> mapper) {
return new PageData<>(getData().stream().map(mapper).collect(Collectors.toList()), getTotalPages(), getTotalElements(), hasNext());
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\PageData.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDate(XMLGregorianCalendar value) {
this.date = value;
}
}
}
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<http://erpel.at/schemas/1p0/documents/extensions/edifact>Decimal4Type">
* <attribute ref="{http://erpel.at/schemas/1p0/documents/extensions/edifact}Date"/>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class ConfirmedQuantity {
@XmlValue
protected BigDecimal value;
@XmlAttribute(name = "Date", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact")
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar date;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link BigDecimal }
*
|
*/
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Gets the value of the date property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDate() {
return date;
}
/**
* Sets the value of the date property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDate(XMLGregorianCalendar value) {
this.date = 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\ORDRSPListLineItemExtensionType.java
| 2
|
请完成以下Java代码
|
protected void applyFilters(TenantQuery query) {
if (id != null) {
query.tenantId(id);
}
if (name != null) {
query.tenantName(name);
}
if (nameLike != null) {
query.tenantNameLike(nameLike);
}
if (userId != null) {
query.userMember(userId);
}
if (groupId != null) {
query.groupMember(groupId);
}
|
if (Boolean.TRUE.equals(includingGroupsOfUser)) {
query.includingGroupsOfUser(true);
}
}
@Override
protected void applySortBy(TenantQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
} else if (sortBy.equals(SORT_BY_TENANT_NAME_VALUE)) {
query.orderByTenantName();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\TenantQueryDto.java
| 1
|
请完成以下Java代码
|
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Arrays.asList(new SimpleGrantedAuthority(getRole()));
}
public String getPassword() {
|
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
repos\spring-boot-quick-master\quick-oauth2\quick-github-oauth\src\main\java\com\github\oauth\user\User.java
| 1
|
请完成以下Java代码
|
private static String toSql(@NonNull final String columnName, ImmutableSet<StringPattern> tableNamePatterns)
{
if (tableNamePatterns.isEmpty())
{
return null;
}
final StringBuilder sql = new StringBuilder();
for (final StringPattern tableNamePattern : tableNamePatterns)
{
if (sql.length() > 0)
{
sql.append(" OR ");
}
sql.append(columnName)
.append(tableNamePattern.isWithWildcard() ? " LIKE " : "=")
.append(toSqlQuotedString(tableNamePattern.getPattern()));
}
return sql.toString();
}
private static String toSqlQuotedString(@Nullable final String string)
{
if (string != null
&& string.length() > 2
&& string.startsWith("'")
&& string.endsWith("'"))
{
return string;
}
else
{
return DB.TO_STRING(string);
}
}
private static String createTableSql(@NonNull final Config config)
{
final String packageName = config.getPackageName();
final StringBuilder sql = new StringBuilder();
sql.append("SELECT AD_Table_ID FROM AD_Table WHERE IsActive='Y'");
if(packageName.equals("org.compiere.model"))
{
sql.append("\n AND (IsView='N' OR TableName IN ('RV_WarehousePrice','RV_BPartner')");
}
//
// EntityType
final String sqlEntityTypeFiter = toSql("EntityType", config.getEntityTypePatterns());
if (sqlEntityTypeFiter != null && !sqlEntityTypeFiter.isEmpty())
{
sql.append("\n AND (").append(sqlEntityTypeFiter).append(")");
}
|
//
// Table LIKE
final String sqlTableNameFilter = toSql("TableName", config.getTableNamePatterns());
if (sqlTableNameFilter != null && !sqlTableNameFilter.isEmpty())
{
sql.append("\n AND (").append(sqlTableNameFilter).append(")");
}
//
// ORDER BY
sql.append("\n ORDER BY TableName");
//
return sql.toString();
}
@Value
@Builder
private static class Config
{
@NonNull
String directory;
@NonNull
String packageName;
@NonNull
ImmutableSet<StringPattern> entityTypePatterns;
@NonNull
ImmutableSet<StringPattern> tableNamePatterns;
}
@Value(staticConstructor = "of")
private static class StringPattern
{
@NonNull String pattern;
public boolean isWithWildcard() {return pattern.contains("%");}
@Override
public String toString() {return isWithWildcard() ? "LIKE " + pattern : pattern;}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\util\GenerateModel.java
| 1
|
请完成以下Java代码
|
public void setCountProcessed (final int CountProcessed)
{
set_ValueNoCheck (COLUMNNAME_CountProcessed, CountProcessed);
}
@Override
public int getCountProcessed()
{
return get_ValueAsInt(COLUMNNAME_CountProcessed);
}
@Override
public de.metas.async.model.I_C_Queue_PackageProcessor getC_Queue_PackageProcessor()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class);
}
@Override
public void setC_Queue_PackageProcessor(final de.metas.async.model.I_C_Queue_PackageProcessor C_Queue_PackageProcessor)
{
set_ValueFromPO(COLUMNNAME_C_Queue_PackageProcessor_ID, de.metas.async.model.I_C_Queue_PackageProcessor.class, C_Queue_PackageProcessor);
}
|
@Override
public void setC_Queue_PackageProcessor_ID (final int C_Queue_PackageProcessor_ID)
{
if (C_Queue_PackageProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_PackageProcessor_ID, C_Queue_PackageProcessor_ID);
}
@Override
public int getC_Queue_PackageProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_PackageProcessor_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_RV_Async_batch_statistics.java
| 1
|
请完成以下Java代码
|
public void setSendingDepot (java.lang.String SendingDepot)
{
set_Value (COLUMNNAME_SendingDepot, SendingDepot);
}
/** Get Versandlager.
@return Versandlager */
@Override
public java.lang.String getSendingDepot ()
{
return (java.lang.String)get_Value(COLUMNNAME_SendingDepot);
}
/** Set Nachverfolgungs-URL.
@param TrackingURL
URL des Spediteurs um Sendungen zu verfolgen
*/
|
@Override
public void setTrackingURL (java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
/** Get Nachverfolgungs-URL.
@return URL des Spediteurs um Sendungen zu verfolgen
*/
@Override
public java.lang.String getTrackingURL ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrackingURL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder.java
| 1
|
请完成以下Java代码
|
public class HistoricIdentityLinkLogDto {
protected String id;
protected Date time;
protected String type;
protected String userId;
protected String groupId;
protected String taskId;
protected String processDefinitionId;
protected String processDefinitionKey;
protected String operationType;
protected String assignerId;
protected String tenantId;
protected Date removalTime;
protected String rootProcessInstanceId;
public String getId() {
return id;
}
public Date getTime() {
return time;
}
public String getType() {
return type;
}
public String getUserId() {
return userId;
}
public String getGroupId() {
return groupId;
}
public String getTaskId() {
return taskId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
|
public String getOperationType() {
return operationType;
}
public String getAssignerId() {
return assignerId;
}
public String getTenantId() {
return tenantId;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricIdentityLinkLogDto fromHistoricIdentityLink(HistoricIdentityLinkLog historicIdentityLink) {
HistoricIdentityLinkLogDto dto = new HistoricIdentityLinkLogDto();
fromHistoricIdentityLink(dto, historicIdentityLink);
return dto;
}
public static void fromHistoricIdentityLink(HistoricIdentityLinkLogDto dto,
HistoricIdentityLinkLog historicIdentityLink) {
dto.id = historicIdentityLink.getId();
dto.assignerId = historicIdentityLink.getAssignerId();
dto.groupId = historicIdentityLink.getGroupId();
dto.operationType = historicIdentityLink.getOperationType();
dto.taskId = historicIdentityLink.getTaskId();
dto.time = historicIdentityLink.getTime();
dto.type = historicIdentityLink.getType();
dto.processDefinitionId = historicIdentityLink.getProcessDefinitionId();
dto.processDefinitionKey = historicIdentityLink.getProcessDefinitionKey();
dto.userId = historicIdentityLink.getUserId();
dto.tenantId = historicIdentityLink.getTenantId();
dto.removalTime = historicIdentityLink.getRemovalTime();
dto.rootProcessInstanceId = historicIdentityLink.getRootProcessInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricIdentityLinkLogDto.java
| 1
|
请完成以下Java代码
|
public FilterProperty getFilter() {
return filter;
}
public void setFilter(FilterProperty filter) {
this.filter = filter;
}
public String getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(String idGenerator) {
this.idGenerator = idGenerator;
}
public Boolean getJobExecutorAcquireByPriority() {
return jobExecutorAcquireByPriority;
}
public void setJobExecutorAcquireByPriority(Boolean jobExecutorAcquireByPriority) {
this.jobExecutorAcquireByPriority = jobExecutorAcquireByPriority;
}
public Integer getDefaultNumberOfRetries() {
return defaultNumberOfRetries;
}
public void setDefaultNumberOfRetries(Integer defaultNumberOfRetries) {
this.defaultNumberOfRetries = defaultNumberOfRetries;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Boolean getGenerateUniqueProcessEngineName() {
return generateUniqueProcessEngineName;
}
public void setGenerateUniqueProcessEngineName(Boolean generateUniqueProcessEngineName) {
this.generateUniqueProcessEngineName = generateUniqueProcessEngineName;
}
public Boolean getGenerateUniqueProcessApplicationName() {
return generateUniqueProcessApplicationName;
}
public void setGenerateUniqueProcessApplicationName(Boolean generateUniqueProcessApplicationName) {
this.generateUniqueProcessApplicationName = generateUniqueProcessApplicationName;
}
|
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.add("processEngineName=" + processEngineName)
.add("generateUniqueProcessEngineName=" + generateUniqueProcessEngineName)
.add("generateUniqueProcessApplicationName=" + generateUniqueProcessApplicationName)
.add("historyLevel=" + historyLevel)
.add("historyLevelDefault=" + historyLevelDefault)
.add("autoDeploymentEnabled=" + autoDeploymentEnabled)
.add("deploymentResourcePattern=" + Arrays.toString(deploymentResourcePattern))
.add("defaultSerializationFormat=" + defaultSerializationFormat)
.add("licenseFile=" + licenseFile)
.add("metrics=" + metrics)
.add("database=" + database)
.add("jobExecution=" + jobExecution)
.add("webapp=" + webapp)
.add("restApi=" + restApi)
.add("authorization=" + authorization)
.add("genericProperties=" + genericProperties)
.add("adminUser=" + adminUser)
.add("filter=" + filter)
.add("idGenerator=" + idGenerator)
.add("jobExecutorAcquireByPriority=" + jobExecutorAcquireByPriority)
.add("defaultNumberOfRetries" + defaultNumberOfRetries)
.toString();
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CamundaBpmProperties.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "JpaOrder [currencyUnit=" + currencyUnit + ", id=" + id + ", orderLines=" + orderLines + ", totalCost=" + totalCost + "]";
}
void addLineItem(JpaOrderLine orderLine) {
checkNotNull(orderLine);
orderLines.add(orderLine);
}
String getCurrencyUnit() {
return currencyUnit;
}
Long getId() {
return id;
}
List<JpaOrderLine> getOrderLines() {
return new ArrayList<>(orderLines);
}
BigDecimal getTotalCost() {
return totalCost;
}
void removeLineItem(int line) {
orderLines.remove(line);
}
|
void setCurrencyUnit(String currencyUnit) {
this.currencyUnit = currencyUnit;
}
void setTotalCost(BigDecimal totalCost) {
this.totalCost = totalCost;
}
private static void checkNotNull(Object par) {
if (par == null) {
throw new NullPointerException("Parameter cannot be null");
}
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\jpa\JpaOrder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected TaskServiceConfiguration getTaskServiceConfiguration() {
return (TaskServiceConfiguration) getTaskEngineConfiguration().getServiceConfigurations().get(EngineConfigurationConstants.KEY_TASK_SERVICE_CONFIG);
}
protected IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return (IdentityLinkServiceConfiguration) getTaskEngineConfiguration().getServiceConfigurations().get(EngineConfigurationConstants.KEY_IDENTITY_LINK_SERVICE_CONFIG);
}
protected AbstractEngineConfiguration getTaskEngineConfiguration() {
Map<String, AbstractEngineConfiguration> engineConfigurations = CommandContextUtil.getCommandContext().getEngineConfigurations();
AbstractEngineConfiguration engineConfiguration = null;
if (ScopeTypes.CMMN.equals(scopeType)) {
engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG);
} else {
engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_PROCESS_ENGINE_CONFIG);
if (engineConfiguration == null) {
engineConfiguration = engineConfigurations.get(EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG);
}
}
return engineConfiguration;
}
@Override
public String toString() {
|
StringBuilder strb = new StringBuilder();
strb.append("HistoricTaskInstanceEntity[");
strb.append("id=").append(id);
strb.append(", key=").append(taskDefinitionKey);
if (executionId != null) {
strb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId)
.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeId != null) {
strb.append(", scopeInstanceId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
strb.append("]");
return strb.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskInstanceEntityImpl.java
| 2
|
请完成以下Java代码
|
public boolean isNew()
{
return this == BEFORE_NEW || this == AFTER_NEW;
}
public boolean isChange()
{
return this == BEFORE_CHANGE || this == AFTER_CHANGE;
}
public boolean isNewOrChange()
{
return isNew() || isChange();
}
public boolean isChangeOrDelete()
{
return isChange() || isDelete();
}
public boolean isDelete()
{
return this == BEFORE_DELETE || this == AFTER_DELETE;
}
public boolean isBefore()
{
return this == BEFORE_NEW
|| this == BEFORE_CHANGE
|| this == BEFORE_DELETE
|| this == BEFORE_DELETE_REPLICATION
|
|| this == BEFORE_SAVE_TRX;
}
public boolean isAfter()
{
return this == AFTER_NEW
|| this == AFTER_NEW_REPLICATION
|| this == AFTER_CHANGE
|| this == AFTER_CHANGE_REPLICATION
|| this == AFTER_DELETE;
}
public boolean isBeforeSaveTrx()
{
return this == BEFORE_SAVE_TRX;
}
public static boolean isBeforeSaveTrx(final TimingType timingType)
{
return timingType instanceof ModelChangeType
? ((ModelChangeType)timingType).isBeforeSaveTrx()
: false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelChangeType.java
| 1
|
请完成以下Java代码
|
public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg attributeUpdateNotification) {
logUnsupportedCommandMessage(attributeUpdateNotification);
}
@Override
public void onRemoteSessionCloseCommand(UUID sessionId, TransportProtos.SessionCloseNotificationProto sessionCloseNotification) {
}
@Override
public void onDeviceDeleted(DeviceId deviceId) {
}
@Override
public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg toDeviceRequest) {
logUnsupportedCommandMessage(toDeviceRequest);
}
@Override
public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) {
logUnsupportedCommandMessage(toServerResponse);
}
private void logUnsupportedCommandMessage(Object update) {
log.trace("[{}] Ignore unsupported update: {}", state.getDeviceId(), update);
}
public static boolean isConRequest(TbCoapObservationState state) {
if (state != null) {
return state.getExchange().advanced().getRequest().isConfirmable();
} else {
return false;
}
|
}
public static boolean isMulticastRequest(TbCoapObservationState state) {
if (state != null) {
return state.getExchange().advanced().getRequest().isMulticast();
}
return false;
}
protected void respond(Response response) {
response.getOptions().setContentFormat(TbCoapContentFormatUtil.getContentFormat(exchange.getRequestOptions().getContentFormat(), state.getContentFormat()));
response.setConfirmable(exchange.advanced().getRequest().isConfirmable());
exchange.respond(response);
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\callback\AbstractSyncSessionCallback.java
| 1
|
请完成以下Java代码
|
public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*/
@Override
public int getDoc_User_ID()
{
return getSalesRep_ID();
}
/**
* Get Document Approval Amount
*
* @return amount
*/
@Override
|
public BigDecimal getApprovalAmt()
{
return getGrandTotal();
} // getApprovalAmt
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
public boolean isComplete()
{
final DocStatus docStatus = DocStatus.ofCode(getDocStatus());
return docStatus.isCompletedOrClosedOrReversed();
} // isComplete
} // MOrder
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MOrder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
Member getSelectedMember() throws Exception {
if (this.memberSelectTreeType.isAssignableFrom(getInstance().getClass())) {
String expression = this.memberSelectTreeExpressionMethod.invoke(getInstance()).toString();
String identifier = this.memberSelectTreeIdentifierMethod.invoke(getInstance()).toString();
if (expression != null && identifier != null) {
return new Member(expression, identifier);
}
}
return null;
}
List<? extends ExpressionTree> getArrayExpression() throws Exception {
if (this.newArrayTreeType.isAssignableFrom(getInstance().getClass())) {
List<?> elements = (List<?>) this.arrayValueMethod.invoke(getInstance());
List<ExpressionTree> result = new ArrayList<>();
|
if (elements == null) {
return result;
}
for (Object element : elements) {
result.add(new ExpressionTree(element));
}
return result;
}
return null;
}
record Member(String expression, String identifier) {
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\ExpressionTree.java
| 2
|
请完成以下Java代码
|
public int print(final Graphics g, final PageFormat format, final int index) throws PrinterException
{
final int pagenum = index + 1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages())
{
return NO_SUCH_PAGE;
}
final PDFPage pdfPage = pdfFile.getPage(pagenum);
// task 08618: generally don't resize the PDF to fit to the page format. The jasper was made to have a particular size.
//
// However, as we always scaled to the page format and some jaspers might rely on it,
// we do scale *down* if the PDF is bigger than the page format.
// note that we only scale if both the page format's height *and* width are smaller
final Dimension scaledToPageFormat = pdfPage.getUnstretchedSize(
(int)format.getImageableWidth(),
(int)format.getImageableHeight(),
pdfPage.getPageBox());
final int widthToUse;
final int heightToUse;
if (scaledToPageFormat.getWidth() <= pdfPage.getWidth()
&& scaledToPageFormat.getHeight() <= pdfPage.getHeight())
{
// scale down to fit the page format
widthToUse = (int)scaledToPageFormat.getWidth();
heightToUse = (int)scaledToPageFormat.getHeight();
}
else
{
// *don't* scale up to fit the page format
widthToUse = (int)pdfPage.getWidth();
heightToUse = (int)pdfPage.getHeight();
}
final Rectangle bounds = new Rectangle(
(int)format.getImageableX() + calX,
(int)format.getImageableY() + calY,
widthToUse,
heightToUse);
final Graphics2D g2d = (Graphics2D)g;
final PDFRenderer pdfRenderer = new PDFRenderer(
pdfPage,
g2d,
bounds,
null, // Rectangle2D clip
null // Color bgColor
);
|
try
{
pdfPage.waitForFinish();
pdfRenderer.run();
}
catch (final InterruptedException ie)
{
throw new RuntimeException(ie);
}
// debugging: print a rectangle around the whole thing
// g2d.draw(new Rectangle2D.Double(
// format.getImageableX(),
// format.getImageableY(),
// format.getImageableWidth(),
// format.getImageableHeight()));
return PAGE_EXISTS;
}
public int getNumPages()
{
return pdfFile.getNumPages();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintablePDF.java
| 1
|
请完成以下Java代码
|
public class UserInfo implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/**
* 用户基础信息
*/
@Schema(description = "用户")
private User user;
/**
* 权限标识集合
*/
@Schema(description = "权限集合")
|
private List<String> permissions;
/**
* 角色集合
*/
@Schema(description = "角色集合")
private List<String> roles;
/**
* 第三方授权id
*/
@Schema(description = "第三方授权id")
private String oauthId;
}
|
repos\SpringBlade-master\blade-service-api\blade-user-api\src\main\java\org\springblade\system\user\entity\UserInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.subject((userPrincipal.getUsername()))
.issuedAt(new Date())
.expiration(new Date((new Date()).getTime() + jwtExpirationMs))
.signWith(getSigningKey())
.compact();
}
private SecretKey getSigningKey() {
byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
return Keys.hmacShaKeyFor(keyBytes);
}
public String getUserNameFromJwtToken(String token) {
return Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload()
.getSubject();
}
public boolean validateJwtToken(String authToken) {
|
try {
Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(authToken);
return true;
} catch (SignatureException e) {
logger.error("Invalid JWT signature: {}", e.getMessage());
} catch (MalformedJwtException e) {
logger.error("Invalid JWT token: {}", e.getMessage());
} catch (ExpiredJwtException e) {
logger.error("JWT token is expired: {}", e.getMessage());
} catch (UnsupportedJwtException e) {
logger.error("JWT token is unsupported: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.error("JWT claims string is empty: {}", e.getMessage());
}
return false;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\jwtsignkey\jwtconfig\JwtUtils.java
| 2
|
请完成以下Java代码
|
public static ZoneId zoneId()
{
return getTimeSource().zoneId();
}
public static GregorianCalendar asGregorianCalendar()
{
final GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis());
return cal;
}
public static Date asDate()
{
return new Date(millis());
}
public static Timestamp asTimestamp()
{
return new Timestamp(millis());
}
/**
* Same as {@link #asTimestamp()} but the returned date will be truncated to DAY.
*/
public static Timestamp asDayTimestamp()
{
final GregorianCalendar cal = asGregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return new Timestamp(cal.getTimeInMillis());
}
public static Instant asInstant()
{
return Instant.ofEpochMilli(millis());
}
|
public static LocalDateTime asLocalDateTime()
{
return asZonedDateTime().toLocalDateTime();
}
@NonNull
public static LocalDate asLocalDate()
{
return asLocalDate(zoneId());
}
@NonNull
public static LocalDate asLocalDate(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId).toLocalDate();
}
public static ZonedDateTime asZonedDateTime()
{
return asZonedDateTime(zoneId());
}
public static ZonedDateTime asZonedDateTimeAtStartOfDay()
{
return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS);
}
public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId)
{
return asZonedDateTime(zoneId)
.toLocalDate()
.atTime(LocalTime.MAX)
.atZone(zoneId);
}
public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId)
{
return asInstant().atZone(zoneId);
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
| 1
|
请完成以下Java代码
|
protected ByteArrayEntityManager getByteArrayEntityManager() {
return getProcessEngineConfiguration().getByteArrayEntityManager();
}
protected ProcessDefinitionEntityManager getProcessDefinitionEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionEntityManager();
}
protected ProcessDefinitionInfoEntityManager getProcessDefinitionInfoEntityManager() {
return getProcessEngineConfiguration().getProcessDefinitionInfoEntityManager();
}
protected ModelEntityManager getModelEntityManager() {
return getProcessEngineConfiguration().getModelEntityManager();
}
protected ExecutionEntityManager getExecutionEntityManager() {
return getProcessEngineConfiguration().getExecutionEntityManager();
}
protected ActivityInstanceEntityManager getActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getActivityInstanceEntityManager();
}
|
protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\AbstractManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getPublishedDate() {
return publishedDate;
}
public void setPublishedDate(Date publishedDate) {
|
this.publishedDate = publishedDate;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Article{" +
"link='" + link + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", publishedDate=" + publishedDate +
", author='" + author + '\'' +
'}';
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\rss\Article.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Fruit {
@Id
private long id;
private String name;
private String color;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
|
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\entity\Fruit.java
| 2
|
请完成以下Java代码
|
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代码
|
private Map<String, Object> getNameAndValue(ProceedingJoinPoint joinPoint) {
final Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
final String[] names = methodSignature.getParameterNames();
final Object[] args = joinPoint.getArgs();
if (ArrayUtil.isEmpty(names) || ArrayUtil.isEmpty(args)) {
return Collections.emptyMap();
}
if (names.length != args.length) {
log.warn("{}方法参数名和参数值数量不一致", methodSignature.getName());
return Collections.emptyMap();
}
Map<String, Object> map = Maps.newHashMap();
for (int i = 0; i < names.length; i++) {
map.put(names[i], args[i]);
}
return map;
}
private static final String UNKNOWN = "unknown";
/**
* 获取ip地址
*/
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
String comma = ",";
String localhost = "127.0.0.1";
if (ip.contains(comma)) {
ip = ip.split(",")[0];
}
if (localhost.equals(ip)) {
// 获取本机真正的ip地址
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.error(e.getMessage(), e);
}
}
return ip;
}
|
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
static class Log {
// 线程id
private String threadId;
// 线程名称
private String threadName;
// ip
private String ip;
// url
private String url;
// http方法 GET POST PUT DELETE PATCH
private String httpMethod;
// 类方法
private String classMethod;
// 请求参数
private Object requestParams;
// 返回参数
private Object result;
// 接口耗时
private Long timeCost;
// 操作系统
private String os;
// 浏览器
private String browser;
// user-agent
private String userAgent;
}
}
|
repos\spring-boot-demo-master\demo-log-aop\src\main\java\com\xkcoding\log\aop\aspectj\AopLog.java
| 1
|
请完成以下Java代码
|
public static void decompress(Path file, Path destination) throws IOException, ArchiveException, CompressorException {
decompress(Files.newInputStream(file), destination);
}
public static void decompress(InputStream file, Path destination) throws IOException, ArchiveException, CompressorException {
try (InputStream in = file;
BufferedInputStream inputBuffer = new BufferedInputStream(in);
OutputStream out = Files.newOutputStream(destination);
CompressorInputStream decompressor = new CompressorStreamFactory().createCompressorInputStream(inputBuffer)) {
IOUtils.copy(decompressor, out);
}
}
public static void extract(Path archive, Path destination) throws IOException, ArchiveException, CompressorException {
new Expander().expand(archive, destination);
}
public static void compressFile(Path file, Path destination) throws IOException, CompressorException {
String format = FileNameUtils.getExtension(destination);
try (OutputStream out = Files.newOutputStream(destination);
BufferedOutputStream buffer = new BufferedOutputStream(out);
CompressorOutputStream compressor = new CompressorStreamFactory().createCompressorOutputStream(format, buffer)) {
IOUtils.copy(Files.newInputStream(file), compressor);
}
}
public static void zip(Path file, Path destination) throws IOException {
try (InputStream input = Files.newInputStream(file);
OutputStream output = Files.newOutputStream(destination);
ZipArchiveOutputStream archive = new ZipArchiveOutputStream(output)) {
archive.setLevel(Deflater.BEST_COMPRESSION);
archive.setMethod(ZipEntry.DEFLATED);
archive.putArchiveEntry(new ZipArchiveEntry(file.getFileName()
|
.toString()));
IOUtils.copy(input, archive);
archive.closeArchiveEntry();
}
}
public static void extractOne(Path archivePath, String fileName, Path destinationDirectory) throws IOException, ArchiveException {
try (InputStream input = Files.newInputStream(archivePath);
BufferedInputStream buffer = new BufferedInputStream(input);
ArchiveInputStream<?> archive = new ArchiveStreamFactory().createArchiveInputStream(buffer)) {
ArchiveEntry entry;
while ((entry = archive.getNextEntry()) != null) {
if (entry.getName()
.equals(fileName)) {
Path outFile = destinationDirectory.resolve(fileName);
Files.createDirectories(outFile.getParent());
try (OutputStream os = Files.newOutputStream(outFile)) {
IOUtils.copy(archive, os);
}
break;
}
}
}
}
}
|
repos\tutorials-master\libraries-apache-commons-2\src\main\java\com\baeldung\commons\compress\CompressUtils.java
| 1
|
请完成以下Java代码
|
public class ConfigureDeviceHandler implements IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse>
{
private final AbstractTcpScales device;
public ConfigureDeviceHandler(final AbstractTcpScales device)
{
this.device = device;
}
@Override
public IDeviceResponse handleRequest(@NonNull final DeviceRequestConfigureDevice request)
{
final Map<String, IDeviceConfigParam> parameters = request.getParameters();
final IDeviceConfigParam epClass = parameters.get(AbstractTcpScales.PARAM_ENDPOINT_CLASS);
final IDeviceConfigParam epHost = parameters.get(AbstractTcpScales.PARAM_ENDPOINT_IP);
final IDeviceConfigParam epPort = parameters.get(AbstractTcpScales.PARAM_ENDPOINT_PORT);
final IDeviceConfigParam epReturnLastLine = parameters.get(AbstractTcpScales.PARAM_ENDPOINT_RETURN_LAST_LINE);
final IDeviceConfigParam epReadTimeoutMillis = parameters.get(AbstractTcpScales.PARAM_ENDPOINT_READ_TIMEOUT_MILLIS);
final IDeviceConfigParam roundToPrecision = parameters.get(AbstractTcpScales.PARAM_ROUND_TO_PRECISION); // task 09207
TcpConnectionEndPoint ep = null;
try
{
@SuppressWarnings("unchecked")
final Class<TcpConnectionEndPoint> c = (Class<TcpConnectionEndPoint>)Class.forName(epClass.getValue());
ep = c.newInstance();
}
catch (final ClassNotFoundException e)
{
throw new DeviceException("Caught a ClassNotFoundException: " + e.getLocalizedMessage(), e);
}
catch (final InstantiationException e)
{
throw new DeviceException("Caught an InstantiationException: " + e.getLocalizedMessage(), e);
}
catch (final IllegalAccessException e)
{
|
throw new DeviceException("Caught an IllegalAccessException: " + e.getLocalizedMessage(), e);
}
ep.setHost(epHost.getValue());
ep.setPort(Integer.parseInt(epPort.getValue()));
if (ep instanceof TcpConnectionReadLineEndPoint)
{
((TcpConnectionReadLineEndPoint)ep).setReturnLastLine(BooleanUtils.toBoolean(epReturnLastLine.getValue()));
}
ep.setReadTimeoutMillis(Integer.parseInt(epReadTimeoutMillis.getValue()));
device.setEndPoint(ep);
device.setRoundToPrecision(Integer.parseInt(roundToPrecision.getValue()));
device.configureStatic();
return new IDeviceResponse()
{
};
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("device", device)
.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\ConfigureDeviceHandler.java
| 1
|
请完成以下Java代码
|
public class IndexAwareSetWithTwoMaps<E> {
private final Map<E, Integer> elementToIndex;
private final Map<Integer, E> indexToElement;
private int nextIndex;
public IndexAwareSetWithTwoMaps() {
this.elementToIndex = new HashMap<>();
this.indexToElement = new HashMap<>();
this.nextIndex = 0;
}
public boolean add(E element) {
if (elementToIndex.containsKey(element)) {
return false;
}
elementToIndex.put(element, nextIndex);
indexToElement.put(nextIndex, element);
nextIndex++;
return true;
}
public boolean remove(E element) {
Integer index = elementToIndex.get(element);
if (index == null) {
return false;
}
elementToIndex.remove(element);
indexToElement.remove(index);
for (int i = index + 1; i < nextIndex; i++) {
E elementAtI = indexToElement.get(i);
if (elementAtI != null) {
indexToElement.remove(i);
elementToIndex.put(elementAtI, i - 1);
indexToElement.put(i - 1, elementAtI);
|
}
}
nextIndex--;
return true;
}
public int indexOf(E element) {
return elementToIndex.getOrDefault(element, -1);
}
public E get(int index) {
if (index < 0 || index >= nextIndex) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + nextIndex);
}
return indexToElement.get(index);
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\IndexAwareSetWithTwoMaps.java
| 1
|
请完成以下Java代码
|
public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public void setM_CostRevaluation_ID (final int M_CostRevaluation_ID)
{
if (M_CostRevaluation_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostRevaluation_ID, M_CostRevaluation_ID);
}
@Override
public int getM_CostRevaluation_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostRevaluation_ID);
}
@Override
public void setPosted (final boolean Posted)
{
set_Value (COLUMNNAME_Posted, Posted);
}
@Override
public boolean isPosted()
{
return get_ValueAsBoolean(COLUMNNAME_Posted);
}
|
@Override
public void setPostingError_Issue_ID (final int PostingError_Issue_ID)
{
if (PostingError_Issue_ID < 1)
set_Value (COLUMNNAME_PostingError_Issue_ID, null);
else
set_Value (COLUMNNAME_PostingError_Issue_ID, PostingError_Issue_ID);
}
@Override
public int getPostingError_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_PostingError_Issue_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostRevaluation.java
| 1
|
请完成以下Java代码
|
public final class ClientAttributes {
private static final String CLIENT_REGISTRATION_ID_ATTR_NAME = ClientRegistration.class.getName()
.concat(".CLIENT_REGISTRATION_ID");
/**
* Resolves the {@link ClientRegistration#getRegistrationId() clientRegistrationId} to
* be used to look up the {@link OAuth2AuthorizedClient}.
* @param attributes the to search
* @return the registration id to use.
*/
public static String resolveClientRegistrationId(Map<String, Object> attributes) {
return (String) attributes.get(CLIENT_REGISTRATION_ID_ATTR_NAME);
}
/**
|
* Produces a Consumer that adds the {@link ClientRegistration#getRegistrationId()
* clientRegistrationId} to be used to look up the {@link OAuth2AuthorizedClient}.
* @param clientRegistrationId the {@link ClientRegistration#getRegistrationId()
* clientRegistrationId} to be used to look up the {@link OAuth2AuthorizedClient}
* @return the {@link Consumer} to populate the attributes
*/
public static Consumer<Map<String, Object>> clientRegistrationId(String clientRegistrationId) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
return (attributes) -> attributes.put(CLIENT_REGISTRATION_ID_ATTR_NAME, clientRegistrationId);
}
private ClientAttributes() {
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\ClientAttributes.java
| 1
|
请完成以下Java代码
|
public class CFrame extends JFrame
{
/**
*
*/
private static final long serialVersionUID = 6282268921005682543L;
/**
* CFrame
* @throws HeadlessException
*/
public CFrame () throws HeadlessException
{
super ();
} // CFrame
/**
* CFrame
* @param gc
*/
public CFrame (GraphicsConfiguration gc)
{
super (gc);
} // CFrame
/**
* CFrame
* @param title
* @throws HeadlessException
*/
public CFrame (String title) throws HeadlessException
{
super (cleanup(title));
} // CFrame
/**
* CFrame
* @param title
* @param gc
*/
public CFrame (String title, GraphicsConfiguration gc)
{
super (cleanup(title), gc);
} // CFrame
/** Window ID */
private AdWindowId adWindowId;
/**
* Frame Init.
* Install ALT-Pause
*/
@Override
protected void frameInit ()
{
super.frameInit ();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//
Container c = getContentPane();
if (c instanceof JPanel)
{
JPanel panel = (JPanel)c;
panel.getActionMap().put(CDialog.ACTION_DISPOSE, CDialog.s_dialogAction);
panel.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW).put(CDialog.s_disposeKeyStroke, CDialog.ACTION_DISPOSE);
|
}
//
// Window Header Notice
// see http://dewiki908/mediawiki/index.php/05730_Use_different_Theme_colour_on_UAT_system
final WindowHeaderNotice windowHeaderNotice = new WindowHeaderNotice();
c.add(windowHeaderNotice, BorderLayout.NORTH);
this.addWindowListener(new WindowAdapter()
{
@Override
public void windowOpened(WindowEvent e)
{
// NOTE: we need to do this for AMenu which is created before login
windowHeaderNotice.load();
}
});
} // frameInit
/**
* Cleanedup Title
* @param title title
* @return title w/o mn
*/
private static String cleanup (String title)
{
if (title != null)
{
int pos = title.indexOf('&');
if (pos != -1 && title.length() > pos) // We have a mnemonic
{
int mnemonic = title.toUpperCase().charAt(pos+1);
if (mnemonic != ' ')
{
title = title.substring(0, pos) + title.substring(pos+1);
}
}
}
return title;
} // getTitle
/**
* Set Title
* @param title title
*/
@Override
public void setTitle(String title)
{
super.setTitle(cleanup(title));
} // setTitle
public AdWindowId getAdWindowId()
{
return adWindowId;
} // getAD_Window_ID
public void setAdWindowId(@Nullable final AdWindowId adWindowId)
{
this.adWindowId = adWindowId;
}
} // CFrame
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CFrame.java
| 1
|
请完成以下Java代码
|
public class C_Phonecall_Schedule_CreateSalesOrder extends JavaProcess implements IProcessPrecondition
{
private final PhonecallScheduleRepository phonecallSchedueRepo = SpringContextHolder.instance.getBean(PhonecallScheduleRepository.class);
private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
private final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
@Override
protected String doIt() throws Exception
{
final PhonecallSchedule phonecallSchedule = phonecallSchedueRepo.getById(PhonecallScheduleId.ofRepoId(getRecord_ID()));
phonecallSchedueRepo.markAsOrdered(phonecallSchedule);
final DocTypeQuery query = DocTypeQuery.builder()
.docBaseType(X_C_DocType.DOCBASETYPE_SalesOrder)
.docSubType(DocSubType.StandardOrder)
.adClientId(Env.getAD_Client_ID())
.build();
final DocTypeId docTypeId = docTypeDAO.getDocTypeId(query);
final BPartnerLocationId bpartnerAndLocationId = phonecallSchedule.getBpartnerAndLocationId();
final BPartnerId bpartnerId = bpartnerAndLocationId.getBpartnerId();
final BPartnerContactId bpContactId = BPartnerContactId.of(bpartnerId, phonecallSchedule.getContactId());
final I_C_BPartner partnerRecord = bpartnerDAO.getById(bpartnerId);
final LocalDate today = SystemTime.asLocalDate();
final ZoneId orgTimeZone = orgDAO.getTimeZone(phonecallSchedule.getOrgId());
final ZonedDateTime datePromisedEndOfDay = today.atTime(LocalTime.MAX).atZone(orgTimeZone);
|
final I_C_Order draftOrder = OrderFactory.newSalesOrder()
.shipBPartner(bpartnerId, bpartnerAndLocationId, bpContactId)
// // this makes the system create a SO with deactivated BPartner Contact, if you have 3 contacts and the first 2 have IsActive=false
// // kept here for easy repro of https://github.com/metasfresh/metasfresh/issues/6463
// // can be deleted after that bug is fixed
// .shipBPartner(phonecallSchedule.getBpartnerAndLocationId().getBpartnerId())
//
.docType(docTypeId)
.paymentTermId(PaymentTermId.ofRepoIdOrNull(partnerRecord.getC_PaymentTerm_ID()))
.datePromised(datePromisedEndOfDay)
.createDraftOrderHeader();
final String adWindowId = null; // auto
getResult().setRecordToOpen(TableRecordReference.of(draftOrder), adWindowId, OpenTarget.SingleDocument, ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB);
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\phonecall\process\C_Phonecall_Schedule_CreateSalesOrder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CacheController {
@Autowired
PersonService personService;
@RequestMapping("/put")
public long put(@RequestBody Person person) {
Person p = personService.save(person);
return p.getId();
}
@RequestMapping("/able")
public Person cacheable(Person person) {
return personService.findOne(person);
}
|
@RequestMapping("/able1")
public Person cacheable1(Person person) {
return personService.findOne1(person);
}
@RequestMapping("/evit")
public String evit(Long id) {
personService.remove(id);
return "ok";
}
}
|
repos\spring-boot-student-master\spring-boot-student-layering-cache\src\main\java\com\xiaolyuh\controller\CacheController.java
| 2
|
请完成以下Java代码
|
public Builder setOrderBys(final DocumentQueryOrderByList orderBys)
{
if (orderBys == null || orderBys.isEmpty())
{
_orderBys = null;
}
else
{
_orderBys = new ArrayList<>(orderBys.toList());
}
return this;
}
private DocumentQueryOrderByList getOrderBysEffective()
{
return _noSorting
? DocumentQueryOrderByList.EMPTY
: DocumentQueryOrderByList.ofList(_orderBys);
}
public Builder setFirstRow(final int firstRow)
{
this.firstRow = firstRow;
return this;
}
public Builder setPageLength(final int pageLength)
{
this.pageLength = pageLength;
|
return this;
}
public Builder setExistingDocumentsSupplier(final Function<DocumentId, Document> existingDocumentsSupplier)
{
this.existingDocumentsSupplier = existingDocumentsSupplier;
return this;
}
public Builder setChangesCollector(IDocumentChangesCollector changesCollector)
{
this.changesCollector = changesCollector;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentQuery.java
| 1
|
请完成以下Java代码
|
public class PostDto {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private Long id;
private String title;
private String url;
private String date;
private UserDto user;
public Date getSubmissionDateConverted(String timezone) throws ParseException {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
return dateFormat.parse(this.date);
}
public void setSubmissionDate(Date date, String timezone) {
dateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
this.date = dateFormat.format(date);
}
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 getUrl() {
return url;
}
|
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public UserDto getUser() {
return user;
}
public void setUser(UserDto user) {
this.user = user;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\dto\PostDto.java
| 1
|
请完成以下Java代码
|
public Criteria andDetailAddressNotIn(List<String> values) {
addCriterion("detail_address not in", values, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressBetween(String value1, String value2) {
addCriterion("detail_address between", value1, value2, "detailAddress");
return (Criteria) this;
}
public Criteria andDetailAddressNotBetween(String value1, String value2) {
addCriterion("detail_address not between", value1, value2, "detailAddress");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
|
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddressExample.java
| 1
|
请完成以下Java代码
|
String buildAddress1(@NonNull final I_I_Pharma_BPartner importRecord)
{
final StringBuilder sb = new StringBuilder();
if (!Check.isEmpty(importRecord.getb00str()))
{
sb.append(importRecord.getb00str());
}
if (!Check.isEmpty(importRecord.getb00hnrv()))
{
if (sb.length() > 0)
{
sb.append(" ");
}
sb.append(importRecord.getb00hnrv());
}
if (!Check.isEmpty(importRecord.getb00hnrvz()))
{
if (sb.length() > 0)
{
sb.append(" ");
}
sb.append(importRecord.getb00hnrvz());
}
return sb.toString();
}
@VisibleForTesting
String buildAddress2(@NonNull final I_I_Pharma_BPartner importRecord)
{
final StringBuilder sb = new StringBuilder();
if (!Check.isEmpty(importRecord.getb00hnrb()))
{
sb.append(importRecord.getb00hnrb());
}
if (!Check.isEmpty(importRecord.getb00hnrbz()))
{
if (sb.length() > 0)
{
sb.append(" ");
}
sb.append(importRecord.getb00hnrbz());
}
return sb.toString();
}
@VisibleForTesting
String buildPOBox(@NonNull final I_I_Pharma_BPartner importRecord)
{
final StringBuilder sb = new StringBuilder();
if (!Check.isEmpty(importRecord.getb00plzpf1()))
{
sb.append(importRecord.getb00plzpf1());
}
if (!Check.isEmpty(importRecord.getb00ortpf()))
{
if (sb.length() > 0)
{
sb.append("\\n");
}
sb.append(importRecord.getb00plzpf1());
}
if (!Check.isEmpty(importRecord.getb00pf1()))
{
if (sb.length() > 0)
{
sb.append("\\n");
|
}
sb.append(importRecord.getb00pf1());
}
if (!Check.isEmpty(importRecord.getb00plzgk1()))
{
if (sb.length() > 0)
{
sb.append("\\n");
}
sb.append(importRecord.getb00plzgk1());
}
return sb.toString();
}
private void updatePhoneAndFax(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation)
{
if (!Check.isEmpty(importRecord.getb00tel1()))
{
bpartnerLocation.setPhone(importRecord.getb00tel1());
}
if (!Check.isEmpty(importRecord.getb00tel2()))
{
bpartnerLocation.setPhone2(importRecord.getb00tel2());
}
if (!Check.isEmpty(importRecord.getb00fax1()))
{
bpartnerLocation.setFax(importRecord.getb00fax1());
}
if (!Check.isEmpty(importRecord.getb00fax2()))
{
bpartnerLocation.setFax2(importRecord.getb00fax2());
}
}
private void updateEmails(@NonNull final I_I_Pharma_BPartner importRecord, @NonNull final I_C_BPartner_Location bpartnerLocation)
{
if (!Check.isEmpty(importRecord.getb00email()))
{
bpartnerLocation.setEMail(importRecord.getb00email());
}
if (!Check.isEmpty(importRecord.getb00email2()))
{
bpartnerLocation.setEMail2(importRecord.getb00email2());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\impexp\bpartner\IFABPartnerLocationImportHelper.java
| 1
|
请完成以下Java代码
|
public static LocatorQRCode ofScannedCode(final ScannedCode scannedCode) {return LocatorQRCodeJsonConverter.fromGlobalQRCodeJsonString(scannedCode.getAsString());}
public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator)
{
return builder()
.locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID()))
.caption(locator.getValue())
.build();
}
public PrintableQRCode toPrintableQRCode()
{
return PrintableQRCode.builder()
.qrCode(toGlobalQRCodeJsonString())
.bottomText(caption)
.build();
|
}
public GlobalQRCode toGlobalQRCode()
{
return LocatorQRCodeJsonConverter.toGlobalQRCode(this);
}
public ScannedCode toScannedCode()
{
return ScannedCode.ofString(toGlobalQRCodeJsonString());
}
public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode)
{
return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty()
{
return includes.isEmpty();
}
public Set<RoleId> getAllRoleIdsIncluding(final RoleId adRoleId)
{
final Set<RoleId> adRoleIds = new LinkedHashSet<>();
adRoleIds.add(adRoleId);
for (final UserRolePermissionsInclude include : includes)
{
include.collectRoleIds(adRoleIds);
}
return adRoleIds;
}
public static final class Builder
{
private final List<UserRolePermissionsInclude> includes = new ArrayList<>();
private Builder()
{
super();
}
public ImmutableList<UserRolePermissionsInclude> getIncludes()
{
return ImmutableList.copyOf(includes);
}
public UserRolePermissionsIncludesList build()
{
return new UserRolePermissionsIncludesList(this);
}
|
public Builder add(final UserRolePermissionsInclude include)
{
if (!includes.contains(include))
{
includes.add(include);
}
return this;
}
public Builder addAll(final Iterable<UserRolePermissionsInclude> includes)
{
for (final UserRolePermissionsInclude include : includes)
{
add(include);
}
return this;
}
public boolean isEmpty()
{
return includes.isEmpty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsIncludesList.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return toJson();
}
@JsonValue
public String toJson()
{
return value;
}
public int toInt()
{
return toOptionalInt()
.orElseThrow(() -> new AdempiereException("WindowId cannot be converted to int: " + this));
}
public int toIntOr(final int fallbackValue)
{
return toOptionalInt()
.orElse(fallbackValue);
}
private OptionalInt toOptionalInt()
{
OptionalInt valueInt = this.valueInt;
if (valueInt == null)
{
valueInt = this.valueInt = parseOptionalInt();
}
return valueInt;
}
private OptionalInt parseOptionalInt()
{
try
{
return OptionalInt.of(Integer.parseInt(value));
}
catch (final Exception ex)
{
return OptionalInt.empty();
|
}
}
@Nullable
public AdWindowId toAdWindowIdOrNull()
{
return AdWindowId.ofRepoIdOrNull(toIntOr(-1));
}
public AdWindowId toAdWindowId()
{
return AdWindowId.ofRepoId(toInt());
}
public boolean isInt()
{
return toOptionalInt().isPresent();
}
public DocumentId toDocumentId()
{
return DocumentId.of(value);
}
public static boolean equals(@Nullable final WindowId id1, @Nullable final WindowId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\WindowId.java
| 1
|
请完成以下Java代码
|
public Money getInvoiceLineOpenAmt(InvoiceAndLineId invoiceAndLineId)
{
final I_C_InvoiceLine invoiceLine = invoiceBL.getLineById(invoiceAndLineId);
return getInvoiceLineOpenAmt(invoiceLine);
}
public Money getInvoiceLineOpenAmt(I_C_InvoiceLine invoiceLine)
{
final InvoiceId invoiceId = InvoiceId.ofRepoId(invoiceLine.getC_Invoice_ID());
final I_C_Invoice invoice = invoiceBL.getById(invoiceId);
Money openAmt = Money.of(invoiceLine.getLineNetAmt(), CurrencyId.ofRepoId(invoice.getC_Currency_ID()));
final Money matchedAmt = matchInvoiceService.getCostAmountMatched(InvoiceAndLineId.ofRepoId(invoiceId, invoiceLine.getC_InvoiceLine_ID())).orElse(null);
if (matchedAmt != null)
{
openAmt = openAmt.subtract(matchedAmt);
}
return openAmt;
}
public void cloneAllByOrderId(
@NonNull final OrderId orderId,
@NonNull final OrderCostCloneMapper mapper)
{
final List<OrderCost> originalOrderCosts = orderCostRepository.getByOrderId(orderId);
final ImmutableList<OrderCost> clonedOrderCosts = originalOrderCosts.stream()
.map(originalOrderCost -> originalOrderCost.copy(mapper))
.collect(ImmutableList.toImmutableList());
orderCostRepository.saveAll(clonedOrderCosts);
}
public void updateOrderCostsOnOrderLineChanged(final OrderCostDetailOrderLinePart orderLineInfo)
{
orderCostRepository.changeByOrderLineId(
orderLineInfo.getOrderLineId(),
orderCost -> {
orderCost.updateOrderLineInfoIfApplies(orderLineInfo, moneyService::getStdPrecision, uomConversionBL);
updateCreatedOrderLineIfAny(orderCost);
|
});
}
private void updateCreatedOrderLineIfAny(@NonNull final OrderCost orderCost)
{
if (orderCost.getCreatedOrderLineId() == null)
{
return;
}
CreateOrUpdateOrderLineFromOrderCostCommand.builder()
.orderBL(orderBL)
.moneyService(moneyService)
.orderCost(orderCost)
.build()
.execute();
}
public void deleteByCreatedOrderLineId(@NonNull final OrderAndLineId createdOrderLineId)
{
orderCostRepository.deleteByCreatedOrderLineId(createdOrderLineId);
}
public boolean isCostGeneratedOrderLine(@NonNull final OrderLineId orderLineId)
{
return orderCostRepository.hasCostsByCreatedOrderLineIds(ImmutableSet.of(orderLineId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostService.java
| 1
|
请完成以下Java代码
|
private Multimap<PurchaseRow, PurchaseRow> extractLineRow2availabilityRows()
{
final PurchaseView view = getView();
final ListMultimap<PurchaseRow, PurchaseRow> lineRow2AvailabilityRows = getSelectedRowIds().stream()
.map(PurchaseRowId::fromDocumentId) // map to PurchaseRowIds
.filter(PurchaseRowId::isAvailabilityRowId)
.filter(availabilityRowId -> availabilityRowId.getAvailabilityType().equals(Type.AVAILABLE))
.map(availabilityRowId -> ImmutablePair.of( // map to pair (availabilityRowId, availabilityRow)
availabilityRowId,
view.getById(availabilityRowId.toDocumentId())))
.filter(availabilityRowId2row -> isPositive(availabilityRowId2row.getRight().getQtyToPurchase()))
.map(availabilityRowId2row -> ImmutablePair.of( // map to pair (lineRow, availabilityRow)
view.getById(availabilityRowId2row.getLeft().toLineRowId().toDocumentId()),
availabilityRowId2row.getRight()))
.filter(lineRow2availabilityRow -> !lineRow2availabilityRow.getLeft().isProcessed())
.collect(Multimaps.toMultimap(
IPair::getLeft,
IPair::getRight,
MultimapBuilder.hashKeys().arrayListValues()::build));
|
return ImmutableMultimap.copyOf(lineRow2AvailabilityRows);
}
private static final boolean isPositive(final Quantity qty)
{
return qty != null && qty.signum() > 0;
}
private static PurchaseRowChangeRequest createPurchaseRowChangeRequest(final PurchaseRow availabilityRow)
{
final PurchaseRowChangeRequestBuilder requestBuilder = PurchaseRowChangeRequest.builder();
if (availabilityRow.getDatePromised() != null)
{
requestBuilder.purchaseDatePromised(availabilityRow.getDatePromised());
}
requestBuilder.qtyToPurchase(availabilityRow.getQtyToPurchase());
return requestBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\process\WEBUI_SalesOrder_Apply_Availability_Row.java
| 1
|
请完成以下Java代码
|
public void changeAcctSchemaAutomaticPeriodId(@NonNull final AcctSchemaId acctSchemaId, final int periodId)
{
Check.assumeGreaterThanZero(periodId, "periodId");
final I_C_AcctSchema acctSchemaRecord = InterfaceWrapperHelper.loadOutOfTrx(acctSchemaId, I_C_AcctSchema.class);
Check.assumeNotNull(acctSchemaRecord, "Accounting schema shall exists for {}", acctSchemaId);
acctSchemaRecord.setC_Period_ID(periodId);
InterfaceWrapperHelper.saveRecord(acctSchemaRecord);
}
private ImmutableSet<CostElementId> retrievePostOnlyForCostElementIds(@NonNull final AcctSchemaId acctSchemaId)
{
return queryBL
.createQueryBuilderOutOfTrx(I_C_AcctSchema_CostElement.class)
.addEqualsFilter(I_C_AcctSchema_CostElement.COLUMN_C_AcctSchema_ID, acctSchemaId)
.addOnlyActiveRecordsFilter()
.create()
.listDistinct(I_C_AcctSchema_CostElement.COLUMNNAME_M_CostElement_ID, Integer.class)
.stream()
.map(CostElementId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
}
@ToString
private static class AcctSchemasMap
{
private final ImmutableMap<AcctSchemaId, AcctSchema> acctSchemas;
public AcctSchemasMap(final List<AcctSchema> acctSchemas)
{
this.acctSchemas = Maps.uniqueIndex(acctSchemas, AcctSchema::getId);
}
public AcctSchema getById(@NonNull final AcctSchemaId acctSchemaId)
{
final AcctSchema acctSchema = acctSchemas.get(acctSchemaId);
if (acctSchema == null)
{
throw new AdempiereException("No accounting schema found for " + acctSchemaId);
}
return acctSchema;
}
|
public List<AcctSchema> getByClientId(@NonNull final ClientId clientId, @Nullable final AcctSchemaId primaryAcctSchemaId)
{
final ImmutableList.Builder<AcctSchema> result = ImmutableList.builder();
// Primary accounting schema shall be returned first
if (primaryAcctSchemaId != null)
{
result.add(getById(primaryAcctSchemaId));
}
for (final AcctSchema acctSchema : acctSchemas.values())
{
if (acctSchema.getId().equals(primaryAcctSchemaId))
{
continue;
}
if (clientId.equals(acctSchema.getClientId()))
{
result.add(acctSchema);
}
}
return result.build();
}
public List<AcctSchema> getByChartOfAccountsId(@NonNull final ChartOfAccountsId chartOfAccountsId)
{
return acctSchemas.values()
.stream()
.filter(acctSchema -> ChartOfAccountsId.equals(acctSchema.getChartOfAccountsId(), chartOfAccountsId))
.collect(ImmutableList.toImmutableList());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaDAO.java
| 1
|
请完成以下Java代码
|
public class PatternUtil {
/**
* 匹配邮箱正则
*/
private static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
/**
* 验证只包含中英文和数字的字符串
*
* @param keyword
* @return
*/
public static Boolean validKeyword(String keyword) {
String regex = "^[a-zA-Z0-9\u4E00-\u9FA5]+$";
Pattern pattern = Pattern.compile(regex);
Matcher match = pattern.matcher(keyword);
return match.matches();
}
/**
* 判断是否是邮箱
*
* @param emailStr
* @return
*/
public static boolean isEmail(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
/**
|
* 判断是否是网址
*
* @param urlString
* @return
*/
public static boolean isURL(String urlString) {
String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";
Pattern pattern = Pattern.compile(regex);
if (pattern.matcher(urlString).matches()) {
return true;
} else {
return false;
}
}
}
|
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\util\PatternUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String,Object> shotLog(@RequestParam("name")String name,@RequestParam("age") int age){
Map<String,Object> result = new HashMap<>();
result.put("name",name);
result.put("age",age);
return result;
}
@RequestMapping("/show2")
public Map<String,Object> shotLog(@RequestBody String parms){
Map<String,Object> result = new HashMap<>();
// result.put("name",name);
// result.put("age",age);
// System.out.println(parms);
loggerService.showLog();
return result;
|
}
@RequestMapping("s")
public String ss() {
return "123";
}
@GetMapping("/exception")
public String exce() {
System.out.println("异常");
throw new IllegalArgumentException("异常了");
}
}
|
repos\spring-boot-quick-master\quick-log\src\main\java\com\quick\log\controller\ApiController.java
| 2
|
请完成以下Java代码
|
public String toString()
{
// preserve legacy
return "C_BPartner_ID=" + getC_BPartner_ID()
+ ", M_Product_ID=" + getM_Product_ID()
+ ", M_Warehouse_ID=" + getM_Warehouse_ID()
+ ", M_AttributeSetInstance_ID=" + getM_AttributeSetInstance_ID();
}
private final IInvoiceHistoryTabHandler ihTabHandler = new DefaultInvoiceHistoryTabHandler();
//
// Model configuration
private final int C_BPartner_ID;
private final int M_Product_ID;
private final int M_Warehouse_ID;
private final int M_AttributeSetInstance_ID;
private final Timestamp DatePromised;
//
// GUI configuration
private final boolean rowSelectionAllowed;
private InvoiceHistoryContext(final InvoiceHistoryContextBuilder builder)
{
super();
C_BPartner_ID = builder.C_BPartner_ID;
M_Product_ID = builder.M_Product_ID;
M_Warehouse_ID = builder.M_Warehouse_ID;
M_AttributeSetInstance_ID = builder.M_AttributeSetInstance_ID;
DatePromised = builder.DatePromised;
rowSelectionAllowed = builder.rowSelectionAllowed;
}
public IInvoiceHistoryTabHandler getInvoiceHistoryTabHandler()
{
return ihTabHandler;
}
public int getC_BPartner_ID()
{
return C_BPartner_ID;
}
public int getM_Product_ID()
{
return M_Product_ID;
}
public int getM_Warehouse_ID()
{
return M_Warehouse_ID;
}
public int getM_AttributeSetInstance_ID()
{
return M_AttributeSetInstance_ID;
}
public Timestamp getDatePromisedOrNull()
{
return DatePromised;
}
public boolean isRowSelectionAllowed()
{
return rowSelectionAllowed;
}
public static InvoiceHistoryContextBuilder builder()
{
return new InvoiceHistoryContextBuilder();
}
public static class InvoiceHistoryContextBuilder
{
public InvoiceHistoryContext build()
{
return new InvoiceHistoryContext(this);
}
|
private int C_BPartner_ID = -1;
private int M_Product_ID = -1;
private int M_Warehouse_ID = -1;
private int M_AttributeSetInstance_ID = -1;
private Timestamp DatePromised = null;
private boolean rowSelectionAllowed = false;
public InvoiceHistoryContextBuilder setC_BPartner_ID(final int c_BPartner_ID)
{
C_BPartner_ID = c_BPartner_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_Product_ID(final int m_Product_ID)
{
M_Product_ID = m_Product_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_Warehouse_ID(final int m_Warehouse_ID)
{
M_Warehouse_ID = m_Warehouse_ID;
return this;
}
public InvoiceHistoryContextBuilder setM_AttributeSetInstance_ID(final int m_AttributeSetInstance_ID)
{
M_AttributeSetInstance_ID = m_AttributeSetInstance_ID;
return this;
}
public InvoiceHistoryContextBuilder setDatePromised(final Timestamp DatePromised)
{
this.DatePromised = DatePromised;
return this;
}
public InvoiceHistoryContextBuilder setRowSelectionAllowed(final boolean rowSelectionAllowed)
{
this.rowSelectionAllowed = rowSelectionAllowed;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\history\impl\InvoiceHistoryContext.java
| 1
|
请完成以下Java代码
|
public class SecurityContextThreadLocalAccessor implements ThreadLocalAccessor<Object> {
private static final boolean springSecurityPresent = ClassUtils.isPresent(
"org.springframework.security.core.context.SecurityContext",
SecurityContextThreadLocalAccessor.class.getClassLoader());
private final ThreadLocalAccessor<?> delegate;
public SecurityContextThreadLocalAccessor() {
if (springSecurityPresent) {
this.delegate = new DelegateAccessor();
}
else {
this.delegate = new NoOpAccessor();
}
}
@Override
public Object key() {
return this.delegate.key();
}
@Override
public @Nullable Object getValue() {
return this.delegate.getValue();
}
@Override
public void setValue(Object value) {
setValueInternal(value);
}
@SuppressWarnings("unchecked")
private <V> void setValueInternal(Object value) {
((ThreadLocalAccessor<V>) this.delegate).setValue((V) value);
}
@Override
public void setValue() {
this.delegate.setValue();
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
this.delegate.reset();
}
@Override
public void restore(Object previousValue) {
restoreInternal(previousValue);
}
@SuppressWarnings("unchecked")
public <V> void restoreInternal(Object previousValue) {
((ThreadLocalAccessor<V>) this.delegate).restore((V) previousValue);
}
@Override
public void restore() {
this.delegate.restore();
}
private static final class DelegateAccessor implements ThreadLocalAccessor<Object> {
@Override
public Object key() {
return SecurityContext.class.getName();
}
@Override
public Object getValue() {
return SecurityContextHolder.getContext();
}
@Override
public void setValue(Object value) {
SecurityContextHolder.setContext((SecurityContext) value);
}
|
@Override
public void setValue() {
SecurityContextHolder.clearContext();
}
@Override
public void restore(Object previousValue) {
SecurityContextHolder.setContext((SecurityContext) previousValue);
}
@Override
public void restore() {
SecurityContextHolder.clearContext();
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
SecurityContextHolder.clearContext();
}
}
private static final class NoOpAccessor implements ThreadLocalAccessor<Object> {
@Override
public Object key() {
return getClass().getName();
}
@Override
public @Nullable Object getValue() {
return null;
}
@Override
public void setValue(Object value) {
}
@Override
public void setValue() {
}
@Override
public void restore(Object previousValue) {
}
@Override
public void restore() {
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
}
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityContextThreadLocalAccessor.java
| 1
|
请完成以下Java代码
|
public void setEventName(String eventName) {
this.eventName = eventName;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
this.activity = null;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
|
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EventSubscriptionEntity other = (EventSubscriptionEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventType=" + eventType
+ ", eventName=" + eventName
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", activityId=" + activityId
+ ", tenantId=" + tenantId
+ ", configuration=" + configuration
+ ", revision=" + revision
+ ", created=" + created
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionEntity.java
| 1
|
请完成以下Java代码
|
protected CaseDefinition getCaseDefinitionById(String caseDefinitionId, CommandContext commandContext) {
CmmnRepositoryService repositoryService = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getCmmnRepositoryService();
CaseDefinition caseDefinition = repositoryService.createCaseDefinitionQuery()
.caseDefinitionId(caseDefinitionId)
.singleResult();
if (caseDefinition == null) {
throw new FlowableIllegalArgumentException("No deployed case definition found for id '" + caseDefinitionId + "'.");
}
return caseDefinition;
}
protected Case getCase(String caseDefinitionId, CommandContext commandContext) {
CmmnRepositoryService repositoryService = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getCmmnRepositoryService();
CmmnModel cmmnModel = repositoryService.getCmmnModel(caseDefinitionId);
return cmmnModel.getPrimaryCase();
}
protected EventModel getEventModel(String eventDefinitionKey, String tenantId, CommandContext commandContext) {
EventModel eventModel = CommandContextUtil.getEventRepositoryService(commandContext).getEventModelByKey(eventDefinitionKey, tenantId);
if (eventModel == null) {
throw new FlowableIllegalArgumentException("Could not find event model with key '" + eventDefinitionKey + "'.");
}
return eventModel;
}
|
protected String getStartCorrelationConfiguration(String caseDefinitionId, CommandContext commandContext) {
CmmnModel cmmnModel = CommandContextUtil.getCmmnEngineConfiguration(commandContext).getCmmnRepositoryService().getCmmnModel(caseDefinitionId);
if (cmmnModel != null) {
List<ExtensionElement> correlationCfgExtensions = cmmnModel.getPrimaryCase().getExtensionElements()
.getOrDefault(CmmnXmlConstants.START_EVENT_CORRELATION_CONFIGURATION, Collections.emptyList());
if (!correlationCfgExtensions.isEmpty()) {
return correlationCfgExtensions.get(0).getElementText();
}
}
return null;
}
protected EventSubscriptionService getEventSubscriptionService(CommandContext commandContext) {
return CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventSubscriptionServiceConfiguration().getEventSubscriptionService();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\AbstractCaseStartEventSubscriptionCmd.java
| 1
|
请完成以下Java代码
|
public class DocTypeNotFoundException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = -1269337075319916877L;
public DocTypeNotFoundException(final DocBaseType docBaseType, final String additionalInfo)
{
super(buildMsg(docBaseType, additionalInfo));
}
public DocTypeNotFoundException(@NonNull final DocTypeQuery query)
{
super(buildMsg(query));
}
private static ITranslatableString buildMsg(final DocBaseType docBaseType, final String additionalInfo)
{
final TranslatableStringBuilder builder = TranslatableStrings.builder();
builder.appendADMessage(AdMessageKey.of("NotFound")).append(" ").appendADElement("C_DocType_ID");
if (docBaseType != null)
{
final ADReferenceService adReferenceService = ADReferenceService.get();
final String docBaseTypeName = adReferenceService.retrieveListNameTrl(Env.getCtx(), X_C_DocType.DOCBASETYPE_AD_Reference_ID, docBaseType.getCode());
builder.append(" - ")
.appendADElement("DocBaseType")
.append(": ")
.append(docBaseTypeName);
}
if (!Check.isBlank(additionalInfo))
{
builder.append(" (").append(additionalInfo).append(")");
}
return builder.build();
}
|
private static ITranslatableString buildMsg(final DocTypeQuery query)
{
final TranslatableStringBuilder builder = TranslatableStrings.builder();
builder.appendADMessage(AdMessageKey.of("NotFound")).append(" ").appendADElement("C_DocType_ID");
final ADReferenceService adReferenceService = ADReferenceService.get();
final String docBaseTypeName = adReferenceService.retrieveListNameTrl(Env.getCtx(), X_C_DocType.DOCBASETYPE_AD_Reference_ID, query.getDocBaseType().getCode());
builder.append(" - ").appendADElement("DocBaseType").append(": ").append(docBaseTypeName);
builder.append(", ").appendADElement("DocSubType").append(": ").append(query.getDocSubType().getCode());
builder.append(", ").appendADElement("AD_Client_ID").append(": ").append(query.getAdClientId());
builder.append(", ").appendADElement("AD_Org_ID").append(": ").append(query.getAdOrgId());
if (query.getIsSOTrx() != null)
{
builder.append(", ").appendADElement("IsSOTrx").append(": ").append(query.getIsSOTrx());
}
if (!Check.isBlank(query.getName()))
{
builder.append(", ").appendADElement("Name").append(": ").append(query.getName());
}
return builder.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\DocTypeNotFoundException.java
| 1
|
请完成以下Java代码
|
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage)
{
return Msg.getMsg(ctx, adMessage.toAD_Message());
}
@Override
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage, @Nullable final Object[] params)
{
return Msg.getMsg(ctx, adMessage.toAD_Message(), params);
}
@Override
public String getMsg(final AdMessageKey adMessage, final List<Object> params)
{
return getMsg(Env.getCtx(), adMessage, params != null && !params.isEmpty() ? params.toArray() : null);
}
@Override
public String getMsg(final Properties ctx, @NonNull final AdMessageKey adMessage, final boolean text)
{
return Msg.getMsg(ctx, adMessage.toAD_Message(), text);
}
@Override
public Map<String, String> getMsgMap(final String adLanguage, final String prefix, final boolean removePrefix)
{
return Msg.getMsgMap(adLanguage, prefix, removePrefix);
}
@Override
public String translate(final Properties ctx, final String text)
{
return Msg.translate(ctx, text);
}
@Override
public String translate(final String adLanguage, final String text)
{
return Msg.translate(adLanguage, text);
}
@Override
public String translate(final Properties ctx, final String text, final boolean isSOTrx)
{
return Msg.translate(ctx, text, isSOTrx);
}
@Override
public ITranslatableString translatable(final String text)
{
if (Check.isBlank(text))
{
return TranslatableStrings.constant(text);
}
return new ADElementOrADMessageTranslatableString(text);
}
@Override
public String parseTranslation(final Properties ctx, final String message)
{
return Msg.parseTranslation(ctx, message);
}
@Override
public String parseTranslation(final String adLanguage, final String message)
{
return Msg.parseTranslation(adLanguage, message);
}
@Override
public ITranslatableString getTranslatableMsgText(@NonNull final AdMessageKey adMessage, final Object... msgParameters)
{
return new ADMessageTranslatableString(adMessage, msgParameters);
}
@Override
|
public void cacheReset()
{
Msg.cacheReset();
}
@Override
public String getBaseLanguageMsg(@NonNull final AdMessageKey adMessage, @Nullable final Object... msgParameters)
{
return TranslatableStrings.adMessage(adMessage, msgParameters).translate(Language.getBaseAD_Language());
}
@Override
public Optional<AdMessageId> getIdByAdMessage(@NonNull final AdMessageKey adMessage)
{
return Msg.toMap().getIdByAdMessage(adMessage);
}
@Override
public boolean isMessageExists(AdMessageKey adMessage)
{
return Msg.toMap().isMessageExists(adMessage);
}
@Override
public Optional<AdMessageKey> getAdMessageKeyById(final AdMessageId adMessageId)
{
return Msg.toMap().getAdMessageKeyById(adMessageId);
}
@Override
public String getErrorCode(final @NonNull AdMessageKey messageKey)
{
return Msg.getErrorCode(messageKey.toAD_Message());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\MsgBL.java
| 1
|
请完成以下Java代码
|
default Object getProperty(String name) {
return getDelegate().getProperty(name);
};
/**
* <p>refresh.</p>
*/
default void refresh() {
if(getDelegate() instanceof EncryptablePropertySource) {
((EncryptablePropertySource<?>) getDelegate()).refresh();
}
}
/**
* <p>getProperty.</p>
*
* @param resolver a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver} object
* @param filter a {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyFilter} object
* @param source a {@link org.springframework.core.env.PropertySource} object
* @param name a {@link java.lang.String} object
* @return a {@link java.lang.Object} object
*/
default Object getProperty(EncryptablePropertyResolver resolver, EncryptablePropertyFilter filter, PropertySource<T> source, String name) {
Object value = source.getProperty(name);
if (value != null && filter.shouldInclude(source, name) && value instanceof String) {
String stringValue = String.valueOf(value);
return resolver.resolvePropertyValue(stringValue);
}
return value;
}
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override
default Origin getOrigin(String key) {
if(getDelegate() instanceof OriginLookup) {
return ((OriginLookup<String>) getDelegate()).getOrigin(key);
|
}
return null;
}
/** {@inheritDoc} */
@Override
default boolean isImmutable() {
if(getDelegate() instanceof OriginLookup) {
return ((OriginLookup<?>) getDelegate()).isImmutable();
}
return OriginLookup.super.isImmutable();
}
/** {@inheritDoc} */
@Override
default String getPrefix() {
if(getDelegate() instanceof OriginLookup) {
return ((OriginLookup<?>) getDelegate()).getPrefix();
}
return OriginLookup.super.getPrefix();
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\EncryptablePropertySource.java
| 1
|
请完成以下Java代码
|
public final class InvocationResult {
private final @Nullable Object returnValue;
private final @Nullable Expression sendTo;
private final @Nullable Type returnType;
private final @Nullable Object bean;
private final @Nullable Method method;
/**
* Construct an instance with the provided properties.
* @param result the result.
* @param sendTo the sendTo expression.
* @param returnType the return type.
* @param bean the bean.
* @param method the method.
*/
public InvocationResult(@Nullable Object result, @Nullable Expression sendTo, @Nullable Type returnType,
@Nullable Object bean, @Nullable Method method) {
this.returnValue = result;
this.sendTo = sendTo;
this.returnType = returnType;
this.bean = bean;
this.method = method;
}
public @Nullable Object getReturnValue() {
return this.returnValue;
}
public @Nullable Expression getSendTo() {
return this.sendTo;
}
@Nullable
|
public Type getReturnType() {
return this.returnType;
}
@Nullable
public Object getBean() {
return this.bean;
}
@Nullable
public Method getMethod() {
return this.method;
}
@Override
public String toString() {
return "InvocationResult [returnValue=" + this.returnValue
+ (this.sendTo != null ? ", sendTo=" + this.sendTo : "")
+ ", returnType=" + this.returnType
+ ", bean=" + this.bean
+ ", method=" + this.method
+ "]";
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\InvocationResult.java
| 1
|
请完成以下Java代码
|
public class NettyServer {
private int port;
private NettyServer(int port) {
this.port = port;
}
public static void main(String[] args) throws Exception {
int port;
if (args.length > 0) {
port = Integer.parseInt(args[0]);
} else {
port = 8080;
}
new NettyServer(port).run();
}
private void run() throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
|
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new RequestDecoder(), new ResponseDataEncoder(), new ProcessingHandler());
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync();
f.channel().closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}
}
|
repos\tutorials-master\libraries-server\src\main\java\com\baeldung\netty\NettyServer.java
| 1
|
请完成以下Java代码
|
public byte[] printToBytes() throws Exception
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
print(out);
return out.toByteArray();
}
public void print(@NonNull final OutputStream bos) throws Exception
{
final I_C_Print_Job_Instructions print_Job_Instructions = printPackage.getC_Print_Job_Instructions();
final Document document = new Document();
final PdfCopy copy = new PdfCopy(document, bos);
document.open();
final PrintablePDF printable = createPrintable();
if (printable == null)
{
return;
}
try
{
for (final I_C_Print_PackageInfo printPackageInfo : printingDAO.retrievePrintPackageInfos(printPackage))
{
final byte[] pdf = print(printPackageInfo, printable);
final PdfReader reader = new PdfReader(pdf);
for (int page = 0; page < reader.getNumberOfPages(); )
{
|
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}
document.close();
print_Job_Instructions.setErrorMsg(null);
print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Done);
InterfaceWrapperHelper.save(print_Job_Instructions);
}
catch (final Exception e)
{
print_Job_Instructions.setErrorMsg(e.getLocalizedMessage());
print_Job_Instructions.setStatus(X_C_Print_Job_Instructions.STATUS_Error);
InterfaceWrapperHelper.save(print_Job_Instructions);
throw new AdempiereException(e.getLocalizedMessage());
}
}
private byte[] print(@NonNull final I_C_Print_PackageInfo printPackageInfo, @NonNull final PrintablePDF printable)
{
printable.setCalX(printPackageInfo.getCalX());
printable.setCalY(printPackageInfo.getCalY());
final PrintablePDF clone = printable;
return PdfPrinter.print(printable, clone);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrintPackagePDFBuilder.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.