instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | default ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested) {
return receive(requested, DEFAULT_POLL_TIMEOUT);
}
/**
* Receive multiple records. Only absolute, positive offsets are supported.
* @param requested a collection of record requests (topic/partition/offset).
* @param pollTimeout the timeout.
* @return the record or null.
* @since 2.8
*/
ConsumerRecords<K, V> receive(Collection<TopicPartitionOffset> requested, Duration pollTimeout);
/**
* A callback for executing arbitrary operations on the {@link Producer}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/ | interface ProducerCallback<K, V, T> {
T doInKafka(Producer<K, V> producer);
}
/**
* A callback for executing arbitrary operations on the {@link KafkaOperations}.
* @param <K> the key type.
* @param <V> the value type.
* @param <T> the return type.
* @since 1.3
*/
interface OperationsCallback<K, V, T> {
@Nullable
T doInOperations(KafkaOperations<K, V> operations);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\KafkaOperations.java | 1 |
请完成以下Java代码 | public void setPrintoutForOtherUsers(@NonNull final I_C_Printing_Queue item,
final Set<Integer> userToPrintIds)
{
//
// Make sure the item is not null and it was not already printed (i.e. processed)
Check.assume(!item.isProcessed(), "item not already printed: {}", item);
//
// Build a list of valid user to print IDs
Check.assumeNotEmpty(userToPrintIds, "userToPrintIds not empty");
final Set<Integer> userToPrintIdsActual = new HashSet<>();
for (final Integer userToPrintId : userToPrintIds)
{
// skip not valid user IDs
if (userToPrintId == null || userToPrintId <= 0)
{
continue;
}
userToPrintIdsActual.add(userToPrintId);
}
Check.assumeNotEmpty(userToPrintIdsActual, "userToPrintIdsActual not empty");
//
// Delete existing queue item recipients (if any),
// but don't update the aggregation key. We will update it later in this method.
final IPrintingDAO printingDAO = Services.get(IPrintingDAO.class);
printingDAO.deletePrintingQueueRecipients(item);
//
// Create new recipients
// Make sure the item was saved.
// We are not saving it here, because that shall be the responsibility of the caller.
Check.errorIf(item.getC_Printing_Queue_ID() < 0, "Item shall be saved: {}", item);
item.setIsPrintoutForOtherUser(true);
for (final int userToPrintId : userToPrintIdsActual)
{
final I_C_Printing_Queue_Recipient recipient = InterfaceWrapperHelper.newInstance(I_C_Printing_Queue_Recipient.class, item);
recipient.setC_Printing_Queue(item);
recipient.setAD_User_ToPrint_ID(userToPrintId);
printingDAO.setDisableAggregationKeyUpdate(recipient); // don't update the aggregation key
InterfaceWrapperHelper.save(recipient);
}
// Make sure the aggregation key is up2date.
setItemAggregationKey(item);
}
@Override | public PrinterRoutingsQuery createPrinterRoutingsQueryForItem(@NonNull final I_C_Printing_Queue item)
{
return PrinterRoutingsQuery.builder()
.clientId(ClientId.ofRepoIdOrSystem(item.getAD_Client_ID()))
.orgId(OrgId.ofRepoIdOrAny(item.getAD_Org_ID()))
.roleId(RoleId.ofRepoIdOrNull(item.getAD_Role_ID()))
.userId(getPrintToUser(item))
.tableId(AdTableId.ofRepoIdOrNull(item.getAD_Table_ID()))
.processId(AdProcessId.ofRepoIdOrNull(item.getAD_Process_ID()))
.docTypeId(DocTypeId.ofRepoIdOrNull(item.getC_DocType_ID()))
.build();
}
private UserId getPrintToUser(@NonNull final I_C_Printing_Queue printingQueueRecord)
{
return UserId.ofRepoId(printingQueueRecord.getCreatedBy());
}
@Override
public void setProcessedAndSave(@NonNull final I_C_Printing_Queue item)
{
item.setProcessed(true);
InterfaceWrapperHelper.save(item);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueBL.java | 1 |
请完成以下Java代码 | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Merkmals-Wert.
@param M_AttributeValue_ID
Product Attribute Value
*/
@Override
public void setM_AttributeValue_ID (int M_AttributeValue_ID)
{
if (M_AttributeValue_ID < 1)
set_Value (COLUMNNAME_M_AttributeValue_ID, null);
else
set_Value (COLUMNNAME_M_AttributeValue_ID, Integer.valueOf(M_AttributeValue_ID));
}
/** Get Merkmals-Wert.
@return Product Attribute Value
*/
@Override
public int getM_AttributeValue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Attribut substitute.
@param M_AttributeValue_Mapping_ID Attribut substitute */
@Override
public void setM_AttributeValue_Mapping_ID (int M_AttributeValue_Mapping_ID)
{
if (M_AttributeValue_Mapping_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeValue_Mapping_ID, Integer.valueOf(M_AttributeValue_Mapping_ID));
}
/** Get Attribut substitute.
@return Attribut substitute */ | @Override
public int getM_AttributeValue_Mapping_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_Mapping_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Merkmals-Wert Nach.
@param M_AttributeValue_To_ID
Product Attribute Value To
*/
@Override
public void setM_AttributeValue_To_ID (int M_AttributeValue_To_ID)
{
if (M_AttributeValue_To_ID < 1)
set_Value (COLUMNNAME_M_AttributeValue_To_ID, null);
else
set_Value (COLUMNNAME_M_AttributeValue_To_ID, Integer.valueOf(M_AttributeValue_To_ID));
}
/** Get Merkmals-Wert Nach.
@return Product Attribute Value To
*/
@Override
public int getM_AttributeValue_To_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeValue_To_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeValue_Mapping.java | 1 |
请完成以下Java代码 | public String getJob() {
return job;
}
public void setJob(final String job) {
this.job = job;
}
public boolean isReceiveNewsletter() {
return receiveNewsletter;
}
public void setReceiveNewsletter(final boolean receiveNewsletter) {
this.receiveNewsletter = receiveNewsletter;
}
public String[] getHobbies() {
return hobbies;
}
public void setHobbies(final String[] hobbies) {
this.hobbies = hobbies;
}
public List<String> getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(final List<String> favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public String getNotes() {
return notes;
}
public void setNotes(final String notes) { | this.notes = notes;
}
public List<String> getFruit() {
return fruit;
}
public void setFruit(final List<String> fruit) {
this.fruit = fruit;
}
public String getBook() {
return book;
}
public void setBook(final String book) {
this.book = book;
}
public MultipartFile getFile() {
return file;
}
public void setFile(final MultipartFile file) {
this.file = file;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\taglibrary\Person.java | 1 |
请完成以下Java代码 | public final class WarehousePickingGroupsIndex
{
public static WarehousePickingGroupsIndex of(@NonNull final List<WarehousePickingGroup> groups)
{
return new WarehousePickingGroupsIndex(groups);
}
private final ImmutableMap<WarehousePickingGroupId, WarehousePickingGroup> groupsById;
private final ImmutableMap<WarehouseId, WarehousePickingGroup> groupsByWarehouseId;
private WarehousePickingGroupsIndex(final List<WarehousePickingGroup> groups)
{
groupsById = Maps.uniqueIndex(groups, WarehousePickingGroup::getId);
// NOTE: we assume a warehouse is part of one and only one picking group
groupsByWarehouseId = groups.stream()
.flatMap(group -> group.getWarehouseIds()
.stream()
.map(warehouseId -> GuavaCollectors.entry(warehouseId, group)))
.collect(GuavaCollectors.toImmutableMap());
}
public WarehousePickingGroup getById(@NonNull final WarehousePickingGroupId id)
{
final WarehousePickingGroup group = groupsById.get(id);
if (group == null) | {
throw new AdempiereException("No Warehouse Picking Group found for " + id);
}
return group;
}
public Set<WarehouseId> getWarehouseIdsOfSamePickingGroup(@NonNull final WarehouseId warehouseId)
{
final WarehousePickingGroup group = groupsByWarehouseId.get(warehouseId);
if (group == null)
{
return ImmutableSet.of(warehouseId);
}
return group.getWarehouseIds();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\groups\picking\WarehousePickingGroupsIndex.java | 1 |
请完成以下Java代码 | public void save(final I_C_Invoice_Candidate compensationLinePO)
{
Check.assume(!compensationLinePO.isProcessed(), "Changing a processed line is not allowed: {}", compensationLinePO); // shall not happen
setGroupNo(compensationLinePO);
if (performDatabaseChanges)
{
InterfaceWrapperHelper.save(compensationLinePO);
}
}
private void setGroupNo(final I_C_Invoice_Candidate compensationLinePO)
{
if (compensationLinePO.getC_Order_CompensationGroup_ID() <= 0) | {
compensationLinePO.setC_Order_CompensationGroup_ID(groupId.getOrderCompensationGroupId());
}
else if (compensationLinePO.getC_Order_CompensationGroup_ID() != groupId.getOrderCompensationGroupId())
{
throw new AdempiereException("Invoice candidate has already another groupId set: " + compensationLinePO)
.setParameter("expectedGroupId", groupId.getOrderCompensationGroupId())
.appendParametersToMessage();
}
}
public I_C_Invoice_Candidate getByIdIfPresent(final InvoiceCandidateId invoiceCandidateId)
{
return invoiceCandidatesById.get(invoiceCandidateId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidatesStorage.java | 1 |
请完成以下Java代码 | public void updateResourceProduct(final I_S_Resource resource)
{
Services.get(IResourceDAO.class).onResourceChanged(resource);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void deleteResourceProduct(final I_S_Resource resource)
{
final ResourceId resourceId = ResourceId.ofRepoId(resource.getS_Resource_ID());
Services.get(IProductDAO.class).deleteProductByResourceId(resourceId);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_S_Resource.COLUMNNAME_CapacityPerProductionCycle, I_S_Resource.COLUMNNAME_CapacityPerProductionCycle_UOM_ID })
public void validateCapacityUOMID(final I_S_Resource resource)
{ | if (resource.getCapacityPerProductionCycle().signum() < 0)
{
throw new AdempiereException("CapacityPerProductionCycle cannot go below 0!")
.appendParametersToMessage()
.setParameter("S_Resource_ID", resource.getS_Resource_ID())
.markAsUserValidationError();
}
if (resource.getCapacityPerProductionCycle().signum() > 0 && resource.getCapacityPerProductionCycle_UOM_ID() <= 0)
{
throw new AdempiereException("Unit of measurement for capacity per production cycle cannot be missing if capacity is provided!")
.appendParametersToMessage()
.setParameter("S_Resource_ID", resource.getS_Resource_ID())
.markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\interceptor\S_Resource.java | 1 |
请完成以下Java代码 | protected void prepareMqttClientConfig(MqttClientConfig config) {
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (credentials.getType() == CredentialsType.BASIC) {
BasicCredentials basicCredentials = (BasicCredentials) credentials;
config.setUsername(basicCredentials.getUsername());
config.setPassword(basicCredentials.getPassword());
}
}
private SslContext getSslContext() throws SSLException {
return mqttNodeConfiguration.isSsl() ? mqttNodeConfiguration.getCredentials().initSslContext() : null;
}
private String getData(TbMsg tbMsg, boolean parseToPlainText) {
if (parseToPlainText) {
return JacksonUtil.toPlainText(tbMsg.getData());
}
return tbMsg.getData();
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
switch (fromVersion) {
case 0:
String parseToPlainText = "parseToPlainText";
if (!oldConfiguration.has(parseToPlainText)) {
hasChanges = true; | ((ObjectNode) oldConfiguration).put(parseToPlainText, false);
}
case 1:
String protocolVersion = "protocolVersion";
if (!oldConfiguration.has(protocolVersion)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(protocolVersion, MqttVersion.MQTT_3_1.name());
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mqtt\TbMqttNode.java | 1 |
请完成以下Java代码 | public IDocumentNoBuilder forSequenceId(final DocSequenceId sequenceId)
{
return createDocumentNoBuilder()
.setDocumentSequenceInfoBySequenceId(sequenceId);
}
@Override
public DocumentNoBuilder createDocumentNoBuilder()
{
return new DocumentNoBuilder();
}
@Override
public IDocumentNoBuilder createValueBuilderFor(@NonNull final Object modelRecord)
{
final IClientOrgAware clientOrg = create(modelRecord, IClientOrgAware.class);
final ClientId clientId = ClientId.ofRepoId(clientOrg.getAD_Client_ID());
final ProviderResult providerResult = getDocumentSequenceInfo(modelRecord);
return createDocumentNoBuilder()
.setDocumentSequenceInfo(providerResult.getInfoOrNull())
.setClientId(clientId) | .setDocumentModel(modelRecord)
.setFailOnError(false);
}
private ProviderResult getDocumentSequenceInfo(@NonNull final Object modelRecord)
{
for (final ValueSequenceInfoProvider provider : additionalProviders)
{
final ProviderResult result = provider.computeValueInfo(modelRecord);
if (result.hasInfo())
{
return result;
}
}
return tableNameBasedProvider.computeValueInfo(modelRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilderFactory.java | 1 |
请完成以下Java代码 | public static Topic distributed(final String name)
{
return builder().name(name).type(Type.DISTRIBUTED).build();
}
public static Topic distributedAndAsync(final String name)
{
final Topic topic = distributed(name);
EventBusConfig.alwaysConsiderAsync(topic);
return topic;
}
public static Topic local(final String name)
{
return builder().name(name).type(Type.LOCAL).build();
}
public static Topic localAndAsync(final String name)
{
final Topic topic = local(name);
EventBusConfig.alwaysConsiderAsync(topic);
return topic;
}
public static Topic of(final String name, final Type type)
{
return builder().name(name).type(type).build();
}
@Builder(toBuilder = true)
private Topic(
@NonNull final String name,
@NonNull final Type type)
{
if (!EventBusConfig.isEnabled())
{
logger.warn("trying to create a distributed Topic (topicName={}) but EventBusConfig.isEnabled() == false, fallback to Local topic...", name);
this.type = Type.LOCAL; | }
else
{
this.type = type;
}
this.name = Check.assumeNotEmpty(name, "name not empty");
this.fullName = type + "." + name;
}
public Topic toLocal()
{
if (type == Type.LOCAL)
{
return this;
}
return toBuilder().type(Type.LOCAL).build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\Topic.java | 1 |
请完成以下Java代码 | public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
@Override | public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class TreeNodeService
{
private final TreeNodeRepository treeNodeRepo;
private final ChartOfAccountsService chartOfAccountsService;
public TreeNodeService(
@NonNull final TreeNodeRepository treeNodeRepo,
@NonNull final ChartOfAccountsService chartOfAccountsService)
{
this.treeNodeRepo = treeNodeRepo;
this.chartOfAccountsService = chartOfAccountsService;
}
public static TreeNodeService newInstanceForUnitTesting()
{
Adempiere.assertUnitTestMode();
return new TreeNodeService(
new TreeNodeRepository(),
ChartOfAccountsService.newInstanceForUnitTesting()
);
}
public void updateTreeNode(@NonNull final ElementValue elementValue)
{
// treeNode base on all the data from element value
final TreeNode treeNode = toTreeNode(elementValue);
// save entire info from treenode to treenode record
treeNodeRepo.save(treeNode);
}
@NonNull
public TreeNode toTreeNode(@NonNull final ElementValue elementValue)
{
final AdTreeId chartOfAccountsTreeId = chartOfAccountsService.getById(elementValue.getChartOfAccountsId()).getTreeId(); | return TreeNode.builder()
.chartOfAccountsTreeId(chartOfAccountsTreeId)
.nodeId(elementValue.getId())
.parentId(elementValue.getParentId())
.seqNo(elementValue.getSeqNo())
.build();
}
private ImmutableList<TreeNode> toTreeNodes(final @NonNull List<ElementValue> elementValues)
{
return elementValues.stream()
.map(this::toTreeNode)
.collect(ImmutableList.toImmutableList());
}
public void recreateTree(@NonNull final List<ElementValue> elementValues)
{
final ImmutableList<TreeNode> nodes = toTreeNodes(elementValues);
treeNodeRepo.recreateTree(nodes);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\treenode\TreeNodeService.java | 2 |
请完成以下Java代码 | public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
@Override
public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable)
{
set_ValueNoCheck (COLUMNNAME_QtyAvailable, QtyAvailable);
}
@Override
public BigDecimal getQtyAvailable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyBatch (final @Nullable BigDecimal QtyBatch)
{
set_ValueNoCheck (COLUMNNAME_QtyBatch, QtyBatch);
}
@Override
public BigDecimal getQtyBatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyBatchSize (final @Nullable BigDecimal QtyBatchSize)
{
set_ValueNoCheck (COLUMNNAME_QtyBatchSize, QtyBatchSize);
}
@Override
public BigDecimal getQtyBatchSize()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBatchSize);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyBOM (final @Nullable BigDecimal QtyBOM)
{
set_ValueNoCheck (COLUMNNAME_QtyBOM, QtyBOM);
} | @Override
public BigDecimal getQtyBOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand)
{
set_ValueNoCheck (COLUMNNAME_QtyOnHand, QtyOnHand);
}
@Override
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyRequiered (final @Nullable BigDecimal QtyRequiered)
{
set_ValueNoCheck (COLUMNNAME_QtyRequiered, QtyRequiered);
}
@Override
public BigDecimal getQtyRequiered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyRequiered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved)
{
set_ValueNoCheck (COLUMNNAME_QtyReserved, QtyReserved);
}
@Override
public BigDecimal getQtyReserved()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_RV_PP_Order_BOMLine.java | 1 |
请完成以下Java代码 | public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentHandOverLocationAdapter.super.setRenderedAddress(from);
}
@Override
public I_C_Order getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
} | @Override
public OrderHandOverLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new OrderHandOverLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_C_Order.class));
}
public void setFromHandOverLocation(@NonNull final I_C_Order from)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoId(from.getHandOver_Partner_ID());
final BPartnerInfo bpartnerInfo = BPartnerInfo.builder()
.bpartnerId(bpartnerId)
.bpartnerLocationId(BPartnerLocationId.ofRepoId(bpartnerId, from.getHandOver_Location_ID()))
.contactId(BPartnerContactId.ofRepoIdOrNull(bpartnerId, from.getHandOver_User_ID()))
.build();
setFrom(bpartnerInfo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\location\adapter\OrderHandOverLocationAdapter.java | 1 |
请完成以下Java代码 | protected IQueryFilter<I_C_Invoice_Candidate> getSelectionFilter()
{
final SqlViewRowsWhereClause viewSqlWhereClause = getViewSqlWhereClause(getSelectedRowIds());
return viewSqlWhereClause.toQueryFilter();
}
private SqlViewRowsWhereClause getViewSqlWhereClause(@NonNull final DocumentIdsSelection rowIds)
{
final String invoiceCandidateTableName = I_C_Invoice_Candidate.Table_Name;
return getView().getSqlWhereClause(rowIds, SqlOptions.usingTableName(invoiceCandidateTableName));
}
protected abstract boolean isApproveForInvoicing();
protected abstract IQuery<I_C_Invoice_Candidate> retrieveQuery(final boolean includeProcessInfoFilters); | @Override
protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
//
// Notify frontend that the view shall be refreshed because we changed some candidates
if (countUpdated > 0)
{
invalidateView();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\invoicecandidate\process\C_Invoice_Candidate_ProcessHelper.java | 1 |
请完成以下Java代码 | public void replace(final int offset, final int length, String text, final AttributeSet attrs) throws BadLocationException
{
//
// Manual entry (i.e. single char typed)
// If the given char is not valid, do nothing but just provide an error feedback
if (text != null && text.length() == 1)
{
final char ch = text.charAt(0);
if (!isValidChar(ch))
{
provideErrorFeedback();
return;
}
}
if(Check.isEmpty(text, true))
{
text = "";
}
// Case: completely replacing current content with an not empty text
// => make sure the new text is a valid number (this would prevent copy-pasting wrong things)
if (text.length() > 1 && offset == 0 && length == getLength())
{
try
{
m_format.parse(text);
}
catch (final ParseException e)
{
// not a valid number
provideErrorFeedback();
return;
}
}
// Fallback
super.replace(offset, length, text, attrs);
}
private final boolean isValidChar(final char ch)
{
return Character.isDigit(ch)
|| (ch == '-' || ch == m_minusSign)
|| (ch == '+')
|| isDecimalOrGroupingSeparator(ch);
}
private final boolean isDecimalOrGroupingSeparator(final char ch)
{
return ch == m_decimalSeparator || ch == m_groupingSeparator || ch == '.' || ch == ',';
}
/**
* Get Full Text
*
* @return text or empty string; never returns null
*/
private final String getText()
{
final Content content = getContent();
if (content == null)
{
return "";
} | final int length = content.length();
if (length <= 0)
{
return "";
}
String str = "";
try
{
str = content.getString(0, length - 1); // cr at end
}
catch (BadLocationException e)
{
// ignore it, shall not happen
log.debug("Error while getting the string content", e);
}
catch (Exception e)
{
log.debug("Error while getting the string content", e);
}
return str;
} // getString
private final void provideErrorFeedback()
{
UIManager.getLookAndFeel().provideErrorFeedback(m_tc);
}
} // MDocNumber | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocNumber.java | 1 |
请完成以下Java代码 | public Void run() {
Thread.currentThread().setContextClassLoader(classLoader);
return null;
}
});
} else {
Thread.currentThread().setContextClassLoader(classLoader);
}
}
public static ClassLoader getServletContextClassloader(final ServletContextEvent sce) {
if(System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
@Override
public ClassLoader run() {
return sce.getServletContext().getClassLoader();
}
});
} else { | return sce.getServletContext().getClassLoader();
}
}
/**
* Switch the current Thread ClassLoader to the ProcessEngine's
* to assure the loading of the engine classes during job execution.
*
* @return the current Thread ClassLoader
*/
public static ClassLoader switchToProcessEngineClassloader() {
ClassLoader currentClassloader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(ProcessEngine.class.getClassLoader());
return currentClassloader;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClassLoaderUtil.java | 1 |
请完成以下Java代码 | public boolean hasDepartmentName() {
return fieldSetFlags()[1];
}
/**
* Clears the value of the 'departmentName' field.
* @return This builder.
*/
public com.baeldung.schema.EmployeeKey.Builder clearDepartmentName() {
departmentName = null;
fieldSetFlags()[1] = false;
return this;
}
@Override
@SuppressWarnings("unchecked")
public EmployeeKey build() {
try {
EmployeeKey record = new EmployeeKey();
record.id = fieldSetFlags()[0] ? this.id : (java.lang.Integer) defaultValue(fields()[0]);
record.departmentName = fieldSetFlags()[1] ? this.departmentName : (java.lang.CharSequence) defaultValue(fields()[1]);
return record;
} catch (java.lang.Exception e) {
throw new org.apache.avro.AvroRuntimeException(e);
}
}
} | @SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumWriter<EmployeeKey>
WRITER$ = (org.apache.avro.io.DatumWriter<EmployeeKey>)MODEL$.createDatumWriter(SCHEMA$);
@Override public void writeExternal(java.io.ObjectOutput out)
throws java.io.IOException {
WRITER$.write(this, SpecificData.getEncoder(out));
}
@SuppressWarnings("unchecked")
private static final org.apache.avro.io.DatumReader<EmployeeKey>
READER$ = (org.apache.avro.io.DatumReader<EmployeeKey>)MODEL$.createDatumReader(SCHEMA$);
@Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-stream\spring-cloud-stream-kafka\src\main\java\com\baeldung\schema\EmployeeKey.java | 1 |
请完成以下Spring Boot application配置 | spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springbatch?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serv | erTimezone=GMT%2b8
username: root
password: 123456
batch:
job:
enabled: false | repos\SpringAll-master\73.spring-batch-launcher\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public void setAge(int age) {
this.age = age;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getUuid() {
return uuid;
} | public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String toString() {
return "UserProperties{" +
"id=" + id +
", age=" + age +
", desc='" + desc + '\'' +
", uuid='" + uuid + '\'' +
'}';
}
} | repos\springboot-learning-example-master\springboot-properties\src\main\java\org\spring\springboot\property\UserProperties.java | 1 |
请完成以下Java代码 | private boolean isPostBank(@NonNull final I_C_BP_BankAccount bankAccount)
{
final BankId bankId = BankId.ofRepoIdOrNull(bankAccount.getC_Bank_ID());
if (bankId == null)
{
return false;
}
final Bank bank = bankRepo.getById(bankId);
return bank.isEsrPostBank();
}
@Override
public String retrieveESRAccountNo(final I_C_BP_BankAccount bankAccount)
{
Check.assume(bankAccount.isEsrAccount(), bankAccount + " has IsEsrAccount=Y");
final String renderedNo = bankAccount.getESR_RenderedAccountNo();
Check.assume(!Check.isEmpty(renderedNo, true), bankAccount + " has a ESR_RenderedAccountNo"); | if (!renderedNo.contains("-"))
{
// task 07789: the rendered number is not "rendered" to start with. This happens e.g. if the number was parsed from an ESR payment string.
return renderedNo;
}
final String[] renderenNoComponents = renderedNo.split("-");
Check.assume(renderenNoComponents.length == 3, renderedNo + " contains three '-' separated parts");
final StringBuilder sb = new StringBuilder();
sb.append(renderenNoComponents[0]);
sb.append(StringUtils.lpadZero(renderenNoComponents[1], 6, "middle section of " + renderedNo));
sb.append(renderenNoComponents[2]);
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRBPBankAccountBL.java | 1 |
请完成以下Java代码 | public HttpHeaders headers() {
return this.headers;
}
public List<ByteBuffer> body() {
return Collections.unmodifiableList(body);
}
public Date timestamp() {
return this.timestamp;
}
byte[] bodyAsByteArray() throws IOException {
var bodyStream = new ByteArrayOutputStream();
var channel = Channels.newChannel(bodyStream);
for (ByteBuffer byteBuffer : body()) {
channel.write(byteBuffer);
}
return bodyStream.toByteArray();
}
String bodyAsString() throws IOException {
InputStream byteStream = new ByteArrayInputStream(bodyAsByteArray());
if (headers.getOrEmpty(HttpHeaders.CONTENT_ENCODING).contains("gzip")) {
byteStream = new GZIPInputStream(byteStream);
}
return new String(FileCopyUtils.copyToByteArray(byteStream));
}
public static class Builder {
private final HttpStatusCode statusCode;
private final HttpHeaders headers = new HttpHeaders();
private final List<ByteBuffer> body = new ArrayList<>();
private @Nullable Instant timestamp;
public Builder(HttpStatusCode statusCode) {
this.statusCode = statusCode;
} | public Builder header(String name, String value) {
this.headers.add(name, value);
return this;
}
public Builder headers(HttpHeaders headers) {
this.headers.addAll(headers);
return this;
}
public Builder timestamp(Instant timestamp) {
this.timestamp = timestamp;
return this;
}
public Builder timestamp(Date timestamp) {
this.timestamp = timestamp.toInstant();
return this;
}
public Builder body(String data) {
return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8)));
}
public Builder appendToBody(ByteBuffer byteBuffer) {
this.body.add(byteBuffer);
return this;
}
public CachedResponse build() {
return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp));
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} | public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public String toString() {
return "Employee [id=" + id + ", organizationId=" + organizationId + ", departmentId=" + departmentId
+ ", name=" + name + ", position=" + position + "]";
}
} | repos\sample-spring-microservices-new-master\employee-service\src\main\java\pl\piomin\services\employee\model\Employee.java | 2 |
请完成以下Java代码 | public void setC_PrintJob_Line_From(de.metas.printing.model.I_C_Print_Job_Line C_PrintJob_Line_From)
{
set_ValueFromPO(COLUMNNAME_C_PrintJob_Line_From_ID, de.metas.printing.model.I_C_Print_Job_Line.class, C_PrintJob_Line_From);
}
@Override
public void setC_PrintJob_Line_From_ID (int C_PrintJob_Line_From_ID)
{
if (C_PrintJob_Line_From_ID < 1)
set_Value (COLUMNNAME_C_PrintJob_Line_From_ID, null);
else
set_Value (COLUMNNAME_C_PrintJob_Line_From_ID, Integer.valueOf(C_PrintJob_Line_From_ID));
}
@Override
public int getC_PrintJob_Line_From_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PrintJob_Line_From_ID);
}
@Override
public de.metas.printing.model.I_C_Print_Job_Line getC_PrintJob_Line_To()
{
return get_ValueAsPO(COLUMNNAME_C_PrintJob_Line_To_ID, de.metas.printing.model.I_C_Print_Job_Line.class);
}
@Override
public void setC_PrintJob_Line_To(de.metas.printing.model.I_C_Print_Job_Line C_PrintJob_Line_To)
{
set_ValueFromPO(COLUMNNAME_C_PrintJob_Line_To_ID, de.metas.printing.model.I_C_Print_Job_Line.class, C_PrintJob_Line_To);
}
@Override
public void setC_PrintJob_Line_To_ID (int C_PrintJob_Line_To_ID)
{
if (C_PrintJob_Line_To_ID < 1)
set_Value (COLUMNNAME_C_PrintJob_Line_To_ID, null);
else
set_Value (COLUMNNAME_C_PrintJob_Line_To_ID, Integer.valueOf(C_PrintJob_Line_To_ID));
}
@Override
public int getC_PrintJob_Line_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PrintJob_Line_To_ID);
}
@Override
public void setErrorMsg (java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{ | return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
/**
* Status AD_Reference_ID=540384
* Reference name: C_Print_Job_Instructions_Status
*/
public static final int STATUS_AD_Reference_ID=540384;
/** Pending = P */
public static final String STATUS_Pending = "P";
/** Send = S */
public static final String STATUS_Send = "S";
/** Done = D */
public static final String STATUS_Done = "D";
/** Error = E */
public static final String STATUS_Error = "E";
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions.java | 1 |
请完成以下Java代码 | public int getAD_Client_ID()
{
return orderLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return orderLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
final I_C_Order order = getOrder();
return order.isSOTrx();
}
@Override
public I_C_Country getC_Country()
{
final I_C_Order order = getOrder();
final BPartnerLocationAndCaptureId bpLocationId = OrderDocumentLocationAdapterFactory
.locationAdapter(order)
.getBPartnerLocationAndCaptureIdIfExists()
.orElse(null);
if (bpLocationId == null)
{
return null;
} | final CountryId countryId = Services.get(IBPartnerBL.class).getCountryId(bpLocationId);
return Services.get(ICountryDAO.class).getById(countryId);
}
private I_C_Order getOrder()
{
final I_C_Order order = orderLine.getC_Order();
if (order == null)
{
throw new AdempiereException("Order not set for" + orderLine);
}
return order;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\OrderLineCountryAware.java | 1 |
请完成以下Java代码 | public void setQtyOrdered_TU (java.math.BigDecimal QtyOrdered_TU)
{
set_Value (COLUMNNAME_QtyOrdered_TU, QtyOrdered_TU);
}
/** Get Bestellte Menge (TU).
@return Bestellte Menge (TU)
*/
@Override
public java.math.BigDecimal getQtyOrdered_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyOrdered_TU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ausliefermenge (LU).
@param QtyToDeliver_LU Ausliefermenge (LU) */
@Override
public void setQtyToDeliver_LU (java.math.BigDecimal QtyToDeliver_LU)
{
set_Value (COLUMNNAME_QtyToDeliver_LU, QtyToDeliver_LU);
}
/** Get Ausliefermenge (LU).
@return Ausliefermenge (LU) */
@Override
public java.math.BigDecimal getQtyToDeliver_LU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_LU); | if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ausliefermenge (TU).
@param QtyToDeliver_TU Ausliefermenge (TU) */
@Override
public void setQtyToDeliver_TU (java.math.BigDecimal QtyToDeliver_TU)
{
set_Value (COLUMNNAME_QtyToDeliver_TU, QtyToDeliver_TU);
}
/** Get Ausliefermenge (TU).
@return Ausliefermenge (TU) */
@Override
public java.math.BigDecimal getQtyToDeliver_TU ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyToDeliver_TU);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_Tour_Instance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class PropertiesAutoConfigurationMetadata implements AutoConfigurationMetadata {
private final Properties properties;
PropertiesAutoConfigurationMetadata(Properties properties) {
this.properties = properties;
}
@Override
public boolean wasProcessed(String className) {
return this.properties.containsKey(className);
}
@Override
public @Nullable Integer getInteger(String className, String key) {
return getInteger(className, key, null);
}
@Override
public @Nullable Integer getInteger(String className, String key, @Nullable Integer defaultValue) {
String value = get(className, key);
return (value != null) ? Integer.valueOf(value) : defaultValue;
}
@Override
public @Nullable Set<String> getSet(String className, String key) {
return getSet(className, key, null);
}
@Override
public @Nullable Set<String> getSet(String className, String key, @Nullable Set<String> defaultValue) { | String value = get(className, key);
return (value != null) ? StringUtils.commaDelimitedListToSet(value) : defaultValue;
}
@Override
public @Nullable String get(String className, String key) {
return get(className, key, null);
}
@Override
public @Nullable String get(String className, String key, @Nullable String defaultValue) {
String value = this.properties.getProperty(className + "." + key);
return (value != null) ? value : defaultValue;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\AutoConfigurationMetadataLoader.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode()
{
return Objects.hash(fileId, fileType, name, uploadedDate);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class FileInfo {\n");
sb.append(" fileId: ").append(toIndentedString(fileId)).append("\n");
sb.append(" fileType: ").append(toIndentedString(fileType)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" uploadedDate: ").append(toIndentedString(uploadedDate)).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(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\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\FileInfo.java | 2 |
请完成以下Java代码 | private IHandlingUnitsInfo createFromOrderOrBomLine(final I_PP_Order ppOrder,
final I_PP_Order_BOMLine ppOrderBOMLine)
{
final IQueryBuilder<I_PP_Cost_Collector> ccFilter = Services.get(IQueryBL.class).createQueryBuilder(I_PP_Cost_Collector.class, ppOrderBOMLine)
.addOnlyActiveRecordsFilter();
if (ppOrder != null)
{
ccFilter.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID());
}
if (ppOrderBOMLine != null)
{
ccFilter.addEqualsFilter(I_PP_Cost_Collector.COLUMNNAME_PP_Order_BOMLine_ID, ppOrderBOMLine.getPP_Order_BOMLine_ID());
}
final List<I_PP_Cost_Collector> costCollectors = ccFilter
.create()
.list(I_PP_Cost_Collector.class);
final Map<Integer, I_M_HU_PI> topLevelHUIds = new HashMap<>();
for (final I_PP_Cost_Collector costCollector : costCollectors)
{
final List<I_M_HU_Assignment> huAssignments = Services.get(IHUAssignmentDAO.class).retrieveTopLevelHUAssignmentsForModel(costCollector);
for (final I_M_HU_Assignment huAssignment : huAssignments)
{
final I_M_HU hu = huAssignment.getM_HU();
final I_M_HU_PI huPI = Services.get(IHandlingUnitsBL.class).getPI(hu);
topLevelHUIds.put(hu.getM_HU_ID(), huPI);
}
}
IHandlingUnitsInfo result = null;
for (final int huId : topLevelHUIds.keySet())
{
final HUHandlingUnitsInfo current = new HUHandlingUnitsInfo(topLevelHUIds.get(huId), 1);
if (result == null)
{
result = current;
}
else
{
result = result.add(current);
}
}
return result;
}
/**
* NOTE: we assume handlingUnitsInfo was created by this factory
*/
@Override
public void updateInvoiceDetail(final org.compiere.model.I_C_Invoice_Detail invoiceDetail, final IHandlingUnitsInfo handlingUnitsInfo)
{
// nothing to update | if (handlingUnitsInfo == null)
{
return;
}
final I_C_Invoice_Detail huInvoiceDetail = InterfaceWrapperHelper.create(invoiceDetail, I_C_Invoice_Detail.class);
// NOTE: we assume handlingUnitsInfo were created by this factory
final HUHandlingUnitsInfo huInfo = HUHandlingUnitsInfo.cast(handlingUnitsInfo);
huInvoiceDetail.setM_TU_HU_PI(huInfo.getTU_HU_PI());
final BigDecimal qtyTU = BigDecimal.valueOf(huInfo.getQtyTU());
huInvoiceDetail.setQtyTU(qtyTU);
}
/**
* NOTE: we assume handlingUnitsInfo was created by this factory
*/
@Override
public IHandlingUnitsInfoWritableQty createHUInfoWritableQty(IHandlingUnitsInfo template)
{
final HUHandlingUnitsInfo cast = HUHandlingUnitsInfo.cast(template);
return new HUHandlingUnitsInfoRW(cast.getTU_HU_PI(), template.getQtyTU());
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\HUHandlingUnitsInfoFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | String executeScript(@NonNull final String script,
@NonNull final Map<String, Object> bindings) throws RuntimeException
{
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final ByteArrayOutputStream byteArrayErrorStream = new ByteArrayOutputStream();
// 1. Create a new polyglot context with access to the JavaScript language ('js').
try (final Context context = Context.newBuilder("js")
// Allow the script to access members of any Java object passed into the bindings.
.sandbox(SandboxPolicy.CONSTRAINED)
.allowHostAccess(HostAccess.UNTRUSTED)
.out(byteArrayOutputStream)
.err(byteArrayErrorStream)
.build())
{
// 2. Evaluate the script string to define functions (like 'transform').
// We don't need the result of this eval directly, as it's just the function definition.
context.eval("js", script);
// 3. Get the bindings for the context.
final Value contextBindings = context.getBindings("js");
// 4. Populate the context's bindings with the variables from our input map.
// This makes variables like 'messageFromMetasfresh' globally available in the JS context.
for (final Map.Entry<String, Object> entry : bindings.entrySet())
{
contextBindings.putMember(entry.getKey(), entry.getValue());
}
// 5. Get a reference to the 'transform' function from the evaluated script.
final Value transformFunction = contextBindings.getMember("transform");
// 6. Check if the 'transform' function exists and is executable. | if (transformFunction == null || !transformFunction.canExecute())
{
throw new IllegalStateException("JavaScript script must define a 'transform' function that is executable.");
}
// 7. Get the input parameter value from the bindings.
final String messageFromMetasfreshInput = (String)bindings.get(PARAM_SCRIPTEDADAPTER_FROM_MF_METASFRESH_INPUT);
if (messageFromMetasfreshInput == null)
{
throw new IllegalArgumentException("Missing required input parameter: " + PARAM_SCRIPTEDADAPTER_FROM_MF_METASFRESH_INPUT);
}
// 8. Invoke the 'transform' function, passing the 'messageFromMetasfresh' parameter.
final Value result = transformFunction.execute(messageFromMetasfreshInput);
// 9. Convert the result to a Java type and return it.
return result.as(String.class);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-scriptedadapter\src\main\java\de\metas\camel\externalsystems\scriptedadapter\JavaScriptExecutorService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class UpdateMainDataRequest
{
@NonNull
MainDataRecordIdentifier identifier;
@Default
BigDecimal countedQty = BigDecimal.ZERO;
@Default
BigDecimal onHandQtyChange = BigDecimal.ZERO;
@Default
BigDecimal directMovementQty = BigDecimal.ZERO;
/**
* Quantity reserved for our customers
*/
@Default
BigDecimal orderedSalesQty = BigDecimal.ZERO;
/**
* Quantity ordered from our vendors
*/
@Default
BigDecimal orderedPurchaseQty = BigDecimal.ZERO;
@Default
BigDecimal offeredQty = BigDecimal.ZERO;
@Default
BigDecimal offeredQtyNextDay = BigDecimal.ZERO; | @Default
BigDecimal qtyDemandPPOrder = BigDecimal.ZERO;
@Default
BigDecimal qtyDemandSalesOrder = BigDecimal.ZERO;
@Default
BigDecimal qtyDemandDDOrder = BigDecimal.ZERO;
@Default
BigDecimal qtySupplyPurchaseOrder = BigDecimal.ZERO;
@Default
BigDecimal qtySupplyDDOrder = BigDecimal.ZERO;
@Default
BigDecimal qtySupplyPPOrder = BigDecimal.ZERO;
@Default
BigDecimal qtySupplyRequired = BigDecimal.ZERO;
@Default
BigDecimal qtyInventoryCount = BigDecimal.ZERO;
@Default
Instant qtyInventoryTime = Instant.ofEpochSecond(0);
@Nullable
Integer qtyStockEstimateSeqNo;
@Nullable
BigDecimal qtyStockEstimateCount;
@Nullable
Instant qtyStockEstimateTime;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\mainrecord\UpdateMainDataRequest.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ConnectionInfo apply(ConnectionInfo connectionInfo, HttpRequest request) {
String forwardedHeader = request.headers().get(FORWARDED_HEADER);
if (forwardedHeader != null) {
return parseForwardedInfo(connectionInfo, forwardedHeader);
}
return parseXForwardedInfo(connectionInfo, request);
}
private ConnectionInfo parseForwardedInfo(ConnectionInfo connectionInfo, String forwardedHeader) {
String forwarded = forwardedHeader.split(",", 2)[0];
Matcher protoMatcher = FORWARDED_PROTO_PATTERN.matcher(forwarded);
if (protoMatcher.find()) {
connectionInfo = connectionInfo.withScheme(protoMatcher.group(1).trim());
}
Matcher hostMatcher = FORWARDED_HOST_PATTERN.matcher(forwarded);
if (hostMatcher.find()) {
connectionInfo = connectionInfo.withHostAddress(AddressUtils.parseAddress(hostMatcher.group(1),
getDefaultHostPort(connectionInfo.getScheme()), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
Matcher forMatcher = FORWARDED_FOR_PATTERN.matcher(forwarded);
if (forMatcher.find()) {
connectionInfo = connectionInfo.withRemoteAddress(AddressUtils.parseAddress(forMatcher.group(1).trim(),
connectionInfo.getRemoteAddress().getPort(), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
return connectionInfo;
}
private ConnectionInfo parseXForwardedInfo(ConnectionInfo connectionInfo, HttpRequest request) {
String ipHeader = request.headers().get(X_FORWARDED_IP_HEADER);
if (ipHeader != null) {
connectionInfo = connectionInfo.withRemoteAddress(
AddressUtils.parseAddress(ipHeader.split(",", 2)[0], connectionInfo.getRemoteAddress().getPort()));
}
String protoHeader = request.headers().get(X_FORWARDED_PROTO_HEADER);
if (protoHeader != null) {
connectionInfo = connectionInfo.withScheme(protoHeader.split(",", 2)[0].trim());
}
String hostHeader = request.headers().get(X_FORWARDED_HOST_HEADER);
if (hostHeader != null) { | connectionInfo = connectionInfo
.withHostAddress(AddressUtils.parseAddress(hostHeader.split(",", 2)[0].trim(),
getDefaultHostPort(connectionInfo.getScheme()), DEFAULT_FORWARDED_HEADER_VALIDATION));
}
String portHeader = request.headers().get(X_FORWARDED_PORT_HEADER);
if (portHeader != null && !portHeader.isEmpty()) {
String portStr = portHeader.split(",", 2)[0].trim();
if (portStr.chars().allMatch(Character::isDigit)) {
int port = Integer.parseInt(portStr);
connectionInfo = connectionInfo.withHostAddress(
AddressUtils.createUnresolved(connectionInfo.getHostAddress().getHostString(), port),
connectionInfo.getHostName(), port);
}
else if (DEFAULT_FORWARDED_HEADER_VALIDATION) {
throw new IllegalArgumentException("Failed to parse a port from " + portHeader);
}
}
return connectionInfo;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\DefaultNettyHttpForwardedHeaderHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Jws<Claims> parseTokenClaims(String token) {
try {
return getJwtParser(false).parseSignedClaims(token);
} catch (UnsupportedJwtException | MalformedJwtException | IllegalArgumentException ex) {
log.debug("Invalid JWT Token", ex);
throw new BadCredentialsException("Invalid JWT token: ", ex);
} catch (SignatureException | ExpiredJwtException expiredEx) {
log.debug("JWT Token is expired", expiredEx);
throw new JwtExpiredTokenException(token, "JWT Token expired", expiredEx);
}
}
public JwtPair createTokenPair(SecurityUser securityUser) {
securityUser.setSessionId(UUID.randomUUID().toString());
JwtToken accessToken = createAccessJwtToken(securityUser);
JwtToken refreshToken = createRefreshToken(securityUser);
return new JwtPair(accessToken.token(), refreshToken.token());
}
private SecretKey getSecretKey(boolean forceReload) {
if (secretKey == null || forceReload) {
synchronized (this) {
if (secretKey == null || forceReload) {
byte[] decodedToken = Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey());
secretKey = new SecretKeySpec(decodedToken, "HmacSHA512");
} | }
}
return secretKey;
}
private JwtParser getJwtParser(boolean forceReload) {
if (jwtParser == null || forceReload) {
synchronized (this) {
if (jwtParser == null || forceReload) {
jwtParser = Jwts.parser()
.verifyWith(Keys.hmacShaKeyFor(Base64.getDecoder().decode(jwtSettingsService.getJwtSettings().getTokenSigningKey())))
.build();
}
}
}
return jwtParser;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\model\token\JwtTokenFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private MaterialDescriptorQueryBuilder createMaterialDescriptorQueryBuilder(
@NonNull final MaterialDescriptor materialDescriptor)
{
final MaterialDescriptorQueryBuilder builder = MaterialDescriptorQuery
.builder()
.customerIdOperator(CustomerIdOperator.GIVEN_ID_OR_NULL); // want the latest, only excluding records that have a *different* customerId
if (materialDescriptor.getCustomerId() != null && materialDescriptor.isReservedForCustomer())
{
// do include the bpartner in the query, because e.g. an increase for a given bpartner does a raised ATP just for that partner, and not for everyone
builder.customer(BPartnerClassifier.specific(materialDescriptor.getCustomerId()));
}
else
{
// ..on the other hand, if materialDescriptor has *no* bpartner or that partner is just for info, then the respective change in ATP is for everybody
builder.customer(BPartnerClassifier.any());
}
return builder
.productId(materialDescriptor.getProductId())
.storageAttributesKey(materialDescriptor.getStorageAttributesKey())
.warehouseId(materialDescriptor.getWarehouseId());
}
@Nullable
private Candidate getPreviousStockForStockCreation(@NonNull final Candidate candidate)
{
final Candidate previousStockOrNull = getPreviousStockOrNullForCandidate(candidate);
if (!candidate.isSimulated() || previousStockOrNull == null) | {
return previousStockOrNull;
}
//dev-note: we need to make sure it's not it's own Stock as we don't propagate changes to later stocks for simulated candidates
final boolean isOwnStock = CandidateId.isRegularNonNull(candidate.getParentId()) && candidate.getParentId().equals(previousStockOrNull.getId())
|| CandidateId.isRegularNonNull(previousStockOrNull.getParentId()) && previousStockOrNull.getParentId().equals(candidate.getId());
if (!isOwnStock)
{
return previousStockOrNull;
}
return getPreviousStockOrNullForCandidate(previousStockOrNull);
}
@Nullable
private Candidate getPreviousStockOrNullForCandidate(@NonNull final Candidate candidate)
{
final CandidatesQuery previousStockQuery = createStockQueryUntilDate(candidate);
return candidateRepositoryRetrieval.retrievePreviousMatchForCandidateIdOrNull(previousStockQuery, candidate.getId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\candidatechange\StockCandidateService.java | 2 |
请完成以下Java代码 | public class DeleteHistoricProcessInstanceCmd implements Command<Object>, Serializable {
private static final long serialVersionUID = 1L;
protected String processInstanceId;
public DeleteHistoricProcessInstanceCmd(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public Object execute(CommandContext commandContext) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
// Check if process instance is still running
HistoricProcessInstance instance = commandContext
.getHistoricProcessInstanceEntityManager()
.findById(processInstanceId);
if (instance == null) {
throw new ActivitiObjectNotFoundException(
"No historic process instance found with id: " + processInstanceId,
HistoricProcessInstance.class
); | }
if (instance.getEndTime() == null) {
throw new ActivitiException(
"Process instance is still running, cannot delete historic process instance: " + processInstanceId
);
}
executeInternal(commandContext, instance);
return null;
}
protected void executeInternal(CommandContext commandContext, HistoricProcessInstance instance) {
commandContext.getHistoricProcessInstanceEntityManager().delete(processInstanceId);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\DeleteHistoricProcessInstanceCmd.java | 1 |
请完成以下Java代码 | public List<FilterDto> getFilters(UriInfo uriInfo, Boolean itemCount, Integer firstResult, Integer maxResults) {
FilterService filterService = getProcessEngine().getFilterService();
FilterQuery query = getQueryFromQueryParameters(uriInfo.getQueryParameters());
List<Filter> matchingFilters = QueryUtil.list(query, firstResult, maxResults);
List<FilterDto> filters = new ArrayList<FilterDto>();
for (Filter filter : matchingFilters) {
FilterDto dto = FilterDto.fromFilter(filter);
if (itemCount != null && itemCount) {
dto.setItemCount(filterService.count(filter.getId()));
}
filters.add(dto);
}
return filters;
}
@Override
public CountResultDto getFiltersCount(UriInfo uriInfo) {
FilterQuery query = getQueryFromQueryParameters(uriInfo.getQueryParameters());
return new CountResultDto(query.count());
}
@Override
public FilterDto createFilter(FilterDto filterDto) {
FilterService filterService = getProcessEngine().getFilterService();
String resourceType = filterDto.getResourceType();
Filter filter;
if (EntityTypes.TASK.equals(resourceType)) {
filter = filterService.newTaskFilter();
}
else {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "Unable to create filter with invalid resource type '" + resourceType + "'");
}
try {
filterDto.updateFilter(filter, getProcessEngine());
}
catch (NotValidException e) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, e, "Unable to create filter with invalid content");
}
filterService.saveFilter(filter);
return FilterDto.fromFilter(filter);
} | protected FilterQuery getQueryFromQueryParameters(MultivaluedMap<String, String> queryParameters) {
ProcessEngine engine = getProcessEngine();
FilterQueryDto queryDto = new FilterQueryDto(getObjectMapper(), queryParameters);
return queryDto.toQuery(engine);
}
@Override
public ResourceOptionsDto availableOperations(UriInfo context) {
UriBuilder baseUriBuilder = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(FilterRestService.PATH);
ResourceOptionsDto resourceOptionsDto = new ResourceOptionsDto();
// GET /
URI baseUri = baseUriBuilder.build();
resourceOptionsDto.addReflexiveLink(baseUri, HttpMethod.GET, "list");
// GET /count
URI countUri = baseUriBuilder.clone().path("/count").build();
resourceOptionsDto.addReflexiveLink(countUri, HttpMethod.GET, "count");
// POST /create
if (isAuthorized(CREATE)) {
URI createUri = baseUriBuilder.clone().path("/create").build();
resourceOptionsDto.addReflexiveLink(createUri, HttpMethod.POST, "create");
}
return resourceOptionsDto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\FilterRestServiceImpl.java | 1 |
请完成以下Java代码 | public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
} | /** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserGroup.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Application {
@Autowired
private InventoryRepository inventoryRepository;
@Autowired
private OrderRepository orderRepository;
@Transactional(rollbackFor = Exception.class)
public void placeOrder(String productId, int amount) throws Exception {
String orderId = UUID.randomUUID()
.toString();
Inventory inventory = inventoryRepository.getReferenceById(productId);
inventory.setBalance(inventory.getBalance() - amount); | inventoryRepository.save(inventory);
Order order = new Order();
order.setOrderId(orderId);
order.setProductId(productId);
order.setAmount( Long.valueOf(amount));
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Order>> violations = validator.validate(order);
if (violations.size() > 0)
throw new Exception("Invalid instance of an order.");
orderRepository.save(order);
}
} | repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\spring\jpa\Application.java | 2 |
请完成以下Java代码 | public InfoBuilder setInfoWindow(final I_AD_InfoWindow infoWindow)
{
_infoWindowDef = infoWindow;
if (infoWindow != null)
{
final String tableName = Services.get(IADInfoWindowBL.class).getTableName(infoWindow);
setTableName(tableName);
}
return this;
}
private I_AD_InfoWindow getInfoWindow()
{
if (_infoWindowDef != null)
{
return _infoWindowDef;
}
final String tableName = getTableName();
final I_AD_InfoWindow infoWindowFound = Services.get(IADInfoWindowDAO.class).retrieveInfoWindowByTableName(getCtx(), tableName);
if (infoWindowFound != null && infoWindowFound.isActive())
{
return infoWindowFound;
}
return null;
}
/**
* @param iconName icon name (without size and without file extension).
*/
public InfoBuilder setIconName(final String iconName)
{
if (Check.isEmpty(iconName, true))
{
return setIcon(null); | }
else
{
final Image icon = Images.getImage2(iconName + "16");
return setIcon(icon);
}
}
public InfoBuilder setIcon(final Image icon)
{
this._iconImage = icon;
return this;
}
private Image getIconImage()
{
return _iconImage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\InfoBuilder.java | 1 |
请完成以下Java代码 | public int getC_Project_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_Project_ID();
}
/**
* Get Project Phase
*
* @return project phase if based on shipment line and 0 for charge based
*/
public int getC_ProjectPhase_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_ProjectPhase_ID();
}
/**
* Get Project Task
*
* @return project task if based on shipment line and 0 for charge based
*/
public int getC_ProjectTask_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_ProjectTask_ID();
}
/**
* Get Activity
*
* @return project phase if based on shipment line and 0 for charge based
*/
public int getC_Activity_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_Activity_ID();
}
public int getC_Order_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_Order_ID();
}
/**
* Get Campaign
*
* @return campaign if based on shipment line and 0 for charge based
*/
public int getC_Campaign_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getC_Campaign_ID();
}
/**
* Get Org Trx
*
* @return Org Trx if based on shipment line and 0 for charge based
*/
public int getAD_OrgTrx_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getAD_OrgTrx_ID();
}
/**
* Get User1 | *
* @return user1 if based on shipment line and 0 for charge based
*/
public int getUser1_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getUser1_ID();
}
/**
* Get User2
*
* @return user2 if based on shipment line and 0 for charge based
*/
public int getUser2_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getUser2_ID();
}
/**
* Get Attribute Set Instance
*
* @return ASI if based on shipment line and 0 for charge based
*/
public int getM_AttributeSetInstance_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getM_AttributeSetInstance_ID();
}
/**
* Get Locator
*
* @return locator if based on shipment line and 0 for charge based
*/
public int getM_Locator_ID()
{
if (m_ioLine == null)
{
return 0;
}
return m_ioLine.getM_Locator_ID();
}
/**
* Get Tax
*
* @return Tax based on Invoice/Order line and Tax exempt for charge based
*/
public int getC_Tax_ID()
{
return taxId;
}
} // MRMALine | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRMALine.java | 1 |
请完成以下Java代码 | public class CharStack {
private LinkedList<Character> items;
public CharStack() {
this.items = new LinkedList<Character>();
}
public void push(Character item) {
items.push(item);
}
public Character peek() {
return items.getFirst();
} | public Character pop() {
Iterator<Character> iter = items.iterator();
Character item = iter.next();
if (item != null) {
iter.remove();
return item;
}
return null;
}
public int size() {
return items.size();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\charstack\CharStack.java | 1 |
请完成以下Java代码 | public class CoverArt implements Serializable {
private String frontCoverArtUrl;
private String backCoverArtUrl;
private String upcCode;
public String getFrontCoverArtUrl() {
return frontCoverArtUrl;
}
public void setFrontCoverArtUrl(String frontCoverArtUrl) {
this.frontCoverArtUrl = frontCoverArtUrl;
}
public String getBackCoverArtUrl() {
return backCoverArtUrl;
}
public void setBackCoverArtUrl(String backCoverArtUrl) {
this.backCoverArtUrl = backCoverArtUrl;
}
public String getUpcCode() {
return upcCode;
}
public void setUpcCode(String upcCode) {
this.upcCode = upcCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((backCoverArtUrl == null) ? 0 : backCoverArtUrl.hashCode());
result = prime * result + ((frontCoverArtUrl == null) ? 0 : frontCoverArtUrl.hashCode());
result = prime * result + ((upcCode == null) ? 0 : upcCode.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) | return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CoverArt other = (CoverArt) obj;
if (backCoverArtUrl == null) {
if (other.backCoverArtUrl != null)
return false;
} else if (!backCoverArtUrl.equals(other.backCoverArtUrl))
return false;
if (frontCoverArtUrl == null) {
if (other.frontCoverArtUrl != null)
return false;
} else if (!frontCoverArtUrl.equals(other.frontCoverArtUrl))
return false;
if (upcCode == null) {
if (other.upcCode != null)
return false;
} else if (!upcCode.equals(other.upcCode))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\hibernate-libraries\src\main\java\com\baeldung\hibernate\types\CoverArt.java | 1 |
请完成以下Java代码 | private POSProduct toPOSProduct(@NonNull final I_M_ProductPrice productPrice)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final UomId uomId;
final UomId catchWeightUomId;
final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofCode(productPrice.getInvoicableQtyBasedOn());
switch (invoicableQtyBasedOn)
{
case NominalWeight:
uomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
catchWeightUomId = null;
break;
case CatchWeight:
uomId = getProductUomId(productId);
catchWeightUomId = UomId.ofRepoId(productPrice.getC_UOM_ID());
break;
default:
throw new AdempiereException("Unknown invoicableQtyBasedOn: " + invoicableQtyBasedOn);
}
return POSProduct.builder()
.id(productId)
.name(getProductName(productId))
.price(extractPrice(productPrice))
.currencySymbol(currency.getSymbol())
.uom(toUomIdAndSymbol(uomId))
.catchWeightUom(catchWeightUomId != null ? toUomIdAndSymbol(catchWeightUomId) : null)
.taxCategoryId(TaxCategoryId.ofRepoId(productPrice.getC_TaxCategory_ID()))
.build();
}
private ITranslatableString getProductName(final ProductId productId)
{
final I_M_Product product = getProductById(productId); | final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(product);
return trls.getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName());
}
private UomId getProductUomId(final ProductId productId)
{
final I_M_Product product = getProductById(productId);
return UomId.ofRepoId(product.getC_UOM_ID());
}
private Amount extractPrice(final I_M_ProductPrice productPrice)
{
return Amount.of(productPrice.getPriceStd(), currency.getCurrencyCode());
}
private String getUOMSymbol(final UomId uomId)
{
final I_C_UOM uom = uomDAO.getById(uomId);
return StringUtils.trimBlankToOptional(uom.getUOMSymbol()).orElseGet(uom::getName);
}
private UomIdAndSymbol toUomIdAndSymbol(final UomId uomId)
{
return UomIdAndSymbol.of(uomId, getUOMSymbol(uomId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsLoader.java | 1 |
请完成以下Java代码 | public VersionRange parseRange(String text) {
Assert.notNull(text, "Text must not be null");
Matcher matcher = RANGE_REGEX.matcher(text.trim());
if (!matcher.matches()) {
// Try to read it as simple string
Version version = parse(text);
return new VersionRange(version, true, null, true);
}
boolean lowerInclusive = matcher.group(1).equals("[");
Version lowerVersion = parse(matcher.group(2));
Version higherVersion = parse(matcher.group(3));
boolean higherInclusive = matcher.group(4).equals("]");
return new VersionRange(lowerVersion, lowerInclusive, higherVersion, higherInclusive);
}
private Version findLatestVersion(Integer major, Integer minor, Version.Qualifier qualifier) {
List<Version> matches = this.latestVersions.stream().filter((it) -> { | if (major != null && !major.equals(it.getMajor())) {
return false;
}
if (minor != null && !minor.equals(it.getMinor())) {
return false;
}
if (qualifier != null && !qualifier.equals(it.getQualifier())) {
return false;
}
return true;
}).toList();
return (matches.size() != 1) ? null : matches.get(0);
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionParser.java | 1 |
请完成以下Java代码 | public class ContentTypeOptionsProvider extends HeaderSecurityProvider {
public static final String HEADER_NAME = "X-Content-Type-Options";
public static final String HEADER_DEFAULT_VALUE = "nosniff";
public static final String DISABLED_PARAM = "contentTypeOptionsDisabled";
public static final String VALUE_PARAM = "contentTypeOptionsValue";
@Override
public Map<String, String> initParams() {
initParams.put(DISABLED_PARAM, null);
initParams.put(VALUE_PARAM, null);
return initParams;
}
@Override
public void parseParams() {
String disabled = initParams.get(DISABLED_PARAM);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(false);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
String value = initParams.get(VALUE_PARAM);
if (!isDisabled()) {
if (!ServletFilterUtil.isEmpty(value)) {
setValue(value); | } else {
setValue(HEADER_DEFAULT_VALUE);
}
}
}
@Override
public String getHeaderName() {
return HEADER_NAME;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentTypeOptionsProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
return converter;
}
/**
* 非对称密钥加密,获取 public key。
* 自动选择加载方式。
*
* @return public key
*/
private String getPubKey() {
// 如果本地没有密钥,就从授权服务器中获取
return StringUtils.isEmpty(resourceServerProperties.getJwt().getKeyValue()) ? getKeyFromAuthorizationServer() : resourceServerProperties.getJwt().getKeyValue();
}
/**
* 本地没有公钥的时候,从服务器上获取
* 需要进行 Basic 认证
*
* @return public key
*/
private String getKeyFromAuthorizationServer() {
ObjectMapper objectMapper = new ObjectMapper(); | HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
String pubKey = new RestTemplate().getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
try {
JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
log.info("Get Key From Authorization Server.");
return body.getStr("value");
} catch (IOException e) {
log.error("Get public key error: {}", e.getMessage());
}
return null;
}
/**
* 客户端信息
*
* @return basic
*/
private String encodeClient() {
return "Basic " + Base64.getEncoder().encodeToString((resourceServerProperties.getClientId() + ":" + resourceServerProperties.getClientSecret()).getBytes());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-resource-server\src\main\java\com\xkcoding\oauth\config\OauthResourceTokenConfig.java | 2 |
请完成以下Java代码 | public class EntityDependencyOrder {
public static List<Class<? extends Entity>> DELETE_ORDER = new ArrayList<>();
public static List<Class<? extends Entity>> INSERT_ORDER;
public static Collection<Class<? extends Entity>> IMMUTABLE_ENTITIES = new ArrayList<>();
static {
DELETE_ORDER.add(PropertyEntityImpl.class);
DELETE_ORDER.add(BatchPartEntityImpl.class);
DELETE_ORDER.add(BatchEntityImpl.class);
DELETE_ORDER.add(JobEntityImpl.class);
DELETE_ORDER.add(ExternalWorkerJobEntityImpl.class);
DELETE_ORDER.add(TimerJobEntityImpl.class);
DELETE_ORDER.add(SuspendedJobEntityImpl.class);
DELETE_ORDER.add(DeadLetterJobEntityImpl.class);
DELETE_ORDER.add(HistoricTaskLogEntryEntityImpl.class);
DELETE_ORDER.add(HistoryJobEntityImpl.class);
DELETE_ORDER.add(HistoricEntityLinkEntityImpl.class);
DELETE_ORDER.add(HistoricIdentityLinkEntityImpl.class);
DELETE_ORDER.add(HistoricMilestoneInstanceEntityImpl.class);
DELETE_ORDER.add(HistoricTaskInstanceEntityImpl.class);
DELETE_ORDER.add(HistoricCaseInstanceEntityImpl.class);
DELETE_ORDER.add(VariableInstanceEntityImpl.class);
DELETE_ORDER.add(HistoricVariableInstanceEntityImpl.class);
DELETE_ORDER.add(SignalEventSubscriptionEntityImpl.class);
DELETE_ORDER.add(MessageEventSubscriptionEntityImpl.class);
DELETE_ORDER.add(CompensateEventSubscriptionEntityImpl.class);
DELETE_ORDER.add(GenericEventSubscriptionEntityImpl.class);
DELETE_ORDER.add(EventSubscriptionEntityImpl.class);
DELETE_ORDER.add(EntityLinkEntityImpl.class);
DELETE_ORDER.add(IdentityLinkEntityImpl.class);
DELETE_ORDER.add(TaskEntityImpl.class); | DELETE_ORDER.add(MilestoneInstanceEntityImpl.class);
DELETE_ORDER.add(SentryPartInstanceEntityImpl.class);
DELETE_ORDER.add(PlanItemInstanceEntityImpl.class);
DELETE_ORDER.add(HistoricPlanItemInstanceEntityImpl.class);
DELETE_ORDER.add(CaseInstanceEntityImpl.class);
DELETE_ORDER.add(CaseDefinitionEntityImpl.class);
DELETE_ORDER.add(ByteArrayEntityImpl.class);
DELETE_ORDER.add(CmmnResourceEntityImpl.class);
DELETE_ORDER.add(CmmnDeploymentEntityImpl.class);
INSERT_ORDER = new ArrayList<>(DELETE_ORDER);
Collections.reverse(INSERT_ORDER);
IMMUTABLE_ENTITIES.add(EntityLinkEntityImpl.class);
IMMUTABLE_ENTITIES.add(HistoricEntityLinkEntityImpl.class);
IMMUTABLE_ENTITIES.add(HistoricIdentityLinkEntityImpl.class);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\db\EntityDependencyOrder.java | 1 |
请完成以下Java代码 | public void setCreditor(EsrAddressType value) {
this.creditor = value;
}
/**
* Gets the value of the balance property.
*
* @return
* possible object is
* {@link BalanceType }
*
*/
public BalanceType getBalance() {
return balance;
}
/**
* Sets the value of the balance property.
*
* @param value
* allowed object is
* {@link BalanceType }
*
*/
public void setBalance(BalanceType value) {
this.balance = value;
}
/**
* Gets the value of the esr5 property.
*
* @return
* possible object is
* {@link Esr5Type }
*
*/
public Esr5Type getEsr5() {
return esr5;
}
/**
* Sets the value of the esr5 property.
*
* @param value
* allowed object is
* {@link Esr5Type }
*
*/
public void setEsr5(Esr5Type value) {
this.esr5 = value;
}
/**
* Gets the value of the esr9 property.
*
* @return
* possible object is
* {@link Esr9Type }
*
*/
public Esr9Type getEsr9() {
return esr9;
}
/** | * Sets the value of the esr9 property.
*
* @param value
* allowed object is
* {@link Esr9Type }
*
*/
public void setEsr9(Esr9Type value) {
this.esr9 = value;
}
/**
* Gets the value of the esrRed property.
*
* @return
* possible object is
* {@link EsrRedType }
*
*/
public EsrRedType getEsrRed() {
return esrRed;
}
/**
* Sets the value of the esrRed property.
*
* @param value
* allowed object is
* {@link EsrRedType }
*
*/
public void setEsrRed(EsrRedType value) {
this.esrRed = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\ReimbursementType.java | 1 |
请完成以下Java代码 | public <T> IQueryOrderByBuilder<T> createQueryOrderByBuilder(final Class<T> modelClass)
{
return new QueryOrderByBuilder<>();
}
@Override
public IQueryOrderBy createSqlQueryOrderBy(final String orderBy)
{
return SqlQueryOrderBy.of(orderBy);
}
@Override
public <T> ICompositeQueryFilter<T> createCompositeQueryFilter(final Class<T> modelClass)
{
return CompositeQueryFilter.newInstance(modelClass);
}
@Override
public ICompositeQueryFilter<Object> createCompositeQueryFilter(@Nullable final String modelTableName)
{
return CompositeQueryFilter.newInstance(modelTableName);
}
@Override
public <T> ICompositeQueryUpdater<T> createCompositeQueryUpdater(final Class<T> modelClass)
{
return new CompositeQueryUpdater<>();
}
@Override
public <T> String debugAccept(final IQueryFilter<T> filter, final T model)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n-------------------------------------------------------------------------------");
sb.append("\nModel: " + model);
final List<IQueryFilter<T>> filters = extractAllFilters(filter);
for (final IQueryFilter<T> f : filters)
{
final boolean accept = f.accept(model);
sb.append("\nFilter(accept=" + accept + "): " + f);
}
sb.append("\n-------------------------------------------------------------------------------");
return sb.toString();
}
private <T> List<IQueryFilter<T>> extractAllFilters(@Nullable final IQueryFilter<T> filter)
{
if (filter == null)
{
return Collections.emptyList();
}
final List<IQueryFilter<T>> result = new ArrayList<>();
result.add(filter); | if (filter instanceof ICompositeQueryFilter)
{
final ICompositeQueryFilter<T> compositeFilter = (ICompositeQueryFilter<T>)filter;
for (final IQueryFilter<T> f : compositeFilter.getFilters())
{
final List<IQueryFilter<T>> resultLocal = extractAllFilters(f);
result.addAll(resultLocal);
}
}
return result;
}
@Override
public <T> QueryResultPage<T> retrieveNextPage(
@NonNull final Class<T> clazz,
@NonNull final String next)
{
if (Adempiere.isUnitTestMode())
{
return POJOQuery.getPage(clazz, next);
}
return SpringContextHolder.instance
.getBean(PaginationService.class)
.loadPage(clazz, next);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handleEntityDeletionEvent(DeleteEntityEvent<?> event) {
TenantId tenantId = event.getTenantId();
EntityId entityId = event.getEntityId();
EntityType entityType = entityId.getEntityType();
try {
log.trace("[{}][{}][{}] Handling entity deletion event", tenantId, entityType, entityId.getId());
if (!skippedEntities.contains(entityType)) {
cleanUpRelatedData(tenantId, entityId);
}
if (entityType == EntityType.USER && event.getCause() != ActionCause.TENANT_DELETION) {
submitTask(HousekeeperTask.unassignAlarms((User) event.getEntity()));
}
} catch (Throwable e) {
log.error("[{}][{}][{}] Failed to handle entity deletion event", tenantId, entityType, entityId.getId(), e);
}
}
public void cleanUpRelatedData(TenantId tenantId, EntityId entityId) {
log.debug("[{}][{}][{}] Cleaning up related data", tenantId, entityId.getEntityType(), entityId.getId());
relationService.deleteEntityRelations(tenantId, entityId);
submitTask(HousekeeperTask.deleteAttributes(tenantId, entityId));
submitTask(HousekeeperTask.deleteTelemetry(tenantId, entityId));
submitTask(HousekeeperTask.deleteEvents(tenantId, entityId));
submitTask(HousekeeperTask.deleteAlarms(tenantId, entityId)); | submitTask(HousekeeperTask.deleteCalculatedFields(tenantId, entityId));
if (Job.SUPPORTED_ENTITY_TYPES.contains(entityId.getEntityType())) {
submitTask(HousekeeperTask.deleteJobs(tenantId, entityId));
}
}
public void removeTenantEntities(TenantId tenantId, EntityType... entityTypes) {
for (EntityType entityType : entityTypes) {
submitTask(HousekeeperTask.deleteTenantEntities(tenantId, entityType));
}
}
private void submitTask(HousekeeperTask task) {
housekeeperClient.ifPresent(housekeeperClient -> {
housekeeperClient.submitTask(task);
});
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\housekeeper\CleanUpService.java | 2 |
请完成以下Java代码 | public void onManualCompletion(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("complete", execution);
}
// termination ////////////////////////////////////////////////////////
public void onTermination(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, TERMINATED, "terminate");
performTerminate(execution);
}
public void onParentTermination(CmmnActivityExecution execution) {
if (execution.isCompleted()) {
String id = execution.getId();
throw LOG.executionAlreadyCompletedException("parentTerminate", id);
}
performParentTerminate(execution);
}
public void onExit(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("exit", execution);
}
// occur /////////////////////////////////////////////////////////////////
public void onOccur(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, COMPLETED, "occur");
}
// suspension ////////////////////////////////////////////////////////////
public void onSuspension(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, AVAILABLE, SUSPENDED, "suspend");
performSuspension(execution);
}
public void onParentSuspension(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("parentSuspend", execution);
}
// resume ////////////////////////////////////////////////////////////////
public void onResume(CmmnActivityExecution execution) {
ensureTransitionAllowed(execution, SUSPENDED, AVAILABLE, "resume");
CmmnActivityExecution parent = execution.getParent();
if (parent != null) {
if (!parent.isActive()) {
String id = execution.getId();
throw LOG.resumeInactiveCaseException("resume", id);
}
}
resuming(execution);
}
public void onParentResume(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("parentResume", execution); | }
// re-activation ////////////////////////////////////////////////////////
public void onReactivation(CmmnActivityExecution execution) {
throw createIllegalStateTransitionException("reactivate", execution);
}
// sentry ///////////////////////////////////////////////////////////////
protected boolean isAtLeastOneExitCriterionSatisfied(CmmnActivityExecution execution) {
return false;
}
public void fireExitCriteria(CmmnActivityExecution execution) {
throw LOG.criteriaNotAllowedForEventListenerOrMilestonesException("exit", execution.getId());
}
// helper ////////////////////////////////////////////////////////////////
protected CaseIllegalStateTransitionException createIllegalStateTransitionException(String transition, CmmnActivityExecution execution) {
String id = execution.getId();
return LOG.illegalStateTransitionException(transition, id, getTypeName());
}
protected abstract String getTypeName();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\EventListenerOrMilestoneActivityBehavior.java | 1 |
请完成以下Java代码 | public Builder setQtyCUsTotal(final BigDecimal qtyCUsTotal)
{
this.qtyCUsTotal = qtyCUsTotal;
return this;
}
public BigDecimal getQtyCUsTotal()
{
Check.assumeNotNull(qtyCUsTotal, "qtyCUsTotal not null");
return qtyCUsTotal;
}
public Builder setQtyTUsTotal(final BigDecimal qtyTUsTotal)
{
this.qtyTUsTotal = qtyTUsTotal;
return this;
}
public BigDecimal getQtyTUsTotal()
{
if (qtyTUsTotal == null)
{
return Quantity.QTY_INFINITE;
}
return qtyTUsTotal;
}
public Builder setStandardQtyCUsPerTU(final BigDecimal qtyCUsPerTU)
{
this.qtyCUsPerTU = qtyCUsPerTU;
return this;
}
public BigDecimal getStandardQtyCUsPerTU()
{
return qtyCUsPerTU;
}
public Builder setStandardQtyTUsPerLU(final BigDecimal qtyTUsPerLU)
{
this.qtyTUsPerLU = qtyTUsPerLU; | return this;
}
public Builder setStandardQtyTUsPerLU(final int qtyTUsPerLU)
{
return setStandardQtyTUsPerLU(BigDecimal.valueOf(qtyTUsPerLU));
}
public BigDecimal getStandardQtyTUsPerLU()
{
return qtyTUsPerLU;
}
public Builder setStandardQtysAsInfinite()
{
setStandardQtyCUsPerTU(BigDecimal.ZERO);
setStandardQtyTUsPerLU(BigDecimal.ZERO);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\TotalQtyCUBreakdownCalculator.java | 1 |
请完成以下Spring Boot application配置 | #
# Copyright 2015-2022 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permiss | ions and
# limitations under the License.
#
logging.level.root=WARN
logging.level.sample.mybatis.freemarker.legacy.mapper=TRACE
mybatis.mapper-locations=classpath*:/mappers/*.xml
mybatis.type-aliases-package=sample.mybatis.freemarker.legacy.domain | repos\spring-boot-starter-master\mybatis-spring-boot-samples\mybatis-spring-boot-sample-freemarker-legacy\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public class P100 implements Serializable
{
private static final long serialVersionUID = 5689176109531323064L;
private String record;
private String partner;
private String messageNo;
private String positionNo;
private String eanArtNo;
private String buyerArtNo;
private String supplierArtNo;
private String artDescription;
private String deliverQual;
private String deliverQTY;
private String deliverUnit;
private String orderNo;
private String orderPosNo;
private String cUperTU;
private String currency;
private String detailPrice; | private Date deliveryDate;
private Date bestBeforeDate;
private String chargenNo;
private String articleClass;
private String differenceQTY;
private String discrepancyCode;
private Date diffDeliveryDate;
private String eanTU;
private String storeNumber;
private String unitCode;
private Date sellBeforeDate;
private Date productionDate;
private String discrepancyText;
private String grainItemNummer;
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\compudata\P100.java | 1 |
请完成以下Java代码 | private String getParameters(final HttpServletRequest request) {
final StringBuffer posted = new StringBuffer();
final Enumeration<?> e = request.getParameterNames();
if (e != null)
posted.append("?");
while (e != null && e.hasMoreElements()) {
if (posted.length() > 1)
posted.append("&");
final String curr = (String) e.nextElement();
posted.append(curr)
.append("=");
if (curr.contains("password") || curr.contains("answer") || curr.contains("pwd")) {
posted.append("*****");
} else {
posted.append(request.getParameter(curr));
}
}
final String ip = request.getHeader("X-FORWARDED-FOR"); | final String ipAddr = (ip == null) ? getRemoteAddr(request) : ip;
if (!Strings.isNullOrEmpty(ipAddr))
posted.append("&_psip=" + ipAddr);
return posted.toString();
}
private String getRemoteAddr(final HttpServletRequest request) {
final String ipFromHeader = request.getHeader("X-FORWARDED-FOR");
if (ipFromHeader != null && ipFromHeader.length() > 0) {
log.debug("ip from proxy - X-FORWARDED-FOR : " + ipFromHeader);
return ipFromHeader;
}
return request.getRemoteAddr();
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\web\interceptor\LoggerInterceptor.java | 1 |
请完成以下Java代码 | public class SubscriptionDAO extends AbstractSubscriptionDAO
{
public static final String SUBSCRIPTION_NO_SP_AT_DATE_1P = "Subscription_NoSPAtDate_1P";
@Override
public List<I_C_Flatrate_Term> retrieveTermsForOLCand(final I_C_OLCand olCand)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(olCand);
final String trxName = InterfaceWrapperHelper.getTrxName(olCand);
final String wc = I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID + " IN (\n" +
" select " + I_C_Contract_Term_Alloc.COLUMNNAME_C_Flatrate_Term_ID + "\n" +
" from " + I_C_Contract_Term_Alloc.Table_Name + " cta \n" +
" where \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_IsActive + "=" + DB.TO_STRING("Y") + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_AD_Client_ID + "=" + I_C_Flatrate_Term.Table_Name + "." + I_C_Flatrate_Term.COLUMNNAME_AD_Client_ID + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_C_OLCand_ID + "=? \n" +
")";
return new Query(ctx, I_C_Flatrate_Term.Table_Name, wc, trxName) //
.setParameters(olCand.getC_OLCand_ID())
.setClient_ID()
.setOnlyActiveRecords(true)
.setOrderBy(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Term_ID)
.list(I_C_Flatrate_Term.class);
}
@Override
public <T extends I_C_OLCand> List<T> retrieveOLCands(final I_C_Flatrate_Term term, final Class<T> clazz)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(term); | final String trxName = InterfaceWrapperHelper.getTrxName(term);
final String wc = I_C_OLCand.COLUMNNAME_C_OLCand_ID + " IN (\n" +
" select " + I_C_Contract_Term_Alloc.COLUMNNAME_C_OLCand_ID + "\n" +
" from " + I_C_Contract_Term_Alloc.Table_Name + " cta \n" +
" where \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_IsActive + "=" + DB.TO_STRING("Y") + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_AD_Client_ID + "=" + I_C_OLCand.Table_Name + "." + I_C_OLCand.COLUMNNAME_AD_Client_ID + " AND \n" +
" cta." + I_C_Contract_Term_Alloc.COLUMNNAME_C_Flatrate_Term_ID + "=? \n" +
")";
return new Query(ctx, I_C_OLCand.Table_Name, wc, trxName) //
.setParameters(term.getC_Flatrate_Term_ID())
.setClient_ID()
.setOnlyActiveRecords(true)
.setOrderBy(I_C_OLCand.COLUMNNAME_C_OLCand_ID)
.list(clazz);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionDAO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int delete(Long memberId, List<Long> ids) {
OmsCartItem record = new OmsCartItem();
record.setDeleteStatus(1);
OmsCartItemExample example = new OmsCartItemExample();
example.createCriteria().andIdIn(ids).andMemberIdEqualTo(memberId);
return cartItemMapper.updateByExampleSelective(record, example);
}
@Override
public CartProduct getCartProduct(Long productId) {
return productDao.getCartProduct(productId);
}
@Override
public int updateAttr(OmsCartItem cartItem) {
//删除原购物车信息
OmsCartItem updateCart = new OmsCartItem();
updateCart.setId(cartItem.getId());
updateCart.setModifyDate(new Date());
updateCart.setDeleteStatus(1); | cartItemMapper.updateByPrimaryKeySelective(updateCart);
cartItem.setId(null);
add(cartItem);
return 1;
}
@Override
public int clear(Long memberId) {
OmsCartItem record = new OmsCartItem();
record.setDeleteStatus(1);
OmsCartItemExample example = new OmsCartItemExample();
example.createCriteria().andMemberIdEqualTo(memberId);
return cartItemMapper.updateByExampleSelective(record,example);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsCartItemServiceImpl.java | 2 |
请完成以下Java代码 | public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getPickingSlot().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
}
@Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final PickingSlotQRCode pickingSlotQRCode = PickingSlotQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode());
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.allocateAndSetPickingSlot(pickingJob, pickingSlotQRCode)
);
}
@Override
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request)
{
final PickingJob pickingJob = getPickingJob(request.getWfProcess());
final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob);
return toJson(pickingSlotSuggestions);
}
private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions)
{
if (pickingSlotSuggestions.isEmpty())
{
return JsonScannedBarcodeSuggestions.EMPTY;
}
return pickingSlotSuggestions.stream()
.map(SetPickingSlotWFActivityHandler::toJson) | .collect(JsonScannedBarcodeSuggestions.collect());
}
private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion)
{
return JsonScannedBarcodeSuggestion.builder()
.caption(pickingSlotSuggestion.getCaption())
.detail(pickingSlotSuggestion.getDeliveryAddress())
.qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString())
.property1("HU")
.value1(String.valueOf(pickingSlotSuggestion.getCountHUs()))
.additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java | 1 |
请完成以下Java代码 | public IdmEngineConfiguration setUsingRelationalDatabase(boolean usingRelationalDatabase) {
this.usingRelationalDatabase = usingRelationalDatabase;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseTablePrefix(String databaseTablePrefix) {
this.databaseTablePrefix = databaseTablePrefix;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseWildcardEscapeCharacter(String databaseWildcardEscapeCharacter) {
this.databaseWildcardEscapeCharacter = databaseWildcardEscapeCharacter;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseCatalog(String databaseCatalog) {
this.databaseCatalog = databaseCatalog;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseSchema(String databaseSchema) {
this.databaseSchema = databaseSchema;
return this;
}
@Override
public IdmEngineConfiguration setTablePrefixIsSchema(boolean tablePrefixIsSchema) {
this.tablePrefixIsSchema = tablePrefixIsSchema;
return this;
}
public PasswordEncoder getPasswordEncoder() {
return passwordEncoder;
}
public IdmEngineConfiguration setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
return this;
}
public PasswordSalt getPasswordSalt() {
return passwordSalt;
}
public IdmEngineConfiguration setPasswordSalt(PasswordSalt passwordSalt) {
this.passwordSalt = passwordSalt;
return this;
}
@Override
public IdmEngineConfiguration setSessionFactories(Map<Class<?>, SessionFactory> sessionFactories) {
this.sessionFactories = sessionFactories;
return this;
}
@Override
public IdmEngineConfiguration setDatabaseSchemaUpdate(String databaseSchemaUpdate) {
this.databaseSchemaUpdate = databaseSchemaUpdate; | return this;
}
@Override
public IdmEngineConfiguration setEnableEventDispatcher(boolean enableEventDispatcher) {
this.enableEventDispatcher = enableEventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventDispatcher(FlowableEventDispatcher eventDispatcher) {
this.eventDispatcher = eventDispatcher;
return this;
}
@Override
public IdmEngineConfiguration setEventListeners(List<FlowableEventListener> eventListeners) {
this.eventListeners = eventListeners;
return this;
}
@Override
public IdmEngineConfiguration setTypedEventListeners(Map<String, List<FlowableEventListener>> typedEventListeners) {
this.typedEventListeners = typedEventListeners;
return this;
}
@Override
public IdmEngineConfiguration setClock(Clock clock) {
this.clock = clock;
return this;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\IdmEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EqualById {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String email;
public EqualById() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
} | @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof EqualById) {
return ((EqualById) obj).getId().equals(getId());
}
return false;
}
} | repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\equality\EqualById.java | 2 |
请完成以下Java代码 | public class BPMNErrorImpl extends BPMNActivityImpl implements BPMNError {
private String errorCode;
private String errorId;
public BPMNErrorImpl() {}
public BPMNErrorImpl(String elementId) {
this.setElementId(elementId);
}
public BPMNErrorImpl(String elementId, String activityName, String activityType) {
this.setElementId(elementId);
this.setActivityName(activityName);
this.setActivityType(activityType);
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorId() {
return errorId;
}
public void setErrorId(String errorId) {
this.errorId = errorId;
}
@Override
public int hashCode() {
return Objects.hash(getElementId(), getActivityName(), getActivityType(), getErrorId(), getErrorCode());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | BPMNErrorImpl that = (BPMNErrorImpl) o;
return (
Objects.equals(getElementId(), that.getElementId()) &&
Objects.equals(getActivityName(), that.getActivityName()) &&
Objects.equals(getActivityType(), that.getActivityType()) &&
Objects.equals(getErrorCode(), that.getErrorCode()) &&
Objects.equals(getErrorId(), that.getErrorId())
);
}
@Override
public String toString() {
return (
"BPMNActivityImpl{" +
"activityName='" +
getActivityName() +
'\'' +
", activityType='" +
getActivityType() +
'\'' +
", elementId='" +
getElementId() +
'\'' +
", errorId='" +
getErrorId() +
'\'' +
", errorCode='" +
getErrorCode() +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNErrorImpl.java | 1 |
请完成以下Java代码 | public class PropertyManager extends AbstractManager {
public PropertyEntity findPropertyById(String propertyId) {
return getDbEntityManager().selectById(PropertyEntity.class, propertyId);
}
public void acquireExclusiveLock() {
// We lock a special deployment lock property
getDbEntityManager().lock("lockDeploymentLockProperty");
}
public void acquireExclusiveLockForHistoryCleanupJob() {
// We lock a special history cleanup lock property
getDbEntityManager().lock("lockHistoryCleanupJobLockProperty"); | }
public void acquireExclusiveLockForStartup() {
// We lock a special startup lock property
getDbEntityManager().lock("lockStartupLockProperty");
}
public void acquireExclusiveLockForInstallationId() {
// We lock a special installation id lock property
getDbEntityManager().lock("lockInstallationIdLockProperty");
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\PropertyManager.java | 1 |
请完成以下Java代码 | 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 Synonym Name.
@param SynonymName | The synonym for the name
*/
public void setSynonymName (String SynonymName)
{
set_Value (COLUMNNAME_SynonymName, SynonymName);
}
/** Get Synonym Name.
@return The synonym for the name
*/
public String getSynonymName ()
{
return (String)get_Value(COLUMNNAME_SynonymName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Synonym.java | 1 |
请完成以下Java代码 | public String build(@NonNull final ProductId productId)
{
final I_PP_Product_BOM bom = bomsRepo.getDefaultBOMByProductId(productId).orElse(null);
if (bom == null || !bom.isActive())
{
return null;
}
return bomsRepo.retrieveLines(bom)
.stream()
.map(this::toBOMLineString)
.filter(Objects::nonNull)
.collect(Collectors.joining("\r\n"))
.trim();
}
@Nullable
private String toBOMLineString(final I_PP_Product_BOMLine bomLine)
{
if (!bomLine.isActive())
{
return null;
}
final I_M_Product product = productsRepo.getById(bomLine.getM_Product_ID());
final String qtyStr = toBOMLineQtyAndUOMString(bomLine);
return (product.getName() + " " + qtyStr).trim();
}
private String toBOMLineQtyAndUOMString(final I_PP_Product_BOMLine bomLine) | {
if (bomLine.isQtyPercentage())
{
return NumberUtils.stripTrailingDecimalZeros(bomLine.getQtyBatch()) + "%";
}
else if (BigDecimal.ONE.equals(bomLine.getQtyBOM()))
{
return "";
}
else
{
final StringBuilder qtyStr = new StringBuilder();
qtyStr.append(NumberUtils.stripTrailingDecimalZeros(bomLine.getQtyBOM()));
final int uomId = bomLine.getC_UOM_ID();
if (uomId > 0)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
qtyStr.append(" ").append(uom.getUOMSymbol());
}
return qtyStr.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMDescriptionBuilder.java | 1 |
请完成以下Java代码 | class ContextVariablesExpression
{
@NonNull private final Object actualExpression;
@NonNull @Getter private final ImmutableSet<String> requiredContextVariables;
private ContextVariablesExpression(
@NonNull final Object actualExpression,
@NonNull final Set<String> requiredContextVariables)
{
this.actualExpression = actualExpression;
this.requiredContextVariables = ImmutableSet.copyOf(requiredContextVariables);
}
@NonNull
public static ContextVariablesExpression ofLogicExpression(@NonNull final ILogicExpression expression)
{
return new ContextVariablesExpression(expression, expression.getParameterNames());
}
@NonNull
public static ContextVariablesExpression ofLookupDescriptor(@NonNull final LookupDescriptor lookupDescriptor)
{
final HashSet<String> requiredContextVariables = new HashSet<>();
if (lookupDescriptor instanceof SqlLookupDescriptor)
{
// NOTE: don't add lookupDescriptor.getDependsOnFieldNames() because that collection contains the postQueryPredicate's required params,
// which in case they are missing it's hard to determine if that's a problem or not.
// e.g. FilterWarehouseByDocTypeValidationRule requires C_DocType_ID but behaves OK/expected when the C_DocType_ID context var is missing. | final SqlLookupDescriptor sqlLookupDescriptor = (SqlLookupDescriptor)lookupDescriptor;
final GenericSqlLookupDataSourceFetcher lookupDataSourceFetcher = sqlLookupDescriptor.getLookupDataSourceFetcher();
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookups().getParameters()));
requiredContextVariables.addAll(CtxNames.toNames(lookupDataSourceFetcher.getSqlForFetchingLookupById().getParameters()));
}
else
{
requiredContextVariables.addAll(lookupDescriptor.getDependsOnFieldNames());
}
return new ContextVariablesExpression(lookupDescriptor, requiredContextVariables);
}
@Override
public String toString()
{
return String.valueOf(actualExpression);
}
public boolean isConstant()
{
return requiredContextVariables.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariablesExpression.java | 1 |
请完成以下Java代码 | public LookupValuesPage retrieveEntities(final LookupDataSourceContext evalCtx)
{
logger.trace("Retrieving entries for: {}", evalCtx);
if (evalCtx.isAnyFilter())
{
// usually that's the case of dropdowns. In that case we don't want to use elasticsearch.
logger.trace("Fallback to database lookup because ANY filter was used");
return databaseLookup.findEntities(evalCtx);
}
final QueryBuilder query = createElasticsearchQuery(evalCtx);
logger.trace("ES query: {}", query);
final int maxSize = Math.min(evalCtx.getLimit(100), 100);
final SearchResponse searchResponse = elasticsearchClient.prepareSearch(esIndexName)
.setQuery(query)
.setExplain(logger.isTraceEnabled())
.setSize(maxSize)
.addStoredField(esKeyColumnName) // not sure it's right
.get();
logger.trace("ES response: {}", searchResponse);
final List<Integer> recordIds = Stream.of(searchResponse.getHits().getHits())
.map(this::extractId)
.distinct()
.collect(ImmutableList.toImmutableList());
logger.trace("Record IDs: {}", recordIds);
final LookupValuesList lookupValues = databaseLookup.findByIdsOrdered(recordIds);
logger.trace("Lookup values: {}", lookupValues);
return lookupValues.pageByOffsetAndLimit(0, Integer.MAX_VALUE);
}
private int extractId(@NonNull final SearchHit hit)
{
final Object value = hit
.getFields()
.get(esKeyColumnName)
.getValue();
return NumberUtils.asInt(value, -1);
}
private QueryBuilder createElasticsearchQuery(final LookupDataSourceContext evalCtx)
{
final String text = evalCtx.getFilter();
return QueryBuilders.multiMatchQuery(text, esSearchFieldNames);
}
@Override
public boolean isCached()
{
return true;
}
@Override
public String getCachePrefix()
{
return null;
}
@Override
public Optional<String> getLookupTableName() | {
return Optional.of(modelTableName);
}
@Override
public void cacheInvalidate()
{
// nothing
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return this;
}
@Override
public boolean isHighVolume()
{
return true;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.lookup;
}
@Override
public boolean hasParameters()
{
return true;
}
@Override
public boolean isNumericKey()
{
return true;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return null;
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
@Override
public SqlForFetchingLookupById getSqlForFetchingLookupByIdExpression()
{
return sqlLookupDescriptor != null ? sqlLookupDescriptor.getSqlForFetchingLookupByIdExpression() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\FullTextSearchLookupDescriptor.java | 1 |
请完成以下Java代码 | public Optional<ExternalSystemExportAudit> getMostRecentByTableReferenceAndSystem(
@NonNull final TableRecordReference tableRecordReference,
@NonNull final ExternalSystemType externalSystemType)
{
return externalSystemExportAuditRepo.getMostRecentByTableReferenceAndSystem(tableRecordReference, externalSystemType);
}
@NonNull
public ExternalSystemExportAudit createESExportAudit(@NonNull final CreateExportAuditRequest request)
{
return externalSystemExportAuditRepo.createESExportAudit(request);
}
@NonNull
private InsertRemoteIssueRequest createInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem, final PInstanceId pInstanceId)
{
return InsertRemoteIssueRequest.builder()
.issueCategory(jsonErrorItem.getIssueCategory())
.issueSummary(StringUtils.isEmpty(jsonErrorItem.getMessage()) ? DEFAULT_ISSUE_SUMMARY : jsonErrorItem.getMessage())
.sourceClassName(jsonErrorItem.getSourceClassName())
.sourceMethodName(jsonErrorItem.getSourceMethodName())
.stacktrace(jsonErrorItem.getStackTrace())
.errorCode(jsonErrorItem.getErrorCode())
.pInstance_ID(pInstanceId) | .orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode()))
.build();
}
@Nullable
public ExternalSystemType getExternalSystemTypeByCodeOrNameOrNull(@Nullable final String value)
{
final ExternalSystem externalSystem = value != null
? externalSystemRepository.getByLegacyCodeOrValueOrNull(value)
: null;
return externalSystem != null
? externalSystem.getType()
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\externlasystem\dto\ExternalSystemService.java | 1 |
请完成以下Java代码 | @Nullable BufferedStartupStep getParent() {
return this.parent;
}
@Override
public String getName() {
return this.name;
}
@Override
public long getId() {
return this.id;
}
Instant getStartTime() {
return this.startTime;
}
@Override
public @Nullable Long getParentId() {
return (this.parent != null) ? this.parent.getId() : null;
}
@Override
public Tags getTags() {
return Collections.unmodifiableList(this.tags)::iterator;
}
@Override
public StartupStep tag(String key, Supplier<String> value) {
return tag(key, value.get());
}
@Override
public StartupStep tag(String key, String value) {
Assert.state(!this.ended.get(), "StartupStep has already ended.");
this.tags.add(new DefaultTag(key, value));
return this;
}
@Override | public void end() {
this.ended.set(true);
this.recorder.accept(this);
}
boolean isEnded() {
return this.ended.get();
}
static class DefaultTag implements Tag {
private final String key;
private final String value;
DefaultTag(String key, String value) {
this.key = key;
this.value = value;
}
@Override
public String getKey() {
return this.key;
}
@Override
public String getValue() {
return this.value;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\BufferedStartupStep.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class);
}
@Override
public void setM_AttributeSet(org.compiere.model.I_M_AttributeSet M_AttributeSet)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet);
}
/** Set Merkmals-Satz.
@param M_AttributeSet_ID
Product Attribute Set
*/
@Override
public void setM_AttributeSet_ID (int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_Value (COLUMNNAME_M_AttributeSet_ID, null);
else
set_Value (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID));
}
/** Get Merkmals-Satz.
@return Product Attribute Set
*/
@Override
public int getM_AttributeSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ausprägung Merkmals-Satz.
@param M_AttributeSetInstance_ID
Product Attribute Set Instance
*/
@Override
public void setM_AttributeSetInstance_ID (int M_AttributeSetInstance_ID)
{
if (M_AttributeSetInstance_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetInstance_ID, Integer.valueOf(M_AttributeSetInstance_ID));
}
/** Get Ausprägung Merkmals-Satz.
@return Product Attribute Set Instance
*/
@Override
public int getM_AttributeSetInstance_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Lot getM_Lot() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class);
}
@Override
public void setM_Lot(org.compiere.model.I_M_Lot M_Lot)
{
set_ValueFromPO(COLUMNNAME_M_Lot_ID, org.compiere.model.I_M_Lot.class, M_Lot);
}
/** Set Los.
@param M_Lot_ID
Product Lot Definition
*/
@Override
public void setM_Lot_ID (int M_Lot_ID) | {
if (M_Lot_ID < 1)
set_Value (COLUMNNAME_M_Lot_ID, null);
else
set_Value (COLUMNNAME_M_Lot_ID, Integer.valueOf(M_Lot_ID));
}
/** Get Los.
@return Product Lot Definition
*/
@Override
public int getM_Lot_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Lot_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Serien-Nr..
@param SerNo
Product Serial Number
*/
@Override
public void setSerNo (java.lang.String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serien-Nr..
@return Product Serial Number
*/
@Override
public java.lang.String getSerNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SerNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetInstance.java | 1 |
请完成以下Java代码 | public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds)
{
if (packageProcessorIds != null)
{
Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!");
}
this.packageProcessorIds = packageProcessorIds;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom()
*/
@Override
public String getPriorityFrom()
{
return priorityFrom;
}
/**
* @param priorityFrom the priorityFrom to set
*/
public void setPriorityFrom(final String priorityFrom) | {
this.priorityFrom = priorityFrom;
}
@Override
public String toString()
{
return "WorkPackageQuery ["
+ "processed=" + processed
+ ", readyForProcessing=" + readyForProcessing
+ ", error=" + error
+ ", skippedTimeoutMillis=" + skippedTimeoutMillis
+ ", packageProcessorIds=" + packageProcessorIds
+ ", priorityFrom=" + priorityFrom
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AkkaController {
@GetMapping(value = "/Akka/AkkaSendString")
@ResponseBody
public void AkkaSendString() {
//Creates system management objects for all management actors
ActorSystem actorSystem = ActorSystem.create();
//use actorSystem.actorOf to define actorNormal as ActorRef
ActorRef actor = actorSystem.actorOf(Props.create(ActorNormal.class), "actorNormal");
//Send message Object msg (the content of the message, any type of data), final ActorRef sender (indicates that there is no sender (actually an Actor called deadLetters))
actor.tell("kiba", ActorRef.noSender());
}
@GetMapping(value = "/Akka/AkkaSendInt")
@ResponseBody
public void AkkaSendInt() {
ActorSystem actorSystem = ActorSystem.create();
ActorRef actor = actorSystem.actorOf(Props.create(ActorNormal.class), "actorNormal");
actor.tell(518, ActorRef.noSender());//send int
}
@GetMapping(value = "/Akka/AkkaAsk")
@ResponseBody
public void AkkaAsk() {
ActorSystem actorSystem = ActorSystem.create();
ActorRef actor = actorSystem.actorOf(Props.create(ActorNormal.class), "actorNormal"); | Timeout timeout = new Timeout(Duration.create(2, TimeUnit.SECONDS));
Future<Object> future = Patterns.ask(actor, "hello", timeout);
try {
Object obj = Await.result(future, timeout.duration());
String reply = obj.toString();
System.out.println("reply msg: " + reply);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping(value = "/Akka/AkkaAskStruct")
@ResponseBody
public void AkkaAskStruct() {
ActorSystem actorSystem = ActorSystem.create();
ActorRef actor = actorSystem.actorOf(Props.create(ActorStruct.class,new User(1,"kiba")), "actorNormal");
Timeout timeout = new Timeout(Duration.create(2, TimeUnit.SECONDS));
Future<Object> future = Patterns.ask(actor, "hello", timeout);
try {
Object obj = Await.result(future, timeout.duration());
String reply = obj.toString();
System.out.println("reply msg: " + reply);
} catch (Exception e) {
e.printStackTrace();
}
}
} | repos\springboot-demo-master\akka\src\main\java\com\et\akka\controller\AkkaController.java | 2 |
请完成以下Java代码 | class SpringPropertyModel extends NamedModel {
@SuppressWarnings("NullAway.Init")
private String scope;
@SuppressWarnings("NullAway.Init")
private String defaultValue;
@SuppressWarnings("NullAway.Init")
private String source;
String getScope() {
return this.scope;
}
void setScope(String scope) {
this.scope = scope;
}
String getDefaultValue() { | return this.defaultValue;
}
void setDefaultValue(String defaultValue) {
this.defaultValue = defaultValue;
}
String getSource() {
return this.source;
}
void setSource(String source) {
this.source = source;
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\SpringPropertyModel.java | 1 |
请完成以下Java代码 | private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
metadataSources.addAnnotatedClass(TemporalValues.class);
metadataSources.addAnnotatedClass(User.class);
metadataSources.addAnnotatedClass(Student.class);
metadataSources.addAnnotatedClass(Course.class);
metadataSources.addAnnotatedClass(Product.class);
metadataSources.addAnnotatedClass(OrderEntryPK.class);
metadataSources.addAnnotatedClass(OrderEntry.class);
metadataSources.addAnnotatedClass(OrderEntryIdClass.class);
metadataSources.addAnnotatedClass(UserProfile.class);
metadataSources.addAnnotatedClass(Book.class);
metadataSources.addAnnotatedClass(MyEmployee.class);
metadataSources.addAnnotatedClass(MyProduct.class);
metadataSources.addAnnotatedClass(Pen.class);
metadataSources.addAnnotatedClass(Animal.class);
metadataSources.addAnnotatedClass(Pet.class);
metadataSources.addAnnotatedClass(Vehicle.class);
metadataSources.addAnnotatedClass(Car.class);
metadataSources.addAnnotatedClass(Bag.class);
metadataSources.addAnnotatedClass(PointEntity.class);
metadataSources.addAnnotatedClass(PolygonEntity.class);
metadataSources.addAnnotatedClass(DeptEmployee.class);
metadataSources.addAnnotatedClass(com.baeldung.hibernate.entities.Department.class);
metadataSources.addAnnotatedClass(Post.class);
metadataSources.addAnnotatedClass(TennisPlayer.class);
metadataSources.addAnnotatedClass(BaseballPlayer.class);
Metadata metadata = metadataSources.getMetadataBuilder()
.build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException { | return configureServiceRegistry(getProperties());
}
private static ServiceRegistry configureServiceRegistry(Properties properties) throws IOException {
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
public static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\HibernateUtil.java | 1 |
请完成以下Java代码 | public class DefaultApplicationRegistrator implements ApplicationRegistrator {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultApplicationRegistrator.class);
private final ConcurrentHashMap<String, LongAdder> attempts = new ConcurrentHashMap<>();
private final AtomicReference<String> registeredId = new AtomicReference<>();
private final ApplicationFactory applicationFactory;
private final String[] adminUrls;
private final boolean registerOnce;
private final RegistrationClient registrationClient;
public DefaultApplicationRegistrator(ApplicationFactory applicationFactory, RegistrationClient registrationClient,
String[] adminUrls, boolean registerOnce) {
this.applicationFactory = applicationFactory;
this.adminUrls = adminUrls;
this.registerOnce = registerOnce;
this.registrationClient = registrationClient;
}
/**
* Registers the client application at spring-boot-admin-server.
* @return true if successful registration on at least one admin server
*/
@Override
public boolean register() {
Application application = this.applicationFactory.createApplication();
boolean isRegistrationSuccessful = false;
for (String adminUrl : this.adminUrls) {
LongAdder attempt = this.attempts.computeIfAbsent(adminUrl, (k) -> new LongAdder());
boolean successful = register(application, adminUrl, attempt.intValue() == 0);
if (!successful) {
attempt.increment();
}
else {
attempt.reset();
isRegistrationSuccessful = true;
if (this.registerOnce) {
break;
}
}
}
return isRegistrationSuccessful;
}
protected boolean register(Application application, String adminUrl, boolean firstAttempt) {
try {
String id = this.registrationClient.register(adminUrl, application);
if (this.registeredId.compareAndSet(null, id)) {
LOGGER.info("Application registered itself as {}", id);
}
else {
LOGGER.debug("Application refreshed itself as {}", id);
}
return true;
}
catch (Exception ex) {
if (firstAttempt) {
LOGGER.warn(
"Failed to register application as {} at spring-boot-admin ({}): {}. Further attempts are logged on DEBUG level",
application, this.adminUrls, ex.getMessage(), ex);
}
else {
LOGGER.debug("Failed to register application as {} at spring-boot-admin ({}): {}", application,
this.adminUrls, ex.getMessage(), ex); | }
return false;
}
}
@Override
public void deregister() {
String id = this.registeredId.get();
if (id == null) {
return;
}
for (String adminUrl : this.adminUrls) {
try {
this.registrationClient.deregister(adminUrl, id);
this.registeredId.compareAndSet(id, null);
if (this.registerOnce) {
break;
}
}
catch (Exception ex) {
LOGGER.warn("Failed to deregister application (id={}) at spring-boot-admin ({}): {}", id, adminUrl,
ex.getMessage());
}
}
}
@Override
public String getRegisteredId() {
return this.registeredId.get();
}
} | repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\DefaultApplicationRegistrator.java | 1 |
请完成以下Java代码 | public I_C_UOM getUomByProductId(final ProductId productId)
{
final UomId uomId = getProductById(productId).getUomId();
return getUomById(uomId);
}
private void warmUpUOMs(final Collection<UomId> uomIds)
{
if (uomIds.isEmpty())
{
return;
}
CollectionUtils.getAllOrLoad(uomsCache, uomIds, this::retrieveUOMsByIds);
}
private Map<UomId, I_C_UOM> retrieveUOMsByIds(final Collection<UomId> uomIds)
{ | final List<I_C_UOM> uoms = uomDAO.getByIds(uomIds);
return Maps.uniqueIndex(uoms, uom -> UomId.ofRepoId(uom.getC_UOM_ID()));
}
public ImmutableSet<WarehouseId> getAllActiveWarehouseIds()
{
return warehouseRepository.getAllActiveIds();
}
public Warehouse getWarehouseById(@NonNull final WarehouseId warehouseId)
{
return warehouseRepository.getById(warehouseId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowCache.java | 1 |
请完成以下Java代码 | public abstract class SimpleDictionary<V>
{
BinTrie<V> trie = new BinTrie<V>();
public boolean load(String path)
{
try
{
BufferedReader br = new BufferedReader(new InputStreamReader(HanLP.Config.IOAdapter == null ? new FileInputStream(path) : HanLP.Config.IOAdapter.open(path), "UTF-8"));
String line;
while ((line = br.readLine()) != null)
{
Map.Entry<String, V> entry = onGenerateEntry(line);
if (entry == null) continue;
trie.put(entry.getKey(), entry.getValue());
}
br.close();
}
catch (Exception e)
{
Predefine.logger.warning("读取" + path + "失败" + e);
return false;
}
return true;
}
/**
* 查询一个单词
*
* @param key
* @return 单词对应的条目
*/
public V get(String key)
{
return trie.get(key);
}
/**
* 由参数构造一个词条
*
* @param line
* @return
*/
protected abstract Map.Entry<String, V> onGenerateEntry(String line);
/**
* 以我为主词典,合并一个副词典,我有的词条不会被副词典覆盖
* @param other 副词典
*/
public void combine(SimpleDictionary<V> other)
{
if (other.trie == null)
{
Predefine.logger.warning("有个词典还没加载");
return;
}
for (Map.Entry<String, V> entry : other.trie.entrySet())
{
if (trie.containsKey(entry.getKey())) continue;
trie.put(entry.getKey(), entry.getValue());
}
}
/**
* 获取键值对集合
* @return
*/
public Set<Map.Entry<String, V>> entrySet()
{
return trie.entrySet();
}
/**
* 键集合 | * @return
*/
public Set<String> keySet()
{
TreeSet<String> keySet = new TreeSet<String>();
for (Map.Entry<String, V> entry : entrySet())
{
keySet.add(entry.getKey());
}
return keySet;
}
/**
* 过滤部分词条
* @param filter 过滤器
* @return 删除了多少条
*/
public int remove(Filter filter)
{
int size = trie.size();
for (Map.Entry<String, V> entry : entrySet())
{
if (filter.remove(entry))
{
trie.remove(entry.getKey());
}
}
return size - trie.size();
}
public interface Filter<V>
{
boolean remove(Map.Entry<String, V> entry);
}
/**
* 向中加入单词
* @param key
* @param value
*/
public void add(String key, V value)
{
trie.put(key, value);
}
public int size()
{
return trie.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SimpleDictionary.java | 1 |
请完成以下Java代码 | private String getExternalResourceURL(@NonNull final I_M_ReceiptSchedule receiptSchedule)
{
return StringUtils.trimBlankToNull(receiptSchedule.getExternalResourceURL());
}
private Timestamp getMovementDate(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context)
{
return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>()
{
@Override
public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);}
@Override
public Timestamp externalDateIfAvailable() {return getExternalMovementDate(receiptSchedule, context);}
// Use Login Date as movement date because some roles will rely on the fact that they can override it (08247)
@Override
public Timestamp currentDate() {return Env.getDate(context);}
@Override
public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);}
});
}
private Timestamp getDateAcct(@NonNull final I_M_ReceiptSchedule receiptSchedule, @NonNull final Properties context)
{
return movementDateRule.map(new ReceiptMovementDateRule.CaseMapper<Timestamp>() | {
@Override
public Timestamp orderDatePromised() {return getPromisedDate(receiptSchedule, context);}
@Override
public Timestamp externalDateIfAvailable() {return getExternalDateAcct(receiptSchedule, context);}
// Use Login Date as movement date because some roles will rely on the fact that they can override it (08247)
@Override
public Timestamp currentDate() {return Env.getDate(context);}
@Override
public Timestamp fixedDate(@NonNull final Instant fixedDate) {return Timestamp.from(fixedDate);}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\InOutProducer.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
public I_M_DistributionList getM_DistributionList() throws RuntimeException
{
return (I_M_DistributionList)MTable.get(getCtx(), I_M_DistributionList.Table_Name)
.getPO(getM_DistributionList_ID(), get_TrxName()); }
/** Set Distribution List.
@param M_DistributionList_ID
Distribution Lists allow to distribute products to a selected list of partners
*/
public void setM_DistributionList_ID (int M_DistributionList_ID)
{
if (M_DistributionList_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID));
}
/** Get Distribution List.
@return Distribution Lists allow to distribute products to a selected list of partners
*/
public int getM_DistributionList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_DistributionList_ID()));
}
/** Set Distribution List Line.
@param M_DistributionListLine_ID
Distribution List Line with Business Partner and Quantity/Percentage
*/
public void setM_DistributionListLine_ID (int M_DistributionListLine_ID)
{
if (M_DistributionListLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DistributionListLine_ID, Integer.valueOf(M_DistributionListLine_ID));
}
/** Get Distribution List Line.
@return Distribution List Line with Business Partner and Quantity/Percentage
*/ | public int getM_DistributionListLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionListLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Minimum Quantity.
@param MinQty
Minimum quantity for the business partner
*/
public void setMinQty (BigDecimal MinQty)
{
set_Value (COLUMNNAME_MinQty, MinQty);
}
/** Get Minimum Quantity.
@return Minimum quantity for the business partner
*/
public BigDecimal getMinQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Ratio.
@param Ratio
Relative Ratio for Distributions
*/
public void setRatio (BigDecimal Ratio)
{
set_Value (COLUMNNAME_Ratio, Ratio);
}
/** Get Ratio.
@return Relative Ratio for Distributions
*/
public BigDecimal getRatio ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Ratio);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DistributionListLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void cancelSubscription(String sessionId, UnsubscribeCmd cmd) {
cleanupAndCancel(getSubCtx(sessionId, cmd.getCmdId()));
}
private void cleanupAndCancel(TbAbstractSubCtx ctx) {
if (ctx != null) {
ctx.stop();
if (ctx.getSessionId() != null) {
Map<Integer, TbAbstractSubCtx> sessionSubs = subscriptionsBySessionId.get(ctx.getSessionId());
if (sessionSubs != null) {
sessionSubs.remove(ctx.getCmdId());
}
}
}
}
@Override
public void cancelAllSessionSubscriptions(String sessionId) {
Map<Integer, TbAbstractSubCtx> sessionSubs = subscriptionsBySessionId.remove(sessionId); | if (sessionSubs != null) {
sessionSubs.values().forEach(sub -> {
try {
cleanupAndCancel(sub);
} catch (Exception e) {
log.warn("[{}] Failed to remove subscription {} due to ", sub.getTenantId(), sub, e);
}
}
);
}
}
private int getLimit(int limit) {
return limit == 0 ? DEFAULT_LIMIT : limit;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\subscription\DefaultTbEntityDataSubscriptionService.java | 2 |
请完成以下Java代码 | public class ApplicationDictionaryGenericModelValidator<T> implements ModelValidator
{
private final Class<T> itemClass;
private final IADValidator<T> validator;
private final String tableName;
private int adClientId = -1;
public ApplicationDictionaryGenericModelValidator(final Class<T> itemClass, final IADValidator<T> validator)
{
this.itemClass = itemClass;
this.validator = validator;
this.tableName = InterfaceWrapperHelper.getTableName(itemClass);
}
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
adClientId = client == null ? -1 : client.getAD_Client_ID();
engine.addModelChange(tableName, this);
}
@Override
public int getAD_Client_ID()
{
return adClientId;
}
@Override
public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID)
{
return null; | }
@Override
public String modelChange(PO po, int type) throws Exception
{
if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE)
{
final T item = InterfaceWrapperHelper.create(po, itemClass);
validator.validate(item);
}
return null;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\model\validator\ApplicationDictionaryGenericModelValidator.java | 1 |
请完成以下Java代码 | public class SaveTaskCmd implements Command<Task>, Serializable {
private static final long serialVersionUID = 1L;
protected TaskEntity task;
public SaveTaskCmd(Task task) {
this.task = (TaskEntity) task;
}
public Task execute(CommandContext commandContext) {
if (task == null) {
throw new ActivitiIllegalArgumentException("task is null");
}
if (task.getRevision() == 0) {
commandContext.getTaskEntityManager().insert(task, null);
if (commandContext.getEventDispatcher().isEnabled()) {
commandContext
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_CREATED, task));
if (task.getAssignee() != null) { | commandContext
.getEventDispatcher()
.dispatchEvent(ActivitiEventBuilder.createEntityEvent(ActivitiEventType.TASK_ASSIGNED, task));
}
}
} else {
TaskInfo originalTaskEntity = null;
if (commandContext.getProcessEngineConfiguration().getHistoryLevel().isAtLeast(HistoryLevel.AUDIT)) {
originalTaskEntity = commandContext.getHistoricTaskInstanceEntityManager().findById(task.getId());
}
if (originalTaskEntity == null) {
originalTaskEntity = commandContext.getTaskEntityManager().findById(task.getId());
}
TaskUpdater taskUpdater = new TaskUpdater(commandContext);
taskUpdater.updateTask(originalTaskEntity, task);
return commandContext.getTaskEntityManager().update(task);
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\SaveTaskCmd.java | 1 |
请完成以下Java代码 | private void doCopy()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.copy();
}
private void doCut()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.cut();
}
private void doPaste()
{ | final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
textComponent.paste();
}
private void doSelectAll()
{
final JTextComponent textComponent = getTextComponent();
if (textComponent == null)
{
return;
}
// NOTE: we need to request focus first because it seems in some case the code below is not working when the component does not have the focus.
textComponent.requestFocus();
textComponent.selectAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ui\editor\JComboBoxCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | public class EvalParameters
{
/**
* 将输出与参数映射起来,下标可以用 <code>pmap</code> 查询到
*/
private Context[] params;
/**
* 一共有几种输出
*/
private final int numOutcomes;
/**
* 一个事件中最多包含的特征数
*/
private double correctionConstant;
/**
* correctionConstant的倒数
*/
private final double constantInverse;
/**
* 修正参数
*/
private double correctionParam;
/**
* 创建一个参数,可被用于预测
*
* @param params 环境
* @param correctionParam 修正参数
* @param correctionConstant 一个事件中最多包含的特征数
* @param numOutcomes 事件的可能label数
*/
public EvalParameters(Context[] params, double correctionParam, double correctionConstant, int numOutcomes)
{
this.params = params;
this.correctionParam = correctionParam;
this.numOutcomes = numOutcomes;
this.correctionConstant = correctionConstant;
this.constantInverse = 1.0 / correctionConstant;
} | public EvalParameters(Context[] params, int numOutcomes)
{
this(params, 0, 0, numOutcomes);
}
public Context[] getParams()
{
return params;
}
public int getNumOutcomes()
{
return numOutcomes;
}
public double getCorrectionConstant()
{
return correctionConstant;
}
public double getConstantInverse()
{
return constantInverse;
}
public double getCorrectionParam()
{
return correctionParam;
}
public void setCorrectionParam(double correctionParam)
{
this.correctionParam = correctionParam;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\maxent\EvalParameters.java | 1 |
请完成以下Java代码 | protected List<FormDefinition> getFormDefinitionsFromModel(BpmnModel bpmnModel, ProcessDefinition processDefinition) {
Set<String> formKeys = new HashSet<>();
List<FormDefinition> formDefinitions = new ArrayList<>();
// for all start events
List<StartEvent> startEvents = bpmnModel.getMainProcess().findFlowElementsOfType(StartEvent.class, true);
for (StartEvent startEvent : startEvents) {
if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
formKeys.add(startEvent.getFormKey());
}
}
// for all user tasks
List<UserTask> userTasks = bpmnModel.getMainProcess().findFlowElementsOfType(UserTask.class, true);
for (UserTask userTask : userTasks) {
if (StringUtils.isNotEmpty(userTask.getFormKey())) {
formKeys.add(userTask.getFormKey());
}
}
for (String formKey : formKeys) {
addFormDefinitionToCollection(formDefinitions, formKey, processDefinition);
}
return formDefinitions;
}
protected void addFormDefinitionToCollection(List<FormDefinition> formDefinitions, String formKey, ProcessDefinition processDefinition) { | FormDefinitionQuery formDefinitionQuery = formRepositoryService.createFormDefinitionQuery().formDefinitionKey(formKey);
Deployment deployment = CommandContextUtil.getDeploymentEntityManager().findById(processDefinition.getDeploymentId());
if (deployment.getParentDeploymentId() != null) {
List<FormDeployment> formDeployments = formRepositoryService.createDeploymentQuery().parentDeploymentId(deployment.getParentDeploymentId()).list();
if (formDeployments != null && formDeployments.size() > 0) {
formDefinitionQuery.deploymentId(formDeployments.get(0).getId());
} else {
formDefinitionQuery.latestVersion();
}
} else {
formDefinitionQuery.latestVersion();
}
FormDefinition formDefinition = formDefinitionQuery.singleResult();
if (formDefinition != null) {
formDefinitions.add(formDefinition);
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetFormDefinitionsForProcessDefinitionCmd.java | 1 |
请完成以下Java代码 | public Optional<PPCostCollectorId> getPPCostCollectorId(@NonNull final OrderLineId orderLineId)
{
final String sql = "SELECT " + org.compiere.model.I_C_OrderLine.COLUMNNAME_PP_Cost_Collector_ID
+ " FROM C_OrderLine WHERE C_OrderLine_ID=? AND PP_Cost_Collector_ID IS NOT NULL";
return Optional.ofNullable(PPCostCollectorId.ofRepoIdOrNull(DB.getSQLValueEx(ITrx.TRXNAME_ThreadInherited, sql, orderLineId)));
}
public boolean hasDeliveredItems(@NonNull final OrderId orderId)
{
return queryBL.createQueryBuilder(I_C_OrderLine.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId)
.addCompareFilter(I_C_OrderLine.COLUMNNAME_QtyDelivered, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO)
.create()
.anyMatch();
}
@NonNull
private Optional<I_C_Order> getOrderByExternalId(@NonNull final OrderQuery orderQuery)
{
final OrgId orgId = assumeNotNull(orderQuery.getOrgId(), "Param query needs to have a non-null orgId; query={}", orderQuery);
final ExternalId externalId = assumeNotNull(orderQuery.getExternalId(), "Param query needs to have a non-null externalId; query={}", orderQuery);
final IQueryBuilder<I_C_Order> queryBuilder = createQueryBuilder()
.addEqualsFilter(I_C_Order.COLUMNNAME_AD_Org_ID, orgId)
.addEqualsFilter(I_C_Order.COLUMNNAME_ExternalId, externalId.getValue());
final InputDataSourceId dataSourceId = orderQuery.getInputDataSourceId();
if (dataSourceId != null)
{ | queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_AD_InputDataSource_ID, dataSourceId);
}
final ExternalSystemId externalSystemId = orderQuery.getExternalSystemId();
if (externalSystemId != null)
{
queryBuilder.addEqualsFilter(I_C_Order.COLUMNNAME_ExternalSystem_ID, externalSystemId);
}
return queryBuilder
.create()
.firstOnlyOptional();
}
public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter)
{
return queryBL.createQueryBuilder(I_C_Order.class)
.filter(queryFilter)
.create()
.list();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\AbstractOrderDAO.java | 1 |
请完成以下Java代码 | public String getAutonomy() {
return autonomy;
}
public void setAutonomy(String autonomy) {
this.autonomy = autonomy;
}
public String getChargingTime() {
return chargingTime;
}
public void setChargingTime(String chargingTime) {
this.chargingTime = chargingTime;
}
}
public static class FuelVehicle extends Vehicle {
String fuelType;
String transmissionType; | public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public String getTransmissionType() {
return transmissionType;
}
public void setTransmissionType(String transmissionType) {
this.transmissionType = transmissionType;
}
}
} | repos\tutorials-master\jackson-modules\jackson-polymorphic-deserialization\src\main\java\com\baeldung\jackson\polymorphic\deserialization\typeHandlingAnnotations\Vehicle.java | 1 |
请完成以下Java代码 | public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
public static class Cors {
/**
* Enable/disable CORS filter.
*/
private boolean enabled = false;
/**
* Allow/disallow CORS credentials.
*/
private boolean allowCredentials = false;
/**
* Allowed CORS origins, use * for all, but not in production. Default empty.
*/
private Set<String> allowedOrigins;
/**
* Allowed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> allowedHeaders;
/**
* Exposed CORS headers, use * for all, but not in production. Default empty.
*/
private Set<String> exposedHeaders;
/**
* Allowed CORS methods, use * for all, but not in production. Default empty.
*/
private Set<String> allowedMethods;
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
} | public boolean isAllowCredentials() {
return allowCredentials;
}
public void setAllowCredentials(boolean allowCredentials) {
this.allowCredentials = allowCredentials;
}
public Set<String> getAllowedOrigins() {
return allowedOrigins == null ? Collections.emptySet() : allowedOrigins;
}
public void setAllowedOrigins(Set<String> allowedOrigins) {
this.allowedOrigins = allowedOrigins;
}
public Set<String> getAllowedHeaders() {
return allowedHeaders == null ? Collections.emptySet() : allowedHeaders;
}
public void setAllowedHeaders(Set<String> allowedHeaders) {
this.allowedHeaders = allowedHeaders;
}
public Set<String> getExposedHeaders() {
return exposedHeaders == null ? Collections.emptySet() : exposedHeaders;
}
public void setExposedHeaders(Set<String> exposedHeaders) {
this.exposedHeaders = exposedHeaders;
}
public Set<String> getAllowedMethods() {
return allowedMethods == null ? Collections.emptySet() : allowedMethods;
}
public void setAllowedMethods(Set<String> allowedMethods) {
this.allowedMethods = allowedMethods;
}
}
} | repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\RestAppProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GreetingId implements RepoIdAware
{
@JsonCreator
public static GreetingId ofRepoId(final int repoId)
{
return new GreetingId(repoId);
}
public static GreetingId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new GreetingId(repoId) : null;
}
public static int toRepoId(@Nullable final GreetingId greetingId)
{
return toRepoIdOr(greetingId, -1);
}
public static int toRepoIdOr(
@Nullable final GreetingId greetingId, | final int defaultValue)
{
return greetingId != null ? greetingId.getRepoId() : defaultValue;
}
int repoId;
private GreetingId(final int greetingRepoId)
{
this.repoId = Check.assumeGreaterThanZero(greetingRepoId, "greetingRepoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\greeting\GreetingId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String fetchInventory(@PathVariable Long id, Model model) {
if (!model.containsAttribute(BINDING_RESULT)) {
model.addAttribute(INVENTORY_ATTR, inventoryService.fetchInventoryById(id));
}
return "index";
}
@PostMapping("/update")
public String updateInventory(@Validated @ModelAttribute(INVENTORY_ATTR) Inventory inventory,
BindingResult bindingResult, RedirectAttributes redirectAttributes, SessionStatus sessionStatus) {
if (!bindingResult.hasErrors()) {
try {
Inventory updatedInventory = inventoryService.updateInventory(inventory);
redirectAttributes.addFlashAttribute("updatedInventory", updatedInventory);
} catch (OptimisticLockingFailureException e) {
bindingResult.reject("", "Another user updated the data. Press the link above to reload it.");
}
}
if (bindingResult.hasErrors()) { | redirectAttributes.addFlashAttribute(BINDING_RESULT, bindingResult);
return "redirect:load/" + inventory.getId();
}
sessionStatus.setComplete();
return "redirect:success";
}
@GetMapping(value = "/success")
public String success() {
return "success";
}
@InitBinder
void allowFields(WebDataBinder webDataBinder
) {
webDataBinder.setAllowedFields("quantity");
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootHTTPLongConversationDetachedEntity\src\main\java\com\bookstore\controller\InventoryController.java | 2 |
请完成以下Java代码 | public void setIsClosed (boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, Boolean.valueOf(IsClosed));
}
/** Get Geschlossen.
@return The status is closed
*/
public boolean isClosed ()
{
Object oo = get_Value(COLUMNNAME_IsClosed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public org.compiere.model.I_M_Package getM_Package() throws RuntimeException
{
return (org.compiere.model.I_M_Package)MTable.get(getCtx(), org.compiere.model.I_M_Package.Table_Name)
.getPO(getM_Package_ID(), get_TrxName()); }
/** Set PackstĂĽck.
@param M_Package_ID
Shipment Package
*/
public void setM_Package_ID (int M_Package_ID)
{
if (M_Package_ID < 1)
set_Value (COLUMNNAME_M_Package_ID, null);
else
set_Value (COLUMNNAME_M_Package_ID, Integer.valueOf(M_Package_ID));
}
/** Get PackstĂĽck.
@return Shipment Package
*/ | public int getM_Package_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Package_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Virtual Package.
@param M_PackageTree_ID Virtual Package */
public void setM_PackageTree_ID (int M_PackageTree_ID)
{
if (M_PackageTree_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PackageTree_ID, Integer.valueOf(M_PackageTree_ID));
}
/** Get Virtual Package.
@return Virtual Package */
public int getM_PackageTree_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PackageTree_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\compiere\model\X_M_PackageTree.java | 1 |
请完成以下Java代码 | public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType)
{
set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType);
}
@Override
public java.lang.String getPickingJobAggregationType()
{
return get_ValueAsString(COLUMNNAME_PickingJobAggregationType);
}
/**
* PickingLineGroupBy AD_Reference_ID=541899
* Reference name: PickingLineGroupByValues
*/
public static final int PICKINGLINEGROUPBY_AD_Reference_ID=541899;
/** Product_Category = product_category */
public static final String PICKINGLINEGROUPBY_Product_Category = "product_category";
@Override
public void setPickingLineGroupBy (final @Nullable java.lang.String PickingLineGroupBy)
{
set_Value (COLUMNNAME_PickingLineGroupBy, PickingLineGroupBy);
}
@Override
public java.lang.String getPickingLineGroupBy()
{
return get_ValueAsString(COLUMNNAME_PickingLineGroupBy);
} | /**
* PickingLineSortBy AD_Reference_ID=541900
* Reference name: PickingLineSortByValues
*/
public static final int PICKINGLINESORTBY_AD_Reference_ID=541900;
/** ORDER_LINE_SEQ_NO = ORDER_LINE_SEQ_NO */
public static final String PICKINGLINESORTBY_ORDER_LINE_SEQ_NO = "ORDER_LINE_SEQ_NO";
/** QTY_TO_PICK_ASC = QTY_TO_PICK_ASC */
public static final String PICKINGLINESORTBY_QTY_TO_PICK_ASC = "QTY_TO_PICK_ASC";
/** QTY_TO_PICK_DESC = QTY_TO_PICK_DESC */
public static final String PICKINGLINESORTBY_QTY_TO_PICK_DESC = "QTY_TO_PICK_DESC";
@Override
public void setPickingLineSortBy (final @Nullable java.lang.String PickingLineSortBy)
{
set_Value (COLUMNNAME_PickingLineSortBy, PickingLineSortBy);
}
@Override
public java.lang.String getPickingLineSortBy()
{
return get_ValueAsString(COLUMNNAME_PickingLineSortBy);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static void updateRecord(@NonNull final I_MobileUI_UserProfile_MFG record, @NonNull final MobileUIManufacturingConfig from)
{
record.setIsScanResourceRequired(from.getIsScanResourceRequired().toBooleanString());
record.setIsAllowIssuingAnyHU(from.getIsAllowIssuingAnyHU().toBooleanString());
}
private Optional<MobileUIManufacturingConfig> retrieveGlobalConfig(@NonNull final ClientId clientId)
{
return queryBL.createQueryBuilder(I_MobileUI_MFG_Config.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_MobileUI_MFG_Config.COLUMNNAME_AD_Client_ID, clientId)
.create()
.firstOnlyOptional(I_MobileUI_MFG_Config.class)
.map(MobileUIManufacturingConfigRepository::fromRecord);
}
private static MobileUIManufacturingConfig fromRecord(@NonNull final I_MobileUI_MFG_Config record) | {
return MobileUIManufacturingConfig.builder()
.isScanResourceRequired(OptionalBoolean.ofBoolean(record.isScanResourceRequired()))
.isAllowIssuingAnyHU(OptionalBoolean.ofBoolean(record.isAllowIssuingAnyHU()))
.build();
}
public void saveUserConfig(@NonNull final MobileUIManufacturingConfig newConfig, @NonNull final UserId userId)
{
final I_MobileUI_UserProfile_MFG record = retrieveUserConfigRecord(userId).orElseGet(() -> InterfaceWrapperHelper.newInstance(I_MobileUI_UserProfile_MFG.class));
record.setIsActive(true);
record.setAD_User_ID(userId.getRepoId());
updateRecord(record, newConfig);
InterfaceWrapperHelper.save(record);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\config\MobileUIManufacturingConfigRepository.java | 2 |
请完成以下Java代码 | public static String getCustomizedConfigPath() {
String homePath = getHomePath();
String separator = java.io.File.separator;
return homePath + separator + "config" + separator + "application.properties";
}
public synchronized static void restorePropertiesFromEnvFormat(Properties properties) {
Iterator<Map.Entry<Object, Object>> iterator = properties.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Object, Object> entry = iterator.next();
String key = entry.getKey().toString();
String value = entry.getValue().toString();
if (value.trim().startsWith("${") && value.trim().endsWith("}")) {
int beginIndex = value.indexOf(":");
if (beginIndex < 0) { | beginIndex = value.length() - 1;
}
int endIndex = value.length() - 1;
String envKey = value.substring(2, beginIndex);
String envValue = System.getenv(envKey);
if (envValue == null || "".equals(envValue.trim())) {
value = value.substring(beginIndex + 1, endIndex);
} else {
value = envValue;
}
properties.setProperty(key, value);
}
}
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\ConfigUtils.java | 1 |
请完成以下Java代码 | public BigDecimal getQM_QtyDeliveredPercOfRaw()
{
return ppOrder.getQM_QtyDeliveredPercOfRaw();
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg);
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return ppOrder.getQM_QtyDeliveredAvg();
}
@Override
public Object getModel()
{
return ppOrder;
}
@Override
public String getVariantGroup()
{
return null;
}
@Override
public BOMComponentType getComponentType()
{
return null;
} | @Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
if (!_handlingUnitsInfoLoaded)
{
_handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder);
_handlingUnitsInfoLoaded = true;
}
return _handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
// there is no substitute for a produced material
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java | 1 |
请完成以下Java代码 | public void setHash (final @Nullable java.lang.String Hash)
{
set_Value (COLUMNNAME_Hash, Hash);
}
@Override
public java.lang.String getHash()
{
return get_ValueAsString(COLUMNNAME_Hash);
}
@Override
public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid() | {
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_ImportFile.java | 1 |
请完成以下Java代码 | public ResourceParameterBinding newInstance(ModelTypeInstanceContext instanceContext) {
return new ResourceParameterBindingImpl(instanceContext);
}
});
parameterRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_PARAMETER_REF)
.required()
.qNameAttributeReference(ResourceParameter.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
expressionChild = sequenceBuilder.element(Expression.class)
.required()
.build();
typeBuilder.build();
}
public ResourceParameterBindingImpl(ModelTypeInstanceContext instanceContext) { | super(instanceContext);
}
public ResourceParameter getParameter() {
return parameterRefAttribute.getReferenceTargetElement(this);
}
public void setParameter(ResourceParameter parameter) {
parameterRefAttribute.setReferenceTargetElement(this, parameter);
}
public Expression getExpression() {
return expressionChild.getChild(this);
}
public void setExpression(Expression expression) {
expressionChild.setChild(this, expression);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ResourceParameterBindingImpl.java | 1 |
请完成以下Java代码 | 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 XY Separator.
@param XYSeparator
The separator between the X and Y function.
*/
public void setXYSeparator (String XYSeparator)
{
set_Value (COLUMNNAME_XYSeparator, XYSeparator);
}
/** Get XY Separator.
@return The separator between the X and Y function.
*/
public String getXYSeparator ()
{
return (String)get_Value(COLUMNNAME_XYSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_ValueNoCheck (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());
}
public I_PA_ReportLine getPA_ReportLine() throws RuntimeException
{
return (I_PA_ReportLine)MTable.get(getCtx(), I_PA_ReportLine.Table_Name)
.getPO(getPA_ReportLine_ID(), get_TrxName()); }
/** Set Report Line.
@param PA_ReportLine_ID Report Line */
public void setPA_ReportLine_ID (int PA_ReportLine_ID)
{
if (PA_ReportLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID));
}
/** Get Report Line.
@return Report Line */
public int getPA_ReportLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/ | public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Report.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected JobParametersConverter getJobParametersConverter() {
return (this.jobParametersConverter != null) ? this.jobParametersConverter
: super.getJobParametersConverter();
}
@Override
protected TaskExecutor getTaskExecutor() {
return (this.taskExecutor != null) ? this.taskExecutor : super.getTaskExecutor();
}
@Configuration(proxyBeanMethods = false)
@Conditional(OnBatchDatasourceInitializationCondition.class)
static class DataSourceInitializerConfiguration {
@Bean
@ConditionalOnMissingBean
BatchDataSourceScriptDatabaseInitializer batchDataSourceInitializer(DataSource dataSource,
@BatchDataSource ObjectProvider<DataSource> batchDataSource, BatchJdbcProperties properties) {
return new BatchDataSourceScriptDatabaseInitializer(batchDataSource.getIfAvailable(() -> dataSource), | properties);
}
}
static class OnBatchDatasourceInitializationCondition extends OnDatabaseInitializationCondition {
OnBatchDatasourceInitializationCondition() {
super("Batch", "spring.batch.jdbc.initialize-schema");
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcAutoConfiguration.java | 2 |
请完成以下Java代码 | public class OauthResourceTokenConfig {
private final ResourceServerProperties resourceServerProperties;
/**
* 这里并不是对令牌的存储,他将访问令牌与身份验证进行转换
* 在需要 {@link TokenStore} 的任何地方可以使用此方法
*
* @return TokenStore
*/
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter());
}
/**
* jwt 令牌转换
*
* @return jwt
*/
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setVerifierKey(getPubKey());
return converter;
}
/**
* 非对称密钥加密,获取 public key。
* 自动选择加载方式。
*
* @return public key
*/
private String getPubKey() {
// 如果本地没有密钥,就从授权服务器中获取
return StringUtils.isEmpty(resourceServerProperties.getJwt().getKeyValue()) ? getKeyFromAuthorizationServer() : resourceServerProperties.getJwt().getKeyValue();
}
/**
* 本地没有公钥的时候,从服务器上获取 | * 需要进行 Basic 认证
*
* @return public key
*/
private String getKeyFromAuthorizationServer() {
ObjectMapper objectMapper = new ObjectMapper();
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(HttpHeaders.AUTHORIZATION, encodeClient());
HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
String pubKey = new RestTemplate().getForObject(resourceServerProperties.getJwt().getKeyUri(), String.class, requestEntity);
try {
JSONObject body = objectMapper.readValue(pubKey, JSONObject.class);
log.info("Get Key From Authorization Server.");
return body.getStr("value");
} catch (IOException e) {
log.error("Get public key error: {}", e.getMessage());
}
return null;
}
/**
* 客户端信息
*
* @return basic
*/
private String encodeClient() {
return "Basic " + Base64.getEncoder().encodeToString((resourceServerProperties.getClientId() + ":" + resourceServerProperties.getClientSecret()).getBytes());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-resource-server\src\main\java\com\xkcoding\oauth\config\OauthResourceTokenConfig.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.