instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public final class JvmMetricsAutoConfiguration {
private static final String VIRTUAL_THREAD_METRICS_CLASS = "io.micrometer.java21.instrument.binder.jdk.VirtualThreadMetrics";
@Bean
@ConditionalOnMissingBean
JvmGcMetrics jvmGcMetrics() {
return new JvmGcMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmHeapPressureMetrics jvmHeapPressureMetrics() {
return new JvmHeapPressureMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmMemoryMetrics jvmMemoryMetrics() {
return new JvmMemoryMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmThreadMetrics jvmThreadMetrics() {
return new JvmThreadMetrics();
}
@Bean
@ConditionalOnMissingBean
ClassLoaderMetrics classLoaderMetrics() {
return new ClassLoaderMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmInfoMetrics jvmInfoMetrics() { | return new JvmInfoMetrics();
}
@Bean
@ConditionalOnMissingBean
JvmCompilationMetrics jvmCompilationMetrics() {
return new JvmCompilationMetrics();
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(name = VIRTUAL_THREAD_METRICS_CLASS)
static class VirtualThreadMetricsConfiguration {
@Bean
@ConditionalOnMissingBean(type = VIRTUAL_THREAD_METRICS_CLASS)
@ImportRuntimeHints(VirtualThreadMetricsRuntimeHintsRegistrar.class)
MeterBinder virtualThreadMetrics() throws ClassNotFoundException {
Class<?> virtualThreadMetricsClass = ClassUtils.forName(VIRTUAL_THREAD_METRICS_CLASS,
getClass().getClassLoader());
return (MeterBinder) BeanUtils.instantiateClass(virtualThreadMetricsClass);
}
}
static final class VirtualThreadMetricsRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.reflection()
.registerTypeIfPresent(classLoader, VIRTUAL_THREAD_METRICS_CLASS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\jvm\JvmMetricsAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setAD_Language (final java.lang.String AD_Language)
{
set_ValueNoCheck (COLUMNNAME_AD_Language, AD_Language);
}
@Override
public java.lang.String getAD_Language()
{
return get_ValueAsString(COLUMNNAME_AD_Language);
}
@Override
public void setAD_Message_ID (final int AD_Message_ID)
{
if (AD_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Message_ID, AD_Message_ID);
}
@Override
public int getAD_Message_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Message_ID);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override | public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public void setMsgText (final java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
@Override
public java.lang.String getMsgText()
{
return get_ValueAsString(COLUMNNAME_MsgText);
}
@Override
public void setMsgTip (final @Nullable java.lang.String MsgTip)
{
set_Value (COLUMNNAME_MsgTip, MsgTip);
}
@Override
public java.lang.String getMsgTip()
{
return get_ValueAsString(COLUMNNAME_MsgTip);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Message_Trl.java | 1 |
请完成以下Java代码 | public Criteria andCategoryNameNotIn(List<String> values) {
addCriterion("category_name not in", values, "categoryName");
return (Criteria) this;
}
public Criteria andCategoryNameBetween(String value1, String value2) {
addCriterion("category_name between", value1, value2, "categoryName");
return (Criteria) this;
}
public Criteria andCategoryNameNotBetween(String value1, String value2) {
addCriterion("category_name not between", value1, value2, "categoryName");
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\CmsSubjectExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult create(@RequestBody List<SmsFlashPromotionProductRelation> relationList) {
int count = relationService.create(relationList);
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 SmsFlashPromotionProductRelation relation) {
int count = relationService.update(id, relation);
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 = relationService.delete(id);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation("获取关联商品促销信息")
@RequestMapping(value = "/{id}", method = RequestMethod.GET) | @ResponseBody
public CommonResult<SmsFlashPromotionProductRelation> getItem(@PathVariable Long id) {
SmsFlashPromotionProductRelation relation = relationService.getItem(id);
return CommonResult.success(relation);
}
@ApiOperation("分页查询不同场次关联及商品信息")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<SmsFlashPromotionProduct>> list(@RequestParam(value = "flashPromotionId") Long flashPromotionId,
@RequestParam(value = "flashPromotionSessionId") Long flashPromotionSessionId,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
List<SmsFlashPromotionProduct> flashPromotionProductList = relationService.list(flashPromotionId, flashPromotionSessionId, pageSize, pageNum);
return CommonResult.success(CommonPage.restPage(flashPromotionProductList));
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\SmsFlashPromotionProductRelationController.java | 2 |
请完成以下Java代码 | public void pairCardReader(@NonNull JsonPairReaderRequest request)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("merchants", merchantCode.getAsString(), "readers")
.toUriString();
httpCall(uri, HttpMethod.POST, request, JsonPairReaderResponse.class);
}
/**
* @implSpec <a href="https://developer.sumup.com/api/readers/delete-reader">spec</a>
*/
public void deleteCardReader(@NonNull SumUpCardReaderExternalId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("merchants", merchantCode.getAsString(), "readers", id.getAsString())
.toUriString();
httpCall(uri, HttpMethod.DELETE, null, null);
}
/**
* @implSpec <a href="https://developer.sumup.com/api/readers/create-reader-checkout">spec</a>
*/
public JsonReaderCheckoutResponse cardReaderCheckout(@NonNull final SumUpCardReaderExternalId id, @NonNull final JsonReaderCheckoutRequest request)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("merchants", merchantCode.getAsString(), "readers", id.getAsString(), "checkout")
.toUriString();
return httpCall(uri, HttpMethod.POST, request, JsonReaderCheckoutResponse.class);
}
/**
* @implSpec <a href="https://developer.sumup.com/api/transactions/get">spec</a>
*/
public JsonGetTransactionResponse getTransactionById(@NonNull final SumUpClientTransactionId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "transactions")
.queryParam("client_transaction_id", id.getAsString())
.toUriString();
final String json = httpCall(uri, HttpMethod.GET, null, String.class);
try
{
return jsonObjectMapper.readValue(json, JsonGetTransactionResponse.class) | .withJson(json);
}
catch (JsonProcessingException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
/**
* @implSpec <a href="https://developer.sumup.com/api/transactions/get">spec</a>
*/
public JsonGetTransactionResponse getTransactionById(@NonNull final SumUpTransactionExternalId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "transactions")
.queryParam("id", id.getAsString())
.toUriString();
final String json = httpCall(uri, HttpMethod.GET, null, String.class);
try
{
return jsonObjectMapper.readValue(json, JsonGetTransactionResponse.class)
.withJson(json);
}
catch (JsonProcessingException ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
public void refundTransaction(@NonNull final SumUpTransactionExternalId id)
{
final String uri = UriComponentsBuilder.fromHttpUrl(BASE_URL)
.pathSegment("me", "refund", id.getAsString())
.toUriString();
httpCall(uri, HttpMethod.POST, null, null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java\de\metas\payment\sumup\client\SumUpClient.java | 1 |
请完成以下Java代码 | public <K, V> void putMapEntry(PropertyMapKey<K, V> property, K key, V value) {
Map<K, V> map = get(property);
if (!property.allowsOverwrite() && map.containsKey(key)) {
throw new ProcessEngineException("Cannot overwrite property key " + key + ". Key already exists");
}
map.put(key, value);
if (!contains(property)) {
set(property, map);
}
}
/**
* Returns <code>true</code> if this properties contains a mapping for the specified property key.
*
* @param property
* the property key whose presence is to be tested
* @return <code>true</code> if this properties contains a mapping for the specified property key
*/
public boolean contains(PropertyKey<?> property) {
return properties.containsKey(property.getName());
}
/**
* Returns <code>true</code> if this properties contains a mapping for the specified property key.
*
* @param property
* the property key whose presence is to be tested
* @return <code>true</code> if this properties contains a mapping for the specified property key
*/
public boolean contains(PropertyListKey<?> property) {
return properties.containsKey(property.getName());
}
/**
* Returns <code>true</code> if this properties contains a mapping for the specified property key.
*
* @param property | * the property key whose presence is to be tested
* @return <code>true</code> if this properties contains a mapping for the specified property key
*/
public boolean contains(PropertyMapKey<?, ?> property) {
return properties.containsKey(property.getName());
}
/**
* Returns a map view of this properties. Changes to the map are not reflected
* to the properties.
*
* @return a map view of this properties
*/
public Map<String, Object> toMap() {
return new HashMap<String, Object>(properties);
}
@Override
public String toString() {
return "Properties [properties=" + properties + "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\Properties.java | 1 |
请完成以下Java代码 | public static void registerType(ModelBuilder modelBuilder) {
final ModelElementTypeBuilder typeBuilder =
modelBuilder
.defineType(Group.class, BPMN_ELEMENT_GROUP)
.namespaceUri(BPMN20_NS)
.extendsType(Artifact.class)
.instanceProvider(
new ModelTypeInstanceProvider<Group>() {
@Override
public Group newInstance(ModelTypeInstanceContext instanceContext) {
return new GroupImpl(instanceContext);
}
});
categoryValueRefAttribute =
typeBuilder
.stringAttribute(BPMN_ATTRIBUTE_CATEGORY_VALUE_REF)
.qNameAttributeReference(CategoryValue.class)
.build(); | typeBuilder.build();
}
@Override
public CategoryValue getCategory() {
return categoryValueRefAttribute.getReferenceTargetElement(this);
}
@Override
public void setCategory(CategoryValue categoryValue) {
categoryValueRefAttribute.setReferenceTargetElement(this, categoryValue);
}
@Override
public BpmnEdge getDiagramElement() {
return (BpmnEdge) super.getDiagramElement();
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\GroupImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Application implements InitializingBean
{
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Value("${msv3server.startup.requestAllData:false}")
private boolean requestAllDataOnStartup;
@Value("${msv3server.startup.requestConfigData:true}")
private boolean requestConfigDataOnStartup;
@Autowired
private MSV3ServerPeerService msv3ServerPeerService;
public static void main(final String[] args)
{
new SpringApplicationBuilder(Application.class)
.headless(true)
.web(WebApplicationType.SERVLET)
.run(args);
}
@Bean
public ObjectMapper jsonObjectMapper()
{
final ObjectMapper jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.findAndRegisterModules();
return jsonObjectMapper;
}
@Bean
public MSV3PeerAuthToken authTokenString(@Value("${msv3server.peer.authToken:}") final String authTokenStringValue)
{
if (authTokenStringValue == null || authTokenStringValue.trim().isEmpty())
{
// a token is needed on the receiver side, even if it's not valid
return MSV3PeerAuthToken.TOKEN_NOT_SET;
}
return MSV3PeerAuthToken.of(authTokenStringValue);
} | @Override
public void afterPropertiesSet()
{
try
{
if (requestAllDataOnStartup)
{
msv3ServerPeerService.requestAllUpdates();
}
else if (requestConfigDataOnStartup)
{
msv3ServerPeerService.requestConfigUpdates();
}
}
catch (Exception ex)
{
logger.warn("Error while requesting ALL updates. Skipped.", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\Application.java | 2 |
请完成以下Java代码 | private IQueryBuilder<I_C_OrderLine> createAllOrderLinesQuery(final I_EDI_DesadvLine desadvLine)
{
return queryBL.createQueryBuilder(I_C_OrderLine.class, desadvLine)
// .addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_EDI_DesadvLine_ID, desadvLine.getEDI_DesadvLine_ID());
}
@Override
public de.metas.handlingunits.model.I_M_ShipmentSchedule retrieveM_ShipmentScheduleOrNull(@NonNull final I_EDI_DesadvLine desadvLine)
{
final IQueryBuilder<I_C_OrderLine> orderLinesQuery = createAllOrderLinesQuery(desadvLine);
final IQueryBuilder<I_M_ShipmentSchedule> queryBuilder = orderLinesQuery
.andCollectChildren(I_M_ShipmentSchedule.COLUMN_C_OrderLine_ID, I_M_ShipmentSchedule.class);
queryBuilder.orderBy()
.addColumn(I_M_ShipmentSchedule.COLUMN_M_ShipmentSchedule_ID);
return queryBuilder.create().first(de.metas.handlingunits.model.I_M_ShipmentSchedule.class);
}
@Override
public BigDecimal retrieveMinimumSumPercentage()
{
final String minimumPercentageAccepted_Value = sysConfigBL.getValue(
SYS_CONFIG_DefaultMinimumPercentage, SYS_CONFIG_DefaultMinimumPercentage_DEFAULT);
try
{
return new BigDecimal(minimumPercentageAccepted_Value);
}
catch (final NumberFormatException e)
{
Check.errorIf(true, "AD_SysConfig {} = {} can't be parsed as a number", SYS_CONFIG_DefaultMinimumPercentage, minimumPercentageAccepted_Value);
return null; // shall not be reached
}
}
@Override
public void save(@NonNull final I_EDI_Desadv ediDesadv) | {
InterfaceWrapperHelper.save(ediDesadv);
}
@Override
public void save(@NonNull final I_EDI_DesadvLine ediDesadvLine)
{
InterfaceWrapperHelper.save(ediDesadvLine);
}
@Override
@NonNull
public List<I_M_InOut> retrieveShipmentsWithStatus(@NonNull final I_EDI_Desadv desadv, @NonNull final ImmutableSet<EDIExportStatus> statusSet)
{
return queryBL.createQueryBuilder(I_M_InOut.class, desadv)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut.COLUMNNAME_EDI_Desadv_ID, desadv.getEDI_Desadv_ID())
.addInArrayFilter(I_M_InOut.COLUMNNAME_EDI_ExportStatus, statusSet)
.create()
.list(I_M_InOut.class);
}
@Override
@NonNull
public I_M_InOut_Desadv_V getInOutDesadvByInOutId(@NonNull final InOutId shipmentId)
{
return queryBL.createQueryBuilder(I_M_InOut_Desadv_V.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_InOut_Desadv_V.COLUMNNAME_M_InOut_ID, shipmentId)
.create()
.firstOnlyNotNull(I_M_InOut_Desadv_V.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\impl\DesadvDAO.java | 1 |
请完成以下Java代码 | public void setPageFrom(final int pageFrom)
{
this.pageFrom = pageFrom;
}
public int getPageFrom()
{
if (pageFrom != null)
{
return pageFrom;
}
return initialPageFrom;
}
public void setPageTo(final int pageTo)
{
this.pageTo = pageTo;
}
public int getPageTo()
{
if (pageTo != null)
{
return pageTo;
}
return initialPageTo;
} | public boolean isPageRange()
{
return I_AD_PrinterRouting.ROUTINGTYPE_PageRange.equals(routingType);
}
public boolean isLastPages()
{
return I_AD_PrinterRouting.ROUTINGTYPE_LastPages.equals(routingType);
}
public boolean isQueuedForExternalSystems()
{
return isMatchingOutputType(OutputType.Queue)
&& printer.getExternalSystemParentConfigId() != null;
}
public boolean isMatchingOutputType(@NonNull OutputType outputType)
{
return OutputType.equals(printer.getOutputType(), outputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\printingdata\PrintingSegment.java | 1 |
请完成以下Java代码 | private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(InvoiceId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
}
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final de.metas.edi.model.I_C_Invoice invoice = ediDocOutBoundLogService.retreiveById(InvoiceId.ofRepoId(getRecord_ID()));
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(invoice.getEDI_ExportStatus()); | return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
{
final InvoiceId invoiceId = InvoiceId.ofRepoId(getRecord_ID());
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
ChangeEDI_ExportStatusHelper.C_InvoiceDoIt(invoiceId, targetExportStatus);
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_C_Invoice_SingleView.java | 1 |
请完成以下Java代码 | private InvoiceCandidatesStorage retrieveStorage(final GroupId groupId)
{
final List<I_C_Invoice_Candidate> invoiceCandidates = retrieveInvoiceCandidatesForGroupQuery(groupId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true)
.create()
.list(I_C_Invoice_Candidate.class);
return InvoiceCandidatesStorage.builder()
.groupId(groupId)
.invoiceCandidates(invoiceCandidates)
.performDatabaseChanges(true)
.build();
}
public Group createPartialGroupFromCompensationLine(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{
InvoiceCandidateCompensationGroupUtils.assertCompensationLine(invoiceCandidate);
final GroupCompensationLine compensationLine = createCompensationLine(invoiceCandidate);
final GroupRegularLine aggregatedRegularLine = GroupRegularLine.builder()
.lineNetAmt(compensationLine.getBaseAmt())
.build();
final I_C_Order order = invoiceCandidate.getC_Order();
if (order == null)
{
throw new AdempiereException("Invoice candidate has no order: " + invoiceCandidate);
}
return Group.builder()
.groupId(extractGroupId(invoiceCandidate)) | .pricePrecision(orderBL.getPricePrecision(order))
.amountPrecision(orderBL.getAmountPrecision(order))
.regularLine(aggregatedRegularLine)
.compensationLine(compensationLine)
.build();
}
public InvoiceCandidatesStorage createNotSaveableSingleOrderLineStorage(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{
return InvoiceCandidatesStorage.builder()
.groupId(extractGroupId(invoiceCandidate))
.invoiceCandidate(invoiceCandidate)
.performDatabaseChanges(false)
.build();
}
public void invalidateCompensationInvoiceCandidatesOfGroup(final GroupId groupId)
{
final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesForGroupQuery(groupId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true) // only compensation lines
.create();
invoiceCandDAO.invalidateCandsFor(query);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateGroupRepository.java | 1 |
请完成以下Java代码 | protected CComboBox<FindPanelSearchField> getEditor()
{
if (_editor == null)
{
_editor = new CComboBox<>();
_editor.setRenderer(new ToStringListCellRenderer<FindPanelSearchField>()
{
private static final long serialVersionUID = 1L;
@Override
protected String renderToString(final FindPanelSearchField value)
{
return value == null ? "" : value.getDisplayNameTrl();
}
});
_editor.enableAutoCompletion();
}
return _editor;
}
private void updateEditor(final JTable table)
{
final CComboBox<FindPanelSearchField> editor = getEditor(); | //
// Set available search fields if not already set
if (editor.getItemCount() == 0)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final Collection<FindPanelSearchField> availableSearchFields = model.getAvailableSearchFields();
if (availableSearchFields != null)
{
final List<FindPanelSearchField> availableSearchFieldsList = new ArrayList<>(availableSearchFields);
Collections.sort(availableSearchFieldsList, Comparator.comparing(FindPanelSearchField::getDisplayNameTrl));
editor.setModel(new ListComboBoxModel<FindPanelSearchField>(availableSearchFieldsList));
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindColumnNameCellEditor.java | 1 |
请完成以下Java代码 | public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public de.metas.invoicecandidate.model.I_M_ProductGroup getM_ProductGroup()
{
return get_ValueAsPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class);
}
@Override
public void setM_ProductGroup(final de.metas.invoicecandidate.model.I_M_ProductGroup M_ProductGroup)
{
set_ValueFromPO(COLUMNNAME_M_ProductGroup_ID, de.metas.invoicecandidate.model.I_M_ProductGroup.class, M_ProductGroup);
} | @Override
public void setM_ProductGroup_ID (final int M_ProductGroup_ID)
{
if (M_ProductGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_ID, M_ProductGroup_ID);
}
@Override
public int getM_ProductGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_ID);
}
@Override
public void setM_ProductGroup_Product_ID (final int M_ProductGroup_Product_ID)
{
if (M_ProductGroup_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_ProductGroup_Product_ID, M_ProductGroup_Product_ID);
}
@Override
public int getM_ProductGroup_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_ProductGroup_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_M_ProductGroup_Product.java | 1 |
请完成以下Java代码 | private static final class EncodePasswordOptionHandler extends OptionHandler {
@SuppressWarnings("NullAway.Init")
private OptionSpec<String> algorithm;
@Override
protected void options() {
this.algorithm = option(Arrays.asList("algorithm", "a"),
"The algorithm to use. Supported algorithms: "
+ StringUtils.collectionToDelimitedString(ENCODERS.keySet(), ", ")
+ ". The default algorithm uses bcrypt")
.withRequiredArg()
.defaultsTo("default");
}
@Override
protected ExitStatus run(OptionSet options) {
if (options.nonOptionArguments().size() != 1) {
Log.error("A single password option must be provided"); | return ExitStatus.ERROR;
}
String algorithm = options.valueOf(this.algorithm);
String password = (String) options.nonOptionArguments().get(0);
Supplier<PasswordEncoder> encoder = ENCODERS.get(algorithm);
if (encoder == null) {
Log.error("Unknown algorithm, valid options are: "
+ StringUtils.collectionToCommaDelimitedString(ENCODERS.keySet()));
return ExitStatus.ERROR;
}
Log.info(encoder.get().encode(password));
return ExitStatus.OK;
}
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\encodepassword\EncodePasswordCommand.java | 1 |
请完成以下Java代码 | public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getFromEmail() {
return fromEmail;
}
public void setFromEmail(String fromEmail) {
this.fromEmail = fromEmail;
}
public String getFromName() {
return fromName;
}
public void setFromName(String fromName) {
this.fromName = fromName;
} | public HydrationAlertNotification getHydrationAlertNotification() {
return hydrationAlertNotification;
}
public void setHydrationAlertNotification(HydrationAlertNotification hydrationAlertNotification) {
this.hydrationAlertNotification = hydrationAlertNotification;
}
class HydrationAlertNotification {
@NotBlank(message = "Template-id must be configured")
@Pattern(regexp = "^d-[a-f0-9]{32}$", message = "Invalid template ID format")
private String templateId;
public String getTemplateId() {
return templateId;
}
public void setTemplateId(String templateId) {
this.templateId = templateId;
}
}
} | repos\tutorials-master\saas-modules\sendgrid\src\main\java\com\baeldung\sendgrid\SendGridConfigurationProperties.java | 1 |
请完成以下Java代码 | public static File getResourceAsFile(String path) {
URL resource = getResource(path);
try {
return new File(resource.toURI());
} catch (URISyntaxException e) {
throw new ModelException("Exception while loading resource file " + path, e);
}
}
/**
* Create a new instance of the provided type
*
* @param type the class to create a new instance of
* @param parameters the parameters to pass to the constructor
* @return the created instance
*/
public static <T> T createInstance(Class<T> type, Object... parameters) { | // get types for parameters
Class<?>[] parameterTypes = new Class<?>[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Object parameter = parameters[i];
parameterTypes[i] = parameter.getClass();
}
try {
// create instance
Constructor<T> constructor = type.getConstructor(parameterTypes);
return constructor.newInstance(parameters);
} catch (Exception e) {
throw new ModelException("Exception while creating an instance of type "+type, e);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\ReflectUtil.java | 1 |
请完成以下Java代码 | public final boolean isEnabled()
{
return enabled;
}
@Override
public void setEnabled(final boolean enabled)
{
this.enabled = enabled;
}
@Override
public TrxLevel getTrxLevel()
{
return this.trxLevel;
}
@Override
public void setTrxLevel(final TrxLevel trxLevel)
{
Check.assumeNotNull(trxLevel, "trxLevel not null");
this.trxLevel = trxLevel;
}
@Override
public CacheMapType getCacheMapType()
{
return cacheMapType;
}
@Override
public void setCacheMapType(CacheMapType cacheMapType)
{
Check.assumeNotNull(cacheMapType, "cacheMapType not null");
this.cacheMapType = cacheMapType;
}
@Override
public int getInitialCapacity()
{
return initialCapacity; | }
@Override
public void setInitialCapacity(int initalCapacity)
{
Check.assume(initalCapacity > 0, "initialCapacity > 0");
this.initialCapacity = initalCapacity;
}
@Override
public int getMaxCapacity()
{
return maxCapacity;
}
@Override
public void setMaxCapacity(int maxCapacity)
{
this.maxCapacity = maxCapacity;
}
@Override
public int getExpireMinutes()
{
return expireMinutes;
}
@Override
public void setExpireMinutes(int expireMinutes)
{
this.expireMinutes = expireMinutes > 0 ? expireMinutes : EXPIREMINUTES_Never;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\MutableTableCacheConfig.java | 1 |
请完成以下Java代码 | public final void doUpdateAfterFirstPass(
final Properties ctx,
final IShipmentSchedulesDuringUpdate candidates)
{
purgeLinesOK(ctx, candidates);
}
/**
* Removes all inOutLines (and afterwards also empty inOuts) that have {@link CompleteStatus#OK} <b>and</b>
* {@link PostageFreeStatus#OK}
*/
private void purgeLinesOK(final Properties ctx, final IShipmentSchedulesDuringUpdate candidates)
{
for (final DeliveryGroupCandidate groupCandidate : candidates.getCandidates())
{
for (final DeliveryLineCandidate lineCandidate : groupCandidate.getLines())
{
try (final MDCCloseable mdcClosable = ShipmentSchedulesMDC.putShipmentScheduleId(lineCandidate.getShipmentScheduleId()))
{
// check the complete and postage free status
final CompleteStatus completeStatus = lineCandidate.getCompleteStatus();
if (!CompleteStatus.OK.equals(completeStatus))
{
logger.debug("Discard lineCandidate because completeStatus={}", completeStatus);
lineCandidate.setDiscarded();
}
//
//
final IProductBL productBL = Services.get(IProductBL.class);
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
// task 08745: by default we don't allow this, to stay backwards compatible
final boolean allowShipSingleNonItems = sysConfigBL.getBooleanValue(AD_SYSCONFIG_DE_METAS_INOUTCANDIDATE_ALLOW_SHIP_SINGLE_NON_ITEMS, false);
final boolean isItemProduct = productBL.getProductType(ProductId.ofRepoId(lineCandidate.getProductId())).isItem();
if (!allowShipSingleNonItems && !isItemProduct)
{ | // allowShipSingleNonItems was true, we wouldn't have to care.
// product is not an item -> check if there if there would
// also be an item on the same inOut
boolean inOutContainsItem = false;
for (final DeliveryLineCandidate searchIol : groupCandidate.getLines())
{
if (productBL.getProductType(ProductId.ofRepoId(searchIol.getProductId())).isItem())
{
inOutContainsItem = true;
break;
}
}
if (!inOutContainsItem)
{
// check if the delivery of this non-item has been
// enforced using QtyToDeliver_Override>0
final BigDecimal qtyToDeliverOverride = lineCandidate.getQtyToDeliverOverride();
if (qtyToDeliverOverride == null || qtyToDeliverOverride.signum() <= 0)
{
logger.debug("Discard lineCandidate because its groupCandidate contains no 'item' products and qtyToDeliverOverride is not set");
lineCandidate.setDiscarded();
candidates.addStatusInfo(lineCandidate, Services.get(IMsgBL.class).getMsg(ctx, MSG_NO_ITEM_TO_SHIP));
}
}
}
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\DefaultCandidateProcessor.java | 1 |
请完成以下Java代码 | public void handleMemberDeparted(MemberDepartedEvent event) { }
/**
* @inheritDoc
*/
@Override
public final void memberJoined(DistributionManager manager, InternalDistributedMember member) {
MemberJoinedEvent event = new MemberJoinedEvent(manager)
.withMember(member);
handleMemberJoined(event);
}
public void handleMemberJoined(MemberJoinedEvent event) { }
/**
* @inheritDoc
*/
@Override
public final void memberSuspect(DistributionManager manager, InternalDistributedMember member,
InternalDistributedMember suspectMember, String reason) {
MemberSuspectEvent event = new MemberSuspectEvent(manager)
.withMember(member)
.withReason(reason)
.withSuspect(suspectMember);
handleMemberSuspect(event);
}
public void handleMemberSuspect(MemberSuspectEvent event) { }
/**
* @inheritDoc | */
@Override
public final void quorumLost(DistributionManager manager, Set<InternalDistributedMember> failedMembers,
List<InternalDistributedMember> remainingMembers) {
QuorumLostEvent event = new QuorumLostEvent(manager)
.withFailedMembers(failedMembers)
.withRemainingMembers(remainingMembers);
handleQuorumLost(event);
}
public void handleQuorumLost(QuorumLostEvent event) { }
/**
* Registers this {@link MembershipListener} with the given {@literal peer} {@link Cache}.
*
* @param peerCache {@literal peer} {@link Cache} on which to register this {@link MembershipListener}.
* @return this {@link MembershipListenerAdapter}.
* @see org.apache.geode.cache.Cache
*/
@SuppressWarnings("unchecked")
public T register(Cache peerCache) {
Optional.ofNullable(peerCache)
.map(Cache::getDistributedSystem)
.filter(InternalDistributedSystem.class::isInstance)
.map(InternalDistributedSystem.class::cast)
.map(InternalDistributedSystem::getDistributionManager)
.ifPresent(distributionManager -> distributionManager
.addMembershipListener(this));
return (T) this;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipListenerAdapter.java | 1 |
请完成以下Java代码 | public Date getDateAfter() {
return getDateAfter(null);
}
public Date getDateAfter(Date date) {
if (isRepeat) {
return getDateAfterRepeat(date == null ? ClockUtil.getCurrentTime() : date);
}
//TODO: is this correct?
if (end != null) {
return end;
}
return add(start, period);
}
public int getTimes() {
return times;
}
public boolean isRepeat() {
return isRepeat;
}
private Date getDateAfterRepeat(Date date) {
// use date without the current offset for due date calculation to get the
// next due date as it would be without any modifications, later add offset
Date dateWithoutOffset = new Date(date.getTime() - repeatOffset);
if (start != null) {
Date cur = start;
for (int i = 0; i < times && !cur.after(dateWithoutOffset); i++) {
cur = add(cur, period);
}
if (cur.before(dateWithoutOffset)) {
return null;
}
// add offset to calculated due date
return repeatOffset == 0L ? cur : new Date(cur.getTime() + repeatOffset);
}
Date cur = add(end, period.negate());
Date next = end; | for (int i=0;i<times && cur.after(date);i++) {
next = cur;
cur = add(cur, period.negate());
}
return next.before(date) ? null : next;
}
private Date add(Date date, Duration duration) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
duration.addTo(calendar);
return calendar.getTime();
}
private Duration parsePeriod(String period) {
if (period.matches(PnW_PATTERN)) {
return parsePnWDuration(period);
}
return datatypeFactory.newDuration(period);
}
private Duration parsePnWDuration(String period) {
String weeks = period.replaceAll("\\D", "");
long duration = Long.parseLong(weeks) * MS_PER_WEEK;
return datatypeFactory.newDuration(duration);
}
private boolean isDuration(String time) {
return time.startsWith("P");
}
public void setRepeatOffset(long repeatOffset) {
this.repeatOffset = repeatOffset;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\calendar\DurationHelper.java | 1 |
请完成以下Java代码 | private static ManufacturingOrderExportAuditItem createExportErrorAuditItem(final I_PP_Order order, final AdIssueId adIssueId)
{
return ManufacturingOrderExportAuditItem.builder()
.orderId(PPOrderId.ofRepoId(order.getPP_Order_ID()))
.orgId(OrgId.ofRepoIdOrAny(order.getAD_Org_ID()))
.exportStatus(APIExportStatus.ExportError)
.issueId(adIssueId)
.build();
}
private AdIssueId createAdIssueId(final Throwable ex)
{
return errorManager.createIssue(IssueCreateRequest.builder()
.throwable(ex)
.loggerName(logger.getName())
.sourceClassname(ManufacturingOrderAPIService.class.getName())
.summary(ex.getMessage())
.build());
}
private List<I_PP_Order_BOMLine> getBOMLinesByOrderId(final PPOrderId orderId)
{
return getBOMLinesByOrderId().get(orderId);
}
private ImmutableListMultimap<PPOrderId, I_PP_Order_BOMLine> getBOMLinesByOrderId()
{
if (_bomLinesByOrderId != null)
{
return _bomLinesByOrderId;
}
final ImmutableSet<PPOrderId> orderIds = getOrders()
.stream()
.map(order -> PPOrderId.ofRepoId(order.getPP_Order_ID()))
.collect(ImmutableSet.toImmutableSet());
_bomLinesByOrderId = ppOrderBOMDAO.retrieveOrderBOMLines(orderIds, I_PP_Order_BOMLine.class)
.stream()
.collect(ImmutableListMultimap.toImmutableListMultimap( | bomLine -> PPOrderId.ofRepoId(bomLine.getPP_Order_ID()),
bomLine -> bomLine));
return _bomLinesByOrderId;
}
private Product getProductById(@NonNull final ProductId productId)
{
if (_productsById == null)
{
final HashSet<ProductId> allProductIds = new HashSet<>();
allProductIds.add(productId);
getOrders().stream()
.map(order -> ProductId.ofRepoId(order.getM_Product_ID()))
.forEach(allProductIds::add);
getBOMLinesByOrderId()
.values()
.stream()
.map(bomLine -> ProductId.ofRepoId(bomLine.getM_Product_ID()))
.forEach(allProductIds::add);
_productsById = productRepo.getByIds(allProductIds)
.stream()
.collect(GuavaCollectors.toHashMapByKey(Product::getId));
}
return _productsById.computeIfAbsent(productId, productRepo::getById);
}
private List<I_PP_Order> getOrders()
{
if (_orders == null)
{
_orders = ppOrderDAO.retrieveManufacturingOrders(query);
}
return _orders;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v1\ManufacturingOrdersExportCommand.java | 1 |
请完成以下Java代码 | public void setDocBaseType (final @Nullable java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
@Override
public java.lang.String getDocBaseType()
{
return get_ValueAsString(COLUMNNAME_DocBaseType);
}
@Override
public void setDocumentNo (final @Nullable java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setDR_Account (final @Nullable java.lang.String DR_Account)
{
set_Value (COLUMNNAME_DR_Account, DR_Account);
}
@Override
public java.lang.String getDR_Account()
{
return get_ValueAsString(COLUMNNAME_DR_Account);
}
@Override
public void setDueDate (final @Nullable java.sql.Timestamp DueDate)
{
set_ValueNoCheck (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{
set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public java.lang.String getIsSOTrx()
{
return get_ValueAsString(COLUMNNAME_IsSOTrx);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference); | }
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setPostingType (final @Nullable java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
@Override
public java.lang.String getPostingType()
{
return get_ValueAsString(COLUMNNAME_PostingType);
}
@Override
public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource);
}
@Override
public BigDecimal getTaxAmtSource()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATCode (final @Nullable java.lang.String VATCode)
{
set_ValueNoCheck (COLUMNNAME_VATCode, VATCode);
}
@Override
public java.lang.String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private GetTeamTimeRecordsRequest buildGetTeamTimeRecordsRequest(@NonNull final String apiKey,
@NonNull final LocalDateInterval interval)
{
return GetTeamTimeRecordsRequest.builder()
.apiKey(apiKey)
.from(interval.getStartDate())
.to(interval.getEndDate())
.build();
}
private void storeFailed(
@NonNull final TimeRecord timeRecord, @NonNull final String errorMsg, @NonNull OrgId orgId)
{
final StringBuilder errorMessage = new StringBuilder(errorMsg);
String jsonValue = null;
try
{
jsonValue = objectMapper.writeValueAsString(timeRecord);
}
catch (final JsonProcessingException e)
{
Loggables.withLogger(log, Level.ERROR)
.addLog(IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX + e.getMessage());
errorMessage.append("\n Error while trying to write TimeRecord as JSON: ").append(e.getMessage());
}
final FailedTimeBooking failedTimeBooking = FailedTimeBooking.builder()
.jsonValue(jsonValue)
.orgId(orgId)
.externalId(timeRecord.getId())
.externalSystem(externalSystemRepository.getByType(ExternalSystemType.Everhour))
.errorMsg(errorMessage.toString())
.build();
failedTimeBookingRepository.save(failedTimeBooking);
}
private void importFailedTimeBookings()
{
Loggables.withLogger(log, Level.DEBUG).addLog(" {} start importing failed time bookings",
IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX);
final Stopwatch stopWatch = Stopwatch.createStarted();
final ImmutableList<FailedTimeBooking> failedTimeBookings = failedTimeBookingRepository.listBySystem(externalSystemRepository.getByType(ExternalSystemType.Everhour));
for (FailedTimeBooking failedTimeBooking : failedTimeBookings) | {
if (Check.isBlank(failedTimeBooking.getJsonValue()))
{
continue;
}
importTimeBooking(getTimeRecordFromFailed(failedTimeBooking), failedTimeBooking.getOrgId());
}
Loggables.withLogger(log, Level.DEBUG).addLog(" {} finished importing failed time bookings! elapsed time: {}",
IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX, stopWatch);
}
private TimeRecord getTimeRecordFromFailed(@NonNull final FailedTimeBooking failedTimeBooking)
{
try
{
return objectMapper.readValue(failedTimeBooking.getJsonValue(), TimeRecord.class);
}
catch (final Exception e)
{
throw new AdempiereException("Failed to read value from failed time booking!")
.appendParametersToMessage()
.setParameter("failedTimeBooking.getJsonValue()", failedTimeBooking.getJsonValue());
}
}
private void acquireLock()
{
final boolean lockAcquired = lock.tryLock();
if (!lockAcquired)
{
throw new AdempiereException("The import is already running!");
}
log.debug(" {} EverhourImporterService: lock acquired, starting the import!", IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX);
}
private void releaseLock()
{
lock.unlock();
log.debug(" {} EverhourImporterService: lock released!", IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\everhour\EverhourImporterService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setUserId(String userId) {
this.userId = userId;
}
@Override
public void setData(String data) {
this.data = data;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
@Override
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getIdPrefix() {
// id prefix is empty because sequence is used instead of id prefix
return "";
}
@Override
public void setLogNumber(long logNumber) {
this.logNumber = logNumber;
}
@Override
public long getLogNumber() {
return logNumber;
}
@Override
public String getType() {
return type;
}
@Override
public String getTaskId() {
return taskId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override | public String getUserId() {
return userId;
}
@Override
public String getData() {
return data;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public String getProcessInstanceId() {
return processInstanceId;
}
@Override
public String getProcessDefinitionId() {
return processDefinitionId;
}
@Override
public String getScopeId() {
return scopeId;
}
@Override
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String toString() {
return this.getClass().getName() + "(" + logNumber + ", " + getTaskId() + ", " + type +")";
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\HistoricTaskLogEntryEntityImpl.java | 2 |
请完成以下Java代码 | public void trace(@RequestBody final JsonUITraceEventsRequest request)
{
traceService.create(toUITraceEventCreateRequest(request));
}
private static List<UITraceEventCreateRequest> toUITraceEventCreateRequest(final JsonUITraceEventsRequest request)
{
return request.getEvents()
.stream()
.map(UITraceRestController::toUITraceEventCreateRequest)
.collect(Collectors.toList());
}
private static UITraceEventCreateRequest toUITraceEventCreateRequest(final JsonUITraceEvent json)
{ | return UITraceEventCreateRequest.builder()
.id(UITraceExternalId.ofString(json.getId()))
.eventName(json.getEventName())
.timestamp(json.getTimestamp() > 0 ? Instant.ofEpochMilli(json.getTimestamp()) : SystemTime.asInstant())
.url(json.getUrl().orElse(null))
.username(json.getUsername().orElse(null))
.caption(json.getCaption().orElse(null))
.applicationId(json.getApplicationId().orElse(null))
.deviceId(json.getDeviceId().orElse(null))
.tabId(json.getTabId().orElse(null))
.userAgent(json.getUserAgent().orElse(null))
.properties(json.getProperties())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\UITraceRestController.java | 1 |
请完成以下Java代码 | public class SideActionsGroupsListModel implements ISideActionsGroupsListModel
{
private final DefaultListModel<ISideActionsGroupModel> groups = new DefaultListModel<>();
private final Map<String, ISideActionsGroupModel> groupId2group = new HashMap<>();
public SideActionsGroupsListModel()
{
super();
}
@Override
public void addGroup(final ISideActionsGroupModel group)
{
Check.assumeNotNull(group, "group not null");
final String groupId = group.getId();
this.groups.addElement(group);
this.groupId2group.put(groupId, group);
}
@Override
public ListModel<ISideActionsGroupModel> getGroups() | {
return this.groups;
}
@Override
public ISideActionsGroupModel getGroupByIdOrNull(final String id)
{
return groupId2group.get(id);
}
@Override
public final ISideActionsGroupModel getGroupById(final String id)
{
final ISideActionsGroupModel group = getGroupByIdOrNull(id);
Check.assumeNotNull(group, "group shall exist for ID={}", id);
return group;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\sideactions\model\SideActionsGroupsListModel.java | 1 |
请完成以下Java代码 | public boolean isEmpty() {
return this.services.isEmpty();
}
/**
* Specify if this container has a service customization with the specified
* {@code name}.
* @param name the name of a service
* @return {@code true} if a customization for a service with the specified
* {@code name} exists
*/
public boolean has(String name) {
return this.services.containsKey(name);
}
/**
* Return the {@link ComposeService services} to customize.
* @return the compose services
*/
public Stream<ComposeService> values() {
return this.services.values().stream().map(Builder::build);
}
/**
* Add a {@link ComposeService} with the specified name and {@link Consumer} to
* customize the object. If the service has already been added, the consumer can be | * used to further tune the existing service configuration.
* @param name the name of the service
* @param service a {@link Consumer} to customize the {@link ComposeService}
*/
public void add(String name, Consumer<Builder> service) {
service.accept(this.services.computeIfAbsent(name, Builder::new));
}
/**
* Remove the service with the specified {@code name}.
* @param name the name of the service
* @return {@code true} if such a service was registered, {@code false} otherwise
*/
public boolean remove(String name) {
return this.services.remove(name) != null;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeServiceContainer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ReportResult exportAsExcel(final JasperPrint jasperPrint) throws JRException
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
final MetasJRXlsExporter exporter = new MetasJRXlsExporter();
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, out); // Output
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); // Input
// Make sure our cells will be locked by default
// and assume that cells which shall not be locked are particularly specified.
jasperPrint.setProperty(XlsReportConfiguration.PROPERTY_CELL_LOCKED, "true");
// there are cases when we don't want the cells to be blocked by password
// in those cases we put in jrxml the password property with empty value, which will indicate we don't want password
// if there is no such property we take default password. If empty we set no password and if set, we use that password from the report
//noinspection StatementWithEmptyBody
if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD) == null)
{
// do nothing; | }
else if (jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD).isEmpty())
{
exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, null);
}
else
{
exporter.setParameter(JRXlsAbstractExporterParameter.PASSWORD, jasperPrint.getProperty(XlsReportConfiguration.PROPERTY_PASSWORD));
}
exporter.exportReport();
return ReportResult.builder()
.outputType(OutputType.XLS)
.reportContentBase64(Util.encodeBase64(out.toByteArray()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\JasperEngine.java | 2 |
请完成以下Java代码 | public void springBeanPointcut() {
//method is empty as this is just a Pointcut, the implementations are in the advices.
}
//https://www.javaguides.net/p/spring-boot-tutorial.html
/***
* PointCut that matches all Spring beans in the application's main packages.
* */
@Pointcut("within(spring.aop.aspect..*)" +
"|| within(spring.aop.aspect.service..*)" +
"|| within( spring.aop.aspect.controller..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a pointcut, the implementations are the advices.
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
log.error("Exception in {}.{} with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL");
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/ | @Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if(log.isDebugEnabled()) {
log.debug("Enter : {}.{} with argument[s] = {}", joinPoint.getSignature().getDeclaringType(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if(log.isDebugEnabled()) {
log.debug("Exit: {}.{} () with result ={}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalAccessError e){
log.error("Illegal argument: {} in {}.{} ()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
} | repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\Aspect Oriented Programming\SpringAspectOrinentProgram\src\main\java\spring\aop\aspect\LoggingAspect.java | 1 |
请完成以下Java代码 | public ImmutableSet<UserDashboardItemId> getItemIds(final DashboardWidgetType dashboardWidgetType)
{
return getItemsById(dashboardWidgetType).keySet();
}
public Collection<UserDashboardItem> getItems(final DashboardWidgetType dashboardWidgetType)
{
return getItemsById(dashboardWidgetType).values();
}
public UserDashboardItem getItemById(
@NonNull final DashboardWidgetType dashboardWidgetType,
@NonNull final UserDashboardItemId itemId)
{
final UserDashboardItem item = getItemsById(dashboardWidgetType).get(itemId); | if (item == null)
{
throw new EntityNotFoundException("No " + dashboardWidgetType + " item found")
.setParameter("itemId", itemId);
}
return item;
}
public void assertItemIdExists(
@NonNull final DashboardWidgetType dashboardWidgetType,
@NonNull final UserDashboardItemId itemId)
{
getItemById(dashboardWidgetType, itemId); // will fail if itemId does not exist
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\UserDashboard.java | 1 |
请完成以下Java代码 | public class ReferentialTransparency {
private static Logger logger = Logger.getGlobal();
public void main() {
String data = new SimpleData().setData("Baeldung")
.getData();
logger.log(Level.INFO, new SimpleData().setData("Baeldung")
.getData());
logger.log(Level.INFO, data);
logger.log(Level.INFO, "Baeldung");
}
public class SimpleData {
private Logger logger = Logger.getGlobal(); | private String data;
public String getData() {
logger.log(Level.INFO, "Get data called for SimpleData");
return data;
}
public SimpleData setData(String data) {
logger.log(Level.INFO, "Set data called for SimpleData");
this.data = data;
return this;
}
}
} | repos\tutorials-master\core-java-modules\core-java-functional\src\main\java\com\baeldung\functional\ReferentialTransparency.java | 1 |
请完成以下Java代码 | public void componentMoved(ComponentEvent e)
{
}
@Override
public void componentResized(ComponentEvent e)
{
}
@Override
public void componentShown(ComponentEvent e)
{
}
@Override
public void windowActivated(WindowEvent e)
{
}
@Override
public void windowClosed(WindowEvent e)
{
Window w = e.getWindow();
if (w instanceof Window)
{
w.removeComponentListener(this);
w.removeWindowListener(this);
windowManager.remove(w);
}
} | @Override
public void windowClosing(WindowEvent e)
{
}
@Override
public void windowDeactivated(WindowEvent e)
{
}
@Override
public void windowDeiconified(WindowEvent e)
{
}
@Override
public void windowIconified(WindowEvent e)
{
}
@Override
public void windowOpened(WindowEvent e)
{
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\WindowManager.java | 1 |
请完成以下Java代码 | public int length()
{
return e - b;
}
@Override
public char charAt(int index)
{
return value[b + index];
}
@Override
public CharSequence subSequence(int start, int end)
{
return new SString(value, b + start, b + end);
}
@Override
public String toString()
{
return new String(value, b, e - b);
}
@Override
public int compareTo(SString anotherString)
{
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim)
{
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2)
{
return c1 - c2;
}
k++;
}
return len1 - len2; | }
public char[] toCharArray()
{
return Arrays.copyOfRange(value, b, e);
}
public static SString valueOf(char word)
{
SString s = new SString(new char[]{word}, 0, 1);
return s;
}
public SString add(SString other)
{
char[] value = new char[length() + other.length()];
System.arraycopy(this.value, b, value, 0, length());
System.arraycopy(other.value, other.b, value, length(), other.length());
b = 0;
e = length() + other.length();
this.value = value;
return this;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\sequence\SString.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderStateTimeEntity implements Serializable{
/** 订单ID */
private String orderId;
/** 订单状态 */
private OrderStateEnum orderStateEnum;
/** 时间 */
private Timestamp time;
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public OrderStateEnum getOrderStateEnum() {
return orderStateEnum;
}
public void setOrderStateEnum(OrderStateEnum orderStateEnum) {
this.orderStateEnum = orderStateEnum;
}
public Timestamp getTime() { | return time;
}
public void setTime(Timestamp time) {
this.time = time;
}
@Override
public String toString() {
return "OrderStateTimeEntity{" +
"orderId='" + orderId + '\'' +
", orderStateEnum=" + orderStateEnum +
", time=" + time +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrderStateTimeEntity.java | 2 |
请完成以下Java代码 | public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setReconciledBy_SAP_GLJournal_ID (final int ReconciledBy_SAP_GLJournal_ID)
{
if (ReconciledBy_SAP_GLJournal_ID < 1)
set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, null);
else
set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournal_ID, ReconciledBy_SAP_GLJournal_ID);
}
@Override
public int getReconciledBy_SAP_GLJournal_ID()
{
return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournal_ID);
}
@Override
public void setReconciledBy_SAP_GLJournalLine_ID (final int ReconciledBy_SAP_GLJournalLine_ID)
{
if (ReconciledBy_SAP_GLJournalLine_ID < 1)
set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, null);
else
set_Value (COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID, ReconciledBy_SAP_GLJournalLine_ID);
}
@Override
public int getReconciledBy_SAP_GLJournalLine_ID()
{
return get_ValueAsInt(COLUMNNAME_ReconciledBy_SAP_GLJournalLine_ID);
}
@Override
public void setReferenceNo (final @Nullable java.lang.String ReferenceNo)
{
set_Value (COLUMNNAME_ReferenceNo, ReferenceNo);
}
@Override
public java.lang.String getReferenceNo()
{
return get_ValueAsString(COLUMNNAME_ReferenceNo);
}
@Override
public void setStatementLineDate (final java.sql.Timestamp StatementLineDate)
{
set_Value (COLUMNNAME_StatementLineDate, StatementLineDate);
}
@Override
public java.sql.Timestamp getStatementLineDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StatementLineDate);
} | @Override
public void setStmtAmt (final BigDecimal StmtAmt)
{
set_Value (COLUMNNAME_StmtAmt, StmtAmt);
}
@Override
public BigDecimal getStmtAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StmtAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setTrxAmt (final BigDecimal TrxAmt)
{
set_Value (COLUMNNAME_TrxAmt, TrxAmt);
}
@Override
public BigDecimal getTrxAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TrxAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValutaDate (final java.sql.Timestamp ValutaDate)
{
set_Value (COLUMNNAME_ValutaDate, ValutaDate);
}
@Override
public java.sql.Timestamp getValutaDate()
{
return get_ValueAsTimestamp(COLUMNNAME_ValutaDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementLine.java | 1 |
请完成以下Java代码 | public class CopyFromBOM extends JavaProcess
{
private final IProductBOMDAO productBOMsRepo = Services.get(IProductBOMDAO.class);
private int toProductBOMId = 0;
private int fromProductBOMId = 0;
/**
* Prepare - e.g., get Parameters.
*/
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParameters())
{
final String name = para.getParameterName();
if (para.getParameter() == null)
{
;
}
else if (name.equals("PP_Product_BOM_ID"))
{
fromProductBOMId = para.getParameterAsInt();
}
else
{
log.error("prepare - Unknown Parameter: " + name);
}
}
toProductBOMId = getRecord_ID();
} // prepare
@Override
protected String doIt() | {
log.info("From PP_Product_BOM_ID=" + fromProductBOMId + " to " + toProductBOMId);
if (toProductBOMId == 0)
{
throw new AdempiereException("Target PP_Product_BOM_ID == 0");
}
if (fromProductBOMId == 0)
{
throw new AdempiereException("Source PP_Product_BOM_ID == 0");
}
if (toProductBOMId == fromProductBOMId)
{
return MSG_OK;
}
final I_PP_Product_BOM fromBom = productBOMsRepo.getById(fromProductBOMId);
final I_PP_Product_BOM toBOM = productBOMsRepo.getById(toProductBOMId);
if (!productBOMsRepo.retrieveLines(toBOM).isEmpty())
{
throw new AdempiereException("@Error@ Existing BOM Line(s)");
}
for (final I_PP_Product_BOMLine fromBOMLine : productBOMsRepo.retrieveLines(fromBom))
{
final I_PP_Product_BOMLine toBOMLine = InterfaceWrapperHelper.copy()
.setFrom(fromBOMLine)
.copyToNew(I_PP_Product_BOMLine.class);
toBOMLine.setPP_Product_BOM_ID(toBOM.getPP_Product_BOM_ID());
InterfaceWrapperHelper.saveRecord(toBOMLine);
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\process\CopyFromBOM.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultVariableTypes implements VariableTypes, Serializable {
private static final long serialVersionUID = 1L;
private final List<VariableType> typesList = new ArrayList<>();
private final Map<String, VariableType> typesMap = new HashMap<>();
@Override
public DefaultVariableTypes addType(VariableType type) {
return addType(type, typesList.size());
}
@Override
public DefaultVariableTypes addType(VariableType type, int index) {
typesList.add(index, type);
typesMap.put(type.getTypeName(), type);
return this;
}
public void setTypesList(List<VariableType> typesList) {
this.typesList.clear();
this.typesList.addAll(typesList);
this.typesMap.clear();
for (VariableType type : typesList) {
typesMap.put(type.getTypeName(), type);
}
}
@Override
public VariableType getVariableType(String typeName) {
return typesMap.get(typeName);
}
@Override
public VariableType findVariableType(Object value) {
for (VariableType type : typesList) {
if (type.isAbleToStore(value)) {
return type;
}
}
throw new FlowableException("couldn't find a variable type that is able to serialize " + value); | }
@Override
public int getTypeIndex(VariableType type) {
return typesList.indexOf(type);
}
@Override
public int getTypeIndex(String typeName) {
VariableType type = typesMap.get(typeName);
if (type != null) {
return getTypeIndex(type);
} else {
return -1;
}
}
@Override
public VariableTypes removeType(VariableType type) {
typesList.remove(type);
typesMap.remove(type.getTypeName());
return this;
}
public int size() {
return typesList.size();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\DefaultVariableTypes.java | 2 |
请完成以下Java代码 | protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected AuthorizationManager getAuthorizationManager() {
return getSession(AuthorizationManager.class);
}
protected void configureQuery(AbstractQuery<?,?> query, Resource resource) {
getAuthorizationManager().configureQuery(query, resource);
}
protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
getAuthorizationManager().checkAuthorization(permission, resource, resourceId);
}
public boolean isAuthorizationEnabled() {
return Context.getProcessEngineConfiguration().isAuthorizationEnabled();
}
protected Authentication getCurrentAuthentication() {
return Context.getCommandContext().getAuthentication();
}
protected ResourceAuthorizationProvider getResourceAuthorizationProvider() {
return Context.getProcessEngineConfiguration()
.getResourceAuthorizationProvider();
}
protected void deleteAuthorizations(Resource resource, String resourceId) {
getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId);
}
protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId);
}
protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) { | getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId);
}
public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
if(authorization.getId() == null) {
authorizationManager.insert(authorization);
} else {
authorizationManager.update(authorization);
}
}
return null;
}
});
}
}
public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
authorizationManager.delete(authorization);
}
return null;
}
});
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public ItemControl getItemControl() {
return itemControlChild.getChild(this);
}
public void setItemControl(ItemControl itemControl) {
itemControlChild.setChild(this, itemControl);
}
public Collection<EntryCriterion> getEntryCriterions() {
return entryCriterionCollection.get(this);
}
public Collection<ExitCriterion> getExitCriterions() {
return exitCriterionCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DiscretionaryItem.class, CMMN_ELEMENT_DISCRETIONARY_ITEM)
.namespaceUri(CMMN11_NS)
.extendsType(TableItem.class)
.instanceProvider(new ModelTypeInstanceProvider<DiscretionaryItem>() {
public DiscretionaryItem newInstance(ModelTypeInstanceContext instanceContext) {
return new DiscretionaryItemImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
definitionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DEFINITION_REF) | .idAttributeReference(PlanItemDefinition.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
itemControlChild = sequenceBuilder.element(ItemControl.class)
.build();
entryCriterionCollection = sequenceBuilder.elementCollection(EntryCriterion.class)
.build();
exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DiscretionaryItemImpl.java | 1 |
请完成以下Java代码 | public class RelationsRepo {
private final ConcurrentMap<UUID, Set<RelationInfo>> fromRelations = new ConcurrentHashMap<>();
private final ConcurrentMap<UUID, Set<RelationInfo>> toRelations = new ConcurrentHashMap<>();
public boolean add(EntityData<?> from, EntityData<?> to, String type) {
boolean addedFromRelation = fromRelations.computeIfAbsent(from.getId(), k -> ConcurrentHashMap.newKeySet()).add(new RelationInfo(type, to));
boolean addedToRelation = toRelations.computeIfAbsent(to.getId(), k -> ConcurrentHashMap.newKeySet()).add(new RelationInfo(type, from));
return addedFromRelation || addedToRelation;
}
public Set<RelationInfo> getFrom(UUID entityId) {
var result = fromRelations.get(entityId);
return result == null ? Collections.emptySet() : result;
}
public Set<RelationInfo> getTo(UUID entityId) {
var result = toRelations.get(entityId);
return result == null ? Collections.emptySet() : result;
} | public boolean remove(UUID from, UUID to, String type) {
boolean removedFromRelation = false;
boolean removedToRelation = false;
Set<RelationInfo> fromRelations = this.fromRelations.get(from);
if (fromRelations != null) {
removedFromRelation = fromRelations.removeIf(relationInfo -> relationInfo.getTarget().getId().equals(to) && relationInfo.getType().equals(type));
}
Set<RelationInfo> toRelations = this.toRelations.get(to);
if (toRelations != null) {
removedToRelation = toRelations.removeIf(relationInfo -> relationInfo.getTarget().getId().equals(from) && relationInfo.getType().equals(type));
}
return removedFromRelation || removedToRelation;
}
} | repos\thingsboard-master\common\edqs\src\main\java\org\thingsboard\server\edqs\data\RelationsRepo.java | 1 |
请完成以下Java代码 | public final void onStartup(ServletContext servletContext) throws ServletException {
String description = getDescription();
if (!isEnabled()) {
logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
return;
}
register(description, servletContext);
}
/**
* Return a description of the registration. For example "Servlet resourceServlet"
* @return a description of the registration
*/
protected abstract String getDescription();
/**
* Register this bean with the servlet context.
* @param description a description of the item being registered
* @param servletContext the servlet context
*/
protected abstract void register(String description, ServletContext servletContext);
/**
* Flag to indicate that the registration is enabled.
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* Return if the registration is enabled.
* @return if enabled (default {@code true})
*/
public boolean isEnabled() {
return this.enabled;
} | /**
* Set the order of the registration bean.
* @param order the order
*/
public void setOrder(int order) {
this.order = order;
}
/**
* Get the order of the registration bean.
* @return the order
*/
@Override
public int getOrder() {
return this.order;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\RegistrationBean.java | 1 |
请完成以下Java代码 | public LookupValuesList getM_HU_PI_Item_Products()
{
return getPackingInfoParams().getM_HU_PI_Item_Products();
}
/**
* For the currently selected pip this method loads att
*/
@ProcessParamLookupValuesProvider(parameterName = PackingInfoProcessParams.PARAM_M_HU_PI_Item_ID, dependsOn = PackingInfoProcessParams.PARAM_M_HU_PI_Item_Product_ID, numericKey = true, lookupTableName = I_M_HU_PI_Item.Table_Name)
public LookupValuesList getM_HU_PI_Item_IDs()
{
return getPackingInfoParams().getM_HU_PI_Item_IDs(p_M_HU_PI_Item_Product);
}
@Override
@RunOutOfTrx
protected String doIt()
{
final IPPOrderReceiptHUProducer producer = newReceiptCandidatesProducer()
.bestBeforeDate(computeBestBeforeDate());
if (isReceiveIndividualCUs)
{
producer.withPPOrderLocatorId()
.receiveIndividualPlanningCUs(getIndividualCUsCount());
}
else
{
producer.packUsingLUTUConfiguration(getPackingInfoParams().createAndSaveNewLUTUConfig())
.createDraftReceiptCandidatesAndPlanningHUs();
}
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
// Invalidate the view because for sure we have changes
final PPOrderLinesView ppOrderLinesView = getView();
ppOrderLinesView.invalidateAll();
getViewsRepo().notifyRecordsChangedAsync(I_PP_Order.Table_Name, ppOrderLinesView.getPpOrderId().getRepoId());
}
@Nullable
LocalDate computeBestBeforeDate()
{
if (attributesBL.isAutomaticallySetBestBeforeDate())
{
final PPOrderLineRow row = getSingleSelectedRow();
final int guaranteeDaysMin = productDAO.getProductGuaranteeDaysMinFallbackProductCategory(row.getProductId());
if (guaranteeDaysMin <= 0)
{
return null;
} | final I_PP_Order ppOrderPO = huPPOrderBL.getById(row.getOrderId());
final LocalDate datePromised = TimeUtil.asLocalDate(ppOrderPO.getDatePromised());
return datePromised.plusDays(guaranteeDaysMin);
}
else
{
return null;
}
}
private IPPOrderReceiptHUProducer newReceiptCandidatesProducer()
{
final PPOrderLineRow row = getSingleSelectedRow();
final PPOrderLineType type = row.getType();
if (type == PPOrderLineType.MainProduct)
{
final PPOrderId ppOrderId = row.getOrderId();
return huPPOrderBL.receivingMainProduct(ppOrderId);
}
else if (type == PPOrderLineType.BOMLine_ByCoProduct)
{
final PPOrderBOMLineId ppOrderBOMLineId = row.getOrderBOMLineId();
return huPPOrderBL.receivingByOrCoProduct(ppOrderBOMLineId);
}
else
{
throw new AdempiereException("Receiving is not allowed");
}
}
@NonNull
private Quantity getIndividualCUsCount()
{
if (p_NumberOfCUs <= 0)
{
throw new FillMandatoryException(PARAM_NumberOfCUs);
}
return Quantity.of(p_NumberOfCUs, getSingleSelectedRow().getUomNotNull());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_Receipt.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-consumer # Spring 应用名
cloud:
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
server:
port: 28080 # 服务器端口。默认为 8080
feign:
# Feign Apache HttpClient 配置项,对应 FeignHttpClientProperties 配置属性类
httpclient:
| enabled: true # 是否开启。默认为 true
max-connections: 200 # 最大连接数。默认为 200
max-connections-per-route: 50 # 每个路由的最大连接数。默认为 50。router = host + port | repos\SpringBoot-Labs-master\labx-03-spring-cloud-feign\labx-03-sc-feign-demo06A-consumer\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public class ShipperTestHelper
{
@NonNull
public static I_C_Location createLocation(@NonNull final Address pickupAddress)
{
final I_C_Location pickupFromLocation = InterfaceWrapperHelper.newInstance(I_C_Location.class);
pickupFromLocation.setAddress1(pickupAddress.getStreet1() + " " + pickupAddress.getHouseNo());
pickupFromLocation.setAddress2(pickupAddress.getStreet2());
pickupFromLocation.setPostal(pickupAddress.getZipCode());
pickupFromLocation.setCity(pickupAddress.getCity());
final I_C_Country i_c_country = InterfaceWrapperHelper.newInstance(I_C_Country.class);
i_c_country.setCountryCode(pickupAddress.getCountry().getAlpha2());
InterfaceWrapperHelper.save(i_c_country);
pickupFromLocation.setC_Country(i_c_country);
return pickupFromLocation;
}
@NonNull
public static I_C_BPartner createBPartner(@NonNull final Address pickupAddress)
{
final I_C_BPartner pickupFromBPartner = InterfaceWrapperHelper.newInstance(I_C_BPartner.class);
pickupFromBPartner.setName(pickupAddress.getCompanyName1());
pickupFromBPartner.setName2(pickupAddress.getCompanyName2()); | return pickupFromBPartner;
}
public static void dumpPdfToDisk(final byte[] pdf)
{
try
{
Files.write(Paths.get("C:", "a", Instant.now().toString().replace(":", ".") + ".pdf"), pdf);
}
catch (final IOException e)
{
e.printStackTrace();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\ShipperTestHelper.java | 1 |
请完成以下Java代码 | public class SpringContextUtil implements ApplicationContextAware {
// Spring应用上下文环境
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的回调方法,设置上下文环境
*
* @param applicationContext
*/
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/ | public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取对象 这里重写了bean方法,起主要作用
*
* @param name
* @return Object 一个以所给名字注册的bean的实例
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
} | repos\roncoo-pay-master\roncoo-pay-app-reconciliation\src\main\java\com\roncoo\pay\app\reconciliation\utils\SpringContextUtil.java | 1 |
请完成以下Java代码 | public class DeleteProcessDefinitionsByKeyCmd extends AbstractDeleteProcessDefinitionCmd {
private static final long serialVersionUID = 1L;
private final String processDefinitionKey;
private final String tenantId;
private final boolean isTenantIdSet;
public DeleteProcessDefinitionsByKeyCmd(String processDefinitionKey, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings, String tenantId, boolean isTenantIdSet) {
this.processDefinitionKey = processDefinitionKey;
this.cascade = cascade;
this.skipCustomListeners = skipCustomListeners;
this.skipIoMappings = skipIoMappings;
this.tenantId = tenantId;
this.isTenantIdSet = isTenantIdSet;
}
@Override | public Void execute(CommandContext commandContext) {
ensureNotNull("processDefinitionKey", processDefinitionKey);
List<ProcessDefinition> processDefinitions = commandContext.getProcessDefinitionManager()
.findDefinitionsByKeyAndTenantId(processDefinitionKey, tenantId, isTenantIdSet);
ensureNotEmpty(NotFoundException.class, "No process definition found with key '" + processDefinitionKey + "'",
"processDefinitions", processDefinitions);
for (ProcessDefinition processDefinition: processDefinitions) {
String processDefinitionId = processDefinition.getId();
deleteProcessDefinitionCmd(commandContext, processDefinitionId, cascade, skipCustomListeners, skipIoMappings);
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteProcessDefinitionsByKeyCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DmnRuleServiceRequest {
protected String decisionKey;
protected String tenantId;
protected String parentDeploymentId;
protected List<EngineRestVariable> inputVariables;
protected boolean disableHistory;
public String getDecisionKey() {
return decisionKey;
}
public void setDecisionKey(String decisionKey) {
this.decisionKey = decisionKey;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
public List<EngineRestVariable> getInputVariables() {
return inputVariables;
}
public void setInputVariables(List<EngineRestVariable> variables) {
this.inputVariables = variables;
}
public boolean isDisableHistory() {
return disableHistory;
}
public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory;
}
} | repos\flowable-engine-main\modules\flowable-dmn-rest\src\main\java\org\flowable\dmn\rest\service\api\decision\DmnRuleServiceRequest.java | 2 |
请完成以下Java代码 | private TrxStatus getTrxStatus()
{
return trxStatus;
}
private void setTrxStatus(final TrxStatus trxStatus)
{
final String detailMsg = null;
setTrxStatus(trxStatus, detailMsg);
}
private void setTrxStatus(final TrxStatus trxStatus, @Nullable final String detailMsg)
{
final TrxStatus trxStatusOld = this.trxStatus;
this.trxStatus = trxStatus;
// Log it
if (debugLog != null)
{
final StringBuilder msg = new StringBuilder();
msg.append(trxStatusOld).append("->").append(trxStatus); | if (!Check.isEmpty(detailMsg, true))
{
msg.append(" (").append(detailMsg).append(")");
}
logTrxAction(msg.toString());
}
}
private void logTrxAction(final String message)
{
if (debugLog == null)
{
return;
}
debugLog.add(message);
logger.info("{}: trx action: {}", getTrxName(), message);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\PlainTrx.java | 1 |
请完成以下Java代码 | private static RecordAccessId extractId(final I_AD_User_Record_Access record)
{
return RecordAccessId.ofRepoId(record.getAD_User_Record_Access_ID());
}
@Nullable
public String buildUserGroupRecordAccessSqlWhereClause(
final String tableName,
@NonNull final AdTableId adTableId,
@NonNull final String keyColumnNameFQ,
@NonNull final UserId userId,
@NonNull final Set<UserGroupId> userGroupIds,
@NonNull final RoleId roleId)
{
if (!isApplyUserGroupRecordAccess(roleId, tableName))
{
return null;
}
final StringBuilder sql = new StringBuilder();
sql.append(" EXISTS (SELECT 1 FROM " + I_AD_User_Record_Access.Table_Name + " z " + " WHERE " + " z.AD_Table_ID = ").append(adTableId.getRepoId()).append(" AND z.Record_ID=").append(keyColumnNameFQ).append(" AND z.IsActive='Y'");
//
// User or User Group
sql.append(" AND (AD_User_ID=").append(userId.getRepoId());
if (!userGroupIds.isEmpty())
{
sql.append(" OR ").append(DB.buildSqlList("z.AD_UserGroup_ID", userGroupIds));
}
sql.append(")");
//
sql.append(" )"); // EXISTS
//
return sql.toString();
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean isApplyUserGroupRecordAccess(
@NonNull final RoleId roleId,
@NonNull final String tableName)
{
return configs
.getByRoleId(roleId)
.isTableHandled(tableName);
} | public boolean hasRecordPermission(
@NonNull final UserId userId,
@NonNull final RoleId roleId,
@NonNull final TableRecordReference recordRef,
@NonNull final Access permission)
{
if (!isApplyUserGroupRecordAccess(roleId, recordRef.getTableName()))
{
return true;
}
final RecordAccessQuery query = RecordAccessQuery.builder()
.recordRef(recordRef)
.permission(permission)
.principals(getPrincipals(userId))
.build();
return recordAccessRepository.query(query)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
private Set<Principal> getPrincipals(@NonNull final UserId userId)
{
final ImmutableSet.Builder<Principal> principals = ImmutableSet.builder();
principals.add(Principal.userId(userId));
for (final UserGroupId userGroupId : userGroupsRepo.getAssignedGroupIdsByUserId(userId))
{
principals.add(Principal.userGroupId(userGroupId));
}
return principals.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessService.java | 1 |
请完成以下Java代码 | private synchronized void rateLimitAsNeeded()
{
final Instant shouldBeBeforeNow = lastRequestTime.plusMillis(millisBetweenRequests);
if (shouldBeBeforeNow.isAfter(Instant.now()))
{
final long timeToSleep = Duration.between(Instant.now(), shouldBeBeforeNow).toMillis();
sleepMillis(timeToSleep);
}
}
@NonNull
private ImmutableList<GeographicalCoordinates> queryAllCoordinates(final @NonNull GeoCoordinatesRequest request)
{
final Map<String, String> parameterList = prepareParameterList(request);
//@formatter:off
final ParameterizedTypeReference<List<NominatimOSMGeographicalCoordinatesJSON>> returnType = new ParameterizedTypeReference<List<NominatimOSMGeographicalCoordinatesJSON>>(){};
//@formatter:on
final HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.USER_AGENT, "openstreetmapbot@metasfresh.com");
final HttpEntity<String> entity = new HttpEntity<>(headers);
final ResponseEntity<List<NominatimOSMGeographicalCoordinatesJSON>> exchange = restTemplate.exchange(
baseUrl + QUERY_STRING,
HttpMethod.GET,
entity,
returnType,
parameterList);
final List<NominatimOSMGeographicalCoordinatesJSON> coords = exchange.getBody();
lastRequestTime = Instant.now();
final ImmutableList<GeographicalCoordinates> result = coords.stream()
.map(NominatimOSMGeocodingProviderImpl::toGeographicalCoordinates)
.collect(GuavaCollectors.toImmutableList());
logger.debug("Got result for {}: {}", request, result);
return result;
}
@SuppressWarnings("SpellCheckingInspection")
@NonNull | private Map<String, String> prepareParameterList(final @NonNull GeoCoordinatesRequest request)
{
final String defaultEmptyValue = "";
final Map<String, String> m = new HashMap<>();
m.put("numberAndStreet", CoalesceUtil.coalesce(request.getAddress(), defaultEmptyValue));
m.put("postalcode", CoalesceUtil.coalesce(request.getPostal(), defaultEmptyValue));
m.put("city", CoalesceUtil.coalesce(request.getCity(), defaultEmptyValue));
m.put("countrycodes", request.getCountryCode2());
m.put("format", "json");
m.put("dedupe", "1");
m.put("email", "openstreetmapbot@metasfresh.com");
m.put("polygon_geojson", "0");
m.put("polygon_kml", "0");
m.put("polygon_svg", "0");
m.put("polygon_text", "0");
return m;
}
private static GeographicalCoordinates toGeographicalCoordinates(final NominatimOSMGeographicalCoordinatesJSON json)
{
return GeographicalCoordinates.builder()
.latitude(new BigDecimal(json.getLat()))
.longitude(new BigDecimal(json.getLon()))
.build();
}
private void sleepMillis(final long timeToSleep)
{
if (timeToSleep <= 0)
{
return;
}
try
{
logger.trace("Sleeping {}ms (rate limit)", timeToSleep);
TimeUnit.MILLISECONDS.sleep(timeToSleep);
}
catch (final InterruptedException e)
{
// nothing to do here
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\openstreetmap\NominatimOSMGeocodingProviderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WFActivityId implements RepoIdAware
{
@JsonCreator
public static WFActivityId ofRepoId(final int repoId)
{
return new WFActivityId(repoId);
}
public static WFActivityId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new WFActivityId(repoId) : null;
}
int repoId;
private WFActivityId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_WF_Activity_ID");
} | @JsonValue
@Override
public int getRepoId()
{
return repoId;
}
public static int toRepoId(@Nullable final WFActivityId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final WFActivityId id1, @Nullable final WFActivityId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFActivityId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CarRepositoryImpl extends BaseJinqRepositoryImpl<Car> implements CarRepository {
@Override
public Optional<Car> findByModel(String model) {
return stream().where(c -> c.getModel()
.equals(model))
.findFirst();
}
@Override
public List<Car> findByModelAndDescription(String model, String desc) {
return stream().where(c -> c.getModel()
.equals(model)
&& c.getDescription()
.contains(desc))
.toList();
}
@Override
public List<Tuple3<String, Integer, String>> findWithModelYearAndEngine() {
return stream().select(c -> new Tuple3<>(c.getModel(), c.getYear(), c.getEngine()))
.toList();
}
@Override
public Optional<Manufacturer> findManufacturerByModel(String model) {
return stream().where(c -> c.getModel()
.equals(model))
.select(c -> c.getManufacturer())
.findFirst();
}
@Override | public List<Pair<Manufacturer, Car>> findCarsPerManufacturer() {
return streamOf(Manufacturer.class).join(m -> JinqStream.from(m.getCars()))
.toList();
}
@Override
public long countCarsByModel(String model) {
return stream().where(c -> c.getModel()
.equals(model))
.count();
}
@Override
public List<Car> findAll(int skip, int limit) {
return stream().skip(skip)
.limit(limit)
.toList();
}
@Override
protected Class<Car> entityType() {
return Car.class;
}
} | repos\tutorials-master\spring-jinq\src\main\java\com\baeldung\spring\jinq\repositories\CarRepositoryImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void setOwner(TenantId tenantId, WidgetTypeDetails widgetsBundle, IdProvider idProvider) {
widgetsBundle.setTenantId(tenantId);
}
@Override
protected WidgetTypeDetails prepare(EntitiesImportCtx ctx, WidgetTypeDetails widgetTypeDetails, WidgetTypeDetails old, WidgetTypeExportData exportData, IdProvider idProvider) {
return widgetTypeDetails;
}
@Override
protected WidgetTypeDetails saveOrUpdate(EntitiesImportCtx ctx, WidgetTypeDetails widgetsBundle, WidgetTypeExportData exportData, IdProvider idProvider, CompareResult compareResult) {
return widgetTypeService.saveWidgetType(widgetsBundle);
}
@Override | protected CompareResult compare(EntitiesImportCtx ctx, WidgetTypeExportData exportData, WidgetTypeDetails prepared, WidgetTypeDetails existing) {
return new CompareResult(true);
}
@Override
protected WidgetTypeDetails deepCopy(WidgetTypeDetails widgetsBundle) {
return new WidgetTypeDetails(widgetsBundle);
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGET_TYPE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\WidgetTypeImportService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public T deserialize(@Nullable byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length == 0) {
return null;
} else {
try {
return this.objectMapper.readValue(bytes, 0, bytes.length, this.javaType);
} catch (Exception var3) {
throw new SerializationException("Could not read JSON: " + var3.getMessage(), var3);
}
}
}
public byte[] serialize(@Nullable Object t) throws SerializationException {
if (t == null) {
return new byte[0];
} else {
try {
return this.objectMapper.writeValueAsBytes(t);
} catch (Exception var3) {
throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3); | }
}
}
public void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "'objectMapper' must not be null");
this.objectMapper = objectMapper;
}
protected JavaType getJavaType(Class<?> clazz) {
return TypeFactory.defaultInstance().constructType(clazz);
}
static {
DEFAULT_CHARSET = StandardCharsets.UTF_8;
}
} | repos\springboot-demo-master\gzip\src\main\java\com\et\gzip\config\JacksonRedisSerializer.java | 2 |
请完成以下Java代码 | private boolean parseYesNo(String valueStr)
{
return StringUtils.toBoolean(valueStr, false);
}
private String normalizeNumberString(String info)
{
if (Check.isEmpty(info, true))
{
return "0";
}
final boolean hasPoint = info.indexOf('.') != -1;
boolean hasComma = info.indexOf(',') != -1;
// delete thousands
if (hasComma && decimalSeparator.isDot())
{
info = info.replace(',', ' ');
}
if (hasPoint && decimalSeparator.isComma())
{
info = info.replace('.', ' ');
}
hasComma = info.indexOf(',') != -1;
// replace decimal
if (hasComma && decimalSeparator.isComma())
{
info = info.replace(',', '.');
}
// remove everything but digits & '.' & '-'
char[] charArray = info.toCharArray(); | final StringBuilder sb = new StringBuilder();
for (char element : charArray)
{
if (Character.isDigit(element) || element == '.' || element == '-')
{
sb.append(element);
}
}
final String numberStringNormalized = sb.toString().trim();
if (numberStringNormalized.isEmpty())
{
return "0";
}
return numberStringNormalized;
}
} // ImpFormatFow | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\format\ImpFormatColumn.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getMaxConnectionPoolSize() {
return this.maxConnectionPoolSize;
}
public void setMaxConnectionPoolSize(int maxConnectionPoolSize) {
this.maxConnectionPoolSize = maxConnectionPoolSize;
}
public @Nullable Duration getIdleTimeBeforeConnectionTest() {
return this.idleTimeBeforeConnectionTest;
}
public void setIdleTimeBeforeConnectionTest(@Nullable Duration idleTimeBeforeConnectionTest) {
this.idleTimeBeforeConnectionTest = idleTimeBeforeConnectionTest;
}
public Duration getMaxConnectionLifetime() {
return this.maxConnectionLifetime;
}
public void setMaxConnectionLifetime(Duration maxConnectionLifetime) {
this.maxConnectionLifetime = maxConnectionLifetime;
}
public Duration getConnectionAcquisitionTimeout() {
return this.connectionAcquisitionTimeout;
}
public void setConnectionAcquisitionTimeout(Duration connectionAcquisitionTimeout) {
this.connectionAcquisitionTimeout = connectionAcquisitionTimeout;
}
}
public static class Security {
/**
* Whether the driver should use encrypted traffic.
*/
private boolean encrypted;
/**
* Trust strategy to use.
*/
private TrustStrategy trustStrategy = TrustStrategy.TRUST_SYSTEM_CA_SIGNED_CERTIFICATES;
/**
* Path to the file that holds the trusted certificates.
*/
private @Nullable File certFile;
/**
* Whether hostname verification is required.
*/
private boolean hostnameVerificationEnabled = true;
public boolean isEncrypted() {
return this.encrypted;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted; | }
public TrustStrategy getTrustStrategy() {
return this.trustStrategy;
}
public void setTrustStrategy(TrustStrategy trustStrategy) {
this.trustStrategy = trustStrategy;
}
public @Nullable File getCertFile() {
return this.certFile;
}
public void setCertFile(@Nullable File certFile) {
this.certFile = certFile;
}
public boolean isHostnameVerificationEnabled() {
return this.hostnameVerificationEnabled;
}
public void setHostnameVerificationEnabled(boolean hostnameVerificationEnabled) {
this.hostnameVerificationEnabled = hostnameVerificationEnabled;
}
public enum TrustStrategy {
/**
* Trust all certificates.
*/
TRUST_ALL_CERTIFICATES,
/**
* Trust certificates that are signed by a trusted certificate.
*/
TRUST_CUSTOM_CA_SIGNED_CERTIFICATES,
/**
* Trust certificates that can be verified through the local system store.
*/
TRUST_SYSTEM_CA_SIGNED_CERTIFICATES
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\autoconfigure\Neo4jProperties.java | 2 |
请完成以下Java代码 | public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public Date getLastUpdateTime() {
return lastUpdateTime;
}
@Override
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
@Override
public Integer getVersion() {
return version;
}
@Override
public void setVersion(Integer version) {
this.version = version;
}
@Override
public String getMetaInfo() {
return metaInfo;
}
@Override
public void setMetaInfo(String metaInfo) {
this.metaInfo = metaInfo;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public String getEditorSourceValueId() {
return editorSourceValueId;
}
@Override
public void setEditorSourceValueId(String editorSourceValueId) {
this.editorSourceValueId = editorSourceValueId;
} | @Override
public String getEditorSourceExtraValueId() {
return editorSourceExtraValueId;
}
@Override
public void setEditorSourceExtraValueId(String editorSourceExtraValueId) {
this.editorSourceExtraValueId = editorSourceExtraValueId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean hasEditorSource() {
return this.editorSourceValueId != null;
}
@Override
public boolean hasEditorSourceExtra() {
return this.editorSourceExtraValueId != null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ModelEntityImpl.java | 1 |
请完成以下Java代码 | private void resetLayout()
{
Point p0 = new Point(0, 0);
for (int i = 0; i < centerPanel.getComponentCount(); i++)
{
Component comp = centerPanel.getComponent(i);
comp.setLocation(p0);
}
centerPanel.validate();
} // resetLayout
/**
* Zoom to WorkFlow
*/
private void zoom()
{
if (m_WF_Window_ID == null)
{
m_WF_Window_ID = Services.get(IADTableDAO.class).retrieveWindowId(I_AD_Workflow.Table_Name).orElse(null);
}
if (m_WF_Window_ID == null)
{
throw new AdempiereException("@NotFound@ @AD_Window_ID@");
}
MQuery query = null;
if (workflowModel != null)
{
query = MQuery.getEqualQuery("AD_Workflow_ID", workflowModel.getId().getRepoId());
}
AWindow frame = new AWindow();
if (!frame.initWindow(m_WF_Window_ID, query))
{
return;
}
AEnv.addToWindowManager(frame); | AEnv.showCenterScreen(frame);
frame = null;
} // zoom
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder("WFPanel[");
if (workflowModel != null)
{
sb.append(workflowModel.getId().getRepoId());
}
sb.append("]");
return sb.toString();
} // toString
} // WFPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFPanel.java | 1 |
请完成以下Java代码 | private static long throughput(int workerCount, int iterations, long elapsed) {
return (iterations*workerCount*1000)/elapsed;
}
private static <T> T safeGet(Future<T> f) {
try {
return f.get();
}
catch(Exception ex) {
throw new RuntimeException(ex);
}
}
private static class WorkerResult {
public final long elapsed;
WorkerResult(long elapsed) {
this.elapsed = elapsed;
}
}
private static class Worker implements Callable<WorkerResult> {
private final Connection conn;
private final Channel channel;
private int iterations;
private final CountDownLatch counter;
private final String queue;
private final byte[] payload;
private long extraWork;
Worker(String queue, Connection conn, int iterations, CountDownLatch counter,int payloadSize,long extraWork) throws IOException {
this.conn = conn;
this.iterations = iterations;
this.counter = counter;
this.queue = queue;
this.extraWork = extraWork;
channel = conn.createChannel();
channel.queueDeclare(queue, false, false, true, null); | this.payload = new byte[payloadSize];
new Random().nextBytes(payload);
}
@Override
public WorkerResult call() throws Exception {
try {
long start = System.currentTimeMillis();
for ( int i = 0 ; i < iterations ; i++ ) {
channel.basicPublish("", queue, null,payload);
Thread.sleep(extraWork);
}
long elapsed = System.currentTimeMillis() - start - (extraWork*iterations);
channel.queueDelete(queue);
return new WorkerResult(elapsed);
}
finally {
counter.countDown();
}
}
}
} | repos\tutorials-master\messaging-modules\rabbitmq\src\main\java\com\baeldung\benchmark\SharedConnectionPublisher.java | 1 |
请完成以下Java代码 | protected void reconfigureBackoffLevel(JobAcquisitionContext context) {
// if for any engine, jobs could not be locked due to optimistic locking, back off
if (context.hasJobAcquisitionLockFailureOccurred()) {
numAcquisitionsWithoutLockingFailure = 0;
applyJitter = true;
if (backoffLevel < maxBackoffLevel) {
backoffLevel++;
}
}
else {
applyJitter = false;
numAcquisitionsWithoutLockingFailure++;
if (numAcquisitionsWithoutLockingFailure >= backoffDecreaseThreshold && backoffLevel > 0) {
backoffLevel--;
numAcquisitionsWithoutLockingFailure = 0;
}
}
}
protected void reconfigureNumberOfJobsToAcquire(JobAcquisitionContext context) {
// calculate the number of jobs to acquire next time
jobsToAcquire.clear();
for (Map.Entry<String, AcquiredJobs> acquiredJobsEntry : context.getAcquiredJobsByEngine().entrySet()) {
String engineName = acquiredJobsEntry.getKey();
int numJobsToAcquire = (int) (baseNumJobsToAcquire * Math.pow(backoffIncreaseFactor, backoffLevel));
List<List<String>> rejectedJobBatchesForEngine = context.getRejectedJobsByEngine().get(engineName);
if (rejectedJobBatchesForEngine != null) {
numJobsToAcquire -= rejectedJobBatchesForEngine.size();
}
numJobsToAcquire = Math.max(0, numJobsToAcquire);
jobsToAcquire.put(engineName, numJobsToAcquire);
}
}
@Override
public long getWaitTime() {
if (idleLevel > 0) {
return calculateIdleTime();
}
else if (backoffLevel > 0) {
return calculateBackoffTime();
}
else if (executionSaturated) {
return executionSaturationWaitTime;
}
else {
return 0;
}
}
protected long calculateIdleTime() {
if (idleLevel <= 0) {
return 0;
} else if (idleLevel >= maxIdleLevel) {
return maxIdleWaitTime; | }
else {
return (long) (baseIdleWaitTime * Math.pow(idleIncreaseFactor, idleLevel - 1));
}
}
protected long calculateBackoffTime() {
long backoffTime = 0;
if (backoffLevel <= 0) {
backoffTime = 0;
} else if (backoffLevel >= maxBackoffLevel) {
backoffTime = maxBackoffWaitTime;
}
else {
backoffTime = (long) (baseBackoffWaitTime * Math.pow(backoffIncreaseFactor, backoffLevel - 1));
}
if (applyJitter) {
// add a bounded random jitter to avoid multiple job acquisitions getting exactly the same
// polling interval
backoffTime += Math.random() * (backoffTime / 2);
}
return backoffTime;
}
@Override
public int getNumJobsToAcquire(String processEngine) {
Integer numJobsToAcquire = jobsToAcquire.get(processEngine);
if (numJobsToAcquire != null) {
return numJobsToAcquire;
}
else {
return baseNumJobsToAcquire;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\BackoffJobAcquisitionStrategy.java | 1 |
请完成以下Java代码 | public void setPickFrom_MovementLine(final org.compiere.model.I_M_MovementLine PickFrom_MovementLine)
{
set_ValueFromPO(COLUMNNAME_PickFrom_MovementLine_ID, org.compiere.model.I_M_MovementLine.class, PickFrom_MovementLine);
}
@Override
public void setPickFrom_MovementLine_ID (final int PickFrom_MovementLine_ID)
{
if (PickFrom_MovementLine_ID < 1)
set_Value (COLUMNNAME_PickFrom_MovementLine_ID, null);
else
set_Value (COLUMNNAME_PickFrom_MovementLine_ID, PickFrom_MovementLine_ID);
}
@Override
public int getPickFrom_MovementLine_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_MovementLine_ID);
}
@Override
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
{
if (PickFrom_Warehouse_ID < 1)
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyToPick (final BigDecimal QtyToPick)
{
set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick);
}
@Override
public BigDecimal getQtyToPick()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); | return bd != null ? bd : BigDecimal.ZERO;
}
/**
* RejectReason AD_Reference_ID=541422
* Reference name: QtyNotPicked RejectReason
*/
public static final int REJECTREASON_AD_Reference_ID=541422;
/** NotFound = N */
public static final String REJECTREASON_NotFound = "N";
/** Damaged = D */
public static final String REJECTREASON_Damaged = "D";
@Override
public void setRejectReason (final @Nullable java.lang.String RejectReason)
{
set_Value (COLUMNNAME_RejectReason, RejectReason);
}
@Override
public java.lang.String getRejectReason()
{
return get_ValueAsString(COLUMNNAME_RejectReason);
}
/**
* Status AD_Reference_ID=541435
* Reference name: DD_OrderLine_Schedule_Status
*/
public static final int STATUS_AD_Reference_ID=541435;
/** NotStarted = NS */
public static final String STATUS_NotStarted = "NS";
/** InProgress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_OrderLine_HU_Candidate.java | 1 |
请完成以下Java代码 | public static JsonNode validateIfNodeIsTextual(JsonNode node) {
if (node != null && !node.isNull() && node.isTextual() && StringUtils.isNotEmpty(node.asText())) {
try {
node = validateIfNodeIsTextual(objectMapper.readTree(node.asText()));
} catch (Exception e) {
logger.error("Error converting textual node", e);
}
}
return node;
}
public static String getValueAsString(String name, JsonNode objectNode) {
String propertyValue = null;
JsonNode propertyNode = objectNode.get(name);
if (propertyNode != null && !propertyNode.isNull()) {
propertyValue = propertyNode.asText();
}
return propertyValue;
}
public static String getPropertyValueAsString(String name, JsonNode objectNode) {
String propertyValue = null;
JsonNode propertyNode = getProperty(name, objectNode); | if (propertyNode != null && propertyNode.isNull() == false) {
propertyValue = propertyNode.asText();
}
return propertyValue;
}
public static JsonNode getProperty(String name, JsonNode objectNode) {
JsonNode propertyNode = null;
if (objectNode.get(EDITOR_SHAPE_PROPERTIES) != null) {
JsonNode propertiesNode = objectNode.get(EDITOR_SHAPE_PROPERTIES);
propertyNode = propertiesNode.get(name);
}
return propertyNode;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BpmnJsonConverterUtil.java | 1 |
请完成以下Java代码 | public class RuleNodeException extends RuleEngineException {
private static final long serialVersionUID = -1776681087370749776L;
public static final String UNKNOWN = "Unknown";
@Getter
private final String ruleChainName;
@Getter
private final String ruleNodeName;
@Getter
private final RuleChainId ruleChainId;
@Getter
private final RuleNodeId ruleNodeId;
public RuleNodeException(String message, String ruleChainName, RuleNode ruleNode) {
super(message);
this.ruleChainName = ruleChainName;
if (ruleNode != null) {
this.ruleNodeName = ruleNode.getName();
this.ruleChainId = ruleNode.getRuleChainId();
this.ruleNodeId = ruleNode.getId();
} else {
ruleNodeName = UNKNOWN;
ruleChainId = new RuleChainId(RuleChainId.NULL_UUID); | ruleNodeId = new RuleNodeId(RuleNodeId.NULL_UUID);
}
}
public String toJsonString(int maxMessageLength) {
try {
return mapper.writeValueAsString(mapper.createObjectNode()
.put("ruleNodeId", ruleNodeId.toString())
.put("ruleChainId", ruleChainId.toString())
.put("ruleNodeName", ruleNodeName)
.put("ruleChainName", ruleChainName)
.put("message", truncateIfNecessary(getMessage(), maxMessageLength)));
} catch (JsonProcessingException e) {
log.warn("Failed to serialize exception ", e);
throw new RuntimeException(e);
}
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\queue\RuleNodeException.java | 1 |
请完成以下Java代码 | public class AddFlowRuleReqVo {
private String app;
private String ip;
private Integer port;
private String resource;
private Integer resourceMode;
private Integer grade;
private Double count;
private Long interval;
private Integer intervalUnit;
private Integer controlBehavior;
private Integer burst;
private Integer maxQueueingTimeoutMs;
private GatewayParamFlowItemVo paramItem;
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public Integer getResourceMode() {
return resourceMode;
}
public void setResourceMode(Integer resourceMode) {
this.resourceMode = resourceMode;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
public Double getCount() {
return count;
}
public void setCount(Double count) {
this.count = count;
}
public Long getInterval() {
return interval;
} | public void setInterval(Long interval) {
this.interval = interval;
}
public Integer getIntervalUnit() {
return intervalUnit;
}
public void setIntervalUnit(Integer intervalUnit) {
this.intervalUnit = intervalUnit;
}
public Integer getControlBehavior() {
return controlBehavior;
}
public void setControlBehavior(Integer controlBehavior) {
this.controlBehavior = controlBehavior;
}
public Integer getBurst() {
return burst;
}
public void setBurst(Integer burst) {
this.burst = burst;
}
public Integer getMaxQueueingTimeoutMs() {
return maxQueueingTimeoutMs;
}
public void setMaxQueueingTimeoutMs(Integer maxQueueingTimeoutMs) {
this.maxQueueingTimeoutMs = maxQueueingTimeoutMs;
}
public GatewayParamFlowItemVo getParamItem() {
return paramItem;
}
public void setParamItem(GatewayParamFlowItemVo paramItem) {
this.paramItem = paramItem;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\rule\AddFlowRuleReqVo.java | 1 |
请完成以下Java代码 | public void onSplitTransaction(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
final I_M_ReceiptSchedule referencedModel = findReceiptScheduleFromSplitTransactions(huContext, unloadTrx, loadTrx);
if (referencedModel == null)
{
return;
}
unloadTrx.setReferencedModel(referencedModel);
loadTrx.setReferencedModel(referencedModel);
}
@Nullable
private I_M_ReceiptSchedule findReceiptScheduleFromSplitTransactions(final IHUContext huContext, final IHUTransactionCandidate unloadTrx, final IHUTransactionCandidate loadTrx)
{
//
// If referenced model of the load transaction is a Receipt Schedule, use that
final Object loadReferencedModel = loadTrx.getReferencedModel();
if (InterfaceWrapperHelper.isInstanceOf(loadReferencedModel, I_M_ReceiptSchedule.class))
{
return InterfaceWrapperHelper.create(loadReferencedModel, I_M_ReceiptSchedule.class);
}
//
// If referenced model of the unload transaction is a Receipt Schedule, use that
final Object unloadReferencedModel = unloadTrx.getReferencedModel();
if (InterfaceWrapperHelper.isInstanceOf(unloadReferencedModel, I_M_ReceiptSchedule.class))
{
return InterfaceWrapperHelper.create(unloadReferencedModel, I_M_ReceiptSchedule.class);
} | //
// Find the receipt schedule of the VHU from where we split
final I_M_HU fromVHU = unloadTrx.getVHU();
if(X_M_HU.HUSTATUS_Planning.equals(fromVHU.getHUStatus()))
{
final IHUReceiptScheduleDAO huReceiptScheduleDAO = Services.get(IHUReceiptScheduleDAO.class);
return huReceiptScheduleDAO.retrieveReceiptScheduleForVHU(fromVHU);
}
// Fallback
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUTrxListener.java | 1 |
请完成以下Java代码 | public void approveIt(final DocumentTableFields docFields)
{
approveIt(extractRecord(docFields));
}
private void approveIt(final I_SAP_GLJournal glJournal)
{
glJournal.setIsApproved(true);
}
@Override
public String completeIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> {
glJournal.assertHasLines();
glJournal.updateLineAcctAmounts(glJournalService.getCurrencyConverter());
glJournal.assertTotalsBalanced();
glJournal.setProcessed(true);
}
);
glJournalRecord.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
} | private static void assertPeriodOpen(final I_SAP_GLJournal glJournalRecord)
{
MPeriod.testPeriodOpen(Env.getCtx(), glJournalRecord.getDateAcct(), glJournalRecord.getC_DocType_ID(), glJournalRecord.getAD_Org_ID());
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_SAP_GLJournal glJournalRecord = extractRecord(docFields);
assertPeriodOpen(glJournalRecord);
glJournalService.updateWhileSaving(
glJournalRecord,
glJournal -> glJournal.setProcessed(false)
);
factAcctDAO.deleteForDocumentModel(glJournalRecord);
glJournalRecord.setPosted(false);
glJournalRecord.setProcessed(false);
glJournalRecord.setDocAction(X_GL_Journal.DOCACTION_Complete);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\document\SAPGLJournalDocumentHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JobDetail job2Detail() {
return JobBuilder.newJob()
.ofType(quartzJobTwo.getClass())
.withIdentity("quartzJobTwo", "group1")
.storeDurably()
.build();
}
@Bean
public Trigger job1Trigger(JobDetail job1Detail) {
return TriggerBuilder.newTrigger()
.forJob(job1Detail)
.withIdentity("quartzJobOneTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
.build();
}
@Bean
public Trigger job2Trigger(JobDetail job2Detail) {
return TriggerBuilder.newTrigger() | .forJob(job2Detail)
.withIdentity("quartzJobTwoTrigger", "group1")
.withSchedule(CronScheduleBuilder.cronSchedule("0/15 * * * * ?"))
.build();
}
@Bean
public SchedulerFactoryBean schedulerFactoryBean() {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setJobDetails(job1Detail(), job2Detail());
schedulerFactory.setTriggers(job1Trigger(job1Detail()), job2Trigger(job2Detail()));
return schedulerFactory;
}
} | repos\tutorials-master\spring-batch-2\src\main\java\com\baeldung\springbatch\jobs\quartz\QuartzConfig.java | 2 |
请完成以下Java代码 | public int getC_Job_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getC_Job_ID()));
}
/** Set Position Remuneration.
@param C_JobRemuneration_ID
Remuneration for the Position
*/
public void setC_JobRemuneration_ID (int C_JobRemuneration_ID)
{
if (C_JobRemuneration_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_JobRemuneration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_JobRemuneration_ID, Integer.valueOf(C_JobRemuneration_ID));
}
/** Get Position Remuneration.
@return Remuneration for the Position
*/
public int getC_JobRemuneration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobRemuneration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Remuneration getC_Remuneration() throws RuntimeException
{
return (I_C_Remuneration)MTable.get(getCtx(), I_C_Remuneration.Table_Name)
.getPO(getC_Remuneration_ID(), get_TrxName()); }
/** Set Remuneration.
@param C_Remuneration_ID
Wage or Salary
*/
public void setC_Remuneration_ID (int C_Remuneration_ID)
{
if (C_Remuneration_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Remuneration_ID, Integer.valueOf(C_Remuneration_ID));
}
/** Get Remuneration.
@return Wage or Salary
*/
public int getC_Remuneration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Remuneration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description. | @param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobRemuneration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Result<?> importExcel(HttpServletRequest request, HttpServletResponse response, Class<T> clazz) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
// 获取上传文件对象
MultipartFile file = entity.getValue();
ImportParams params = new ImportParams();
params.setTitleRows(2);
params.setHeadRows(1);
params.setNeedSave(true);
try {
List<T> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
// 代码逻辑说明: 批量插入数据
long start = System.currentTimeMillis();
service.saveBatch(list);
//400条 saveBatch消耗时间1592毫秒 循环插入消耗时间1947毫秒
//1200条 saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
return Result.ok("文件导入成功!数据行数:" + list.size());
} catch (Exception e) { | // 代码逻辑说明: 导入数据重复增加提示
String msg = e.getMessage();
log.error(msg, e);
if(msg!=null && msg.indexOf("Duplicate entry")>=0){
return Result.error("文件导入失败:有重复数据!");
}else{
return Result.error("文件导入失败:" + e.getMessage());
}
} finally {
try {
file.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return Result.error("文件导入失败!");
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\base\controller\JeecgController.java | 2 |
请完成以下Java代码 | public ShipmentScheduleAndJobScheduleIdSet toShipmentScheduleAndJobScheduleIdSet()
{
return list.stream()
.map(PickingJobSchedule::getShipmentScheduleAndJobScheduleId)
.collect(ShipmentScheduleAndJobScheduleIdSet.collect());
}
public boolean isAllProcessed()
{
return list.stream().allMatch(PickingJobSchedule::isProcessed);
}
public Optional<Quantity> getQtyToPick()
{
return list.stream()
.map(PickingJobSchedule::getQtyToPick)
.reduce(Quantity::add);
}
public Optional<PickingJobSchedule> getSingleScheduleByShipmentScheduleId(@NonNull ShipmentScheduleId shipmentScheduleId)
{ | final ImmutableList<PickingJobSchedule> schedules = byShipmentScheduleId.get(shipmentScheduleId);
if (schedules.isEmpty())
{
return Optional.empty();
}
else if (schedules.size() == 1)
{
return Optional.of(schedules.get(0));
}
else
{
throw new AdempiereException("Only one schedule was expected for " + shipmentScheduleId + " but found " + schedules);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\job_schedule\model\PickingJobScheduleCollection.java | 1 |
请完成以下Java代码 | public static Map<String, DmnEngine> getDmnEngines() {
return dmnEngines;
}
/**
* closes all dmn engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, DmnEngine> engines = new HashMap<>(dmnEngines);
dmnEngines = new HashMap<>();
for (String dmnEngineName : engines.keySet()) {
DmnEngine dmnEngine = engines.get(dmnEngineName);
try {
dmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (dmnEngineName == null ? "the default dmn engine" : "dmn engine " + dmnEngineName), e);
}
} | dmnEngineInfosByName.clear();
dmnEngineInfosByResourceUrl.clear();
dmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
DmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngines.java | 1 |
请完成以下Java代码 | public void setHR_ListType_ID (int HR_ListType_ID)
{
if (HR_ListType_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListType_ID, Integer.valueOf(HR_ListType_ID));
}
/** Get Payroll List Type.
@return Payroll List Type */
public int getHR_ListType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/ | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EngineConfigurationConfigurer<SpringProcessEngineConfiguration> idmProcessEngineConfigurationConfigurer(
IdmEngineConfigurator idmEngineConfigurator
) {
return processEngineConfiguration -> processEngineConfiguration.setIdmEngineConfigurator(idmEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public IdmEngineConfigurator idmEngineConfigurator(SpringIdmEngineConfiguration configuration) {
SpringIdmEngineConfigurator idmEngineConfigurator = new SpringIdmEngineConfigurator();
idmEngineConfigurator.setIdmEngineConfiguration(configuration);
invokeConfigurers(configuration);
return idmEngineConfigurator;
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(type = {
"org.flowable.app.spring.SpringAppEngineConfiguration"
})
public static class IdmEngineAppConfiguration extends BaseEngineConfigurationWithConfigurers<SpringIdmEngineConfiguration> {
@Bean | @ConditionalOnMissingBean(name = "idmAppEngineConfigurationConfigurer")
public EngineConfigurationConfigurer<SpringAppEngineConfiguration> idmAppEngineConfigurationConfigurer(
IdmEngineConfigurator idmEngineConfigurator
) {
return appEngineConfiguration -> appEngineConfiguration.setIdmEngineConfigurator(idmEngineConfigurator);
}
@Bean
@ConditionalOnMissingBean
public IdmEngineConfigurator idmEngineConfigurator(SpringIdmEngineConfiguration configuration) {
SpringIdmEngineConfigurator idmEngineConfigurator = new SpringIdmEngineConfigurator();
idmEngineConfigurator.setIdmEngineConfiguration(configuration);
invokeConfigurers(configuration);
return idmEngineConfigurator;
}
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\idm\IdmEngineAutoConfiguration.java | 2 |
请完成以下Java代码 | public class ResetExpiredJobsRunnable implements Runnable {
private static Logger log = LoggerFactory.getLogger(ResetExpiredJobsRunnable.class);
protected final AsyncExecutor asyncExecutor;
protected volatile boolean isInterrupted;
protected final Object MONITOR = new Object();
protected final AtomicBoolean isWaiting = new AtomicBoolean(false);
public ResetExpiredJobsRunnable(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
}
public synchronized void run() {
log.info("{} starting to reset expired jobs");
Thread.currentThread().setName("activiti-reset-expired-jobs");
while (!isInterrupted) {
try {
List<JobEntity> expiredJobs = asyncExecutor
.getProcessEngineConfiguration()
.getCommandExecutor()
.execute(new FindExpiredJobsCmd(asyncExecutor.getResetExpiredJobsPageSize()));
List<String> expiredJobIds = new ArrayList<String>(expiredJobs.size());
for (JobEntity expiredJob : expiredJobs) {
expiredJobIds.add(expiredJob.getId());
}
if (expiredJobIds.size() > 0) {
asyncExecutor
.getProcessEngineConfiguration()
.getCommandExecutor()
.execute(new ResetExpiredJobsCmd(expiredJobIds));
}
} catch (Throwable e) {
if (e instanceof ActivitiOptimisticLockingException) {
log.debug("Optmistic lock exception while resetting locked jobs", e);
} else {
log.error("exception during resetting expired jobs", e.getMessage(), e);
}
}
// Sleep
try { | synchronized (MONITOR) {
if (!isInterrupted) {
isWaiting.set(true);
MONITOR.wait(asyncExecutor.getResetExpiredJobsInterval());
}
}
} catch (InterruptedException e) {
if (log.isDebugEnabled()) {
log.debug("async reset expired jobs wait interrupted");
}
} finally {
isWaiting.set(false);
}
}
log.info("{} stopped resetting expired jobs");
}
public void stop() {
synchronized (MONITOR) {
isInterrupted = true;
if (isWaiting.compareAndSet(true, false)) {
MONITOR.notifyAll();
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\ResetExpiredJobsRunnable.java | 1 |
请完成以下Java代码 | public void setAvailableInAPI (final boolean AvailableInAPI)
{
set_Value (COLUMNNAME_AvailableInAPI, AvailableInAPI);
}
@Override
public boolean isAvailableInAPI()
{
return get_ValueAsBoolean(COLUMNNAME_AvailableInAPI);
}
@Override
public void setDataEntry_Tab_ID (final int DataEntry_Tab_ID)
{
if (DataEntry_Tab_ID < 1)
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, DataEntry_Tab_ID);
}
@Override
public int getDataEntry_Tab_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_Tab_ID);
}
@Override
public org.compiere.model.I_AD_Window getDataEntry_TargetWindow()
{
return get_ValueAsPO(COLUMNNAME_DataEntry_TargetWindow_ID, org.compiere.model.I_AD_Window.class);
}
@Override
public void setDataEntry_TargetWindow(final org.compiere.model.I_AD_Window DataEntry_TargetWindow)
{
set_ValueFromPO(COLUMNNAME_DataEntry_TargetWindow_ID, org.compiere.model.I_AD_Window.class, DataEntry_TargetWindow);
}
@Override
public void setDataEntry_TargetWindow_ID (final int DataEntry_TargetWindow_ID)
{
if (DataEntry_TargetWindow_ID < 1)
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, null);
else
set_Value (COLUMNNAME_DataEntry_TargetWindow_ID, DataEntry_TargetWindow_ID);
}
@Override
public int getDataEntry_TargetWindow_ID()
{
return get_ValueAsInt(COLUMNNAME_DataEntry_TargetWindow_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
} | @Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTabName (final java.lang.String TabName)
{
set_Value (COLUMNNAME_TabName, TabName);
}
@Override
public java.lang.String getTabName()
{
return get_ValueAsString(COLUMNNAME_TabName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Tab.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class Bucket4jFilterConfiguration {
@Bean
public Bucket4jFilterFunctions.FilterSupplier bucket4jFilterFunctionsSupplier() {
return new Bucket4jFilterFunctions.FilterSupplier();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(CircuitBreaker.class)
static class CircuitBreakerFilterConfiguration {
@Bean
public CircuitBreakerFilterFunctions.FilterSupplier circuitBreakerFilterFunctionsSupplier() {
return new CircuitBreakerFilterFunctions.FilterSupplier();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(LoadBalancerClient.class)
public static class LoadBalancerHandlerConfiguration {
@Bean
public Function<RouteProperties, HandlerFunctionDefinition> lbHandlerFunctionDefinition() {
return routeProperties -> {
Objects.requireNonNull(routeProperties.getUri(), "routeProperties.uri must not be null");
return new HandlerFunctionDefinition.Default("lb", HandlerFunctions.http(), Collections.emptyList(),
Collections.singletonList(LoadBalancerFilterFunctions.lb(routeProperties.getUri().getHost())));
};
}
}
@Configuration(proxyBeanMethods = false)
static class RetryFilterConfiguration {
private final GatewayMvcProperties properties;
RetryFilterConfiguration(GatewayMvcProperties properties) {
this.properties = properties; | }
@Bean
public RetryFilterFunctions.FilterSupplier retryFilterFunctionsSupplier() {
RetryFilterFunctions.setUseFrameworkRetry(properties.isUseFrameworkRetryFilter());
return new RetryFilterFunctions.FilterSupplier();
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(OAuth2AuthorizedClient.class)
static class TokenRelayFilterConfiguration {
@Bean
public TokenRelayFilterFunctions.FilterSupplier tokenRelayFilterFunctionsSupplier() {
return new TokenRelayFilterFunctions.FilterSupplier();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\FilterAutoConfiguration.java | 2 |
请完成以下Java代码 | public DateAndPlaceOfBirth getDtAndPlcOfBirth() {
return dtAndPlcOfBirth;
}
/**
* Sets the value of the dtAndPlcOfBirth property.
*
* @param value
* allowed object is
* {@link DateAndPlaceOfBirth }
*
*/
public void setDtAndPlcOfBirth(DateAndPlaceOfBirth value) {
this.dtAndPlcOfBirth = value;
}
/**
* Gets the value of the othr property.
*
* @return
* possible object is | * {@link GenericPersonIdentification1 }
*
*/
public GenericPersonIdentification1 getOthr() {
return othr;
}
/**
* Sets the value of the othr property.
*
* @param value
* allowed object is
* {@link GenericPersonIdentification1 }
*
*/
public void setOthr(GenericPersonIdentification1 value) {
this.othr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PersonIdentification5CH.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PatientPrimaryDoctorInstitution description(String description) {
this.description = description;
return this;
}
/**
* Name und Ort der Institution
* @return description
**/
@Schema(example = "Krankenhaus Martha-Maria, 90491 Nürnberg", description = "Name und Ort der Institution")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public PatientPrimaryDoctorInstitution institutionId(String institutionId) {
this.institutionId = institutionId;
return this;
}
/**
* Alberta-Id des Institution (nur bei Pfelgeheim und Klinik)
* @return institutionId
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Alberta-Id des Institution (nur bei Pfelgeheim und Klinik)")
public String getInstitutionId() {
return institutionId;
}
public void setInstitutionId(String institutionId) {
this.institutionId = institutionId;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientPrimaryDoctorInstitution patientPrimaryDoctorInstitution = (PatientPrimaryDoctorInstitution) o;
return Objects.equals(this.type, patientPrimaryDoctorInstitution.type) &&
Objects.equals(this.description, patientPrimaryDoctorInstitution.description) &&
Objects.equals(this.institutionId, patientPrimaryDoctorInstitution.institutionId);
} | @Override
public int hashCode() {
return Objects.hash(type, description, institutionId);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientPrimaryDoctorInstitution {\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" description: ").append(toIndentedString(description)).append("\n");
sb.append(" institutionId: ").append(toIndentedString(institutionId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\PatientPrimaryDoctorInstitution.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private BoundStatement getProductVariantInsertStatement(Product product,UUID productId) {
String insertQuery = new StringBuilder("").append("INSERT INTO ").append(PRODUCT_TABLE_NAME)
.append("(product_id,variant_id,product_name,description,price) ").append("VALUES (").append(":product_id")
.append(", ").append(":variant_id").append(", ").append(":product_name").append(", ")
.append(":description").append(", ").append(":price").append(");").toString();
PreparedStatement preparedStatement = session.prepare(insertQuery);
return preparedStatement.bind(productId, UUID.randomUUID(),
product.getProductName(),
product.getDescription(),
product.getPrice());
}
private BoundStatement getProductInsertStatement(Product product,UUID productId,String productTableName) { | String cqlQuery1 = new StringBuilder("").append("INSERT INTO ").append(productTableName)
.append("(product_id,product_name,description,price) ").append("VALUES (").append(":product_id")
.append(", ").append(":product_name").append(", ").append(":description").append(", ")
.append(":price").append(");").toString();
PreparedStatement preparedStatement = session.prepare(cqlQuery1);
return preparedStatement.bind(productId,
product.getProductName(),
product.getDescription(),
product.getPrice());
}
} | repos\tutorials-master\persistence-modules\java-cassandra\src\main\java\com\baeldung\cassandra\batch\repository\ProductRepository.java | 2 |
请完成以下Java代码 | AnsiString append(String text, Code... codes) {
if (codes.length == 0 || !isAnsiSupported()) {
this.value.append(text);
return this;
}
Ansi ansi = Ansi.ansi();
for (Code code : codes) {
ansi = applyCode(ansi, code);
}
this.value.append(ansi.a(text).reset().toString());
return this;
}
private Ansi applyCode(Ansi ansi, Code code) {
if (code.isColor()) {
if (code.isBackground()) {
return ansi.bg(code.getColor()); | }
return ansi.fg(code.getColor());
}
return ansi.a(code.getAttribute());
}
private boolean isAnsiSupported() {
return this.terminal.isAnsiSupported();
}
@Override
public String toString() {
return this.value.toString();
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\AnsiString.java | 1 |
请完成以下Java代码 | private static OrderAndLineId extractOrderAndLineId(final I_M_ShipmentSchedule shipmentSchedule)
{
return OrderAndLineId.ofRepoIds(shipmentSchedule.getC_Order_ID(), shipmentSchedule.getC_OrderLine_ID());
}
@VisibleForTesting
static ZonedDateTime computeOrderLineDeliveryDate(
@NonNull final I_C_OrderLine orderLine,
@NonNull final I_C_Order order)
{
final ZonedDateTime presetDateShipped = TimeUtil.asZonedDateTime(orderLine.getPresetDateShipped());
if (presetDateShipped != null)
{
return presetDateShipped;
}
// Fetch it from order line if possible
final ZonedDateTime datePromised = TimeUtil.asZonedDateTime(orderLine.getDatePromised());
if (datePromised != null)
{
return datePromised;
}
// Fetch it from order header if possible
final ZonedDateTime datePromisedFromOrder = TimeUtil.asZonedDateTime(order.getDatePromised());
if (datePromisedFromOrder != null)
{
return datePromisedFromOrder;
} | // Fail miserably...
throw new AdempiereException("@NotFound@ @DeliveryDate@")
.appendParametersToMessage()
.setParameter("oderLine", orderLine)
.setParameter("order", order);
}
private static DocumentLineDescriptor createDocumentLineDescriptor(
@NonNull final OrderAndLineId orderAndLineId,
@NonNull final I_C_Order order)
{
return OrderLineDescriptor.builder()
.orderId(orderAndLineId.getOrderRepoId())
.orderLineId(orderAndLineId.getOrderLineRepoId())
.orderBPartnerId(order.getC_BPartner_ID())
.docTypeId(order.getC_DocType_ID())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\ShipmentScheduleOrderReferenceProvider.java | 1 |
请完成以下Java代码 | public static String escapeString(String originStr) {
return originStr.replaceAll("井", "\\#").replaceAll("¥", "\\$");
}
/**
* freemarker config
*/
private static Configuration freemarkerConfig = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
static {
try {
//2020-06-21 zhengkai 修复path问题导致jar无法运行而本地项目可以运行的bug
freemarkerConfig.setClassForTemplateLoading(FreemarkerUtil.class, "/templates/code-generator");
freemarkerConfig.setTemplateLoader(new ClassTemplateLoader(FreemarkerUtil.class, "/templates/code-generator"));
//freemarkerConfig.setDirectoryForTemplateLoading(new File(templatePath, "templates/code-generator"));
freemarkerConfig.setNumberFormat("#");
freemarkerConfig.setClassicCompatible(true);
freemarkerConfig.setDefaultEncoding("UTF-8");
freemarkerConfig.setLocale(Locale.CHINA);
freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* process Template Into String
*
* @param template
* @param model | * @return
* @throws IOException
* @throws TemplateException
*/
public static String processTemplateIntoString(Template template, Object model)
throws IOException, TemplateException {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
}
/**
* process String
*
* @param templateName
* @param params
* @return
* @throws IOException
* @throws TemplateException
*/
public static String processString(String templateName, Map<String, Object> params)
throws IOException, TemplateException {
Template template = freemarkerConfig.getTemplate(templateName);
String htmlText = escapeString(processTemplateIntoString(template, params));
return htmlText;
}
} | repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\util\FreemarkerUtil.java | 1 |
请完成以下Java代码 | public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID)
{
if (PickFrom_Locator_ID < 1)
set_Value (COLUMNNAME_PickFrom_Locator_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID);
}
@Override
public int getPickFrom_Locator_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID);
}
@Override
public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID)
{
if (PickFrom_Warehouse_ID < 1) | set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null);
else
set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID);
}
@Override
public int getPickFrom_Warehouse_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID);
}
@Override
public void setQtyAvailable (final BigDecimal QtyAvailable)
{
set_Value (COLUMNNAME_QtyAvailable, QtyAvailable);
}
@Override
public BigDecimal getQtyAvailable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_HUAlternative.java | 1 |
请完成以下Java代码 | public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); }
public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); }
public short damage() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 0; }
public boolean mutateDamage(short damage) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, damage); return true; } else { return false; } }
public static int createEffect(FlatBufferBuilder builder,
int nameOffset,
short damage) {
builder.startTable(2);
Effect.addName(builder, nameOffset);
Effect.addDamage(builder, damage);
return Effect.endEffect(builder);
}
public static void startEffect(FlatBufferBuilder builder) { builder.startTable(2); } | public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); }
public static void addDamage(FlatBufferBuilder builder, short damage) { builder.addShort(1, damage, 0); }
public static int endEffect(FlatBufferBuilder builder) {
int o = builder.endTable();
return o;
}
public static final class Vector extends BaseVector {
public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; }
public Effect get(int j) { return get(new Effect(), j); }
public Effect get(Effect obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); }
}
} | repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGame\terrains\Effect.java | 1 |
请完成以下Java代码 | public List<AccountInterest2> getIntrst() {
if (intrst == null) {
intrst = new ArrayList<AccountInterest2>();
}
return this.intrst;
}
/**
* Gets the value of the txsSummry property.
*
* @return
* possible object is
* {@link TotalTransactions2 }
*
*/
public TotalTransactions2 getTxsSummry() {
return txsSummry;
}
/**
* Sets the value of the txsSummry property.
*
* @param value
* allowed object is
* {@link TotalTransactions2 }
*
*/
public void setTxsSummry(TotalTransactions2 value) {
this.txsSummry = value;
}
/**
* Gets the value of the ntry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ntry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ReportEntry2 }
*
*
*/ | public List<ReportEntry2> getNtry() {
if (ntry == null) {
ntry = new ArrayList<ReportEntry2>();
}
return this.ntry;
}
/**
* Gets the value of the addtlNtfctnInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlNtfctnInf() {
return addtlNtfctnInf;
}
/**
* Sets the value of the addtlNtfctnInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlNtfctnInf(String value) {
this.addtlNtfctnInf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_02\de\metas\payment\camt054_001_02\AccountNotification2.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public KStream<String, IotSensorData> iotStream(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
stream.split()
.branch((key, value) -> value.getSensorType() != null,
Branched.withConsumer(ks -> ks.to((key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType()))))
.noDefaultBranch();
return stream;
}
@Bean
public KStream<String, IotSensorData> iotBrancher(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
new KafkaStreamBrancher<String, IotSensorData>()
.branch((key, value) -> "temp".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_temp")) | .branch((key, value) -> "move".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_move"))
.branch((key, value) -> "hum".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_hum"))
.defaultBranch(ks -> ks.to(String.format("%s_unknown", iotTopicName)))
.onTopOf(stream);
return stream;
}
@Bean
public KStream<String, IotSensorData> iotTopicExtractor(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
TopicNameExtractor<String, IotSensorData> sensorTopicExtractor = (key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType());
stream.to(sensorTopicExtractor);
return stream;
}
} | repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\kafkasplitting\KafkaStreamsConfig.java | 2 |
请完成以下Java代码 | public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_User_Occupation_AdditionalSpecialization_ID (final int AD_User_Occupation_AdditionalSpecialization_ID)
{
if (AD_User_Occupation_AdditionalSpecialization_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID, AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public int getAD_User_Occupation_AdditionalSpecialization_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_AdditionalSpecialization_ID);
}
@Override
public org.compiere.model.I_CRM_Occupation getCRM_Occupation()
{
return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class);
}
@Override
public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation)
{ | set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation);
}
@Override
public void setCRM_Occupation_ID (final int CRM_Occupation_ID)
{
if (CRM_Occupation_ID < 1)
set_Value (COLUMNNAME_CRM_Occupation_ID, null);
else
set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID);
}
@Override
public int getCRM_Occupation_ID()
{
return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_AdditionalSpecialization.java | 1 |
请完成以下Java代码 | public List<TransportType.Via> getVia() {
if (via == null) {
via = new ArrayList<TransportType.Via>();
}
return this.via;
}
/**
* Gets the value of the from property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFrom() {
return from;
}
/**
* Sets the value of the from property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFrom(String value) {
this.from = value;
}
/**
* Gets the value of the to property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTo() {
return to;
}
/**
* Sets the value of the to property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTo(String value) {
this.to = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <attribute name="via" use="required" type="{http://www.forum-datenaustausch.ch/invoice}eanPartyType" />
* <attribute name="sequence_id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedShort" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Via {
@XmlAttribute(name = "via", required = true)
protected String via; | @XmlAttribute(name = "sequence_id", required = true)
@XmlSchemaType(name = "unsignedShort")
protected int sequenceId;
/**
* Gets the value of the via property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVia() {
return via;
}
/**
* Sets the value of the via property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVia(String value) {
this.via = value;
}
/**
* Gets the value of the sequenceId property.
*
*/
public int getSequenceId() {
return sequenceId;
}
/**
* Sets the value of the sequenceId property.
*
*/
public void setSequenceId(int value) {
this.sequenceId = value;
}
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TransportType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
prioritySet = true;
}
public String getParentTaskId() {
return parentTaskId;
}
public void setParentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
parentTaskIdSet = true;
}
public void setCategory(String category) {
this.category = category;
categorySet = true;
}
public String getCategory() {
return category;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
tenantIdSet = true;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
formKeySet = true;
} | public boolean isOwnerSet() {
return ownerSet;
}
public boolean isAssigneeSet() {
return assigneeSet;
}
public boolean isDelegationStateSet() {
return delegationStateSet;
}
public boolean isNameSet() {
return nameSet;
}
public boolean isDescriptionSet() {
return descriptionSet;
}
public boolean isDuedateSet() {
return duedateSet;
}
public boolean isPrioritySet() {
return prioritySet;
}
public boolean isParentTaskIdSet() {
return parentTaskIdSet;
}
public boolean isCategorySet() {
return categorySet;
}
public boolean isTenantIdSet() {
return tenantIdSet;
}
public boolean isFormKeySet() {
return formKeySet;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalSystemParentConfigId implements RepoIdAware
{
int repoId;
@JsonCreator
@NonNull
public static ExternalSystemParentConfigId ofRepoId(final int repoId)
{
return new ExternalSystemParentConfigId(repoId);
}
@Nullable
public static ExternalSystemParentConfigId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new ExternalSystemParentConfigId(repoId) : null;
}
public static int toRepoId(@Nullable final ExternalSystemParentConfigId externalSystemParentConfigId) | {
return externalSystemParentConfigId != null ? externalSystemParentConfigId.getRepoId() : -1;
}
@JsonValue
public int toJson()
{
return getRepoId();
}
private ExternalSystemParentConfigId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_Config_ID");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\audit\data\ExternalSystemParentConfigId.java | 2 |
请完成以下Java代码 | public BankAccountId getBPartnerBankAccountId()
{
return bpBankAccountId;
}
public static final class Builder
{
private String paymentRule;
@Getter private @Nullable InvoiceId invoiceId;
@Getter private @Nullable OrderId orderId;
@Getter private @Nullable OrderPayScheduleId orderPayScheduleId;
private Boolean isSOTrx;
private BPartnerId bpartnerId;
private @Nullable BankAccountId bpBankAccountId;
// Amounts
private BigDecimal _openAmt;
private BigDecimal _discountAmt;
PaySelectionLineCandidate build()
{
return new PaySelectionLineCandidate(this);
}
public String getPaymentRule()
{
Check.assumeNotNull(paymentRule, "paymentRule not null");
return paymentRule;
}
public Builder setPaymentRule(final String paymentRule)
{
this.paymentRule = paymentRule;
return this;
}
public Builder setInvoiceId(final @Nullable InvoiceId invoiceId)
{
this.invoiceId = invoiceId;
return this;
}
public Builder setOrderPayScheduleId(final @Nullable OrderPayScheduleId orderPayScheduleId)
{
this.orderPayScheduleId = orderPayScheduleId;
return this;
}
public Builder setOrderId(final @Nullable OrderId orderId)
{
this.orderId = orderId;
return this;
}
public Builder setIsSOTrx(final boolean isSOTrx)
{
this.isSOTrx = isSOTrx;
return this;
}
public boolean isSOTrx()
{
return isSOTrx;
}
public BPartnerId getBPartnerId()
{
return bpartnerId;
}
public Builder setBPartnerId(final BPartnerId bpartnerId)
{
this.bpartnerId = bpartnerId;
return this;
}
public @Nullable BankAccountId getBPartnerBankAccountId()
{
return bpBankAccountId;
}
public Builder setBPartnerBankAccountId(final @Nullable BankAccountId bpBankAccountId) | {
this.bpBankAccountId = bpBankAccountId;
return this;
}
public BigDecimal getOpenAmt()
{
return CoalesceUtil.coalesceNotNull(_openAmt, BigDecimal.ZERO);
}
public Builder setOpenAmt(final BigDecimal openAmt)
{
this._openAmt = openAmt;
return this;
}
public BigDecimal getPayAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(discountAmt);
}
public BigDecimal getDiscountAmt()
{
return CoalesceUtil.coalesceNotNull(_discountAmt, BigDecimal.ZERO);
}
public Builder setDiscountAmt(final BigDecimal discountAmt)
{
this._discountAmt = discountAmt;
return this;
}
public BigDecimal getDifferenceAmt()
{
final BigDecimal openAmt = getOpenAmt();
final BigDecimal payAmt = getPayAmt();
final BigDecimal discountAmt = getDiscountAmt();
return openAmt.subtract(payAmt).subtract(discountAmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionLineCandidate.java | 1 |
请完成以下Java代码 | public int getVariableCount() {
return variableCount;
}
public void setVariableCount(int variableCount) {
this.variableCount = variableCount;
}
public int getIdentityLinkCount() {
return identityLinkCount;
}
public void setIdentityLinkCount(int identityLinkCount) {
this.identityLinkCount = identityLinkCount;
}
@Override
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
@Override
public Integer getAppVersion() {
return appVersion;
}
//toString ///////////////////////////////////////////////////////////////// | public String toString() {
if (isProcessInstanceType()) {
return "ProcessInstance[" + getId() + "]";
} else {
StringBuilder strb = new StringBuilder();
if (isScope) {
strb.append("Scoped execution[ id '" + getId() + "' ]");
} else if (isMultiInstanceRoot) {
strb.append("Multi instance root execution[ id '" + getId() + "' ]");
} else {
strb.append("Execution[ id '" + getId() + "' ]");
}
if (activityId != null) {
strb.append(" - activity '" + activityId);
}
if (parentId != null) {
strb.append(" - parent '" + parentId + "'");
}
return strb.toString();
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ExecutionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MinMaxDescriptor
{
public static final MinMaxDescriptor ZERO = new MinMaxDescriptor(BigDecimal.ZERO, BigDecimal.ZERO);
BigDecimal min;
BigDecimal max;
boolean highPriority;
private MinMaxDescriptor(
@JsonProperty("min") @Nullable final BigDecimal min,
@JsonProperty("max") @Nullable final BigDecimal max)
{
this(min, max, false);
}
@JsonCreator
@Builder | private MinMaxDescriptor(
@JsonProperty("min") @Nullable final BigDecimal min,
@JsonProperty("max") @Nullable final BigDecimal max,
@JsonProperty("highPriority") final @Nullable Boolean highPriority)
{
this.min = coalesceNotNull(min, BigDecimal.ZERO);
this.max = coalesceNotNull(max, this.min);
Check.errorIf(this.min.compareTo(this.max) > 0, "Minimum={} maybe not be bigger than maximum={}", this.min, this.max);
this.highPriority = coalesceNotNull(highPriority, false);
}
@JsonIgnore
public boolean isZero() {return min.signum() == 0 && max.signum() == 0;}
@Nullable
@JsonIgnore
public MinMaxDescriptor toNullIfZero() {return isZero() ? null : this;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\MinMaxDescriptor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getMessage()
{
return "";
}
@Override
public String getSubject()
{
return subject;
}
@Override
public String getTitle()
{
return Msg.getMsg(Env.getCtx(), MSG_SEND_MAIL);
}
@Override
public String getTo()
{
return to;
}
@Override | public String getExportFilePrefix()
{
return EXPORT_FILE_PREFIX;
}
@Override
public MADBoilerPlate getDefaultTextPreset()
{
if (defaultBoilerPlateId != null && defaultBoilerPlateId > 0)
{
return new MADBoilerPlate(Env.getCtx(), defaultBoilerPlateId, null);
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\DocumentEmailParams.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MainApplication {
@Autowired
private BookstoreService bookstoreService;
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
@Bean
public ApplicationRunner init() {
return args -> {
System.out.println("\n\npersistAuthorWithBooks():");
bookstoreService.persistAuthorWithBooks();
System.out.println("\n\nfetchBookByTitle():");
bookstoreService.fetchBookByTitle(); | System.out.println("\n\nfetchPaperback():");
bookstoreService.fetchPaperback();
System.out.println("\n\nfetchEbook():");
bookstoreService.fetchEbook();
System.out.println("\n\nfetchBooksByAuthorId():");
bookstoreService.fetchBooksByAuthorId();
System.out.println("\n\nfetchAuthorAndBooksLazy():");
bookstoreService.fetchAuthorAndBooksLazy();
System.out.println("\n\nfetchAuthorAndBooksEager():");
bookstoreService.fetchAuthorAndBooksEager();
};
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinTableInheritance\src\main\java\com\bookstore\MainApplication.java | 2 |
请完成以下Java代码 | public static void setCurrentTheme (final PlasticTheme theme)
{
if (theme != null)
{
THEME_CURRENT = theme;
PlasticLookAndFeel.setCurrentTheme(THEME_CURRENT);
}
}
/**
* Get Current Theme
* @return Metal Theme
*/
public static PlasticTheme getCurrentTheme()
{
return THEME_CURRENT;
}
/**
* Error Feedback.
* <p>
* Invoked when the user attempts an invalid operation,
* such as pasting into an uneditable <code>JTextField</code> | * that has focus.
* </p>
* <p>
* If the user has enabled visual error indication on
* the desktop, this method will flash the caption bar
* of the active window. The user can also set the
* property awt.visualbell=true to achieve the same
* results.
* </p>
* @param component Component the error occurred in, may be
* null indicating the error condition is
* not directly associated with a
* <code>Component</code>.
*/
@Override
public void provideErrorFeedback (Component component)
{
super.provideErrorFeedback (component);
}
} // AdempiereLookAndFeel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\plaf\AdempiereLookAndFeel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("pass"))
.roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder().encode("pass"))
.roles("ADMIN");
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry.anyRequest().authenticated() | .anyRequest().access(accessDecisionManager()))
.formLogin(AbstractAuthenticationFilterConfigurer::permitAll)
.logout(httpSecurityLogoutConfigurer ->
httpSecurityLogoutConfigurer.permitAll().deleteCookies("JSESSIONID")
.logoutSuccessUrl("/login"));
return http.build();
}
@Bean
public AuthorizationManager<RequestAuthorizationContext> accessDecisionManager() {
return AuthorizationManagers.allOf(new MinuteBasedVoter());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\java\com\baeldung\roles\voter\WebSecurityConfig.java | 2 |
请完成以下Java代码 | public class EncryptionPropertyType {
@XmlMixed
@XmlAnyElement(lax = true)
protected List<Object> content;
@XmlAttribute(name = "Target")
@XmlSchemaType(name = "anyURI")
protected String target;
@XmlAttribute(name = "Id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
@XmlAnyAttribute
private Map<QName, String> otherAttributes = new HashMap<QName, String>();
/**
* Gets the value of the content property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the content property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getContent().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Element }
* {@link Object }
* {@link String }
*
*
*/
public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the target property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTarget() {
return target;
}
/**
* Sets the value of the target property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTarget(String value) {
this.target = value; | }
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptionPropertyType.java | 1 |
请完成以下Java代码 | public GridFieldVOsLoader setAD_Tab_ID(final int AD_Tab_ID)
{
_adTabId = AD_Tab_ID;
return this;
}
public GridFieldVOsLoader setTemplateTabId(int templateTabId)
{
this._templateTabId = templateTabId;
return this;
}
private int getAD_Tab_ID()
{
return _adTabId;
}
private int getTemplateTabIdEffective()
{
return _templateTabId > 0 ? _templateTabId : getAD_Tab_ID();
}
public GridFieldVOsLoader setTabIncludeFiltersStrategy(@NonNull final TabIncludeFiltersStrategy tabIncludeFiltersStrategy)
{
this.tabIncludeFiltersStrategy = tabIncludeFiltersStrategy;
return this;
}
public GridFieldVOsLoader setTabReadOnly(final boolean tabReadOnly)
{
_tabReadOnly = tabReadOnly;
return this; | }
private boolean isTabReadOnly()
{
return _tabReadOnly;
}
public GridFieldVOsLoader setLoadAllLanguages(final boolean loadAllLanguages)
{
_loadAllLanguages = loadAllLanguages;
return this;
}
private boolean isLoadAllLanguages()
{
return _loadAllLanguages;
}
public GridFieldVOsLoader setApplyRolePermissions(final boolean applyRolePermissions)
{
this._applyRolePermissions = applyRolePermissions;
return this;
}
private boolean isApplyRolePermissions()
{
return _applyRolePermissions;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVOsLoader.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.