instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public PageData<User> findByAuthorityAndTenantProfilesIds(Authority authority, List<TenantProfileId> tenantProfilesIds, PageLink pageLink) {
return DaoUtil.toPageData(userRepository.findByAuthorityAndTenantProfilesIds(authority, DaoUtil.toUUIDs(tenantProfilesIds),
DaoUtil.toPageable(pageLink)));
}
@Override
public UserAuthDetails findUserAuthDetailsByUserId(UUID tenantId, UUID userId) {
TbPair<UserEntity, Boolean> result = userRepository.findUserAuthDetailsByUserId(userId);
return result != null ? new UserAuthDetails(result.getFirst().toData(), result.getSecond()) : null;
}
@Override
public int countTenantAdmins(UUID tenantId) {
return userRepository.countByTenantIdAndAuthority(tenantId, Authority.TENANT_ADMIN);
}
@Override
public List<User> findUsersByTenantIdAndIds(UUID tenantId, List<UUID> userIds) {
return DaoUtil.convertDataList(userRepository.findUsersByTenantIdAndIdIn(tenantId, userIds));
}
@Override | public Long countByTenantId(TenantId tenantId) {
return userRepository.countByTenantId(tenantId.getId());
}
@Override
public PageData<User> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<UserFields> findNextBatch(UUID id, int batchSize) {
return userRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.USER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\user\JpaUserDao.java | 1 |
请完成以下Java代码 | public void deleteDocuments(final DocumentIdsSelection documentIds)
{
throw new InvalidDocumentStateException(parentDocument, RESULT_TabReadOnly.getName());
}
@Override
public DocumentValidStatus checkAndGetValidStatus(final OnValidStatusChanged onValidStatusChanged)
{
return DocumentValidStatus.documentValid();
}
@Override
public boolean hasChangesRecursivelly()
{
return false;
}
@Override
public void saveIfHasChanges()
{
}
@Override
public void markStaleAll()
{
} | @Override
public void markStale(final DocumentIdsSelection rowIds)
{
}
@Override
public boolean isStale()
{
return false;
}
@Override
public int getNextLineNo()
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | private void assertNoCycles()
{
if (fallback == null)
{
return;
}
final IdentityHashSet<DocumentPrintOptions> trace = new IdentityHashSet<>();
DocumentPrintOptions current = this;
while (current != null)
{
if (!trace.add(current))
{
throw new AdempiereException("Cycle in printing options fallback detected: " + trace);
}
current = current.fallback;
}
}
public static DocumentPrintOptions ofMap(
@NonNull final Map<String, String> map,
@Nullable final String sourceName)
{
if (map.isEmpty() && sourceName == null)
{
return NONE;
}
final HashMap<String, Boolean> options = new HashMap<>();
for (final String name : map.keySet())
{
final Boolean value = StringUtils.toBoolean(map.get(name), null);
if (value == null)
{
continue;
}
options.put(name, value);
}
return builder()
.sourceName(sourceName)
.options(options)
.build();
}
public boolean isEmpty()
{
return options.isEmpty();
}
private boolean isNone()
{
return this.equals(NONE);
}
public ImmutableSet<String> getOptionNames()
{
if (fallback != null && !fallback.isEmpty())
{
return ImmutableSet.<String>builder()
.addAll(options.keySet())
.addAll(fallback.getOptionNames())
.build();
}
else
{
return options.keySet();
}
}
public DocumentPrintOptionValue getOption(@NonNull final String name)
{
final Boolean value = options.get(name); | if (value != null)
{
return DocumentPrintOptionValue.builder()
.value(OptionalBoolean.ofBoolean(value))
.sourceName(sourceName)
.build();
}
else if (fallback != null)
{
return fallback.getOption(name);
}
else
{
return DocumentPrintOptionValue.MISSING;
}
}
public DocumentPrintOptions mergeWithFallback(@NonNull final DocumentPrintOptions fallback)
{
if (fallback.isNone())
{
return this;
}
else if (isNone())
{
return fallback;
}
else
{
if (this == fallback)
{
throw new IllegalArgumentException("Merging with itself is not allowed");
}
final DocumentPrintOptions newFallback;
if (this.fallback != null)
{
newFallback = this.fallback.mergeWithFallback(fallback);
}
else
{
newFallback = fallback;
}
return !Objects.equals(this.fallback, newFallback)
? toBuilder().fallback(newFallback).build()
: this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentPrintOptions.java | 1 |
请完成以下Java代码 | public void setOrAlphabetic(boolean orAlphabetic) {
this.orAlphabetic = orAlphabetic;
}
public boolean isNot() {
return not;
}
public void setNot(boolean not) {
this.not = not;
}
public boolean isNotAlphabetic() {
return notAlphabetic;
}
public void setNotAlphabetic(boolean notAlphabetic) { | this.notAlphabetic = notAlphabetic;
}
@Override
public String toString() {
return "SpelLogical{" +
"and=" + and +
", andAlphabetic=" + andAlphabetic +
", or=" + or +
", orAlphabetic=" + orAlphabetic +
", not=" + not +
", notAlphabetic=" + notAlphabetic +
'}';
}
} | repos\tutorials-master\spring-spel\src\main\java\com\baeldung\spring\spel\examples\SpelLogical.java | 1 |
请完成以下Java代码 | public PageData<Customer> findCustomersWithTheSameTitle(PageLink pageLink) {
return DaoUtil.toPageData(
customerRepository.findCustomersWithTheSameTitle(DaoUtil.toPageable(pageLink))
);
}
@Override
public List<Customer> findCustomersByTenantIdAndIds(UUID tenantId, List<UUID> customerIds) {
return DaoUtil.convertDataList(customerRepository.findCustomersByTenantIdAndIdIn(tenantId, customerIds));
}
@Override
public PageData<Customer> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
} | @Override
public List<CustomerFields> findNextBatch(UUID id, int batchSize) {
return customerRepository.findNextBatch(id, Limit.of(batchSize));
}
@Override
public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
return customerRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\customer\JpaCustomerDao.java | 1 |
请完成以下Java代码 | public Map<String, String> getTemplateData() {
return mapOf(
"comment", comment,
"action", action,
"userTitle", User.getTitle(userEmail, userFirstName, userLastName),
"userEmail", userEmail,
"userFirstName", userFirstName,
"userLastName", userLastName,
"alarmType", alarmType,
"alarmId", alarmId.toString(),
"alarmSeverity", alarmSeverity.name().toLowerCase(),
"alarmStatus", alarmStatus.toString(),
"alarmOriginatorEntityType", alarmOriginator.getEntityType().getNormalName(),
"alarmOriginatorId", alarmOriginator.getId().toString(),
"alarmOriginatorName", alarmOriginatorName,
"alarmOriginatorLabel", alarmOriginatorLabel
);
} | @Override
public CustomerId getAffectedCustomerId() {
return alarmCustomerId;
}
@Override
public EntityId getStateEntityId() {
return alarmOriginator;
}
@Override
public DashboardId getDashboardId() {
return dashboardId;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\notification\info\AlarmCommentNotificationInfo.java | 1 |
请完成以下Java代码 | public static <T> boolean elementIsContainedInList(T element, Collection<T> values) {
if (element != null && values != null) {
return values.contains(element);
}
else {
return false;
}
}
/**
* Checks if the element is contained within the list of values.
*
* @param element to check
* @param values to check in
* @param <T> the type of the element
* @return {@code true} if the element and values are not {@code null} and the values contain the element,
* {@code false} otherwise
*/
public static <T> boolean elementIsContainedInArray(T element, T... values) {
if (element != null && values != null) {
return elementIsContainedInList(element, Arrays.asList(values));
}
else {
return false; | }
}
/**
* Returns any element if obj1.compareTo(obj2) == 0
*/
public static <T extends Comparable<T>> T min(T obj1, T obj2) {
return obj1.compareTo(obj2) <= 0 ? obj1 : obj2;
}
/**
* Returns any element if obj1.compareTo(obj2) == 0
*/
public static <T extends Comparable<T>> T max(T obj1, T obj2) {
return obj1.compareTo(obj2) >= 0 ? obj1 : obj2;
}
public static <T> boolean elementsAreContainedInArray(Collection<T> subset, T[] superset) {
if (subset != null && !subset.isEmpty() && superset != null && superset.length > 0 && superset.length >= subset.size()) {
return new HashSet<>(Arrays.asList(superset)).containsAll(subset);
}
return false;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CompareUtil.java | 1 |
请完成以下Java代码 | public class MpmcBenchmark {
public static final String PARAM_UNSAFE = "MpmcArrayQueue";
public static final String PARAM_AFU = "MpmcAtomicArrayQueue";
public static final String PARAM_JDK = "ArrayBlockingQueue";
public static final int PRODUCER_THREADS_NUMBER = 32;
public static final int CONSUMER_THREADS_NUMBER = 32;
public static final String GROUP_NAME = "MyGroup";
public static final int CAPACITY = 128;
@Param({PARAM_UNSAFE, PARAM_AFU, PARAM_JDK})
public volatile String implementation;
public volatile Queue<Long> queue;
@Setup(Level.Trial)
public void setUp() {
switch (implementation) {
case PARAM_UNSAFE:
queue = new MpmcArrayQueue<>(CAPACITY);
break;
case PARAM_AFU:
queue = new MpmcAtomicArrayQueue<>(CAPACITY);
break;
case PARAM_JDK:
queue = new ArrayBlockingQueue<>(CAPACITY);
break;
default:
throw new UnsupportedOperationException("Unsupported implementation " + implementation);
}
}
@Benchmark
@Group(GROUP_NAME) | @GroupThreads(PRODUCER_THREADS_NUMBER)
public void write(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && !queue.offer(1L)) {
// Is intentionally left blank
}
}
@Benchmark
@Group(GROUP_NAME)
@GroupThreads(CONSUMER_THREADS_NUMBER)
public void read(Control control) {
//noinspection StatementWithEmptyBody
while (!control.stopMeasurement && queue.poll() == null) {
// Is intentionally left blank
}
}
} | repos\tutorials-master\libraries-concurrency\src\main\java\com\baeldung\jctools\MpmcBenchmark.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WEBUI_PP_Order_HUEditor_Create_M_Source_HUs
extends WEBUI_PP_Order_HUEditor_ProcessBase
implements IProcessPrecondition
{
@Autowired
private SourceHUsService sourceHuService;
private final Set<HuId> topLevelHUIdsProcessed = new HashSet<>();
@Override
public final ProcessPreconditionsResolution checkPreconditionsApplicable()
{
final boolean anyHuMatches = retrieveSelectedAndEligibleHUEditorRows()
.anyMatch(huRow -> huRow.isTopLevel());
if (anyHuMatches)
{
return ProcessPreconditionsResolution.accept();
}
final ITranslatableString reason = Services.get(IMsgBL.class).getTranslatableMsgText(MSG_WEBUI_SELECT_ACTIVE_UNSELECTED_HU);
return ProcessPreconditionsResolution.reject(reason);
}
@Override
protected String doIt() throws Exception
{
retrieveSelectedAndEligibleHUEditorRows().forEach(this::createSourceHU);
return MSG_OK;
}
private void createSourceHU(final HUEditorRow row)
{
Check.assume(row.isTopLevel(), "Only top level rows are allowed"); // shall not happen
final HuId topLevelHUId = row.getHuId();
sourceHuService.addSourceHuMarker(topLevelHUId);
topLevelHUIdsProcessed.add(topLevelHUId); | }
@Override
protected void postProcess(boolean success)
{
if (!success)
{
return;
}
// PP_Order
invalidateParentView();
// HU Editor
getView().removeHUIdsAndInvalidate(topLevelHUIdsProcessed);
// invalidateView();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_HUEditor_Create_M_Source_HUs.java | 2 |
请完成以下Java代码 | public class ListenerContainerPartitionIdleEvent extends KafkaEvent {
private static final long serialVersionUID = 1L;
private final long idleTime;
private final String listenerId;
private final TopicPartition topicPartition;
private final boolean paused;
private transient final Consumer<?, ?> consumer;
/**
* Construct an instance with the provided arguments.
* @param source the container instance that generated the event.
* @param container the container or the parent container if the container is a child.
* @param idleTime the idle time.
* @param id the container id.
* @param topicPartition the topic/partition.
* @param consumer the consumer.
* @param paused true if the consumer partition is paused.
* @since 2.7
*/
public ListenerContainerPartitionIdleEvent(Object source, Object container,
long idleTime, String id,
TopicPartition topicPartition, Consumer<?, ?> consumer, boolean paused) {
super(source, container);
this.idleTime = idleTime;
this.listenerId = id;
this.topicPartition = topicPartition;
this.consumer = consumer;
this.paused = paused;
}
/**
* How long the partition has been idle.
* @return the time in milliseconds.
*/
public long getIdleTime() {
return this.idleTime;
}
/**
* The idle TopicPartition.
* @return the TopicPartition.
*/
public TopicPartition getTopicPartition() {
return this.topicPartition;
}
/**
* The id of the listener (if {@code @KafkaListener}) or the container bean name.
* @return the id.
*/
public String getListenerId() {
return this.listenerId; | }
/**
* Retrieve the consumer. Only populated if the listener is consumer-aware.
* Allows the listener to resume a paused consumer.
* @return the consumer.
* @since 2.0
*/
public Consumer<?, ?> getConsumer() {
return this.consumer;
}
/**
* Return true if the consumer was paused at the time the idle event was published.
* @return paused.
* @since 2.1.5
*/
public boolean isPaused() {
return this.paused;
}
@Override
public String toString() {
return "ListenerContainerPartitionIdleEvent [idleTime="
+ ((float) this.idleTime / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic #
+ ", container=" + getSource()
+ ", paused=" + this.paused
+ ", topicPartition=" + this.topicPartition + "]";
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ListenerContainerPartitionIdleEvent.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void doInTransactionWithoutResult(
TransactionStatus status) {
log.info("Starting first transaction (A) ...");
authorRepository.findById(1L).orElseThrow(); // get the lock
authorRepository.updateGenre("Comedy", 1L);
try {
log.info("Holding in place first transaction (A) for 10s ...");
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
log.info("First transaction (A) attempts to update a book (id:1) ...");
bookRepository.findById(1L).orElseThrow(); // this cannot be done, transaction (B) holds the lock
bookRepository.updateTitle("A happy day", 1L);
}
});
log.info("First transaction (A) committed!");
});
Thread tB = new Thread(() -> {
template.setPropagationBehavior(
TransactionDefinition.PROPAGATION_REQUIRES_NEW);
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(
TransactionStatus status) {
log.info("Starting second transaction (B) ..."); | bookRepository.findById(1L).orElseThrow(); // get the lock
bookRepository.updateTitle("A long night", 1L);
try {
log.info("Holding in place second transaction (B) for 10s ...");
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
log.info("Second transaction (B) attempts to update an author (id:1) ...");
authorRepository.findById(1L).orElseThrow(); // this cannot be done, transaction (A) holds the lock
authorRepository.updateGenre("Horror", 1L);
}
});
log.info("Second transaction (B) committed!");
});
tA.start();
Thread.sleep(5000);
tB.start();
tA.join();
tB.join();
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDeadlockExample\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<HistoricDecisionInputInstance> getInputs() {
if(inputs != null) {
return inputs;
} else {
throw LOG.historicDecisionInputInstancesNotFetchedException();
}
}
@Override
public List<HistoricDecisionOutputInstance> getOutputs() {
if(outputs != null) {
return outputs;
} else {
throw LOG.historicDecisionOutputInstancesNotFetchedException();
}
}
public void setInputs(List<HistoricDecisionInputInstance> inputs) {
this.inputs = inputs;
}
public void setOutputs(List<HistoricDecisionOutputInstance> outputs) {
this.outputs = outputs;
}
public void delete() {
Context
.getCommandContext()
.getDbEntityManager()
.delete(this);
}
public void addInput(HistoricDecisionInputInstance decisionInputInstance) {
if(inputs == null) {
inputs = new ArrayList<HistoricDecisionInputInstance>();
}
inputs.add(decisionInputInstance);
}
public void addOutput(HistoricDecisionOutputInstance decisionOutputInstance) {
if(outputs == null) {
outputs = new ArrayList<HistoricDecisionOutputInstance>();
}
outputs.add(decisionOutputInstance);
}
public Double getCollectResultValue() { | return collectResultValue;
}
public void setCollectResultValue(Double collectResultValue) {
this.collectResultValue = collectResultValue;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public void setRootDecisionInstanceId(String rootDecisionInstanceId) {
this.rootDecisionInstanceId = rootDecisionInstanceId;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public void setDecisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public void setDecisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDecisionInstanceEntity.java | 1 |
请完成以下Java代码 | public Boolean getMRPAvailable()
{
return _mrpAvailable;
}
public boolean isOnlyActiveRecords()
{
return _onlyActiveRecords;
}
@Override
public MRPQueryBuilder setOnlyActiveRecords(final boolean onlyActiveRecords)
{
this._onlyActiveRecords = onlyActiveRecords;
return this;
}
@Override
public MRPQueryBuilder setOrderType(final String orderType)
{
this._orderTypes.clear();
if (orderType != null)
{
this._orderTypes.add(orderType);
}
return this;
}
private Set<String> getOrderTypes()
{
return this._orderTypes;
} | @Override
public MRPQueryBuilder setReferencedModel(final Object referencedModel)
{
this._referencedModel = referencedModel;
return this;
}
public Object getReferencedModel()
{
return this._referencedModel;
}
@Override
public void setPP_Order_BOMLine_Null()
{
this._ppOrderBOMLine_Null = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\mrp\api\impl\MRPQueryBuilder.java | 1 |
请完成以下Java代码 | public InputValues getInputValues() {
return inputValuesChild.getChild(this);
}
public void setInputValues(InputValues inputValues) {
inputValuesChild.setChild(this, inputValues);
}
// camunda extensions
public String getCamundaInputVariable() {
return camundaInputVariableAttribute.getValue(this);
}
public void setCamundaInputVariable(String inputVariable) {
camundaInputVariableAttribute.setValue(this, inputVariable);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(InputClause.class, DMN_ELEMENT_INPUT_CLAUSE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<InputClause>() { | public InputClause newInstance(ModelTypeInstanceContext instanceContext) {
return new InputClauseImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputExpressionChild = sequenceBuilder.element(InputExpression.class)
.required()
.build();
inputValuesChild = sequenceBuilder.element(InputValues.class)
.build();
// camunda extensions
camundaInputVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_INPUT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\InputClauseImpl.java | 1 |
请完成以下Java代码 | public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsantwortArtikel getMSV3_VerfuegbarkeitsantwortArtikel() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MSV3_VerfuegbarkeitsantwortArtikel_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsantwortArtikel.class);
}
@Override
public void setMSV3_VerfuegbarkeitsantwortArtikel(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsantwortArtikel MSV3_VerfuegbarkeitsantwortArtikel)
{
set_ValueFromPO(COLUMNNAME_MSV3_VerfuegbarkeitsantwortArtikel_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_VerfuegbarkeitsantwortArtikel.class, MSV3_VerfuegbarkeitsantwortArtikel);
}
/** Set VerfuegbarkeitsantwortArtikel.
@param MSV3_VerfuegbarkeitsantwortArtikel_ID VerfuegbarkeitsantwortArtikel */
@Override
public void setMSV3_VerfuegbarkeitsantwortArtikel_ID (int MSV3_VerfuegbarkeitsantwortArtikel_ID)
{
if (MSV3_VerfuegbarkeitsantwortArtikel_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsantwortArtikel_ID, null); | else
set_ValueNoCheck (COLUMNNAME_MSV3_VerfuegbarkeitsantwortArtikel_ID, Integer.valueOf(MSV3_VerfuegbarkeitsantwortArtikel_ID));
}
/** Get VerfuegbarkeitsantwortArtikel.
@return VerfuegbarkeitsantwortArtikel */
@Override
public int getMSV3_VerfuegbarkeitsantwortArtikel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_VerfuegbarkeitsantwortArtikel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_VerfuegbarkeitAnteil.java | 1 |
请完成以下Java代码 | public final void setDateNextRun(final Timestamp dateNextRun)
{
p_model.setDateNextRun(dateNextRun);
// NOTE: we need to save it because some BL is relying on this (e.g. Scheduler)
save(p_model, ITrx.TRXNAME_None);
}
/**
* Get the date Last run
*
* @return date last run
*/
public final Timestamp getDateLastRun()
{
return p_model.getDateLastRun();
} // getDateLastRun
/**
* Get Description
*
* @return Description
*/
public final String getDescription()
{
return p_model.getDescription();
} // getDescription
/**
* Get Model
*
* @return Model
*/
public final AdempiereProcessor getModel()
{
return p_model;
} // getModel
/**
* Calculate Sleep ms
*
* @return miliseconds
*/
protected final long calculateSleep()
{
String frequencyType = p_model.getFrequencyType();
int frequency = p_model.getFrequency();
if (frequency < 1)
{
frequency = 1;
}
//
final long typeSec;
if (frequencyType == null)
{
typeSec = 300; // 5 minutes (default)
}
else if (X_R_RequestProcessor.FREQUENCYTYPE_Minute.equals(frequencyType))
{
typeSec = 60;
}
else if (X_R_RequestProcessor.FREQUENCYTYPE_Hour.equals(frequencyType))
{
typeSec = 3600;
}
else if (X_R_RequestProcessor.FREQUENCYTYPE_Day.equals(frequencyType))
{
typeSec = 86400;
}
else // Unknown Frequency
{ | typeSec = 600; // 10 min
log.warn("Unknown FrequencyType=" + frequencyType + ". Using Frequency=" + typeSec + "seconds.");
}
//
return typeSec * 1000 * frequency; // ms
} // calculateSleep
/**
* Is Sleeping
*
* @return sleeping
*/
public final boolean isSleeping()
{
return sleeping.get();
} // isSleeping
@Override
public final String toString()
{
final boolean sleeping = isSleeping();
final StringBuilder sb = new StringBuilder(getName())
.append(",Prio=").append(getPriority())
.append(",").append(getThreadGroup())
.append(",Alive=").append(isAlive())
.append(",Sleeping=").append(sleeping)
.append(",Last=").append(getDateLastRun());
if (sleeping)
{
sb.append(",Next=").append(getDateNextRun(false));
}
return sb.toString();
}
public final Timestamp getStartTime()
{
final long startTimeMillis = this.serverStartTimeMillis;
return startTimeMillis > 0 ? new Timestamp(startTimeMillis) : null;
}
public final AdempiereProcessorLog[] getLogs()
{
return p_model.getLogs();
}
/**
* Set the initial nap/sleep when server starts.
*
* Mainly this method is used by tests.
*
* @param initialNapSeconds
*/
public final void setInitialNapSeconds(final int initialNapSeconds)
{
Check.assume(initialNapSeconds >= 0, "initialNapSeconds >= 0");
this.m_initialNapSecs = initialNapSeconds;
}
protected final int getRunCount()
{
return p_runCount;
}
protected final Timestamp getStartWork()
{
return new Timestamp(workStartTimeMillis);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServer.java | 1 |
请完成以下Java代码 | Builder payload(ByteBuf payload) {
this.payload = payload;
return this;
}
Builder message(MqttPublishMessage message) {
this.message = message;
return this;
}
Builder qos(MqttQoS qos) {
this.qos = qos;
return this;
}
Builder ownerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) { | this.retransmissionConfig = retransmissionConfig;
return this;
}
Builder pendingOperation(PendingOperation pendingOperation) {
this.pendingOperation = pendingOperation;
return this;
}
MqttPendingPublish build() {
return new MqttPendingPublish(messageId, future, payload, message, qos, ownerId, retransmissionConfig, pendingOperation);
}
}
} | repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingPublish.java | 1 |
请完成以下Java代码 | private void commonInit()
{
this.setJMenuBar(m_APanel.getMenuBar());
this.setTitle(m_APanel.getTitle());
//
Image image = m_APanel.getImage();
if (image != null)
{
setIconImage(image);
}
this.setTransferHandler(new AttachmentDnDTransferHandler(m_APanel)); // metas: drag&drop support for attachments
} // commonInit
/*************************************************************************
* Set Window Busy
* @param busy busy
*/
public void setBusy (final boolean busy)
{
if (busy == m_glassPane.isVisible())
{
return;
}
log.debug("set busy: {}, window={}", busy, this);
m_glassPane.setMessage(null);
m_glassPane.setVisible(busy);
if (busy)
{
m_glassPane.requestFocus();
}
} // setBusy
/**
* Set Busy Message
* @param AD_Message message
*/
public void setBusyMessage (String AD_Message)
{
m_glassPane.setMessage(AD_Message);
}
public void setBusyMessagePlain(final String messagePlain)
{
m_glassPane.setMessagePlain(messagePlain);
}
/**
* Set and start Busy Counter
* @param time in seconds
*/
public void setBusyTimer (int time)
{
m_glassPane.setBusyTimer (time);
} // setBusyTimer
/**
* Window Events
* @param e event
*/
@Override
protected void processWindowEvent(WindowEvent e)
{
super.processWindowEvent(e);
// System.out.println(">> Apps WE_" + e.getID() // + " Frames=" + getFrames().length
// + " " + e);
} // processWindowEvent
/**
* Get Application Panel
* @return application panel
*/
public APanel getAPanel()
{
return m_APanel;
} // getAPanel | /**
* Dispose
*/
@Override
public void dispose()
{
if (Env.hideWindow(this))
{
return;
}
log.debug("disposing: {}", this);
if (m_APanel != null)
{
m_APanel.dispose();
}
m_APanel = null;
this.removeAll();
super.dispose();
// System.gc();
} // dispose
/**
* Get Window No of Panel
* @return window no
*/
public int getWindowNo()
{
if (m_APanel != null)
{
return m_APanel.getWindowNo();
}
return 0;
} // getWindowNo
/**
* String Representation
* @return Name
*/
@Override
public String toString()
{
return getName() + "_" + getWindowNo();
} // toString
// metas: begin
public GridWindow getGridWindow()
{
if (m_APanel == null)
{
return null;
}
return m_APanel.getGridWorkbench().getMWindowById(getAdWindowId());
}
// metas: end
} // AWindow | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\AWindow.java | 1 |
请完成以下Java代码 | public Quantity allocate(@NonNull final AllocablePackageable allocable)
{
return allocate(allocable, allocable.getQtyToAllocate());
}
public Quantity allocate(
@NonNull final AllocablePackageable allocable,
@NonNull final Quantity requestedQtyToAllocate)
{
// Nothing requested to allocate
if (requestedQtyToAllocate.isZero())
{
return requestedQtyToAllocate.toZero();
}
final Quantity qtyFreeToAllocateEffective = getQtyFreeToAllocateFor(allocable.getReservationRef().orElse(null));
final Quantity qtyToAllocateEffective = computeEffectiveQtyToAllocate(requestedQtyToAllocate, qtyFreeToAllocateEffective);
forceAllocate(allocable, qtyToAllocateEffective);
return qtyToAllocateEffective;
}
public void forceAllocate(final AllocablePackageable allocable, final Quantity qtyToAllocate)
{
assertSameProductId(allocable);
qtyFreeToAllocate = qtyFreeToAllocate.subtract(qtyToAllocate);
allocable.allocateQty(qtyToAllocate);
}
public boolean hasQtyFreeToAllocateFor(@Nullable final HUReservationDocRef reservationDocRef)
{
return getQtyFreeToAllocateFor(reservationDocRef).isPositive();
}
public Quantity getQtyFreeToAllocateFor(@Nullable final HUReservationDocRef reservationDocRef)
{
return isReserved() && !isReservedOnlyFor(reservationDocRef)
? qtyFreeToAllocate.toZero()
: qtyFreeToAllocate;
}
private boolean isReserved()
{ | return reservationDocRef != null;
}
public boolean isReservedOnlyFor(@NonNull final AllocablePackageable allocable)
{
return isReservedOnlyFor(allocable.getReservationRef().orElse(null));
}
public boolean isReservedOnlyFor(@Nullable final HUReservationDocRef reservationDocRef)
{
return this.reservationDocRef != null
&& HUReservationDocRef.equals(this.reservationDocRef, reservationDocRef);
}
private void assertSameProductId(final AllocablePackageable allocable)
{
if (!ProductId.equals(productId, allocable.getProductId()))
{
throw new AdempiereException("ProductId not matching")
.appendParametersToMessage()
.setParameter("allocable", allocable)
.setParameter("storage", this);
}
}
private static Quantity computeEffectiveQtyToAllocate(
@NonNull final Quantity requestedQtyToAllocate,
@NonNull final Quantity qtyFreeToAllocate)
{
if (requestedQtyToAllocate.signum() <= 0)
{
return requestedQtyToAllocate.toZero();
}
else if (qtyFreeToAllocate.signum() <= 0)
{
return requestedQtyToAllocate.toZero();
}
else
{
return requestedQtyToAllocate.min(qtyFreeToAllocate);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\allocableHUStorages\VHUAllocableStorage.java | 1 |
请完成以下Java代码 | private AdMessageKey getNotificationAD_Message(final I_M_InOut inout)
{
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inout.getDocStatus());
if (docStatus.isReversedOrVoided())
{
return inout.isSOTrx() ? MSG_Event_ShipmentReversed : MSG_Event_ReceiptReversed;
}
else
{
return inout.isSOTrx() ? MSG_Event_ShipmentGenerated : MSG_Event_ReceiptGenerated;
}
}
private UserId getNotificationRecipientUserId(final I_M_InOut inout)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inout.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final int currentUserId = Env.getAD_User_ID(Env.getCtx()); // current/triggering user
if (currentUserId > 0)
{
return UserId.ofRepoId(currentUserId);
}
return UserId.ofRepoId(inout.getUpdatedBy()); // last updated
}
// | // Fallback: notify only the creator
else
{
return UserId.ofRepoId(inout.getCreatedBy());
}
}
public InOutUserNotificationsProducer notifyShipmentError(
@NonNull final String sourceInfo,
@NonNull final String errorMessage)
{
// don't send after commit, because the trx will very probably be rolled back if an error happened
notificationBL.send(newUserNotificationRequest()
.recipientUserId(Env.getLoggedUserId())
.contentADMessage(MSG_Event_ShipmentError)
.contentADMessageParam(sourceInfo)
.contentADMessageParam(errorMessage)
.build());
return this;
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
notificationBL.sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\event\InOutUserNotificationsProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getTaxAmtSumTaxBaseAmt()
{
return taxAmtSumTaxBaseAmt;
}
public void setTaxAmtSumTaxBaseAmt(final BigDecimal taxAmtSumTaxBaseAmt)
{
this.taxAmtSumTaxBaseAmt = taxAmtSumTaxBaseAmt;
}
public String getESRNumber()
{
return ESRNumber;
}
public void setESRNumber(final String eSRNumber)
{
ESRNumber = eSRNumber;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + (ESRNumber == null ? 0 : ESRNumber.hashCode());
result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode());
result = prime * result + (rate == null ? 0 : rate.hashCode());
result = prime * result + (taxAmt == null ? 0 : taxAmt.hashCode());
result = prime * result + (taxAmtSumTaxBaseAmt == null ? 0 : taxAmtSumTaxBaseAmt.hashCode());
result = prime * result + (taxBaseAmt == null ? 0 : taxBaseAmt.hashCode());
result = prime * result + (totalAmt == null ? 0 : totalAmt.hashCode());
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final Cctop901991V other = (Cctop901991V)obj;
if (ESRNumber == null)
{
if (other.ESRNumber != null)
{
return false;
}
}
else if (!ESRNumber.equals(other.ESRNumber))
{
return false;
}
if (cInvoiceID == null)
{
if (other.cInvoiceID != null)
{
return false;
}
}
else if (!cInvoiceID.equals(other.cInvoiceID)) | {
return false;
}
if (rate == null)
{
if (other.rate != null)
{
return false;
}
}
else if (!rate.equals(other.rate))
{
return false;
}
if (taxAmt == null)
{
if (other.taxAmt != null)
{
return false;
}
}
else if (!taxAmt.equals(other.taxAmt))
{
return false;
}
if (taxAmtSumTaxBaseAmt == null)
{
if (other.taxAmtSumTaxBaseAmt != null)
{
return false;
}
}
else if (!taxAmtSumTaxBaseAmt.equals(other.taxAmtSumTaxBaseAmt))
{
return false;
}
if (taxBaseAmt == null)
{
if (other.taxBaseAmt != null)
{
return false;
}
}
else if (!taxBaseAmt.equals(other.taxBaseAmt))
{
return false;
}
if (totalAmt == null)
{
if (other.totalAmt != null)
{
return false;
}
}
else if (!totalAmt.equals(other.totalAmt))
{
return false;
}
return true;
}
@Override
public String toString()
{
return "Cctop901991V [cInvoiceID=" + cInvoiceID + ", rate=" + rate + ", taxAmt=" + taxAmt + ", taxBaseAmt=" + taxBaseAmt + ", totalAmt=" + totalAmt + ", ESRNumber=" + ESRNumber
+ ", taxAmtSumTaxBaseAmt=" + taxAmtSumTaxBaseAmt + "]";
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop901991V.java | 2 |
请完成以下Java代码 | public ITableCacheConfigBuilder setTrxLevel(final TrxLevel trxLevel)
{
this.trxLevel = trxLevel;
return this;
}
public TrxLevel getTrxLevel()
{
if (trxLevel != null)
{
return trxLevel;
}
if (template != null)
{
return template.getTrxLevel();
}
throw new IllegalStateException("Cannot get TrxLevel");
}
@Override
public ITableCacheConfigBuilder setCacheMapType(final CacheMapType cacheMapType)
{
this.cacheMapType = cacheMapType;
return this;
}
public CacheMapType getCacheMapType()
{
if (cacheMapType != null)
{
return cacheMapType;
}
if (template != null)
{
return template.getCacheMapType();
}
throw new IllegalStateException("Cannot get CacheMapType");
}
public int getInitialCapacity()
{
if (initialCapacity > 0)
{
return initialCapacity;
}
else if (template != null)
{
return template.getInitialCapacity();
}
throw new IllegalStateException("Cannot get InitialCapacity");
}
@Override
public ITableCacheConfigBuilder setInitialCapacity(final int initialCapacity)
{
this.initialCapacity = initialCapacity; | return this;
}
public int getMaxCapacity()
{
if (maxCapacity > 0)
{
return maxCapacity;
}
else if (template != null)
{
return template.getMaxCapacity();
}
return -1;
}
@Override
public ITableCacheConfigBuilder setMaxCapacity(final int maxCapacity)
{
this.maxCapacity = maxCapacity;
return this;
}
public int getExpireMinutes()
{
if (expireMinutes > 0 || expireMinutes == ITableCacheConfig.EXPIREMINUTES_Never)
{
return expireMinutes;
}
else if (template != null)
{
return template.getExpireMinutes();
}
throw new IllegalStateException("Cannot get ExpireMinutes");
}
@Override
public ITableCacheConfigBuilder setExpireMinutes(final int expireMinutes)
{
this.expireMinutes = expireMinutes;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\TableCacheConfigBuilder.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getName() {
return name;
}
public byte[] getBytes() {
ensureInitialized();
return (entity != null ? entity.getBytes() : null);
}
public void setValue(String name, byte[] bytes) {
this.name = name;
setBytes(bytes);
}
private void setBytes(byte[] bytes) {
if (id == null) {
if (bytes != null) {
ByteArrayEntityManager byteArrayEntityManager = Context.getCommandContext().getByteArrayEntityManager();
entity = byteArrayEntityManager.create();
entity.setName(name);
entity.setBytes(bytes);
byteArrayEntityManager.insert(entity);
id = entity.getId();
}
} else {
ensureInitialized();
entity.setBytes(bytes);
}
}
public ByteArrayEntity getEntity() {
ensureInitialized();
return entity;
}
public void delete() {
if (!deleted && id != null) {
if (entity != null) {
// if the entity has been loaded already,
// we might as well use the safer optimistic locking delete. | Context.getCommandContext().getByteArrayEntityManager().delete(entity);
} else {
Context.getCommandContext().getByteArrayEntityManager().deleteByteArrayById(id);
}
entity = null;
id = null;
deleted = true;
}
}
private void ensureInitialized() {
if (id != null && entity == null) {
entity = Context.getCommandContext().getByteArrayEntityManager().findById(id);
name = entity.getName();
}
}
public boolean isDeleted() {
return deleted;
}
@Override
public String toString() {
return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]");
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayRef.java | 1 |
请完成以下Java代码 | public HistoricVariableInstanceRestService getVariableInstanceService() {
return new HistoricVariableInstanceRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricProcessDefinitionRestService getProcessDefinitionService() {
return new HistoricProcessDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDecisionDefinitionRestService getDecisionDefinitionService() {
return new HistoricDecisionDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDecisionStatisticsRestService getDecisionStatisticsService() {
return new HistoricDecisionStatisticsRestServiceImpl(getProcessEngine());
}
public HistoricCaseDefinitionRestService getCaseDefinitionService() {
return new HistoricCaseDefinitionRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public UserOperationLogRestService getUserOperationLogRestService() {
return new UserOperationLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDetailRestService getDetailService() {
return new HistoricDetailRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricTaskInstanceRestService getTaskInstanceService() {
return new HistoricTaskInstanceRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricIncidentRestService getIncidentService() {
return new HistoricIncidentRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricIdentityLinkLogRestService getIdentityLinkService() {
return new HistoricIdentityLinkLogRestServiceImpl(getObjectMapper(), getProcessEngine()); | }
public HistoricJobLogRestService getJobLogService() {
return new HistoricJobLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricDecisionInstanceRestService getDecisionInstanceService() {
return new HistoricDecisionInstanceRestServiceImpl(getObjectMapper(), getProcessEngine());
}
public HistoricBatchRestService getBatchService() {
return new HistoricBatchRestServiceImpl(getObjectMapper(), getProcessEngine());
}
@Override
public HistoricExternalTaskLogRestService getExternalTaskLogService() {
return new HistoricExternalTaskLogRestServiceImpl(getObjectMapper(), getProcessEngine());
}
@Override
public HistoryCleanupRestService getHistoryCleanupRestService() {
return new HistoryCleanupRestServiceImpl(getObjectMapper(), getProcessEngine());
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryRestServiceImpl.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** TreeType AD_Reference_ID=120 */
public static final int TREETYPE_AD_Reference_ID=120;
/** Menu = MM */
public static final String TREETYPE_Menu = "MM";
/** Element Value = EV */
public static final String TREETYPE_ElementValue = "EV";
/** Product = PR */
public static final String TREETYPE_Product = "PR";
/** BPartner = BP */
public static final String TREETYPE_BPartner = "BP";
/** Organization = OO */
public static final String TREETYPE_Organization = "OO";
/** BoM = BB */
public static final String TREETYPE_BoM = "BB";
/** Project = PJ */
public static final String TREETYPE_Project = "PJ";
/** Sales Region = SR */
public static final String TREETYPE_SalesRegion = "SR";
/** Product Category = PC */
public static final String TREETYPE_ProductCategory = "PC";
/** Campaign = MC */
public static final String TREETYPE_Campaign = "MC";
/** Activity = AY */
public static final String TREETYPE_Activity = "AY";
/** User 1 = U1 */
public static final String TREETYPE_User1 = "U1";
/** User 2 = U2 */
public static final String TREETYPE_User2 = "U2"; | /** User 3 = U3 */
public static final String TREETYPE_User3 = "U3";
/** User 4 = U4 */
public static final String TREETYPE_User4 = "U4";
/** CM Container = CC */
public static final String TREETYPE_CMContainer = "CC";
/** CM Container Stage = CS */
public static final String TREETYPE_CMContainerStage = "CS";
/** CM Template = CT */
public static final String TREETYPE_CMTemplate = "CT";
/** CM Media = CM */
public static final String TREETYPE_CMMedia = "CM";
/** Other = XX */
public static final String TREETYPE_Other = "XX";
/** Set Type | Area.
@param TreeType
Element this tree is built on (i.e Product, Business Partner)
*/
public void setTreeType (String TreeType)
{
set_ValueNoCheck (COLUMNNAME_TreeType, TreeType);
}
/** Get Type | Area.
@return Element this tree is built on (i.e Product, Business Partner)
*/
public String getTreeType ()
{
return (String)get_Value(COLUMNNAME_TreeType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Tree.java | 1 |
请完成以下Java代码 | protected boolean sameFile(URL url1, URL url2) {
if (!url1.getProtocol().equals(PROTOCOL) || !url2.getProtocol().equals(PROTOCOL)) {
return false;
}
String file1 = url1.getFile();
String file2 = url2.getFile();
int indexOfSeparator1 = file1.indexOf(SEPARATOR);
int indexOfSeparator2 = file2.indexOf(SEPARATOR);
if (indexOfSeparator1 == -1 || indexOfSeparator2 == -1) {
return super.sameFile(url1, url2);
}
String entry1 = file1.substring(indexOfSeparator1 + 2);
String entry2 = file2.substring(indexOfSeparator2 + 2);
if (!entry1.equals(entry2)) {
return false;
}
try {
URL innerUrl1 = new URL(file1.substring(0, indexOfSeparator1));
URL innerUrl2 = new URL(file2.substring(0, indexOfSeparator2));
if (!super.sameFile(innerUrl1, innerUrl2)) {
return false;
}
}
catch (MalformedURLException unused) {
return super.sameFile(url1, url2);
}
return true;
}
static int indexOfSeparator(String spec) {
return indexOfSeparator(spec, 0, spec.length()); | }
static int indexOfSeparator(String spec, int start, int limit) {
for (int i = limit - 1; i >= start; i--) {
if (spec.charAt(i) == '!' && (i + 1) < limit && spec.charAt(i + 1) == '/') {
return i;
}
}
return -1;
}
/**
* Clear any internal caches.
*/
public static void clearCache() {
JarUrlConnection.clearCache();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\Handler.java | 1 |
请完成以下Java代码 | protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.cors()
.and()
.exceptionHandling().authenticationEntryPoint(new Http401AuthenticationEntryPoint("Unauthenticated"))
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET, "/articles/feed").authenticated()
.antMatchers(HttpMethod.POST, "/users", "/users/login").permitAll()
.antMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags").permitAll()
.anyRequest().authenticated();
http.addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Bean | public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(asList("*"));
configuration.setAllowedMethods(asList("HEAD",
"GET", "POST", "PUT", "DELETE", "PATCH"));
// setAllowCredentials(true) is important, otherwise:
// The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
configuration.setAllowCredentials(true);
// setAllowedHeaders is important! Without it, OPTIONS preflight request
// will fail with 403 Invalid CORS request
configuration.setAllowedHeaders(asList("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
} | repos\spring-boot-realworld-example-app-master (1)\src\main\java\io\spring\api\security\WebSecurityConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
@Override
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@Override
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
} | return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@Override
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Redis\src\main\java\com\gaoxi\redis\service\RedisServiceImpl.java | 2 |
请完成以下Java代码 | public Category name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@ApiModelProperty(value = "")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(this.id, category.id) &&
Objects.equals(this.name, category.name);
}
@Override
public int hashCode() { | return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\Category.java | 1 |
请完成以下Java代码 | public static LocalToRemoteSyncResult updated(@NonNull final DataRecord datarecord)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.UPDATED_ON_REMOTE)
.build();
}
public static LocalToRemoteSyncResult deleted(@NonNull final DataRecord datarecord)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.DELETED_ON_REMOTE)
.build();
}
public static LocalToRemoteSyncResult error(
@NonNull final DataRecord datarecord,
@NonNull final String errorMessage)
{
return LocalToRemoteSyncResult.builder()
.synchedDataRecord(datarecord)
.localToRemoteStatus(LocalToRemoteStatus.ERROR)
.errorMessage(errorMessage)
.build();
}
public enum LocalToRemoteStatus
{
INSERTED_ON_REMOTE,
UPDATED_ON_REMOTE,
UPSERTED_ON_REMOTE,
DELETED_ON_REMOTE, UNCHANGED, ERROR;
} | LocalToRemoteStatus localToRemoteStatus;
String errorMessage;
DataRecord synchedDataRecord;
@Builder
private LocalToRemoteSyncResult(
@NonNull final DataRecord synchedDataRecord,
@Nullable final LocalToRemoteStatus localToRemoteStatus,
@Nullable final String errorMessage)
{
this.synchedDataRecord = synchedDataRecord;
this.localToRemoteStatus = localToRemoteStatus;
this.errorMessage = errorMessage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\LocalToRemoteSyncResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private @Nullable String htmlEscape(@Nullable Object input) {
return (input != null) ? HtmlUtils.htmlEscape(input.toString()) : null;
}
private String getMessage(Map<String, ?> model) {
Object path = model.get("path");
String message = "Cannot render error page for request [" + path + "]";
if (model.get("message") != null) {
message += " and exception [" + model.get("message") + "]";
}
message += " as the response has already been committed.";
message += " As a result, the response may have the wrong status code.";
return message;
}
@Override
public String getContentType() {
return "text/html";
}
}
/**
* {@link ErrorPageRegistrar} that configures the server's error pages.
*/
static class ErrorPageCustomizer implements ErrorPageRegistrar, Ordered {
private final WebProperties properties;
private final DispatcherServletPath dispatcherServletPath;
protected ErrorPageCustomizer(WebProperties properties, DispatcherServletPath dispatcherServletPath) {
this.properties = properties;
this.dispatcherServletPath = dispatcherServletPath;
}
@Override
public void registerErrorPages(ErrorPageRegistry errorPageRegistry) {
ErrorPage errorPage = new ErrorPage(
this.dispatcherServletPath.getRelativePath(this.properties.getError().getPath()));
errorPageRegistry.addErrorPages(errorPage); | }
@Override
public int getOrder() {
return 0;
}
}
/**
* {@link BeanFactoryPostProcessor} to ensure that the target class of ErrorController
* MVC beans are preserved when using AOP.
*/
static class PreserveErrorControllerTargetClassPostProcessor implements BeanFactoryPostProcessor {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
String[] errorControllerBeans = beanFactory.getBeanNamesForType(ErrorController.class, false, false);
for (String errorControllerBean : errorControllerBeans) {
try {
beanFactory.getBeanDefinition(errorControllerBean)
.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
}
catch (Throwable ex) {
// Ignore
}
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\error\ErrorMvcAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void reservePickFromHU(@NonNull final PickingJobStep step, @Nullable final BPartnerId customerId)
{
huReservationService.makeReservation(
ReserveHUsRequest.builder()
.customerId(customerId)
.documentRef(HUReservationDocRef.ofPickingJobStepId(step.getId()))
.productId(step.getProductId())
.qtyToReserve(step.getQtyToPick())
.huId(step.getPickFrom(PickingJobStepPickFromKey.MAIN).getPickFromHUId())
.build())
.orElseThrow(() -> new AdempiereException("Cannot reserve HU for " + step)); // shall not happen
}
public void releaseAllReservations(@NonNull final PickingJob pickingJob)
{
final ImmutableSet<HUReservationDocRef> reservationDocRefs = pickingJob
.getLines().stream()
.flatMap(line -> line.getSteps().stream())
.map(step -> HUReservationDocRef.ofPickingJobStepId(step.getId()))
.collect(ImmutableSet.toImmutableSet());
huReservationService.deleteReservationsByDocumentRefs(reservationDocRefs);
}
@Nullable
public ProductAvailableStocks newAvailableStocksProvider(@NonNull final Workplace workplace)
{
final Set<LocatorId> pickFromLocatorIds = warehouseService.getPickFromLocatorIds(workplace);
if (pickFromLocatorIds.isEmpty())
{
return null;
}
return ProductAvailableStocks.builder()
.handlingUnitsBL(handlingUnitsBL)
.pickFromLocatorIds(pickFromLocatorIds)
.build();
} | public boolean containsProduct(@NonNull final HuId huId, @NonNull ProductId productId)
{
return getHUProductStorage(huId, productId)
.map(IHUProductStorage::getQty)
.map(Quantity::isPositive)
.orElse(false);
}
private Optional<IHUProductStorage> getHUProductStorage(final @NotNull HuId huId, final @NotNull ProductId productId)
{
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
return Optional.ofNullable(storageFactory.getStorage(hu).getProductStorageOrNull(productId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\hu\PickingJobHUService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void createBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
if (t.getId() == null) {
t.setId(UUID.randomUUID().toString());
}
JsonDocument doc = converter.toDocument(t);
return asyncBucket.insert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
}
}).last().toBlocking().single();
}
@Override
public void updateBulk(Iterable<T> items) {
final AsyncBucket asyncBucket = bucket.async();
Observable.from(items).flatMap(new Func1<T, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(final T t) {
JsonDocument doc = converter.toDocument(t);
return asyncBucket.upsert(doc).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
} | }).last().toBlocking().single();
}
@Override
public void deleteBulk(Iterable<String> ids) {
final AsyncBucket asyncBucket = bucket.async();
Observable.from(ids).flatMap(new Func1<String, Observable<JsonDocument>>() {
@SuppressWarnings("unchecked")
@Override
public Observable<JsonDocument> call(String key) {
return asyncBucket.remove(key).retryWhen(RetryBuilder.anyOf(BackpressureException.class).delay(Delay.exponential(TimeUnit.MILLISECONDS, 100)).max(10).build());
}
}).last().toBlocking().single();
}
@Override
public boolean exists(String id) {
return bucket.exists(id);
}
} | repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\async\service\AbstractCrudService.java | 2 |
请完成以下Java代码 | public class Employee implements Comparable<Employee>{
@Nonnull
private String name;
private Date joiningDate;
public Employee(String name, Date joiningDate) {
this.name = name;
this.joiningDate = joiningDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getJoiningDate() {
return joiningDate;
}
public void setJoiningDate(Date joiningDate) {
this.joiningDate = joiningDate;
}
@Override
public boolean equals(Object obj) {
return ((Employee) obj).getName()
.equals(getName());
} | @Override
public String toString() {
return new StringBuffer().append("(")
.append(getName())
.append(",")
.append(getJoiningDate())
.append(")")
.toString();
}
@Override
public int compareTo(Employee employee) {
return getJoiningDate().compareTo(employee.getJoiningDate());
}
} | repos\tutorials-master\core-java-modules\core-java-collections\src\main\java\com\baeldung\collections\sorting\list\Employee.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getSizeParameter() {
return this.sizeParameter;
}
public void setSizeParameter(String sizeParameter) {
this.sizeParameter = sizeParameter;
}
public boolean isOneIndexedParameters() {
return this.oneIndexedParameters;
}
public void setOneIndexedParameters(boolean oneIndexedParameters) {
this.oneIndexedParameters = oneIndexedParameters;
}
public String getPrefix() {
return this.prefix;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public String getQualifierDelimiter() {
return this.qualifierDelimiter;
}
public void setQualifierDelimiter(String qualifierDelimiter) {
this.qualifierDelimiter = qualifierDelimiter;
}
public int getDefaultPageSize() {
return this.defaultPageSize;
}
public void setDefaultPageSize(int defaultPageSize) {
this.defaultPageSize = defaultPageSize;
}
public int getMaxPageSize() {
return this.maxPageSize;
}
public void setMaxPageSize(int maxPageSize) {
this.maxPageSize = maxPageSize; | }
public PageSerializationMode getSerializationMode() {
return this.serializationMode;
}
public void setSerializationMode(PageSerializationMode serializationMode) {
this.serializationMode = serializationMode;
}
}
/**
* Sort properties.
*/
public static class Sort {
/**
* Sort parameter name.
*/
private String sortParameter = "sort";
public String getSortParameter() {
return this.sortParameter;
}
public void setSortParameter(String sortParameter) {
this.sortParameter = sortParameter;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebProperties.java | 2 |
请完成以下Java代码 | public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery)
{
set_Value (COLUMNNAME_NextDelivery, NextDelivery);
}
@Override
public java.sql.Timestamp getNextDelivery()
{
return get_ValueAsTimestamp(COLUMNNAME_NextDelivery);
}
@Override
public void setRootId (final @Nullable java.lang.String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public java.lang.String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setSalesLineId (final @Nullable java.lang.String SalesLineId)
{
set_Value (COLUMNNAME_SalesLineId, SalesLineId);
}
@Override
public java.lang.String getSalesLineId()
{
return get_ValueAsString(COLUMNNAME_SalesLineId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
} | @Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
@Override
public void setTimePeriod (final @Nullable BigDecimal TimePeriod)
{
set_Value (COLUMNNAME_TimePeriod, TimePeriod);
}
@Override
public BigDecimal getTimePeriod()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUnit (final @Nullable java.lang.String Unit)
{
set_Value (COLUMNNAME_Unit, Unit);
}
@Override
public java.lang.String getUnit()
{
return get_ValueAsString(COLUMNNAME_Unit);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_C_OLCand_AlbertaOrder.java | 1 |
请完成以下Java代码 | public void setQtyShipped (final @Nullable BigDecimal QtyShipped)
{
set_Value (COLUMNNAME_QtyShipped, QtyShipped);
}
@Override
public BigDecimal getQtyShipped()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyShipped_CatchWeight (final @Nullable BigDecimal QtyShipped_CatchWeight)
{
set_Value (COLUMNNAME_QtyShipped_CatchWeight, QtyShipped_CatchWeight);
}
@Override
public BigDecimal getQtyShipped_CatchWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyShipped_CatchWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyShipped_CatchWeight_UOM_ID (final int QtyShipped_CatchWeight_UOM_ID)
{
if (QtyShipped_CatchWeight_UOM_ID < 1)
set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, null);
else
set_Value (COLUMNNAME_QtyShipped_CatchWeight_UOM_ID, QtyShipped_CatchWeight_UOM_ID);
}
@Override
public int getQtyShipped_CatchWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_QtyShipped_CatchWeight_UOM_ID);
} | @Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setReplicationTrxErrorMsg (final @Nullable java.lang.String ReplicationTrxErrorMsg)
{
throw new IllegalArgumentException ("ReplicationTrxErrorMsg is virtual column"); }
@Override
public java.lang.String getReplicationTrxErrorMsg()
{
return get_ValueAsString(COLUMNNAME_ReplicationTrxErrorMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCand.java | 1 |
请完成以下Java代码 | public boolean checkRateLimit(LimitedApi api, Object level, String rateLimitConfig) {
RateLimitKey key = new RateLimitKey(api, level);
if (StringUtils.isEmpty(rateLimitConfig)) {
rateLimits.invalidate(key);
return true;
}
log.trace("[{}] Checking rate limit for {} ({})", level, api, rateLimitConfig);
TbRateLimits rateLimit = rateLimits.asMap().compute(key, (k, limit) -> {
if (limit == null || !limit.getConfiguration().equals(rateLimitConfig)) {
limit = new TbRateLimits(rateLimitConfig, api.isRefillRateLimitIntervally());
log.trace("[{}] Created new rate limit bucket for {} ({})", level, api, rateLimitConfig);
}
return limit;
});
boolean success = rateLimit.tryConsume();
if (!success) {
log.debug("[{}] Rate limit exceeded for {} ({})", level, api, rateLimitConfig);
}
return success; | }
@Override
public void cleanUp(LimitedApi api, Object level) {
RateLimitKey key = new RateLimitKey(api, level);
rateLimits.invalidate(key);
}
@Data(staticConstructor = "of")
private static class RateLimitKey {
private final LimitedApi api;
private final Object level;
}
} | repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\limits\DefaultRateLimitService.java | 1 |
请完成以下Java代码 | private Money computeLineNetAmt(final ProductPrice priceActual, final Quantity quantity)
{
final MoneyService moneyService = SpringContextHolder.instance.getBean(MoneyService.class);
return moneyService.multiply(quantity, priceActual);
}
private Percent getQualityDiscountPercent(final I_C_Invoice_Candidate candidate)
{
final Percent qualityDiscoutPercent = invoiceCandBL.getQualityDiscountPercentEffective(candidate);
// return qualityDiscoutPercent.setScale(2, RoundingMode.HALF_UP); // make sure the number looks nice
return qualityDiscoutPercent;
}
/**
* Gets description prefix to be used when creating an invoice line for given invoice candidate.
*/
private String getDescriptionPrefix(final I_C_Invoice_Candidate candidate)
{
final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class);
final int bpartnerId = candidate.getBill_BPartner_ID();
String descriptionPrefix = bpartnerId2descriptionPrefix.get(bpartnerId);
// Build descriptionPrefix if not already built
if (descriptionPrefix == null)
{
final I_C_BPartner billBPartner = bpartnerDAO.getById(BPartnerId.ofRepoId(candidate.getBill_BPartner_ID()));
final String adLanguage = billBPartner.getAD_Language();
descriptionPrefix = msgBL.getMsg(adLanguage, MSG_QualityDiscount, new Object[] {});
bpartnerId2descriptionPrefix.put(bpartnerId, descriptionPrefix); | }
return descriptionPrefix;
}
private void setNetLineAmt(final IInvoiceLineRW invoiceLine)
{
final Quantity stockQty = invoiceLine.getQtysToInvoice().getStockQty();
final Quantity uomQty = invoiceLine.getQtysToInvoice().getUOMQtyOpt().orElse(stockQty);
final ProductPrice priceActual = invoiceLine.getPriceActual();
final Money lineNetAmt = computeLineNetAmt(priceActual, uomQty);
invoiceLine.setNetLineAmt(lineNetAmt);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\invoicecandidate\spi\impl\FreshQuantityDiscountAggregator.java | 1 |
请完成以下Java代码 | public void setMessageName(String messageName) {
this.messageName = messageName;
}
public String getMessageName() {
return messageName;
}
public void setMessageData(Object messageData) {
this.messageData = messageData;
}
public Object getMessageData() {
return messageData;
}
public String getMessageCorrelationKey() { | return correlationKey;
}
public void setMessageCorrelationKey(String correlationKey) {
this.correlationKey = correlationKey;
}
public String getMessageBusinessKey() {
return businessKey;
}
public void setMessageBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiMessageEventImpl.java | 1 |
请完成以下Java代码 | public class Product {
private String name;
private String category;
private Map<String, Object> details = new LinkedHashMap<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category; | }
public void setCategory(String category) {
this.category = category;
}
public Map<String, Object> getDetails() {
return details;
}
@JsonAnySetter
public void setDetail(String key, Object value) {
details.put(key, value);
}
} | repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\dynamicobject\Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DefaultWebSecurityManager securityManager() {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(shiroRealm());
// securityManager.setCacheManager(ehCacheManager());
return securityManager;
}
/**
* ShiroFilterFactoryBean,是个factorybean,为了生成ShiroFilter。
* 它主要保持了三项数据,securityManager,filters,filterChainDefinitionManager。
*/
@Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login");
// filters.put("logout",null);
shiroFilterFactoryBean.setFilters(filters);
Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>();
filterChainDefinitionManager.put("/logout", "logout");
filterChainDefinitionManager.put("/user/**", "authc,roles[ROLE_USER]");
filterChainDefinitionManager.put("/events/**", "authc,roles[ROLE_ADMIN]");
// filterChainDefinitionManager.put("/user/edit/**", "authc,perms[user:edit]");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取
filterChainDefinitionManager.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
shiroFilterFactoryBean.setSuccessUrl("/");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
return shiroFilterFactoryBean;
}
/**
* DefaultAdvisorAutoProxyCreator,Spring的一个bean,由Advisor决定对哪些类的方法进行AOP代理。
*/
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() { | DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
/**
* AuthorizationAttributeSourceAdvisor,shiro里实现的Advisor类,
* 内部使用AopAllianceAnnotationsAuthorizingMethodInterceptor来拦截用以下注解的方法。
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor aASA = new AuthorizationAttributeSourceAdvisor();
aASA.setSecurityManager(securityManager());
return aASA;
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\shiro\ShiroConfiguration.java | 2 |
请完成以下Java代码 | public class SubTypeConversionStructure {
public static abstract class Vehicle {
private String make;
private String model;
protected Vehicle() {
}
protected Vehicle(String make, String model) {
this.make = make;
this.model = model;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
}
public static class Car extends Vehicle {
@JsonIgnore
private int seatingCapacity;
@JsonIgnore
private double topSpeed;
public Car() {
}
public Car(String make, String model, int seatingCapacity, double topSpeed) {
super(make, model);
this.seatingCapacity = seatingCapacity;
this.topSpeed = topSpeed;
} | public int getSeatingCapacity() {
return seatingCapacity;
}
public void setSeatingCapacity(int seatingCapacity) {
this.seatingCapacity = seatingCapacity;
}
public double getTopSpeed() {
return topSpeed;
}
public void setTopSpeed(double topSpeed) {
this.topSpeed = topSpeed;
}
}
public static class Truck extends Vehicle {
@JsonIgnore
private double payloadCapacity;
public Truck() {
}
public Truck(String make, String model, double payloadCapacity) {
super(make, model);
this.payloadCapacity = payloadCapacity;
}
public double getPayloadCapacity() {
return payloadCapacity;
}
public void setPayloadCapacity(double payloadCapacity) {
this.payloadCapacity = payloadCapacity;
}
}
} | repos\tutorials-master\jackson-modules\jackson-core\src\main\java\com\baeldung\jackson\inheritance\SubTypeConversionStructure.java | 1 |
请完成以下Java代码 | private void collectContextValue(
@NonNull final CtxName variableName,
final boolean failIfNotFound)
{
if (valuesCollected.containsKey(variableName.getName()))
{
return;
}
final Object value = findContextValueOrNull(variableName);
if (value == null)
{
if (failIfNotFound)
{
throw ExpressionEvaluationException.newWithTranslatableMessage("@NotFound@: " + variableName);
}
}
else
{
valuesCollected.put(variableName.getName(), value);
}
}
@Nullable
private Object findContextValueOrNull(@NonNull final CtxName variableName)
{
//
// Check given parameters
if (name2value.containsKey(variableName.getName()))
{
final Object valueObj = name2value.get(variableName.getName());
if (valueObj != null)
{
return valueObj;
}
}
if (variableName.getName().equals(PARAM_OrgAccessSql.getName())
&& !Check.isBlank(lookupTableName)
&& UserRolePermissionsKey.fromContextOrNull(ctx) != null)
{
return Env.getUserRolePermissions(ctx).getOrgWhere(lookupTableName, Access.READ)
.orElse("true");
}
// Fallback to document evaluatee
if (parentEvaluatee != null)
{
final Object value = parentEvaluatee.get_ValueIfExists(variableName.getName(), Object.class).orElse(null);
if (value != null)
{
return value;
}
} | // Fallback to the variableName's default value
if (variableName.getDefaultValue() != CtxNames.VALUE_NULL)
{
return variableName.getDefaultValue();
}
// Value not found
return null;
}
@Nullable
private String getContextTableName()
{
try
{
collectContextValue(PARAM_ContextTableName, false);
final Object contextTableNameObj = valuesCollected.get(PARAM_ContextTableName.getName());
return contextTableNameObj != null ? contextTableNameObj.toString() : null;
}
catch (final Exception e)
{
logger.warn(e.getMessage());
return null;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\LookupDataSourceContext.java | 1 |
请完成以下Java代码 | public class TbNotificationNode extends TbAbstractExternalNode {
private TbNotificationNodeConfiguration config;
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
super.init(ctx);
config = TbNodeUtils.convert(configuration, TbNotificationNodeConfiguration.class);
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) throws ExecutionException, InterruptedException, TbNodeException {
RuleEngineOriginatedNotificationInfo notificationInfo = RuleEngineOriginatedNotificationInfo.builder()
.msgOriginator(msg.getOriginator())
.msgCustomerId(msg.getOriginator().getEntityType() == EntityType.CUSTOMER
&& msg.getOriginator().equals(msg.getCustomerId()) ? null : msg.getCustomerId())
.msgMetadata(msg.getMetaData().getData())
.msgData(JacksonUtil.toFlatMap(JacksonUtil.toJsonNode(msg.getData())))
.msgType(msg.getType())
.build();
NotificationRequest notificationRequest = NotificationRequest.builder()
.tenantId(ctx.getTenantId())
.targets(config.getTargets())
.templateId(config.getTemplateId())
.info(notificationInfo)
.additionalConfig(new NotificationRequestConfig()) | .originatorEntityId(ctx.getSelf().getRuleChainId())
.build();
var tbMsg = ackIfNeeded(ctx, msg);
var callback = new FutureCallback<NotificationRequestStats>() {
@Override
public void onSuccess(NotificationRequestStats stats) {
TbMsgMetaData metaData = tbMsg.getMetaData().copy();
metaData.putValue("notificationRequestResult", JacksonUtil.toString(stats));
tellSuccess(ctx, tbMsg.transform()
.metaData(metaData)
.build());
}
@Override
public void onFailure(Throwable e) {
tellFailure(ctx, tbMsg, e);
}
};
var future = ctx.getNotificationExecutor().executeAsync(() ->
ctx.getNotificationCenter().processNotificationRequest(ctx.getTenantId(), notificationRequest, callback));
DonAsynchron.withCallback(future, r -> {}, callback::onFailure);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\notification\TbNotificationNode.java | 1 |
请完成以下Java代码 | static class HeaderWriterRequest extends HttpServletRequestWrapper {
private final HeaderWriterResponse response;
HeaderWriterRequest(HttpServletRequest request, HeaderWriterResponse response) {
super(request);
this.response = response;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return new HeaderWriterRequestDispatcher(super.getRequestDispatcher(path), this.response);
}
}
static class HeaderWriterRequestDispatcher implements RequestDispatcher {
private final RequestDispatcher delegate; | private final HeaderWriterResponse response;
HeaderWriterRequestDispatcher(RequestDispatcher delegate, HeaderWriterResponse response) {
this.delegate = delegate;
this.response = response;
}
@Override
public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.delegate.forward(request, response);
}
@Override
public void include(ServletRequest request, ServletResponse response) throws ServletException, IOException {
this.response.onResponseCommitted();
this.delegate.include(request, response);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\HeaderWriterFilter.java | 1 |
请完成以下Java代码 | public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final UomId id1, @Nullable final UomId id2)
{
return Objects.equals(id1, id2);
}
@NonNull
@SafeVarargs
public static <T> UomId getCommonUomIdOfAll(
@NonNull final Function<T, UomId> getUomId,
@NonNull final String name,
@Nullable final T... objects)
{
if (objects == null || objects.length == 0)
{
throw new AdempiereException("No " + name + " provided");
}
else if (objects.length == 1 && objects[0] != null)
{
return getUomId.apply(objects[0]);
}
else
{
UomId commonUomId = null;
for (final T object : objects)
{
if (object == null) | {
continue;
}
final UomId uomId = getUomId.apply(object);
if (commonUomId == null)
{
commonUomId = uomId;
}
else if (!UomId.equals(commonUomId, uomId))
{
throw new AdempiereException("All given " + name + "(s) shall have the same UOM: " + Arrays.asList(objects));
}
}
if (commonUomId == null)
{
throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects));
}
return commonUomId;
}
}
public boolean isEach() {return EACH.equals(this);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UomId.java | 1 |
请完成以下Java代码 | public void setId(String id) {
// For the sake of Entity caching the id is necessary
this.id = id;
}
public UserEntity getUser() {
return user;
}
public void setUser(UserEntity user) {
this.user = user;
}
public GroupEntity getGroup() {
return group;
}
public void setGroup(GroupEntity group) {
this.group = group;
} | // required for mybatis
public String getUserId(){
return user.getId();
}
// required for mybatis
public String getGroupId(){
return group.getId();
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[user=" + user
+ ", group=" + group
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MembershipEntity.java | 1 |
请完成以下Java代码 | public class BookDto implements Serializable {
private static final long serialVersionUID = 1L;
private Long bookId;
private String title;
public BookDto() {}
public BookDto(Long bookId, String title) {
this.bookId = bookId;
this.title = title;
}
public Long getId() {
return bookId;
}
public void setId(Long bookId) { | this.bookId = bookId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "BookDto{" + "bookId="
+ bookId + ", title=" + title + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDtoCustomResultTransformer\src\main\java\com\bookstore\dto\BookDto.java | 1 |
请完成以下Java代码 | private I_M_MatchPO createMatchPO(final I_M_InOutLine sLine, final Timestamp dateTrx, final BigDecimal qty)
{
final I_M_MatchPO matchPO = newInstance(I_M_MatchPO.class);
matchPO.setAD_Org_ID(sLine.getAD_Org_ID());
matchPO.setM_InOutLine_ID(sLine.getM_InOutLine_ID());
matchPO.setC_OrderLine_ID(sLine.getC_OrderLine_ID());
if (dateTrx != null)
{
matchPO.setDateTrx(dateTrx);
}
matchPO.setM_Product_ID(sLine.getM_Product_ID());
matchPO.setM_AttributeSetInstance_ID(sLine.getM_AttributeSetInstance_ID());
matchPO.setQty(qty);
matchPO.setProcessed(true); // auto
return matchPO;
}
private I_M_MatchPO createMatchPO(final I_C_InvoiceLine iLine, final Timestamp dateTrx, final BigDecimal qty)
{
final I_M_MatchPO matchPO = newInstance(I_M_MatchPO.class);
matchPO.setAD_Org_ID(iLine.getAD_Org_ID());
matchPO.setC_InvoiceLine(iLine);
if (iLine.getC_OrderLine_ID() != 0)
{
matchPO.setC_OrderLine_ID(iLine.getC_OrderLine_ID());
}
if (dateTrx != null)
{
matchPO.setDateTrx(dateTrx);
}
matchPO.setM_Product_ID(iLine.getM_Product_ID());
matchPO.setM_AttributeSetInstance_ID(iLine.getM_AttributeSetInstance_ID());
matchPO.setQty(qty);
matchPO.setProcessed(true); // auto
return matchPO;
} // MMatchPO
private static DocumentPostRequest toDocumentPostRequest(final I_M_MatchPO matchPO)
{
return DocumentPostRequest.builder()
.record(TableRecordReference.of(I_M_MatchPO.Table_Name, matchPO.getM_MatchPO_ID()))
.clientId(ClientId.ofRepoId(matchPO.getAD_Client_ID()))
.build();
}
@Override
public void unlink(@NonNull final OrderLineId orderLineId, @NonNull final InvoiceAndLineId invoiceAndLineId)
{
for (final I_M_MatchPO matchPO : matchPODAO.getByOrderLineAndInvoiceLine(orderLineId, invoiceAndLineId))
{
if (matchPO.getM_InOutLine_ID() <= 0)
{
matchPO.setProcessed(false);
InterfaceWrapperHelper.delete(matchPO);
}
else
{
matchPO.setC_InvoiceLine_ID(-1);
InterfaceWrapperHelper.save(matchPO);
}
}
}
@Override
public void unlink(@NonNull final InOutId inoutId)
{
for (final I_M_MatchPO matchPO : matchPODAO.getByReceiptId(inoutId))
{ | if (matchPO.getC_InvoiceLine_ID() <= 0)
{
matchPO.setProcessed(false);
InterfaceWrapperHelper.delete(matchPO);
}
else
{
matchPO.setM_InOutLine_ID(-1);
InterfaceWrapperHelper.save(matchPO);
}
}
}
@Override
public void unlink(@NonNull final InvoiceId invoiceId)
{
for (final I_M_MatchPO matchPO : matchPODAO.getByInvoiceId(invoiceId))
{
if (matchPO.getM_InOutLine_ID() <= 0)
{
matchPO.setProcessed(false);
InterfaceWrapperHelper.delete(matchPO);
}
else
{
matchPO.setC_InvoiceLine_ID(-1);
InterfaceWrapperHelper.save(matchPO);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\MatchPOBL.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
} | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\entity\Book.java | 1 |
请完成以下Java代码 | private void setupAggregations()
{
//
// In case there was no aggregation found, fallback to our legacy IC header/line aggregation key builders
final IAggregationFactory aggregationFactory = Services.get(IAggregationFactory.class);
aggregationFactory.setDefaultAggregationKeyBuilder(I_C_Invoice_Candidate.class, X_C_Aggregation.AGGREGATIONUSAGELEVEL_Header, ICHeaderAggregationKeyBuilder_OLD.instance);
aggregationFactory.setDefaultAggregationKeyBuilder(I_C_Invoice_Candidate.class, X_C_Aggregation.AGGREGATIONUSAGELEVEL_Line, ICLineAggregationKeyBuilder_OLD.instance);
//
// On C_Aggregation master data change => invalidate candidates for that aggregation
Services.get(IAggregationListeners.class).addListener(aggregationListener);
}
private void ensureDataDestExists()
{
final Properties ctx = Env.getCtx();
final I_AD_InputDataSource dest = Services.get(IInputDataSourceDAO.class).retrieveInputDataSource(ctx, InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME, false, ITrx.TRXNAME_None); | if (dest == null)
{
final I_AD_InputDataSource newDest = InterfaceWrapperHelper.create(ctx, I_AD_InputDataSource.class, ITrx.TRXNAME_None);
newDest.setEntityType(InvoiceCandidate_Constants.ENTITY_TYPE);
newDest.setInternalName(InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME);
newDest.setIsDestination(true);
newDest.setValue(InvoiceCandidate_Constants.DATA_DESTINATION_INTERNAL_NAME);
newDest.setName(Services.get(IMsgBL.class).translate(ctx, "C_Invoice_ID"));
InterfaceWrapperHelper.save(newDest);
}
}
@Override
protected void setupCaching(final IModelCacheService cachingService)
{
CacheMgt.get().enableRemoteCacheInvalidationForTableName(I_C_Invoice_Candidate.Table_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\ConfigValidator.java | 1 |
请完成以下Java代码 | private static JsonErrorItem toJsonErrorItem(@NonNull final String errorMsg)
{
return JsonObjectMapperHolder.fromJsonNonNull(errorMsg, JsonErrorItem.class);
}
private JsonOLCand toJson(
@NonNull final OLCand olCand,
@NonNull final MasterdataProvider masterdataProvider)
{
final OrgId orgId = OrgId.ofRepoId(olCand.getAD_Org_ID());
final ZoneId orgTimeZone = masterdataProvider.getOrgTimeZone(orgId);
final String orgCode = orgDAO.retrieveOrgValue(orgId);
final OrderLineGroup orderLineGroup = olCand.getOrderLineGroup();
final JsonOrderLineGroup jsonOrderLineGroup = orderLineGroup == null
? null
: JsonOrderLineGroup.builder()
.groupKey(orderLineGroup.getGroupKey())
.isGroupMainItem(orderLineGroup.isGroupMainItem())
.build();
return JsonOLCand.builder()
.id(olCand.getId())
.poReference(olCand.getPOReference())
.externalLineId(olCand.getExternalLineId())
.externalHeaderId(olCand.getExternalHeaderId())
//
.orgCode(orgCode)
//
.bpartner(toJson(orgCode, olCand.getBPartnerInfo(), masterdataProvider))
.billBPartner(toJson(orgCode, olCand.getBillBPartnerInfo(), masterdataProvider))
.dropShipBPartner(toJson(orgCode, olCand.getDropShipBPartnerInfo().orElse(null), masterdataProvider))
.handOverBPartner(toJson(orgCode, olCand.getHandOverBPartnerInfo().orElse(null), masterdataProvider))
//
.dateCandidate(TimeUtil.asLocalDate(olCand.unbox().getDateCandidate(), SystemTime.zoneId()))
.dateOrdered(olCand.getDateOrdered())
.datePromised(TimeUtil.asLocalDate(olCand.getDatePromised(), orgTimeZone))
.flatrateConditionsId(olCand.getFlatrateConditionsId())
//
.productId(olCand.getM_Product_ID())
.productDescription(olCand.getProductDescription())
.qty(olCand.getQty().toBigDecimal())
.uomId(olCand.getQty().getUomId().getRepoId())
.qtyItemCapacity(Quantitys.toBigDecimalOrNull(olCand.getQtyItemCapacityEff()))
.huPIItemProductId(olCand.getHUPIProductItemId())
// | .pricingSystemId(PricingSystemId.toRepoId(olCand.getPricingSystemId()))
.price(olCand.getPriceActual())
.discount(olCand.getDiscount())
//
.warehouseDestId(WarehouseId.toRepoId(olCand.getWarehouseDestId()))
//
.jsonOrderLineGroup(jsonOrderLineGroup)
.description(olCand.unbox().getDescription())
.adIssueId(Optional.ofNullable(olCand.getAdIssueId())
.map(AdIssueId::getRepoId)
.map(JsonMetasfreshId::of)
.orElse(null))
.line(olCand.getLine())
.build();
}
@NonNull
private static AssignSalesRepRule getAssignSalesRepRule(@NonNull final JsonApplySalesRepFrom jsonApplySalesRepFrom)
{
switch (jsonApplySalesRepFrom)
{
case Candidate:
return AssignSalesRepRule.Candidate;
case BPartner:
return AssignSalesRepRule.BPartner;
case CandidateFirst:
return AssignSalesRepRule.CandidateFirst;
default:
throw new AdempiereException("Unsupported JsonApplySalesRepFrom " + jsonApplySalesRepFrom);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\JsonConverters.java | 1 |
请完成以下Java代码 | public String getPeriodType ()
{
return (String)get_Value(COLUMNNAME_PeriodType);
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Start Date. | @param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Period.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected Class<? extends T> getComponentType(Class<?> annotationClass, ConditionContext context,
AnnotatedTypeMetadata metadata) {
Map<String, Object> attributes = metadata.getAnnotationAttributes(annotationClass.getName());
if (attributes != null && attributes.containsKey("value")) {
Class<?> target = (Class<?>) attributes.get("value");
if (target != defaultValueClass()) {
return (Class<? extends T>) target;
}
}
Assert.state(metadata instanceof MethodMetadata && metadata.isAnnotated(Bean.class.getName()),
getClass().getSimpleName() + " must be used on @Bean methods when the value is not specified");
MethodMetadata methodMetadata = (MethodMetadata) metadata;
try {
return (Class<? extends T>) ClassUtils.forName(methodMetadata.getReturnTypeName(),
context.getClassLoader());
}
catch (Throwable ex) {
throw new IllegalStateException("Failed to extract component class for "
+ methodMetadata.getDeclaringClassName() + "." + methodMetadata.getMethodName(), ex);
} | }
private ConditionOutcome determineOutcome(Class<? extends T> componentClass, PropertyResolver resolver) {
String key = PREFIX + normalizeComponentName(componentClass) + SUFFIX;
ConditionMessage.Builder messageBuilder = forCondition(annotationClass().getName(), componentClass.getName());
if ("false".equalsIgnoreCase(resolver.getProperty(key))) {
return ConditionOutcome.noMatch(messageBuilder.because("bean is not available"));
}
return ConditionOutcome.match();
}
protected abstract String normalizeComponentName(Class<? extends T> componentClass);
protected abstract Class<?> annotationClass();
protected abstract Class<? extends T> defaultValueClass();
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\conditional\OnEnabledComponent.java | 2 |
请完成以下Java代码 | public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
return minioClient.getPresignedObjectUrl(args);
}
/**
* get file url
*
* @param bucketName
* @param objectName
* @return url
*/
@SneakyThrows(Exception.class)
public String getPresignedObjectUrl(String bucketName, String objectName) {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.method(Method.GET).build(); | return minioClient.getPresignedObjectUrl(args);
}
/**
* change URLDecoder to UTF8
*
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
return URLDecoder.decode(url, "UTF-8");
}
} | repos\springboot-demo-master\minio\src\main\java\demo\et\minio\util\MinioUtils.java | 1 |
请完成以下Java代码 | private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (isEndedContract(importRecord))
{
contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit);
contract.setNoticeDate(contract.getEndDate());
contract.setIsAutoRenew(false);
contract.setProcessed(true);
contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None);
contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed);
}
}
private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm)
{ | final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm);
newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId()));
newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded());
}
private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm)
{
return FlatrateTermPricing.builder()
.termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID()))
.qty(newTerm.getPlannedQtyPerUnit())
.term(newTerm)
.priceDate(TimeUtil.asLocalDate(newTerm.getStartDate()))
.build()
.computeOrThrowEx();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java | 1 |
请完成以下Java代码 | protected JWSSigner getJwsSigner() throws Exception {
String signingkey = config.getValue("signingkey", String.class);
String pemEncodedRSAPrivateKey = PEMKeyUtils.readKeyAsString(signingkey);
RSAKey rsaKey = (RSAKey) JWK.parseFromPEMEncodedObjects(pemEncodedRSAPrivateKey);
return new RSASSASigner(rsaKey.toRSAPrivateKey());
}
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
//4. Signing
JWSSigner jwsSigner = getJwsSigner();
Instant now = Instant.now();
//Long expiresInMin = 30L;
Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));
//3. JWT Payload or claims
JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
.issuer("http://localhost:9080")
.subject(subject)
.claim("upn", subject)
.claim("client_id", clientId)
.audience("http://localhost:9280")
.claim("scope", approvedScope)
.claim("groups", Arrays.asList(approvedScope.split(" ")))
.expirationTime(expirationTime) // expires in 30 minutes
.notBeforeTime(Date.from(now))
.issueTime(Date.from(now)) | .jwtID(UUID.randomUUID().toString())
.build();
SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
signedJWT.sign(jwsSigner);
return signedJWT.serialize();
}
protected String getRefreshToken(String clientId, String subject, String approvedScope) throws Exception {
JWSSigner jwsSigner = getJwsSigner();
Instant now = Instant.now();
//6.Build refresh token
JWTClaimsSet refreshTokenClaims = new JWTClaimsSet.Builder()
.subject(subject)
.claim("client_id", clientId)
.claim("scope", approvedScope)
//refresh token for 1 day.
.expirationTime(Date.from(now.plus(1, ChronoUnit.DAYS)))
.build();
SignedJWT signedRefreshToken = new SignedJWT(jwsHeader, refreshTokenClaims);
signedRefreshToken.sign(jwsSigner);
return signedRefreshToken.serialize();
}
} | repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-authorization-server\src\main\java\com\baeldung\oauth2\authorization\server\handler\AbstractGrantTypeHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeFunctionalConfig {
@Bean
EmployeeRepository employeeRepository() {
return new EmployeeRepository();
}
@Bean
RouterFunction<ServerResponse> getAllEmployeesRoute() {
return route(GET("/employees"), req -> ok().body(employeeRepository().findAllEmployees(), Employee.class));
}
@Bean
RouterFunction<ServerResponse> getEmployeeByIdRoute() {
return route(GET("/employees/{id}"), req -> ok().body(employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class));
}
@Bean
RouterFunction<ServerResponse> updateEmployeeRoute() {
return route(POST("/employees/update"), req -> req.body(toMono(Employee.class))
.doOnNext(employeeRepository()::updateEmployee)
.then(ok().build()));
}
@Bean
RouterFunction<ServerResponse> composedRoutes() {
return route(GET("/employees"), req -> ok().body(employeeRepository().findAllEmployees(), Employee.class)) | .and(route(GET("/employees/{id}"), req -> ok().body(employeeRepository().findEmployeeById(req.pathVariable("id")), Employee.class)))
.and(route(POST("/employees/update"), req -> req.body(toMono(Employee.class))
.doOnNext(employeeRepository()::updateEmployee)
.then(ok().build())));
}
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.csrf(csrf -> csrf.disable())
.authorizeExchange(
exchanges -> exchanges.anyExchange().permitAll()
);
return http.build();
}
} | repos\tutorials-master\spring-reactive-modules\spring-reactive\src\main\java\com\baeldung\reactive\webflux\functional\EmployeeFunctionalConfig.java | 2 |
请完成以下Java代码 | public static void mergeAllocationResult(
@NonNull final IMutableAllocationResult to,
@NonNull final IAllocationResult from)
{
to.subtractAllocatedQty(from.getQtyAllocated());
to.addTransactions(from.getTransactions());
to.addAttributeTransactions(from.getAttributeTransactions());
}
/**
* @return Empty immutable {@link IAllocationResult}
*/
public static IAllocationResult nullResult()
{
return NullAllocationResult.instance;
}
/**
* Creates an immutable allocation result. For cross-package use.
*
* @return {@link AllocationResult}
*/
public static IAllocationResult createQtyAllocationResult(final BigDecimal qtyToAllocate,
final BigDecimal qtyAllocated,
final List<IHUTransactionCandidate> trxs,
final List<IHUTransactionAttribute> attributeTrxs)
{
return new AllocationResult(qtyToAllocate, qtyAllocated, trxs, attributeTrxs);
}
@Nullable
public static Object getReferencedModel(final IAllocationRequest request)
{
final ITableRecordReference tableRecord = request.getReference();
if (tableRecord == null)
{
return null;
}
final IContextAware context = request.getHuContext();
return tableRecord.getModel(context);
}
/**
* Gets relative request qty (negated if deallocation).
*/
public static Quantity getQuantity(
@NonNull final IAllocationRequest request,
@NonNull final AllocationDirection direction)
{
return request
.getQuantity() // => Quantity (absolute)
.negateIf(direction.isOutboundDeallocation()); // => Quantity (relative)
}
/**
* Use this to create a new allocation request, using the given request as template.
*/
public static IAllocationRequestBuilder derive(@NonNull final IAllocationRequest request)
{
return builder().setBaseAllocationRequest(request);
}
@Nullable
private static BPartnerId getBPartnerId(final IAllocationRequest request)
{ | final Object referencedModel = AllocationUtils.getReferencedModel(request);
if (referencedModel == null)
{
return null;
}
final Integer bpartnerId = InterfaceWrapperHelper.getValueOrNull(referencedModel, I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID);
return BPartnerId.ofRepoIdOrNull(bpartnerId);
}
/**
* Creates and configures an {@link IHUBuilder} based on the given <code>request</code> (bPartner and date).
*
* @return HU builder
*/
public static IHUBuilder createHUBuilder(final IAllocationRequest request)
{
final IHUContext huContext = request.getHuContext();
final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext);
huBuilder.setDate(request.getDate());
huBuilder.setBPartnerId(getBPartnerId(request));
// TODO: huBuilder.setC_BPartner_Location if any
// TODO: set the HU Storage from context to builder
return huBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationUtils.java | 1 |
请完成以下Java代码 | public IHUAttributeTransferStrategy retrieveTransferStrategy()
{
return CopyHUAttributeTransferStrategy.instance;
}
/**
* @return {@code true}.
*/
@Override
public boolean isReadonlyUI()
{
return true;
}
/**
* @return {@code true}.
*/
@Override
public boolean isDisplayedUI()
{
return true;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
/**
* @return our attribute instance's {@code M_Attribute_ID}.
*/ | @Override
public int getDisplaySeqNo()
{
return attributeInstance.getM_Attribute_ID();
}
/**
* @return {@code true}
*/
@Override
public boolean isUseInASI()
{
return true;
}
/**
* @return {@code false}, since no HU-PI attribute is involved.
*/
@Override
public boolean isDefinedByTemplate()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java | 1 |
请完成以下Java代码 | public final class SqlAndParamsExtractor<Context>
{
@Getter
private final String sql;
@FunctionalInterface
public interface ParametersExtractor<Context>
{
List<Object> extractParameters(Context context);
}
private final ImmutableList<ParametersExtractor<Context>> parametersExtractors;
@Builder
private SqlAndParamsExtractor(
@NonNull final String sql, | @NonNull final List<ParametersExtractor<Context>> parametersExtractors)
{
this.sql = sql;
this.parametersExtractors = ImmutableList.copyOf(parametersExtractors);
}
public List<Object> extractParameters(@NonNull final Context context)
{
final List<Object> allParameters = new ArrayList<>();
for (final ParametersExtractor<Context> extractor : parametersExtractors)
{
allParameters.addAll(extractor.extractParameters(context));
}
return allParameters;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\util\SqlAndParamsExtractor.java | 1 |
请完成以下Java代码 | private static Flux<String> resolveTokens(MultiValueMap<String, String> parameters) {
List<String> accessTokens = parameters.get(ACCESS_TOKEN_PARAMETER_NAME);
return CollectionUtils.isEmpty(accessTokens) ? Flux.empty() : Flux.fromIterable(accessTokens);
}
/**
* Set if transport of access token using URI query parameter is supported. Defaults
* to {@code false}.
*
* The spec recommends against using this mechanism for sending bearer tokens, and
* even goes as far as stating that it was only included for completeness.
* @param allowUriQueryParameter if the URI query parameter is supported
*/
public void setAllowUriQueryParameter(boolean allowUriQueryParameter) {
this.allowUriQueryParameter = allowUriQueryParameter;
}
/**
* Set this value to configure what header is checked when resolving a Bearer Token.
* This value is defaulted to {@link HttpHeaders#AUTHORIZATION}.
*
* This allows other headers to be used as the Bearer Token source such as
* {@link HttpHeaders#PROXY_AUTHORIZATION}
* @param bearerTokenHeaderName the header to check when retrieving the Bearer Token.
* @since 5.4 | */
public void setBearerTokenHeaderName(String bearerTokenHeaderName) {
this.bearerTokenHeaderName = bearerTokenHeaderName;
}
/**
* Set if transport of access token using form-encoded body parameter is supported.
* Defaults to {@code false}.
* @param allowFormEncodedBodyParameter if the form-encoded body parameter is
* supported
* @since 6.5
*/
public void setAllowFormEncodedBodyParameter(boolean allowFormEncodedBodyParameter) {
this.allowFormEncodedBodyParameter = allowFormEncodedBodyParameter;
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\web\server\authentication\ServerBearerTokenAuthenticationConverter.java | 1 |
请完成以下Java代码 | private String createRenderedCodeString(
@NonNull final InvoiceReferenceNo invoiceReferenceString,
@NonNull final BigDecimal openInvoiceAmount,
@NonNull final I_C_BP_BankAccount bankAccount)
{
final StringBuilder renderedCodeStr = new StringBuilder();
// 01 is the code for Invoice document type. For the moment it's the only document type handled by the program
renderedCodeStr.append("01");
// Open amount of the invoice multiplied by 100
String amountStr = openInvoiceAmount
.multiply(Env.ONEHUNDRED)
.setScale(0, RoundingMode.HALF_UP)
.toString();
amountStr = StringUtils.lpadZero(amountStr, 10, "Open amount");
renderedCodeStr.append(amountStr);
final int checkDigit = Services.get(IESRImportBL.class).calculateESRCheckDigit(renderedCodeStr.toString());
renderedCodeStr.append(checkDigit);
renderedCodeStr.append(">");
final IESRBPBankAccountBL bankAccountBL = Services.get(IESRBPBankAccountBL.class);
renderedCodeStr.append(invoiceReferenceString.asString());
renderedCodeStr.append("+ ");
renderedCodeStr.append(bankAccountBL.retrieveESRAccountNo(bankAccount));
renderedCodeStr.append(">");
return renderedCodeStr.toString(); | }
private void linkEsrStringsToInvoiceRecord(
@NonNull final InvoiceReferenceNo invoiceReferenceString,
@NonNull final String renderedCodeStr,
@NonNull final I_C_Invoice invoiceRecord)
{
final IContextAware contextAware = InterfaceWrapperHelper.getContextAware(invoiceRecord);
final IReferenceNoDAO referenceNoDAO = Services.get(IReferenceNoDAO.class);
final I_C_ReferenceNo_Type invoiceReferenceNoType = referenceNoDAO.retrieveRefNoTypeByName(ESRConstants.DOCUMENT_REFID_ReferenceNo_Type_InvoiceReferenceNumber);
final I_C_ReferenceNo invoiceReferenceNo = referenceNoDAO.getCreateReferenceNo(invoiceReferenceNoType, invoiceReferenceString.asString(), contextAware);
referenceNoDAO.getCreateReferenceNoDoc(invoiceReferenceNo, TableRecordReference.of(invoiceRecord));
final I_C_ReferenceNo_Type renderedCodeReferenceNoType = referenceNoDAO.retrieveRefNoTypeByName(ESRConstants.DOCUMENT_REFID_ReferenceNo_Type_ReferenceNumber);
final I_C_ReferenceNo renderedCodeReferenceNo = referenceNoDAO.getCreateReferenceNo(renderedCodeReferenceNoType, renderedCodeStr, contextAware);
referenceNoDAO.getCreateReferenceNoDoc(renderedCodeReferenceNo, TableRecordReference.of(invoiceRecord));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\api\impl\ESRBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | Binding delayQueueBind() {
return BindingBuilder.bind(delayQueue4Queue())
.to(delayQueueExchange())
.with(ROUTING_KEY);
}
@Bean
public Queue helloQueue() {
return new Queue("helloQueue");
}
@Bean
public Queue msgQueue() {
return new Queue("msgQueue");
}
//===============以下是验证topic Exchange的队列==========
@Bean
public Queue queueMessage() {
return new Queue("topic.message");
}
@Bean
public Queue queueMessages() {
return new Queue("topic.messages");
}
//===============以上是验证topic Exchange的队列==========
//===============以下是验证Fanout Exchange的队列==========
@Bean
public Queue AMessage() {
return new Queue("fanout.A");
}
@Bean
public Queue BMessage() {
return new Queue("fanout.B");
}
@Bean
public Queue CMessage() {
return new Queue("fanout.C");
}
//===============以上是验证Fanout Exchange的队列==========
@Bean
TopicExchange exchange() {
return new TopicExchange("exchange");
}
@Bean
FanoutExchange fanoutExchange() {
return new FanoutExchange("fanoutExchange");
}
/**
* 将队列topic.message与exchange绑定,binding_key为topic.message,就是完全匹配
* @param queueMessage
* @param exchange
* @return
*/
@Bean
Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) {
return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message");
}
/**
* 将队列topic.messages与exchange绑定,binding_key为topic.#,模糊匹配
* @param queueMessages | * @param exchange
* @return
*/
@Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) {
return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#");
}
@Bean
Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(AMessage).to(fanoutExchange);
}
@Bean
Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(BMessage).to(fanoutExchange);
}
@Bean
Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) {
return BindingBuilder.bind(CMessage).to(fanoutExchange);
}
@Bean
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//必须是prototype类型
public RabbitTemplate rabbitTemplate() {
RabbitTemplate template = new RabbitTemplate(connectionFactory());
return template;
}
} | repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\config\RabbitConfig.java | 2 |
请完成以下Java代码 | public void setSEPA_Export_Line_Retry(de.metas.payment.sepa.model.I_SEPA_Export_Line SEPA_Export_Line_Retry)
{
set_ValueFromPO(COLUMNNAME_SEPA_Export_Line_Retry_ID, de.metas.payment.sepa.model.I_SEPA_Export_Line.class, SEPA_Export_Line_Retry);
}
/** Set SEPA_Export_Line_Retry_ID.
@param SEPA_Export_Line_Retry_ID SEPA_Export_Line_Retry_ID */
@Override
public void setSEPA_Export_Line_Retry_ID (int SEPA_Export_Line_Retry_ID)
{
if (SEPA_Export_Line_Retry_ID < 1)
set_Value (COLUMNNAME_SEPA_Export_Line_Retry_ID, null);
else
set_Value (COLUMNNAME_SEPA_Export_Line_Retry_ID, Integer.valueOf(SEPA_Export_Line_Retry_ID));
}
/** Get SEPA_Export_Line_Retry_ID.
@return SEPA_Export_Line_Retry_ID */
@Override
public int getSEPA_Export_Line_Retry_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SEPA_Export_Line_Retry_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SEPA_MandateRefNo.
@param SEPA_MandateRefNo SEPA_MandateRefNo */
@Override
public void setSEPA_MandateRefNo (java.lang.String SEPA_MandateRefNo)
{
set_Value (COLUMNNAME_SEPA_MandateRefNo, SEPA_MandateRefNo);
}
/** Get SEPA_MandateRefNo.
@return SEPA_MandateRefNo */
@Override
public java.lang.String getSEPA_MandateRefNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SEPA_MandateRefNo);
}
/** Set StructuredRemittanceInfo.
@param StructuredRemittanceInfo
Structured Remittance Information
*/
@Override
public void setStructuredRemittanceInfo (java.lang.String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
/** Get StructuredRemittanceInfo.
@return Structured Remittance Information
*/
@Override
public java.lang.String getStructuredRemittanceInfo ()
{
return (java.lang.String)get_Value(COLUMNNAME_StructuredRemittanceInfo);
}
/** Set Swift code.
@param SwiftCode
Swift Code or BIC
*/ | @Override
public void setSwiftCode (java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
/** Get Swift code.
@return Swift Code or BIC
*/
@Override
public java.lang.String getSwiftCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_SwiftCode);
}
@Override
public void setIsGroupLine (final boolean IsGroupLine)
{
set_Value (COLUMNNAME_IsGroupLine, IsGroupLine);
}
@Override
public boolean isGroupLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsGroupLine);
}
@Override
public void setNumberOfReferences (final int NumberOfReferences)
{
set_Value (COLUMNNAME_NumberOfReferences, NumberOfReferences);
}
@Override
public int getNumberOfReferences()
{
return get_ValueAsInt(COLUMNNAME_NumberOfReferences);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line.java | 1 |
请完成以下Java代码 | public String getHitPolicyName() {
return HitPolicy.UNIQUE.getValue();
}
@Override
public void evaluateRuleValidity(int ruleNumber, ELExecutionContext executionContext) {
//TODO: not on audit container
for (Map.Entry<Integer, RuleExecutionAuditContainer> entry : executionContext.getAuditContainer().getRuleExecutions().entrySet()) {
if (entry.getKey().equals(ruleNumber) == false && entry.getValue().isValid()) {
String hitPolicyViolatedMessage = String.format("HitPolicy %s violated; at least rule %d and rule %d are valid.", getHitPolicyName(), ruleNumber, entry.getKey());
if (CommandContextUtil.getDmnEngineConfiguration().isStrictMode()) {
executionContext.getAuditContainer().getRuleExecutions().get(ruleNumber).setExceptionMessage(hitPolicyViolatedMessage);
executionContext.getAuditContainer().getRuleExecutions().get(entry.getKey()).setExceptionMessage(hitPolicyViolatedMessage);
throw new FlowableException("HitPolicy UNIQUE violated.");
} else {
executionContext.getAuditContainer().getRuleExecutions().get(ruleNumber).setValidationMessage(hitPolicyViolatedMessage);
executionContext.getAuditContainer().getRuleExecutions().get(entry.getKey()).setValidationMessage(hitPolicyViolatedMessage);
break;
}
}
}
}
@Override
public void composeDecisionResults(ELExecutionContext executionContext) {
List<Map<String, Object>> ruleResults = new ArrayList<>(executionContext.getRuleResults().values());
List<Map<String, Object>> decisionResults;
if (ruleResults.size() > 1 && CommandContextUtil.getDmnEngineConfiguration().isStrictMode() == false) { | Map<String, Object> lastResult = new HashMap<>();
for (Map<String, Object> ruleResult : ruleResults) {
for (Map.Entry<String, Object> entry : ruleResult.entrySet()) {
if (entry.getValue() != null) {
lastResult.put(entry.getKey(), entry.getValue());
}
}
}
executionContext.getAuditContainer().setValidationMessage(String.format("HitPolicy %s violated; multiple valid rules. Setting last valid rule result as final result.", getHitPolicyName()));
decisionResults = Collections.singletonList(lastResult);
} else {
decisionResults = ruleResults;
}
updateStackWithDecisionResults(decisionResults, executionContext);
executionContext.getAuditContainer().setDecisionResult(decisionResults);
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\hitpolicy\HitPolicyUnique.java | 1 |
请完成以下Java代码 | public class PaymentStatusResponse {
/**
* статус платежа
*/
private String state;
/**
* сумма платежа в копейках
*/
private String totalAmount;
/**
* время создания платежа (Время должно быть в формате: yyyy-mm-dd hh:mm:ss)
*/
private String createdDate;
/**
* уникальный код провайдера услуг | */
private String providerServCode;
/**
* название провайдера услуг
*/
private String providerName;
/**
* код ошибки, используется для локализации проблемы.(
*/
private String errorCode;
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\payload\payment\PaymentStatusResponse.java | 1 |
请完成以下Java代码 | public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getCardNumber() { | return cardNumber;
}
public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public File getMainDirectory() {
return mainDirectory;
}
public void setMainDirectory(File mainDirectory) {
this.mainDirectory = mainDirectory;
}
} | repos\tutorials-master\apache-libraries-2\src\main\java\com\baeldung\apache\bval\model\User.java | 1 |
请完成以下Java代码 | public void setAD_User_ID (final int AD_User_ID)
{
if (AD_User_ID < 0)
set_Value (COLUMNNAME_AD_User_ID, null);
else
set_Value (COLUMNNAME_AD_User_ID, AD_User_ID);
}
@Override
public int getAD_User_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_User_ID);
}
@Override
public void setAD_WF_Responsible_ID (final int AD_WF_Responsible_ID)
{
if (AD_WF_Responsible_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Responsible_ID, AD_WF_Responsible_ID);
}
@Override
public int getAD_WF_Responsible_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Responsible_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
@Override
public void setEntityType (final java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
@Override
public java.lang.String getEntityType()
{
return get_ValueAsString(COLUMNNAME_EntityType);
}
@Override
public void setName (final java.lang.String Name)
{ | set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* ResponsibleType AD_Reference_ID=304
* Reference name: WF_Participant Type
*/
public static final int RESPONSIBLETYPE_AD_Reference_ID=304;
/** Organisation = O */
public static final String RESPONSIBLETYPE_Organisation = "O";
/** Human = H */
public static final String RESPONSIBLETYPE_Human = "H";
/** Rolle = R */
public static final String RESPONSIBLETYPE_Rolle = "R";
/** Systemressource = S */
public static final String RESPONSIBLETYPE_Systemressource = "S";
/** Other = X */
public static final String RESPONSIBLETYPE_Other = "X";
@Override
public void setResponsibleType (final java.lang.String ResponsibleType)
{
set_Value (COLUMNNAME_ResponsibleType, ResponsibleType);
}
@Override
public java.lang.String getResponsibleType()
{
return get_ValueAsString(COLUMNNAME_ResponsibleType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Responsible.java | 1 |
请完成以下Java代码 | public static String mergePatterns(String original, String extraBits) {
Assert.notNull(original, "Original string required");
Assert.notNull(extraBits, "Extra Bits string required");
Assert.isTrue(original.length() == extraBits.length(),
"Original and Extra Bits strings must be identical length");
char[] replacement = new char[extraBits.length()];
for (int i = 0; i < extraBits.length(); i++) {
if (extraBits.charAt(i) == Permission.RESERVED_OFF) {
replacement[i] = original.charAt(i);
}
else {
replacement[i] = extraBits.charAt(i);
}
}
return new String(replacement);
}
/**
* Returns a representation of the active bits in the presented mask, with each active
* bit being denoted by character '*'.
* <p>
* Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}.
* @param i the integer bit mask to print the active bits for
* @return a 32-character representation of the bit mask
*/
public static String printBinary(int i) {
return printBinary(i, '*', Permission.RESERVED_OFF);
}
/**
* Returns a representation of the active bits in the presented mask, with each active
* bit being denoted by the passed character.
* <p>
* Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}.
* @param mask the integer bit mask to print the active bits for
* @param code the character to print when an active bit is detected | * @return a 32-character representation of the bit mask
*/
public static String printBinary(int mask, char code) {
Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_ON),
() -> Permission.RESERVED_ON + " is a reserved character code");
Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_OFF),
() -> Permission.RESERVED_OFF + " is a reserved character code");
return printBinary(mask, Permission.RESERVED_ON, Permission.RESERVED_OFF).replace(Permission.RESERVED_ON, code);
}
private static String printBinary(int i, char on, char off) {
String s = Integer.toBinaryString(i);
String pattern = Permission.THIRTY_TWO_RESERVED_OFF;
String temp2 = pattern.substring(0, pattern.length() - s.length()) + s;
return temp2.replace('0', off).replace('1', on);
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AclFormattingUtils.java | 1 |
请完成以下Java代码 | public static String buildSasToken(String host, String sasKey, Clock clock) {
try {
final String targetUri = URLEncoder.encode(host.toLowerCase(), StandardCharsets.UTF_8);
final long expiryTime = buildExpiresOn(clock);
String toSign = targetUri + "\n" + expiryTime;
byte[] keyBytes = Base64.getDecoder().decode(sasKey.getBytes(StandardCharsets.UTF_8));
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(toSign.getBytes(StandardCharsets.UTF_8));
String signature = URLEncoder.encode(Base64.getEncoder().encodeToString(rawHmac), StandardCharsets.UTF_8);
return String.format(SAS_TOKEN_FORMAT, targetUri, signature, expiryTime);
} catch (Exception e) {
throw new RuntimeException("Failed to build SAS token!", e);
}
}
private static long buildExpiresOn(Clock clock) {
return clock.instant().plusSeconds(SAS_TOKEN_VALID_SECS).getEpochSecond();
}
public static String getDefaultCaCert() {
byte[] fileBytes;
if (Files.exists(FULL_FILE_PATH)) {
try {
fileBytes = Files.readAllBytes(FULL_FILE_PATH);
} catch (IOException e) {
log.error("Failed to load Default CaCert file!!! [{}]", FULL_FILE_PATH, e);
throw new RuntimeException("Failed to load Default CaCert file!!!");
}
} else {
Path azureDirectory = FULL_FILE_PATH.getParent(); | try (DirectoryStream<Path> stream = Files.newDirectoryStream(azureDirectory)) {
Iterator<Path> iterator = stream.iterator();
if (iterator.hasNext()) {
Path firstFile = iterator.next();
fileBytes = Files.readAllBytes(firstFile);
} else {
log.error("Default CaCert file not found in the directory [{}]!!!", azureDirectory);
throw new RuntimeException("Default CaCert file not found in the directory!!!");
}
} catch (IOException e) {
log.error("Failed to load Default CaCert file from the directory [{}]!!!", azureDirectory, e);
throw new RuntimeException("Failed to load Default CaCert file from the directory!!!");
}
}
return new String(fileBytes);
}
} | repos\thingsboard-master\common\util\src\main\java\org\thingsboard\common\util\AzureIotHubUtil.java | 1 |
请完成以下Java代码 | public int getC_DunningRun_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DunningRun_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getC_DunningRun_ID()));
}
/** Set Note.
@param Note
Optional additional user defined information
*/
public void setNote (String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Note.
@return Optional additional user defined information
*/
public String getNote ()
{
return (String)get_Value(COLUMNNAME_Note);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_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_C_DunningRunEntry.java | 1 |
请完成以下Java代码 | public Product newProduct(@NonNull final I_M_Product productRecord)
{
return new ProductsCache.Product(productRecord);
}
public void clear()
{
productsCache.clear();
}
final class Product
{
@Getter
private final I_M_Product record;
private Product(@NonNull final I_M_Product record)
{
this.record = record;
}
public ProductId getIdOrNull() | {
return ProductId.ofRepoIdOrNull(record.getM_Product_ID());
}
public int getOrgId()
{
return record.getAD_Org_ID();
}
public void save()
{
productsRepo.save(record);
productsCache.put(getIdOrNull(), this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\ProductsCache.java | 1 |
请完成以下Java代码 | public void onAfterCreated(@NonNull final MatchInv matchInv)
{
if (matchInv.getType().isCost())
{
final MatchInvCostPart matchInvCost = matchInv.getCostPartNotNull();
orderCostService.updateInOutCostById(
matchInvCost.getInoutCostId(),
inoutCost -> inoutCost.addCostAmountInvoiced(matchInvCost.getCostAmountInOut()));
}
}
@Override
public void onAfterDeleted(@NonNull final List<MatchInv> matchInvs)
{
for (final MatchInv matchInv : matchInvs)
{
final MatchInvType type = matchInv.getType();
if (type.isMaterial())
{
clearInvoiceLineFromMatchPOs(matchInv);
}
else if (type.isCost()) | {
final MatchInvCostPart matchInvCost = matchInv.getCostPartNotNull();
orderCostService.updateInOutCostById(
matchInvCost.getInoutCostId(),
inoutCost -> inoutCost.addCostAmountInvoiced(matchInvCost.getCostAmountInOut().negate()));
}
}
matchInvs.forEach(this::clearInvoiceLineFromMatchPOs);
}
private void clearInvoiceLineFromMatchPOs(@NonNull final MatchInv matchInv)
{
matchInvoiceService.getOrderLineId(matchInv)
.ifPresent(orderLineId -> matchPOBL.unlink(orderLineId, matchInv.getInvoiceAndLineId()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\listeners\DefaultMatchInvListener.java | 1 |
请完成以下Java代码 | private @Nullable Object resolveSecurityContextFromAnnotation(CurrentSecurityContext annotation,
MethodParameter parameter, Object securityContext) {
Object securityContextResult = securityContext;
String expressionToParse = annotation.expression();
if (StringUtils.hasLength(expressionToParse)) {
StandardEvaluationContext context = new StandardEvaluationContext();
context.setRootObject(securityContext);
context.setVariable("this", securityContext);
context.setBeanResolver(this.beanResolver);
Expression expression = this.parser.parseExpression(expressionToParse);
securityContextResult = expression.getValue(context);
}
if (isInvalidType(parameter, securityContextResult)) {
if (annotation.errorOnInvalidType()) {
throw new ClassCastException(
securityContextResult + " is not assignable to " + parameter.getParameterType());
}
return null;
}
return securityContextResult;
}
/**
* check if the retrieved value match with the parameter type.
* @param parameter the method parameter.
* @param reactiveSecurityContext the security context.
* @return true = is not invalid type.
*/
private boolean isInvalidType(MethodParameter parameter, @Nullable Object reactiveSecurityContext) {
if (reactiveSecurityContext == null) {
return false;
}
Class<?> typeToCheck = parameter.getParameterType();
boolean isParameterPublisher = Publisher.class.isAssignableFrom(parameter.getParameterType());
if (isParameterPublisher) {
ResolvableType resolvableType = ResolvableType.forMethodParameter(parameter);
Class<?> genericType = resolvableType.resolveGeneric(0);
if (genericType == null) {
return false;
}
typeToCheck = genericType;
}
return !typeToCheck.isAssignableFrom(reactiveSecurityContext.getClass());
}
/**
* Obtains the specified {@link Annotation} on the specified {@link MethodParameter}.
* @param parameter the {@link MethodParameter} to search for an {@link Annotation} | * @return the {@link Annotation} that was found or null.
*/
private @Nullable CurrentSecurityContext findMethodAnnotation(MethodParameter parameter) {
if (this.useAnnotationTemplate) {
return this.scanner.scan(parameter.getParameter());
}
CurrentSecurityContext annotation = parameter.getParameterAnnotation(this.annotationType);
if (annotation != null) {
return annotation;
}
Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
for (Annotation toSearch : annotationsToSearch) {
annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), this.annotationType);
if (annotation != null) {
return MergedAnnotations.from(toSearch).get(this.annotationType).synthesize();
}
}
return null;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\reactive\result\method\annotation\CurrentSecurityContextArgumentResolver.java | 1 |
请完成以下Java代码 | public NotificationRule findNotificationRuleById(TenantId tenantId, NotificationRuleId id) {
return notificationRuleDao.findById(tenantId, id.getId());
}
@Override
public NotificationRuleInfo findNotificationRuleInfoById(TenantId tenantId, NotificationRuleId id) {
return notificationRuleDao.findInfoById(tenantId, id);
}
@Override
public PageData<NotificationRuleInfo> findNotificationRulesInfosByTenantId(TenantId tenantId, PageLink pageLink) {
return notificationRuleDao.findInfosByTenantIdAndPageLink(tenantId, pageLink);
}
@Override
public PageData<NotificationRule> findNotificationRulesByTenantId(TenantId tenantId, PageLink pageLink) {
return notificationRuleDao.findByTenantIdAndPageLink(tenantId, pageLink);
}
@Override
public List<NotificationRule> findEnabledNotificationRulesByTenantIdAndTriggerType(TenantId tenantId, NotificationRuleTriggerType triggerType) {
return notificationRuleDao.findByTenantIdAndTriggerTypeAndEnabled(tenantId, triggerType, true);
}
@Override
public void deleteNotificationRuleById(TenantId tenantId, NotificationRuleId id) {
notificationRuleDao.removeById(tenantId, id.getId());
eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build());
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteNotificationRuleById(tenantId, (NotificationRuleId) id);
}
@Override
public void deleteNotificationRulesByTenantId(TenantId tenantId) { | notificationRuleDao.removeByTenantId(tenantId);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
deleteNotificationRulesByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationRuleById(tenantId, new NotificationRuleId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationRuleDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION_RULE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRuleService.java | 1 |
请完成以下Java代码 | public RoundingMode getRoundingMode()
{
return RoundingMode.UP;
}
public BigDecimal roundIfNeeded(@NonNull final BigDecimal qty)
{
if (qty.scale() > precision)
{
return qty.setScale(precision, getRoundingMode());
}
else
{
return qty;
}
}
public BigDecimal round(@NonNull final BigDecimal qty)
{
return qty.setScale(precision, getRoundingMode());
} | public BigDecimal adjustToPrecisionWithoutRoundingIfPossible(@NonNull final BigDecimal qty)
{
// NOTE: it seems that ZERO is a special case of BigDecimal, so we are computing it right away
if (qty == null || qty.signum() == 0)
{
return BigDecimal.ZERO.setScale(precision);
}
final BigDecimal qtyNoZero = qty.stripTrailingZeros();
final int qtyScale = qtyNoZero.scale();
if (qtyScale >= precision)
{
// Qty's actual scale is bigger than UOM precision, don't touch it
return qtyNoZero;
}
else
{
// Qty's actual scale is less than UOM precision. Try to convert it to UOM precision
// NOTE: we are using without scale because it shall be scaled without any problem
return qtyNoZero.setScale(precision, RoundingMode.HALF_UP);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMPrecision.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class AlreadyInitializedAppEngineConfiguration {
@Bean
public CmmnEngine cmmnEngine(@SuppressWarnings("unused") AppEngine appEngine) {
// The app engine needs to be injected, as otherwise it won't be initialized, which means that the CmmnEngine is not initialized yet
if (!CmmnEngines.isInitialized()) {
throw new IllegalStateException("CMMN engine has not been initialized");
}
return CmmnEngines.getDefaultCmmnEngine();
}
}
/**
* If there is no process engine configuration, then trigger a creation of the cmmn engine.
*/
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(type = {
"org.flowable.cmmn.engine.CmmnEngine",
"org.flowable.engine.ProcessEngine",
"org.flowable.app.engine.AppEngine",
})
static class StandaloneEngineConfiguration extends BaseEngineConfigurationWithConfigurers<SpringCmmnEngineConfiguration> {
@Bean
public CmmnEngineFactoryBean cmmnEngine(SpringCmmnEngineConfiguration cmmnEngineConfiguration) {
CmmnEngineFactoryBean factory = new CmmnEngineFactoryBean();
factory.setCmmnEngineConfiguration(cmmnEngineConfiguration);
invokeConfigurers(cmmnEngineConfiguration);
return factory;
}
}
@Bean
public CmmnRuntimeService cmmnRuntimeService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnRuntimeService(); | }
@Bean
public DynamicCmmnService dynamicCmmnService(CmmnEngine cmmnEngine) {
return cmmnEngine.getDynamicCmmnService();
}
@Bean
public CmmnTaskService cmmnTaskService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnTaskService();
}
@Bean
public CmmnManagementService cmmnManagementService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnManagementService();
}
@Bean
public CmmnRepositoryService cmmnRepositoryService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnRepositoryService();
}
@Bean
public CmmnHistoryService cmmnHistoryService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnHistoryService();
}
@Bean
public CmmnMigrationService cmmnMigrationService(CmmnEngine cmmnEngine) {
return cmmnEngine.getCmmnMigrationService();
}
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\cmmn\CmmnEngineServicesAutoConfiguration.java | 2 |
请完成以下Java代码 | public String getName() {
return "enum";
}
@Override
public Object getInformation(String key) {
if ("values".equals(key)) {
return values;
}
return null;
}
@Override
public Object convertFormValueToModelValue(String propertyValue) {
validateValue(propertyValue);
return propertyValue;
}
@Override
public String convertModelValueToFormValue(Object modelValue) { | if (modelValue != null) {
if (!(modelValue instanceof String)) {
throw new ActivitiIllegalArgumentException("Model value should be a String");
}
validateValue((String) modelValue);
}
return (String) modelValue;
}
protected void validateValue(String value) {
if (value != null) {
if (values != null && !values.containsKey(value)) {
throw new ActivitiIllegalArgumentException("Invalid value for enum form property: " + value);
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\form\EnumFormType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Author {
@Id
private Long id;
private String name;
private Timestamp created_at;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() { | return name;
}
public void setName(String name) {
this.name = name;
}
public Timestamp getCreated_at() {
return created_at;
}
public void setCreated_at(Timestamp created_at) {
this.created_at = created_at;
}
} | repos\tutorials-master\persistence-modules\liquibase\src\main\java\com\baeldung\liquibase\entity\Author.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal retrieveCreditLimitByBPartnerId(final int bpartnerId, @NonNull final Timestamp date)
{
return retrieveCreditLimitsByBPartnerId(bpartnerId, date)
.stream().min(comparator)
.map(I_C_BPartner_CreditLimit::getAmount)
.orElse(BigDecimal.ZERO);
}
private List<I_C_BPartner_CreditLimit> retrieveCreditLimitsByBPartnerId(final int bpartnerId, @NonNull final Timestamp date)
{
return queryBL
.createQueryBuilder(I_C_BPartner_CreditLimit.class)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_Processed, true)
.addCompareFilter(I_C_BPartner_CreditLimit.COLUMNNAME_DateFrom, Operator.LESS_OR_EQUAL, date)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.create()
.list();
}
private Comparator<I_C_BPartner_CreditLimit> createComparator()
{
final Comparator<I_C_BPartner_CreditLimit> byTypeSeqNoReversed = //
Comparator.<I_C_BPartner_CreditLimit, SeqNo>comparing(bpCreditLimit -> getCreditLimitTypeById(bpCreditLimit.getC_CreditLimit_Type_ID()).getSeqNo()).reversed();
final Comparator<I_C_BPartner_CreditLimit> byDateFromRevesed = //
Comparator.<I_C_BPartner_CreditLimit, Date>comparing(I_C_BPartner_CreditLimit::getDateFrom).reversed();
return byDateFromRevesed.thenComparing(byTypeSeqNoReversed);
}
public CreditLimitType getCreditLimitTypeById(final int C_CreditLimit_Type_ID)
{
return cache_creditLimitById.getOrLoad(C_CreditLimit_Type_ID, () -> retrieveCreditLimitTypePOJO(C_CreditLimit_Type_ID));
}
private CreditLimitType retrieveCreditLimitTypePOJO(final int C_CreditLimit_Type_ID)
{
final I_C_CreditLimit_Type type = queryBL
.createQueryBuilder(I_C_CreditLimit_Type.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_CreditLimit_Type.COLUMN_C_CreditLimit_Type_ID, C_CreditLimit_Type_ID)
.create()
.firstOnlyNotNull(I_C_CreditLimit_Type.class); | return CreditLimitType.builder()
.creditLimitTypeId(CreditLimitTypeId.ofRepoId(type.getC_CreditLimit_Type_ID()))
.seqNo(SeqNo.ofInt(type.getSeqNo()))
.name(type.getName())
.autoApproval(type.isAutoApproval())
.build();
}
public Optional<I_C_BPartner_CreditLimit> retrieveCreditLimitByBPartnerId(final int bpartnerId, final int typeId)
{
return queryBL
.createQueryBuilder(I_C_BPartner_CreditLimit.class)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_BPartner_ID, bpartnerId)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_Processed, true)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_CreditLimit_Type_ID, typeId)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
.create()
.stream().min(comparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerCreditLimitRepository.java | 2 |
请完成以下Java代码 | public ThrowMessageDelegate createThrowMessageDelegateExpression(String delegateExpression) {
Expression expression = expressionManager.createExpression(delegateExpression);
return new ThrowMessageDelegateExpression(expression, emptyList());
}
public ThrowMessageDelegate createDefaultThrowMessageDelegate() {
return getThrowMessageDelegateFactory().create();
}
public MessagePayloadMappingProvider createMessagePayloadMappingProvider(
Event bpmnEvent,
MessageEventDefinition messageEventDefinition
) {
return getMessagePayloadMappingProviderFactory().create(
bpmnEvent,
messageEventDefinition,
getExpressionManager()
);
}
protected Optional<String> checkClassDelegate(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "class");
}
protected Optional<String> checkDelegateExpression(Map<String, List<ExtensionAttribute>> attributes) {
return getAttributeValue(attributes, "delegateExpression"); | }
protected Optional<String> getAttributeValue(Map<String, List<ExtensionAttribute>> attributes, String name) {
return Optional.ofNullable(attributes)
.filter(it -> it.containsKey("activiti"))
.map(it -> it.get("activiti"))
.flatMap(it ->
it
.stream()
.filter(el -> name.equals(el.getName()))
.findAny()
)
.map(ExtensionAttribute::getValue);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java | 1 |
请完成以下Java代码 | public TenantRestService getTenantRestService() {
return super.getTenantRestService(null);
}
@Path(SignalRestService.PATH)
public SignalRestService getSignalRestService() {
return super.getSignalRestService(null);
}
@Path(ConditionRestService.PATH)
public ConditionRestService getConditionRestService() {
return super.getConditionRestService(null);
}
@Path(OptimizeRestService.PATH)
public OptimizeRestService getOptimizeRestService() {
return super.getOptimizeRestService(null);
}
@Path(VersionRestService.PATH)
public VersionRestService getVersionRestService() {
return super.getVersionRestService(null); | }
@Path(SchemaLogRestService.PATH)
public SchemaLogRestService getSchemaLogRestService() {
return super.getSchemaLogRestService(null);
}
@Path(EventSubscriptionRestService.PATH)
public EventSubscriptionRestService getEventSubscriptionRestService() {
return super.getEventSubscriptionRestService(null);
}
@Path(TelemetryRestService.PATH)
public TelemetryRestService getTelemetryRestService() {
return super.getTelemetryRestService(null);
}
@Override
protected URI getRelativeEngineUri(String engineName) {
// the default engine
return URI.create("/");
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\DefaultProcessEngineRestServiceImpl.java | 1 |
请完成以下Java代码 | public Process newProcess() {
return repository.save(new Process(counter.incrementAndGet(), State.CREATED, 0));
}
@Transactional
public void run(Integer id) {
var process = lookup(id);
if (!State.CREATED.equals(process.state())) {
return;
}
start(process);
verify(process);
finish(process);
}
private void finish(Process process) { | template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.DONE).inc("transitionCount", 1)).first();
}
void start(Process process) {
template.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.ACTIVE).inc("transitionCount", 1)).first();
}
Process lookup(Integer id) {
return repository.findById(id).get();
}
void verify(Process process) {
Assert.state(process.id() % 3 != 0, "We're sorry but we needed to drop that one");
}
} | repos\spring-data-examples-main\mongodb\transactions\src\main\java\example\springdata\mongodb\imperative\TransitionService.java | 1 |
请完成以下Java代码 | public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
//
//
//
//
//
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
public static class Builder
{
private LookupSource lookupSourceType = LookupSource.list;
private boolean numericKey;
private Function<LookupDataSourceContext, LookupValuesPage> lookupValues;
private Set<String> dependsOnFieldNames;
private Optional<String> lookupTableName = Optional.empty();
private Builder()
{
}
public ListLookupDescriptor build()
{
return new ListLookupDescriptor(this);
}
public Builder setLookupSourceType(@NonNull final LookupSource lookupSourceType)
{
this.lookupSourceType = lookupSourceType;
return this;
}
public Builder setLookupValues(final boolean numericKey, final Function<LookupDataSourceContext, LookupValuesPage> lookupValues) | {
this.numericKey = numericKey;
this.lookupValues = lookupValues;
return this;
}
public Builder setIntegerLookupValues(final Function<LookupDataSourceContext, LookupValuesPage> lookupValues)
{
setLookupValues(true, lookupValues);
return this;
}
public Builder setDependsOnFieldNames(final String[] dependsOnFieldNames)
{
this.dependsOnFieldNames = ImmutableSet.copyOf(dependsOnFieldNames);
return this;
}
public Builder setLookupTableName(final String lookupTableName)
{
this.lookupTableName = Check.isEmpty(lookupTableName, true) ? Optional.empty() : Optional.of(lookupTableName);
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\ListLookupDescriptor.java | 1 |
请完成以下Java代码 | public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public void initialize(ModelValidationEngine engine, MClient client)
{
if (client != null)
{
m_AD_Client_ID = client.getAD_Client_ID();
}
//
engine.addDocValidate(MMShipperTransportation.Table_Name, this);
}
@Override
public String login(int arg0, int arg1, int arg2)
{
return null;
}
@Override
public String modelChange(PO arg0, int arg1) throws Exception
{
return null;
}
private String sendEMail(final MADBoilerPlate text, final MInOut io, final I_AD_User orderUser)
{
final Properties ctx = Env.getCtx();
MADBoilerPlate.sendEMail(new IEMailEditor()
{
@Override
public Object getBaseObject()
{
return io;
}
@Override
public int getAD_Table_ID()
{
return io.get_Table_ID();
}
@Override
public int getRecord_ID()
{
return io.get_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final BoilerPlateContext attributesEffective = attributes.toBuilder()
.setSourceDocumentFromObject(io)
.build();
//
String message = text.getTextSnippetParsed(attributesEffective);
//
if (Check.isEmpty(message, true))
{
return null;
}
//
final StringTokenizer st = new StringTokenizer(toEmail, " ,;", false);
EMailAddress to = EMailAddress.ofString(st.nextToken());
MClient client = MClient.get(ctx, Env.getAD_Client_ID(ctx));
if (orderUser != null)
{
to = EMailAddress.ofString(orderUser.getEMail());
}
EMail email = client.createEMail(
to,
text.getName(),
message,
true);
if (email == null)
{
throw new AdempiereException("Cannot create email. Check log."); | }
while (st.hasMoreTokens())
{
email.addTo(EMailAddress.ofString(st.nextToken()));
}
send(email);
return email;
}
}, false);
return "";
}
private void send(EMail email)
{
int maxRetries = p_SMTPRetriesNo > 0 ? p_SMTPRetriesNo : 0;
int count = 0;
do
{
final EMailSentStatus emailSentStatus = email.send();
count++;
if (emailSentStatus.isSentOK())
{
return;
}
// Timeout => retry
if (emailSentStatus.isSentConnectionError() && count < maxRetries)
{
log.warn("SMTP error: {} [ Retry {}/{} ]", emailSentStatus, count, maxRetries);
}
else
{
throw new EMailSendException(emailSentStatus);
}
}
while (true);
}
private void setNotified(I_M_PackageLine packageLine)
{
InterfaceWrapperHelper.getPO(packageLine).set_ValueOfColumn("IsSentMailNotification", true);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\model\validator\ShipperTransportationMailNotification.java | 1 |
请完成以下Java代码 | public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
} | public String getTips() {
return tips;
}
public void setTips(String tips) {
this.tips = tips;
}
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
} | repos\SpringBootBucket-master\springboot-swagger2\src\main\java\com\xncoding\jwt\api\model\PosParam.java | 1 |
请完成以下Java代码 | public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>();
// Extract list of permission name
this.user.getPermissionList().forEach(p-> {
GrantedAuthority authority = new SimpleGrantedAuthority(p);
authorities.add(authority);
});
// Extract list of roles (ROLE_NAME)
this.user.getRoleList().forEach(r ->{
GrantedAuthority authority = new SimpleGrantedAuthority("ROLE" + r);
authorities.add(authority);
});
return authorities;
}
@Override
public String getPassword() {
return this.user.getPassword();
}
@Override
public String getUsername() {
return this.user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
} | @Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\security\UserPrincipal.java | 1 |
请完成以下Java代码 | public static Set<OrderId> getOrderIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderId).collect(ImmutableSet.toImmutableSet());
}
public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet());
}
OrderId orderId;
OrderLineId orderLineId;
private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId)
{
this.orderId = orderId;
this.orderLineId = orderLineId;
}
public int getOrderRepoId()
{
return orderId.getRepoId();
}
public int getOrderLineRepoId()
{
return orderLineId.getRepoId();
} | public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2)
{
return Objects.equals(o1, o2);
}
@JsonValue
public String toJson()
{
return orderId.getRepoId() + "_" + orderLineId.getRepoId();
}
@JsonCreator
public static OrderAndLineId ofJson(@NonNull String json)
{
try
{
final int idx = json.indexOf("_");
return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1)));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java | 1 |
请完成以下Java代码 | public class DefaultInvoiceLineAttributeAggregator implements IInvoiceLineAttributeAggregator
{
private Set<IInvoiceLineAttribute> currentIntersectionResult = null;
private final Set<IInvoiceLineAttribute> currentUnionResult = new LinkedHashSet<>();
@Override
public List<IInvoiceLineAttribute> aggregate()
{
final ImmutableSet<IInvoiceLineAttribute> finalIntersectionResult = currentIntersectionResult == null ? ImmutableSet.of() : ImmutableSet.copyOf(currentIntersectionResult);
final LinkedHashSet<IInvoiceLineAttribute> result = new LinkedHashSet<>(currentUnionResult);
result.addAll(finalIntersectionResult);
return ImmutableList.copyOf(result);
}
@Override
public void addToIntersection(@NonNull final Set<IInvoiceLineAttribute> invoiceLineAttributesToAdd)
{
// NOTE: we also consider empty sets because those shall also count.
// Adding an empty set will turn our result to be an empty set, for good.
// Case: current result is not set, so we are actually adding the first set
if (currentIntersectionResult == null)
{ | currentIntersectionResult = new LinkedHashSet<>(invoiceLineAttributesToAdd);
}
// Case: already have a current result, so we just need to intersect it with the set we got as parameter.
else
{
currentIntersectionResult = Sets.intersection(currentIntersectionResult, invoiceLineAttributesToAdd);
}
}
@Override
public void addToUnion(@NonNull final List<IInvoiceLineAttribute> invoiceLineAttributesToAdd)
{
currentUnionResult.addAll(invoiceLineAttributesToAdd);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\DefaultInvoiceLineAttributeAggregator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static boolean isGroupMatching(
@NonNull final AvailableToPromiseResultGroupBuilder group,
@NonNull final AddToResultGroupRequest request)
{
if (!Objects.equals(group.getProductId(), request.getProductId()))
{
return false;
}
if (!group.getWarehouse().isMatching(request.getWarehouseId()))
{
return false;
}
if (!group.getBpartner().isMatching(request.getBpartner()))
{
return false;
}
if (!isGroupAttributesKeyMatching(group, request.getStorageAttributesKey()))
{
return false;
}
return true;
}
private static boolean isGroupAttributesKeyMatching(
@NonNull final AvailableToPromiseResultGroupBuilder group,
@NonNull final AttributesKey requestStorageAttributesKey)
{
final AttributesKey groupAttributesKey = group.getStorageAttributesKey();
if (groupAttributesKey.isAll())
{
return true;
}
else if (groupAttributesKey.isOther())
{
// accept it. We assume that the actual matching was done on Bucket level and not on Group level
return true;
}
else if (groupAttributesKey.isNone())
{
// shall not happen
return false;
}
else
{
final AttributesKeyPattern groupAttributePattern = AttributesKeyPatternsUtil.ofAttributeKey(groupAttributesKey);
return groupAttributePattern.matches(requestStorageAttributesKey);
}
}
private AvailableToPromiseResultGroupBuilder newGroup(
@NonNull final AddToResultGroupRequest request,
@NonNull final AttributesKey storageAttributesKey)
{
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(request.getBpartner())
.warehouse(WarehouseClassifier.specific(request.getWarehouseId()))
.productId(request.getProductId()) | .storageAttributesKey(storageAttributesKey)
.build();
groups.add(group);
return group;
}
void addDefaultEmptyGroupIfPossible()
{
if (product.isAny())
{
return;
}
final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null);
if (defaultAttributesKey == null)
{
return;
}
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(bpartner)
.warehouse(warehouse)
.productId(ProductId.ofRepoId(product.getProductId()))
.storageAttributesKey(defaultAttributesKey)
.build();
groups.add(group);
}
@VisibleForTesting
boolean isZeroQty()
{
if (groups.isEmpty())
{
return true;
}
for (AvailableToPromiseResultGroupBuilder group : groups)
{
if (!group.isZeroQty())
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultBucket.java | 2 |
请完成以下Java代码 | public int getM_FreightCost_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCost_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set M_FreightCost_includedTab.
@param M_FreightCost_includedTab M_FreightCost_includedTab */
public void setM_FreightCost_includedTab (String M_FreightCost_includedTab)
{
set_ValueNoCheck (COLUMNNAME_M_FreightCost_includedTab, M_FreightCost_includedTab);
}
/** Get M_FreightCost_includedTab.
@return M_FreightCost_includedTab */
public String getM_FreightCost_includedTab ()
{
return (String)get_Value(COLUMNNAME_M_FreightCost_includedTab);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name. | @param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
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 Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java | 1 |
请完成以下Java代码 | public class UserMutation {
@GraphQLField
public static User createUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email, @NotNull @GraphQLName(SchemaUtils.AGE) final String age) {
List<User> users = getUsers(env);
final User user = new User(name, email, Integer.valueOf(age));
users.add(user);
return user;
}
@GraphQLField
public static User updateUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id, @NotNull @GraphQLName(SchemaUtils.NAME) final String name, @NotNull @GraphQLName(SchemaUtils.EMAIL) final String email,
@NotNull @GraphQLName(SchemaUtils.AGE) final String age) {
final Optional<User> user = getUsers(env).stream()
.filter(c -> c.getId() == Long.parseLong(id))
.findFirst();
if (!user.isPresent()) {
return null;
}
user.get()
.setName(name); | user.get()
.setEmail(email);
user.get()
.setAge(Integer.valueOf(age));
return user.get();
}
@GraphQLField
public static User deleteUser(final DataFetchingEnvironment env, @NotNull @GraphQLName(SchemaUtils.ID) final String id) {
final List<User> users = getUsers(env);
final Optional<User> user = users.stream()
.filter(c -> c.getId() == Long.parseLong(id))
.findFirst();
if (!user.isPresent()) {
return null;
}
users.removeIf(c -> c.getId() == Long.parseLong(id));
return user.get();
}
} | repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphql\mutation\UserMutation.java | 1 |
请完成以下Java代码 | public int getKeyObtentionIterationsInt() {
return Integer.parseInt(keyObtentionIterations);
}
@Data
public static class PropertyConfigurationProperties {
/**
* Specify the name of the bean to be provided for a custom
* {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyDetector}. Default value is
* {@code "encryptablePropertyDetector"}
*/
private String detectorBean = "encryptablePropertyDetector";
/**
* Specify the name of the bean to be provided for a custom
* {@link com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver}. Default value is
* {@code "encryptablePropertyResolver"}
*/
private String resolverBean = "encryptablePropertyResolver";
/**
* Specify the name of the bean to be provided for a custom {@link EncryptablePropertyFilter}. Default value is
* {@code "encryptablePropertyFilter"}
*/
private String filterBean = "encryptablePropertyFilter";
/**
* Specify a custom {@link String} to identify as prefix of encrypted properties. Default value is
* {@code "ENC("}
*/
private String prefix = "ENC(";
/**
* Specify a custom {@link String} to identify as suffix of encrypted properties. Default value is {@code ")"} | */
private String suffix = ")";
@NestedConfigurationProperty
private FilterConfigurationProperties filter = new FilterConfigurationProperties();
@Data
public static class FilterConfigurationProperties {
/**
* Specify the property sources name patterns to be included for decryption
* by{@link EncryptablePropertyFilter}. Default value is {@code null}
*/
private List<String> includeSources = null;
/**
* Specify the property sources name patterns to be EXCLUDED for decryption
* by{@link EncryptablePropertyFilter}. Default value is {@code null}
*/
private List<String> excludeSources = null;
/**
* Specify the property name patterns to be included for decryption by{@link EncryptablePropertyFilter}.
* Default value is {@code null}
*/
private List<String> includeNames = null;
/**
* Specify the property name patterns to be EXCLUDED for decryption by{@link EncryptablePropertyFilter}.
* Default value is {@code jasypt\\.encryptor\\.*}
*/
private List<String> excludeNames = singletonList("^jasypt\\.encryptor\\.*");
}
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\properties\JasyptEncryptorConfigurationProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getServiceValue()
{
return "LocalFileSyncWarehouses";
}
@Override
public String getExternalSystemTypeCode()
{
return PCM_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return START_WAREHOUSE_SYNC_LOCAL_FILE_ROUTE;
}
@Override
public String getDisableCommand()
{ | return STOP_WAREHOUSE_SYNC_LOCAL_FILE_ROUTE;
}
@NonNull
public String getStartWarehouseRouteId()
{
return getExternalSystemTypeCode() + "-" + getEnableCommand();
}
@NonNull
public String getStopWarehouseRouteId()
{
return getExternalSystemTypeCode() + "-" + getDisableCommand();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\warehouse\LocalFileWarehouseSyncServicePCMRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BankStatementLineRefId implements RepoIdAware
{
int repoId;
private BankStatementLineRefId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_BankStatementLine_Ref_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
@NonNull
@JsonCreator | public static BankStatementLineRefId ofRepoId(final int repoId)
{
return new BankStatementLineRefId(repoId);
}
@Nullable
public static BankStatementLineRefId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? ofRepoId(repoId) : null;
}
public static int toRepoId(@Nullable final BankStatementLineRefId id) {return id != null ? id.getRepoId() : -1;}
public static Optional<BankStatementLineRefId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\banking\BankStatementLineRefId.java | 2 |
请完成以下Java代码 | private void setupAndInitializeOpenGLContext() {
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
GL.createCapabilities();
}
private void renderTriangle() {
float[] vertices = {
0.0f, 0.5f, 0.0f,
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f
};
FloatBuffer vertexBuffer = memAllocFloat(vertices.length);
vertexBuffer.put(vertices).flip(); | while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0.0f, 1.0f, 0.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, 0, vertexBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableClientState(GL_VERTEX_ARRAY);
glfwSwapBuffers(window);
}
memFree(vertexBuffer);
glfwDestroyWindow(window);
glfwTerminate();
}
} | repos\tutorials-master\lwjgl\src\main\java\com\baeldung\lwjgl\LWJGLApp.java | 1 |
请完成以下Java代码 | private DocumentFieldDescriptor.Builder createInternalIntegerField(
@NonNull final String fieldName,
@Nullable final Integer defaultValue)
{
return DocumentFieldDescriptor.builder(fieldName)
.setCaption(msgBL.translatable(fieldName))
.setWidgetType(DocumentFieldWidgetType.Integer)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.FALSE)
.setDisplayLogic(ConstantLogicExpression.FALSE)
.setDefaultValueExpression(defaultValue != null ? ConstantStringExpression.of(defaultValue.toString()) : null);
}
private DocumentFieldDescriptor.Builder createInternalYesNoField(
@NonNull final String fieldName,
final boolean defaultValue)
{
return DocumentFieldDescriptor.builder(fieldName)
.setCaption(msgBL.translatable(fieldName))
.setWidgetType(DocumentFieldWidgetType.YesNo)
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.TRUE)
.setDisplayLogic(ConstantLogicExpression.FALSE)
.setDefaultValueExpression(ConstantStringExpression.of(StringUtils.ofBoolean(defaultValue)));
}
private static QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor)
{ | // IMPORTANT: if Qty is not the last field then frontend will not react on pressing "ENTER" to complete the entry
return QuickInputLayoutDescriptor.onlyFields(entityDescriptor, new String[][] {
{ IOrderLineQuickInput.COLUMNNAME_M_Product_ID, IOrderLineQuickInput.COLUMNNAME_M_LU_HU_PI_ID, IOrderLineQuickInput.COLUMNNAME_M_HU_PI_Item_Product_ID },
{ IOrderLineQuickInput.COLUMNNAME_ShipmentAllocation_BestBefore_Policy },
{ IOrderLineQuickInput.COLUMNNAME_C_Flatrate_Conditions_ID },
{ IOrderLineQuickInput.COLUMNNAME_QtyLU, IOrderLineQuickInput.COLUMNNAME_Qty },
});
}
@NonNull
private LookupDescriptorProvider getLookupDescriptorProvider()
{
final AdValRuleId valueRuleId = AdValRuleId.ofRepoIdOrNull(sysConfigBL.getIntValue(SYS_CONFIG_FilterFlatrateConditionsADValRule, -1));
if (valueRuleId == null)
{
return lookupDescriptorProviders.searchInTable(I_C_Flatrate_Conditions.Table_Name);
}
final SqlLookupDescriptorProviderBuilder descriptorProviderBuilder = lookupDescriptorProviders.sql()
.setCtxTableName(I_C_Flatrate_Conditions.Table_Name)
.setCtxColumnName(IOrderLineQuickInput.COLUMNNAME_C_Flatrate_Conditions_ID)
.setDisplayType(DisplayType.Search)
.setAD_Val_Rule_ID(valueRuleId);
return descriptorProviderBuilder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\orderline\OrderLineQuickInputDescriptorFactory.java | 1 |
请完成以下Java代码 | public AdWindowId getAdWindowIdOrNull()
{
if (type == MenuNodeType.Window)
{
return elementId.toId(AdWindowId::ofRepoId);
}
else
{
return null;
}
}
//
//
// -------------------------------------------------------------------------
//
//
public static final class Builder
{
private Integer adMenuId;
private String caption;
private String captionBreadcrumb;
private MenuNodeType type;
@Nullable private DocumentId elementId;
private String mainTableName;
private final List<MenuNode> childrenFirst = new ArrayList<>();
private final List<MenuNode> childrenRest = new ArrayList<>();
private Builder()
{
}
public MenuNode build()
{
return new MenuNode(this);
}
public Builder setAD_Menu_ID(final int adMenuId)
{
this.adMenuId = adMenuId;
return this;
}
public Builder setAD_Menu_ID_None()
{
// NOTE: don't set it to ZERO because ZERO is usually root node's ID.
this.adMenuId = -100;
return this;
}
private int getAD_Menu_ID()
{
Check.assumeNotNull(adMenuId, "adMenuId shall be set");
return adMenuId;
}
private String getId()
{
final int adMenuId = getAD_Menu_ID();
if (type == MenuNodeType.NewRecord)
{
return adMenuId + "-new";
}
else
{
return String.valueOf(adMenuId);
}
}
public Builder setCaption(final String caption)
{
this.caption = caption; | return this;
}
public Builder setCaptionBreadcrumb(final String captionBreadcrumb)
{
this.captionBreadcrumb = captionBreadcrumb;
return this;
}
public Builder setType(final MenuNodeType type, @Nullable final DocumentId elementId)
{
this.type = type;
this.elementId = elementId;
return this;
}
public Builder setTypeNewRecord(@NonNull final AdWindowId adWindowId)
{
return setType(MenuNodeType.NewRecord, DocumentId.of(adWindowId));
}
public void setTypeGroup()
{
setType(MenuNodeType.Group, null);
}
public void addChildToFirstsList(@NonNull final MenuNode child)
{
childrenFirst.add(child);
}
public void addChild(@NonNull final MenuNode child)
{
childrenRest.add(child);
}
public Builder setMainTableName(final String mainTableName)
{
this.mainTableName = mainTableName;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\menu\MenuNode.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.