instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public String getProductUUID()
{
return product.getUuid();
}
public String getBpartnerUUID()
{
return bpartner.getUuid();
}
public LocalDate getDay()
{
return day.toLocalDate();
}
public YearWeek getWeek()
{
return YearWeekUtil.ofLocalDate(day.toLocalDate());
|
}
@Nullable
public Trend getTrend()
{
return Trend.ofNullableCode(trend);
}
@Nullable
public String getTrendAsString()
{
return trend;
}
public void setTrend(@Nullable final Trend trend)
{
this.trend = trend != null ? trend.getCode() : null;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\WeekSupply.java
| 2
|
请完成以下Java代码
|
public boolean removeAll(Collection<?> c) {
boolean result = false;
for (Object o: c) {
result |= remove(o);
}
return result;
}
public boolean retainAll(Collection<?> c) {
throw new UnsupportedModelOperationException("retainAll()", "not implemented");
}
public void clear() {
performClearOperation(referenceSourceElement);
}
};
}
protected void performClearOperation(ModelElementInstance referenceSourceElement) {
setReferenceIdentifier(referenceSourceElement, "");
}
@Override
protected void setReferenceIdentifier(ModelElementInstance referenceSourceElement, String referenceIdentifier) {
if (referenceIdentifier != null && !referenceIdentifier.isEmpty()) {
super.setReferenceIdentifier(referenceSourceElement, referenceIdentifier);
} else {
referenceSourceAttribute.removeAttribute(referenceSourceElement);
}
}
/**
* @param referenceSourceElement
|
* @param o
*/
protected void performRemoveOperation(ModelElementInstance referenceSourceElement, Object o) {
removeReference(referenceSourceElement, (ModelElementInstance) o);
}
protected void performAddOperation(ModelElementInstance referenceSourceElement, T referenceTargetElement) {
String identifier = getReferenceIdentifier(referenceSourceElement);
List<String> references = StringUtil.splitListBySeparator(identifier, separator);
String targetIdentifier = getTargetElementIdentifier(referenceTargetElement);
references.add(targetIdentifier);
identifier = StringUtil.joinList(references, separator);
setReferenceIdentifier(referenceSourceElement, identifier);
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\type\reference\AttributeReferenceCollection.java
| 1
|
请完成以下Java代码
|
public class M_Securpharm_Productdata_Result_Retry extends JavaProcess implements IProcessPrecondition
{
protected final SecurPharmService securPharmService = Adempiere.getBean(SecurPharmService.class);
public static final String PARAM_DataMatrix = "dataMatrix";
@Param(mandatory = true, parameterName = PARAM_DataMatrix)
private String dataMatrixString;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection().toInternal();
}
if (!securPharmService.hasConfig())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No SecurPharm config");
}
//
// Retry makes sense only if the SecurPharm product has errors (i.e. was not acquired yet)
final SecurPharmProductId productDataResultId = SecurPharmProductId.ofRepoId(context.getSingleSelectedRecordId());
final SecurPharmProduct product = securPharmService.getProductById(productDataResultId);
if (!product.isError())
{
ProcessPreconditionsResolution.reject();
|
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final DataMatrixCode dataMatrix = getDataMatrix();
final HuId huId = getHuId();
securPharmService
.newHUScanner()
// TODO: advice the scanner to update the existing SecurPharm product
.scanAndUpdateHUAttributes(dataMatrix, huId);
return MSG_OK;
}
private HuId getHuId()
{
final SecurPharmProductId productId = SecurPharmProductId.ofRepoId(getRecord_ID());
final SecurPharmProduct product = securPharmService.getProductById(productId);
return product.getHuId();
}
private final DataMatrixCode getDataMatrix()
{
return DataMatrixCode.ofString(dataMatrixString);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java\de\metas\vertical\pharma\securpharm\process\M_Securpharm_Productdata_Result_Retry.java
| 1
|
请完成以下Java代码
|
public static void dropBeads(boolean[][] abacus, int[] A, int m) {
for (int i = 1; i < A.length; i++) {
for (int j = m - 1; j >= 0; j--) {
if (abacus[i][j] == true) {
int x = i;
while (x > 0 && abacus[x - 1][j] == false) {
boolean temp = abacus[x - 1][j];
abacus[x - 1][j] = abacus[x][j];
abacus[x][j] = temp;
x--;
}
}
}
}
}
public static void transformToList(boolean[][] abacus, int[] A) {
int index = 0;
for (int i = abacus.length - 1; i >= 0; i--) {
int beads = 0;
|
for (int j = 0; j < abacus[0].length && abacus[i][j] == true; j++) {
beads++;
}
A[index++] = beads;
}
}
public static void sort(int[] A) {
int m = findMax(A);
boolean[][] abacus = setupAbacus(A, m);
dropBeads(abacus, A, m);
// transform abacus into sorted list
transformToList(abacus, A);
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-sorting-3\src\main\java\com\baeldung\algorithms\gravitysort\GravitySort.java
| 1
|
请完成以下Java代码
|
public class SmsFlashPromotionLog implements Serializable {
private Integer id;
private Integer memberId;
private Long productId;
private String memberPhone;
private String productName;
@ApiModelProperty(value = "会员订阅时间")
private Date subscribeTime;
private Date sendTime;
private static final long serialVersionUID = 1L;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getMemberId() {
return memberId;
}
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getMemberPhone() {
return memberPhone;
}
public void setMemberPhone(String memberPhone) {
this.memberPhone = memberPhone;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Date getSubscribeTime() {
|
return subscribeTime;
}
public void setSubscribeTime(Date subscribeTime) {
this.subscribeTime = subscribeTime;
}
public Date getSendTime() {
return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", productId=").append(productId);
sb.append(", memberPhone=").append(memberPhone);
sb.append(", productName=").append(productName);
sb.append(", subscribeTime=").append(subscribeTime);
sb.append(", sendTime=").append(sendTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionLog.java
| 1
|
请完成以下Java代码
|
public SalesRegion getById(final SalesRegionId salesRegionId)
{
return getMap().getById(salesRegionId);
}
private SalesRegionsMap getMap() {return cache.getOrLoad(0, this::retrieveMap);}
private SalesRegionsMap retrieveMap()
{
final ImmutableList<SalesRegion> list = queryBL.createQueryBuilder(I_C_SalesRegion.class)
.create()
.stream()
.map(SalesRegionRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new SalesRegionsMap(list);
}
private static SalesRegion fromRecord(final I_C_SalesRegion record)
{
return SalesRegion.builder()
.id(SalesRegionId.ofRepoId(record.getC_SalesRegion_ID()))
.value(record.getValue())
.name(record.getName())
.isActive(record.isActive())
.salesRepId(UserId.ofRepoIdOrNullIfSystem(record.getSalesRep_ID()))
.build();
}
public Optional<SalesRegion> getBySalesRepId(@NonNull final UserId salesRepId)
{
return getMap().stream()
.filter(salesRegion -> salesRegion.isActive()
&& UserId.equals(salesRegion.getSalesRepId(), salesRepId))
.max(Comparator.comparing(SalesRegion::getId));
}
//
//
//
|
private static class SalesRegionsMap
{
private final ImmutableMap<SalesRegionId, SalesRegion> byId;
public SalesRegionsMap(final List<SalesRegion> list)
{
this.byId = Maps.uniqueIndex(list, SalesRegion::getId);
}
public SalesRegion getById(final SalesRegionId salesRegionId)
{
final SalesRegion salesRegion = byId.get(salesRegionId);
if (salesRegion == null)
{
throw new AdempiereException("No sales region found for " + salesRegionId);
}
return salesRegion;
}
public Stream<SalesRegion> stream() {return byId.values().stream();}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\sales_region\SalesRegionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AsyncJobExecutorConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(AsyncJobExecutorConfiguration configuration) {
this.configuration = configuration;
}
public class AcquireTimerRunnableConfiguration implements AcquireJobsRunnableConfiguration {
@Override
public boolean isGlobalAcquireLockEnabled() {
return configuration.isGlobalAcquireLockEnabled();
}
@Override
public String getGlobalAcquireLockPrefix() {
return configuration.getGlobalAcquireLockPrefix();
}
@Override
public Duration getLockWaitTime() {
return configuration.getTimerLockWaitTime();
}
@Override
public Duration getLockPollRate() {
return configuration.getTimerLockPollRate();
}
@Override
public Duration getLockForceAcquireAfter() {
return configuration.getTimerLockForceAcquireAfter();
}
}
public class AcquireAsyncJobsDueRunnableConfiguration implements AcquireJobsRunnableConfiguration {
@Override
public boolean isGlobalAcquireLockEnabled() {
return configuration.isGlobalAcquireLockEnabled();
}
|
@Override
public String getGlobalAcquireLockPrefix() {
return configuration.getGlobalAcquireLockPrefix();
}
@Override
public Duration getLockWaitTime() {
return configuration.getAsyncJobsGlobalLockWaitTime();
}
@Override
public Duration getLockPollRate() {
return configuration.getAsyncJobsGlobalLockPollRate();
}
@Override
public Duration getLockForceAcquireAfter() {
return configuration.getAsyncJobsGlobalLockForceAcquireAfter();
}
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AbstractAsyncExecutor.java
| 2
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getExceptionStacktrace() {
if (exceptionByteArrayRef == null) {
return null;
}
byte[] bytes = exceptionByteArrayRef.getBytes();
if (bytes == null) {
return null;
}
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("UTF-8 is not a supported encoding");
}
}
public void setExceptionStacktrace(String exception) {
if (exceptionByteArrayRef == null) {
exceptionByteArrayRef = new ByteArrayRef();
}
exceptionByteArrayRef.setValue("stacktrace", getUtf8Bytes(exception));
|
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
}
public ByteArrayRef getExceptionByteArrayRef() {
return exceptionByteArrayRef;
}
protected byte[] getUtf8Bytes(String str) {
if (str == null) {
return null;
}
try {
return str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new ActivitiException("UTF-8 is not a supported encoding");
}
}
@Override
public String toString() {
return getClass().getName() + " [id=" + id + "]";
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntityImpl.java
| 1
|
请完成以下Java代码
|
public Date calculateRemovalTime(HistoricProcessInstanceEventEntity historicRootProcessInstance, ProcessDefinition processDefinition) {
Integer historyTimeToLive = processDefinition.getHistoryTimeToLive();
if (historyTimeToLive != null) {
if (isProcessInstanceRunning(historicRootProcessInstance)) {
Date startTime = historicRootProcessInstance.getStartTime();
return determineRemovalTime(startTime, historyTimeToLive);
} else if (isProcessInstanceEnded(historicRootProcessInstance)) {
Date endTime = historicRootProcessInstance.getEndTime();
return determineRemovalTime(endTime, historyTimeToLive);
}
}
return null;
}
public Date calculateRemovalTime(HistoricDecisionInstanceEntity historicRootDecisionInstance, DecisionDefinition decisionDefinition) {
Integer historyTimeToLive = decisionDefinition.getHistoryTimeToLive();
if (historyTimeToLive != null) {
Date evaluationTime = historicRootDecisionInstance.getEvaluationTime();
return determineRemovalTime(evaluationTime, historyTimeToLive);
}
return null;
}
public Date calculateRemovalTime(HistoricBatchEntity historicBatch) {
String batchOperation = historicBatch.getType();
if (batchOperation != null) {
Integer historyTimeToLive = getTTLByBatchOperation(batchOperation);
if (historyTimeToLive != null) {
if (isBatchRunning(historicBatch)) {
Date startTime = historicBatch.getStartTime();
return determineRemovalTime(startTime, historyTimeToLive);
} else if (isBatchEnded(historicBatch)) {
Date endTime = historicBatch.getEndTime();
return determineRemovalTime(endTime, historyTimeToLive);
}
}
}
return null;
}
protected boolean isBatchRunning(HistoricBatchEntity historicBatch) {
return historicBatch.getEndTime() == null;
|
}
protected boolean isBatchEnded(HistoricBatchEntity historicBatch) {
return historicBatch.getEndTime() != null;
}
protected Integer getTTLByBatchOperation(String batchOperation) {
return Context.getCommandContext()
.getProcessEngineConfiguration()
.getParsedBatchOperationsForHistoryCleanup()
.get(batchOperation);
}
protected boolean isProcessInstanceRunning(HistoricProcessInstanceEventEntity historicProcessInstance) {
return historicProcessInstance.getEndTime() == null;
}
protected boolean isProcessInstanceEnded(HistoricProcessInstanceEventEntity historicProcessInstance) {
return historicProcessInstance.getEndTime() != null;
}
public static Date determineRemovalTime(Date initTime, Integer timeToLive) {
Calendar removalTime = Calendar.getInstance();
removalTime.setTime(initTime);
removalTime.add(Calendar.DATE, timeToLive);
return removalTime.getTime();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\DefaultHistoryRemovalTimeProvider.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8081
spring.kafka.bootstrap-servers=localhost:9092
message.topic.name=baeldung
greeting.topic.name=greeting
filtered.topic.name=filtered
partitioned.topic.name=partitioned
multi.type.topic.name=multitype
# monitoring - lag analysis
monitor.kafka.bootstrap.config=localhost:9092
monitor.kafka.consumer.groupid=baeldungGrp
monitor.topic.name=baeldung
# monitoring - simulation
monitor.producer.simulate=true
monitor.consumer.simulate=true
monitor.kafka.consumer.groupid.simulate=baeldungGrpSimulate
test.topic=testtopic1
test.groupid=baeldung
manag
|
ement.endpoints.web.base-path=/actuator
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
management.endpoint.metrics.enabled=true
management.endpoint.prometheus.enabled=true
spring.jmx.enabled=false
|
repos\tutorials-master\spring-kafka\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public void setAD_Ref_List(final org.compiere.model.I_AD_Ref_List AD_Ref_List)
{
set_ValueFromPO(COLUMNNAME_AD_Ref_List_ID, org.compiere.model.I_AD_Ref_List.class, AD_Ref_List);
}
@Override
public void setAD_Ref_List_ID (final int AD_Ref_List_ID)
{
if (AD_Ref_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Ref_List_ID, AD_Ref_List_ID);
}
@Override
public int getAD_Ref_List_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Ref_List_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
|
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_List_Trl.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
# datasource 数据源配置内容
datasource:
# 订单数据源配置
orders:
jdbc-url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
# 用户数据源配置
users:
jdbc-url: jdbc:mysql://127.0.0.1:3306/tes
|
t_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
|
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-jdbctemplate\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public abstract class NetUtils {
/**
* Pre-loaded local address
*/
public static InetAddress localAddress;
static {
try {
localAddress = getLocalInetAddress();
} catch (SocketException e) {
throw new RuntimeException("fail to get local ip.");
}
}
/**
* Retrieve the first validated local ip address(the Public and LAN ip addresses are validated).
*
* @return the local address
* @throws SocketException the socket exception
*/
public static InetAddress getLocalInetAddress() throws SocketException {
// enumerates all network interfaces
Enumeration<NetworkInterface> enu = NetworkInterface.getNetworkInterfaces();
while (enu.hasMoreElements()) {
NetworkInterface ni = enu.nextElement();
if (ni.isLoopback()) {
continue;
}
Enumeration<InetAddress> addressEnumeration = ni.getInetAddresses();
while (addressEnumeration.hasMoreElements()) {
InetAddress address = addressEnumeration.nextElement();
// ignores all invalidated addresses
if (address.isLinkLocalAddress() || address.isLoopbackAddress() || address.isAnyLocalAddress()) {
|
continue;
}
return address;
}
}
throw new RuntimeException("No validated local address!");
}
/**
* Retrieve local address
*
* @return the string local address
*/
public static String getLocalAddress() {
return localAddress.getHostAddress();
}
}
|
repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\utils\NetUtils.java
| 1
|
请完成以下Java代码
|
private static void writeInt(ByteArrayOutputStream result, int length) throws IOException {
byte[] data = new byte[2];
data[0] = (byte) ((length >> 8) & 0xFF);
data[1] = (byte) (length & 0xFF);
result.write(data);
}
private static int readInt(ByteArrayInputStream result) throws IOException {
byte[] b = new byte[2];
result.read(b);
return ((b[0] & 0xFF) << 8) | (b[1] & 0xFF);
}
private static byte[] decrypt(byte[] text, @Nullable PrivateKey key, RsaAlgorithm alg, String salt, boolean gcm) {
ByteArrayInputStream input = new ByteArrayInputStream(text);
ByteArrayOutputStream output = new ByteArrayOutputStream(text.length);
try {
int length = readInt(input);
byte[] random = new byte[length];
input.read(random);
final Cipher cipher = Cipher.getInstance(alg.getJceName());
cipher.init(Cipher.DECRYPT_MODE, key);
String secret = new String(Hex.encode(cipher.doFinal(random)));
byte[] buffer = new byte[text.length - random.length - 2];
input.read(buffer);
BytesEncryptor aes = gcm ? Encryptors.stronger(secret, salt) : Encryptors.standard(secret, salt);
output.write(aes.decrypt(buffer));
return output.toByteArray();
|
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Cannot decrypt", ex);
}
}
private static boolean isHex(String input) {
try {
Hex.decode(input);
return true;
}
catch (Exception ex) {
return false;
}
}
public boolean canDecrypt() {
return this.privateKey != null;
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\RsaSecretEncryptor.java
| 1
|
请完成以下Java代码
|
private static I_C_Flatrate_Term retrieveTermForCache(@NonNull final I_C_Invoice_Candidate ic)
{
final int flatrateTermTableId = getTableId(I_C_Flatrate_Term.class);
Check.assume(ic.getAD_Table_ID() == flatrateTermTableId, "{} has AD_Table_ID={}", ic, flatrateTermTableId);
final I_C_Flatrate_Term term = TableRecordReference
.ofReferenced(ic)
.getModel(getContextAware(ic), I_C_Flatrate_Term.class);
return Check.assumeNotNull(term,
"The given invoice candidate references a {}; ic={}",
I_C_Flatrate_Term.class.getSimpleName(), ic);
}
/**
* <ul>
* <li>QtyDelivered := QtyOrdered
* <li>DeliveryDate := DateOrdered
* <li>M_InOut_ID: untouched
* </ul>
*
* @see IInvoiceCandidateHandler#setDeliveredData(I_C_Invoice_Candidate)
*/
public static void setDeliveredData(@NonNull final I_C_Invoice_Candidate ic)
{
// note: we can assume that #setQtyOrdered() was already called
ic.setQtyDelivered(ic.getQtyOrdered()); // when changing this, make sure to threat ProductType.Service specially
ic.setQtyDeliveredInUOM(ic.getQtyEntered());
ic.setDeliveryDate(ic.getDateOrdered());
}
public static void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final I_C_Flatrate_Term term = retrieveTerm(ic);
InvoiceCandidateLocationAdapterFactory
.billLocationAdapter(ic)
.setFrom(ContractLocationHelper.extractBillLocation(term));
|
}
public static UomId retrieveUomId(@NonNull final I_C_Invoice_Candidate icRecord)
{
final I_C_Flatrate_Term term = retrieveTerm(icRecord);
if (term.getC_UOM_ID() > 0)
{
return UomId.ofRepoId(term.getC_UOM_ID());
}
if (term.getM_Product_ID() > 0)
{
final IProductBL productBL = Services.get(IProductBL.class);
return productBL.getStockUOMId(term.getM_Product_ID());
}
throw new AdempiereException("The term of param 'icRecord' needs to have a UOM; C_Invoice_Candidate_ID=" + icRecord.getC_Invoice_Candidate_ID())
.appendParametersToMessage()
.setParameter("term", term)
.setParameter("icRecord", icRecord);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\invoicecandidate\HandlerTools.java
| 1
|
请完成以下Java代码
|
public class DocTypeCounterValidate extends JavaProcess
{
/** Counter Document */
private int p_C_DocTypeCounter_ID = 0;
/** Document Relationship */
private MDocTypeCounter m_counter = null;
/**
* Prepare
*/
protected void prepare ()
{
p_C_DocTypeCounter_ID = getRecord_ID();
} // prepare
/**
* Do It
* @return message
*/
protected String doIt () throws Exception
|
{
log.info("C_DocTypeCounter_ID=" + p_C_DocTypeCounter_ID);
m_counter = new MDocTypeCounter (getCtx(), p_C_DocTypeCounter_ID, get_TrxName());
if (m_counter == null || m_counter.get_ID() == 0)
throw new IllegalArgumentException("Not found C_DocTypeCounter_ID=" + p_C_DocTypeCounter_ID);
//
String error = m_counter.validate();
m_counter.save();
if (error != null)
throw new Exception(error);
return "OK";
} // doIt
} // DocTypeCounterValidate
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\DocTypeCounterValidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Cache {
/**
* Allows to set the size of the {@link org.flowable.ldap.LDAPGroupCache}. This is an LRU cache that caches groups for users and thus avoids hitting
* the LDAP system each time the groups of a user needs to be known.
* <p>
* The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done.
* <p>
* Note that the group cache is instantiated on the {@link org.flowable.ldap.LDAPIdentityServiceImpl}. As such, if you have a custom implementation of
* the {@link org.flowable.ldap.LDAPIdentityServiceImpl}, do not forget to add the group cache functionality.
*/
private int groupSize = -1;
/**
* Sets the expiration time of the {@link org.flowable.ldap.LDAPGroupCache} in milliseconds. When groups for a specific user are fetched, and if the
* group cache exists (see {@link #groupSize}), the
* groups will be stored in this cache for the time set in this property. ie. when the groups were fetched at 00:00 and the expiration time is 30 mins, any fetch of the groups for that user after
* 00:30 will not come from the cache, but do a fetch again from the LDAP system. Likewise, everything group fetch for that user done between 00:00 - 00:30 will come from the cache.
* <p>
* By default set to one hour.
*/
//TODO once we move to Boot 2.0 we can use Duration as a parameter’
private long groupExpiration = Duration.of(1, ChronoUnit.HOURS).toMillis();
public int getGroupSize() {
return groupSize;
}
|
public void setGroupSize(int groupSize) {
this.groupSize = groupSize;
}
public long getGroupExpiration() {
return groupExpiration;
}
public void setGroupExpiration(int groupExpiration) {
this.groupExpiration = groupExpiration;
}
public void customize(LDAPConfiguration configuration) {
configuration.setGroupCacheSize(getGroupSize());
configuration.setGroupCacheExpirationTime(getGroupExpiration());
}
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\ldap\FlowableLdapProperties.java
| 2
|
请完成以下Java代码
|
public boolean hasNext()
{
if (next == null)
{
next = iterator.next();
}
return next != null;
}
@Override
public E next()
{
if (next != null)
{
final E retValue = next;
next = null;
return retValue;
}
return iterator.next();
|
}
@Override
public void remove()
{
throw new UnsupportedOperationException("remove operation not supported");
}
@Override
public void close()
{
IteratorUtils.close(iterator);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\BlindIteratorWrapper.java
| 1
|
请完成以下Java代码
|
public class ProductsProposalRowReducers
{
public static ProductsProposalRow reduce(
@NonNull final ProductsProposalRow row,
@NonNull final ProductsProposalRowChangeRequest request)
{
if (request instanceof UserChange)
{
return reduceUserRequest(row, (UserChange)request);
}
else if (request instanceof RowUpdate)
{
return reduceRowUpdate(row, (RowUpdate)request);
}
if (request instanceof RowSaved)
{
return reduceRowSaved(row, (RowSaved)request);
}
else
{
throw new AdempiereException("Unknown request: " + request);
}
}
private static ProductsProposalRow reduceUserRequest(final ProductsProposalRow row, final UserChange request)
{
final ProductsProposalRowBuilder newRowBuilder = row.toBuilder();
if (request.getQty() != null)
{
newRowBuilder.qty(request.getQty().orElse(null));
}
if (request.getPrice() != null)
{
if (!row.isPriceEditable())
{
throw new AdempiereException("Price is not editable")
.setParameter("row", row);
}
final BigDecimal newUserEnteredPriceValue = request.getPrice().orElse(BigDecimal.ZERO);
final ProductProposalPrice newPrice = row.getPrice().withUserEnteredPriceValue(newUserEnteredPriceValue);
newRowBuilder.price(newPrice);
}
|
if (request.getDescription() != null)
{
newRowBuilder.description(request.getDescription().orElse(null));
}
return newRowBuilder.build();
}
private static ProductsProposalRow reduceRowUpdate(final ProductsProposalRow row, final RowUpdate request)
{
return row.toBuilder()
.price(request.getPrice())
.lastShipmentDays(request.getLastShipmentDays())
.copiedFromProductPriceId(request.getCopiedFromProductPriceId())
.build();
}
private static ProductsProposalRow reduceRowSaved(final ProductsProposalRow row, final RowSaved request)
{
return row.toBuilder()
.productPriceId(request.getProductPriceId())
.price(request.getPrice())
.copiedFromProductPriceId(null)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowReducers.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected static final class FreeMarkerTemplateAvailabilityProperties extends TemplateAvailabilityProperties {
private List<String> templateLoaderPath = new ArrayList<>(
Arrays.asList(FreeMarkerProperties.DEFAULT_TEMPLATE_LOADER_PATH));
FreeMarkerTemplateAvailabilityProperties() {
super(FreeMarkerProperties.DEFAULT_PREFIX, FreeMarkerProperties.DEFAULT_SUFFIX);
}
@Override
protected List<String> getLoaderPath() {
return this.templateLoaderPath;
}
public List<String> getTemplateLoaderPath() {
return this.templateLoaderPath;
}
public void setTemplateLoaderPath(List<String> templateLoaderPath) {
this.templateLoaderPath = templateLoaderPath;
}
|
}
static class FreeMarkerTemplateAvailabilityRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
if (ClassUtils.isPresent(REQUIRED_CLASS_NAME, classLoader)) {
BindableRuntimeHintsRegistrar.forTypes(FreeMarkerTemplateAvailabilityProperties.class)
.registerHints(hints, classLoader);
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-freemarker\src\main\java\org\springframework\boot\freemarker\autoconfigure\FreeMarkerTemplateAvailabilityProvider.java
| 2
|
请完成以下Java代码
|
public class RideRequest {
private String passengerId;
private String location;
private String destination;
public RideRequest() {
}
public RideRequest(String passengerId, String location, String destination) {
this.passengerId = passengerId;
this.location = location;
this.destination = destination;
}
public String getPassengerId() {
return passengerId;
}
public void setPassengerId(String passengerId) {
this.passengerId = passengerId;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
|
}
public String getDestination() {
return destination;
}
public void setDestination(String destination) {
this.destination = destination;
}
@Override
public String toString() {
return "RideRequest [passengerId=" + passengerId + ", location=" + location + ", destination=" + destination
+ "]";
}
}
|
repos\tutorials-master\messaging-modules\dapr\dapr-workflows\src\main\java\com\baeldung\dapr\pubsub\model\RideRequest.java
| 1
|
请完成以下Java代码
|
public class ControlSubThread implements Runnable {
private Thread worker;
private int interval = 100;
private AtomicBoolean running = new AtomicBoolean(false);
private AtomicBoolean stopped = new AtomicBoolean(true);
public ControlSubThread(int sleepInterval) {
interval = sleepInterval;
}
public void start() {
worker = new Thread(this);
worker.start();
}
public void stop() {
running.set(false);
}
public void interrupt() {
running.set(false);
worker.interrupt();
}
boolean isRunning() {
return running.get();
}
|
boolean isStopped() {
return stopped.get();
}
public void run() {
running.set(true);
stopped.set(false);
while (running.get()) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread was interrupted, Failed to complete operation");
}
// do something
}
stopped.set(true);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-4\src\main\java\com\baeldung\concurrent\stopping\ControlSubThread.java
| 1
|
请完成以下Java代码
|
class ContextPayloadInterceptorChain implements PayloadInterceptorChain {
private final @Nullable PayloadInterceptor currentInterceptor;
private final @Nullable ContextPayloadInterceptorChain next;
private @Nullable Context context;
ContextPayloadInterceptorChain(List<PayloadInterceptor> interceptors) {
if (interceptors == null) {
throw new IllegalArgumentException("interceptors cannot be null");
}
if (interceptors.isEmpty()) {
throw new IllegalArgumentException("interceptors cannot be empty");
}
ContextPayloadInterceptorChain interceptor = init(interceptors);
this.currentInterceptor = interceptor.currentInterceptor;
this.next = interceptor.next;
}
private static ContextPayloadInterceptorChain init(List<PayloadInterceptor> interceptors) {
ContextPayloadInterceptorChain interceptor = new ContextPayloadInterceptorChain(null, null);
ListIterator<? extends PayloadInterceptor> iterator = interceptors.listIterator(interceptors.size());
while (iterator.hasPrevious()) {
interceptor = new ContextPayloadInterceptorChain(iterator.previous(), interceptor);
}
return interceptor;
}
|
private ContextPayloadInterceptorChain(@Nullable PayloadInterceptor currentInterceptor,
@Nullable ContextPayloadInterceptorChain next) {
this.currentInterceptor = currentInterceptor;
this.next = next;
}
@Override
@SuppressWarnings("NullAway") // Dataflow analysis limitation
public Mono<Void> next(PayloadExchange exchange) {
return Mono.defer(() -> shouldIntercept() ? this.currentInterceptor.intercept(exchange, this.next)
: Mono.deferContextual(Mono::just).cast(Context.class).doOnNext((c) -> this.context = c).then());
}
@Nullable Context getContext() {
if (this.next == null) {
return this.context;
}
return this.next.getContext();
}
private boolean shouldIntercept() {
return this.currentInterceptor != null && this.next != null;
}
@Override
public String toString() {
return getClass().getSimpleName() + "[currentInterceptor=" + this.currentInterceptor + "]";
}
}
|
repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\core\ContextPayloadInterceptorChain.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ArticlesApi {
private ArticleCommandService articleCommandService;
private ArticleQueryService articleQueryService;
@PostMapping
public ResponseEntity createArticle(
@Valid @RequestBody NewArticleParam newArticleParam, @AuthenticationPrincipal User user) {
Article article = articleCommandService.createArticle(newArticleParam, user);
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("article", articleQueryService.findById(article.getId(), user).get());
}
});
}
@GetMapping(path = "feed")
public ResponseEntity getFeed(
@RequestParam(value = "offset", defaultValue = "0") int offset,
@RequestParam(value = "limit", defaultValue = "20") int limit,
@AuthenticationPrincipal User user) {
return ResponseEntity.ok(articleQueryService.findUserFeed(user, new Page(offset, limit)));
|
}
@GetMapping
public ResponseEntity getArticles(
@RequestParam(value = "offset", defaultValue = "0") int offset,
@RequestParam(value = "limit", defaultValue = "20") int limit,
@RequestParam(value = "tag", required = false) String tag,
@RequestParam(value = "favorited", required = false) String favoritedBy,
@RequestParam(value = "author", required = false) String author,
@AuthenticationPrincipal User user) {
return ResponseEntity.ok(
articleQueryService.findRecentArticles(
tag, author, favoritedBy, new Page(offset, limit), user));
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ArticlesApi.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Binding topicBinding2(Queue queueTwo, TopicExchange topicExchange) {
return BindingBuilder.bind(queueTwo).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_TWO);
}
/**
* 主题模式绑定队列3
*
* @param queueThree 队列3
* @param topicExchange 主题模式交换器
*/
@Bean
public Binding topicBinding3(Queue queueThree, TopicExchange topicExchange) {
return BindingBuilder.bind(queueThree).to(topicExchange).with(RabbitConsts.TOPIC_ROUTING_KEY_THREE);
}
/**
* 延迟队列
*/
@Bean
public Queue delayQueue() {
return new Queue(RabbitConsts.DELAY_QUEUE, true);
}
|
/**
* 延迟队列交换器, x-delayed-type 和 x-delayed-message 固定
*/
@Bean
public CustomExchange delayExchange() {
Map<String, Object> args = Maps.newHashMap();
args.put("x-delayed-type", "direct");
return new CustomExchange(RabbitConsts.DELAY_MODE_QUEUE, "x-delayed-message", true, false, args);
}
/**
* 延迟队列绑定自定义交换器
*
* @param delayQueue 队列
* @param delayExchange 延迟交换器
*/
@Bean
public Binding delayBinding(Queue delayQueue, CustomExchange delayExchange) {
return BindingBuilder.bind(delayQueue).to(delayExchange).with(RabbitConsts.DELAY_QUEUE).noargs();
}
}
|
repos\spring-boot-demo-master\demo-mq-rabbitmq\src\main\java\com\xkcoding\mq\rabbitmq\config\RabbitMqConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public AuthenticationManager authManager(HttpSecurity http) throws Exception {
return http.getSharedObject(AuthenticationManagerBuilder.class)
.userDetailsService(userDetailsService)
.and()
.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/login*", "/signin/**", "/signup/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout();
return http.build();
}
|
@Bean
// @Primary
public ProviderSignInController providerSignInController() {
ConnectionFactoryLocator connectionFactoryLocator = connectionFactoryLocator();
UsersConnectionRepository usersConnectionRepository = getUsersConnectionRepository(connectionFactoryLocator);
((InMemoryUsersConnectionRepository) usersConnectionRepository).setConnectionSignUp(facebookConnectionSignup);
return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new FacebookSignInAdapter());
}
private ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new FacebookConnectionFactory(appId, appSecret));
return registry;
}
private UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
return new InMemoryUsersConnectionRepository(connectionFactoryLocator);
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-social-login\src\main\java\com\baeldung\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public void await() {
try {
this.awaitThread = Thread.currentThread();
while (!this.stopAwait) {
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
// continue and check the flag
}
}
} finally {
this.awaitThread = null;
}
}
public void stopAwait() {
this.stopAwait = true;
|
}
@Override
public void destroy() throws Exception {
this.stopAwait();
Thread t = this.awaitThread;
if (t != null) {
t.interrupt();
try {
t.join(1000);
} catch (InterruptedException e) {
// Ignored
}
}
}
}
|
repos\dubbo-spring-boot-starter-master\src\main\java\com\alibaba\dubbo\spring\boot\server\DubboServer.java
| 1
|
请完成以下Java代码
|
public Optional<ProductId> getProductIdByBarcode(@NonNull final String barcode, @NonNull final ClientId clientId)
{
return productDAO.getProductIdByBarcode(barcode, clientId);
}
public Optional<I_M_HU> getHUByBarcode(@NonNull final String barcodeStringParam)
{
final String barcodeString = StringUtils.trimBlankToNull(barcodeStringParam);
if (barcodeString == null)
{
// shall not happen
throw new AdempiereException("No barcode provided");
}
final GlobalQRCode globalQRCode = GlobalQRCode.parse(barcodeString).orNullIfError();
if(globalQRCode != null)
{
final HUQRCode huQRCode = HUQRCode.fromGlobalQRCode(globalQRCode);
return huQRCodesService.getHuIdByQRCodeIfExists(huQRCode)
.map(handlingUnitsDAO::getById);
}
else
{
final I_M_HU hu = handlingUnitsDAO.createHUQueryBuilder()
.setHUStatus(X_M_HU.HUSTATUS_Active)
.setOnlyWithBarcode(barcodeString)
.firstOnly();
return Optional.ofNullable(hu);
}
}
public Optional<I_M_HU> getHUBySSCC18(@NonNull final String sscc18)
{
final I_M_HU hu = handlingUnitsDAO.createHUQueryBuilder()
.setHUStatus(X_M_HU.HUSTATUS_Active)
// match SSCC18 attribute
.addOnlyWithAttribute(AttributeConstants.ATTR_SSCC18_Value, sscc18)
// only HU's with BPartner set shall be considered (06821)
.setOnlyIfAssignedToBPartner(true)
.firstOnly();
return Optional.ofNullable(hu);
}
public Optional<ProductBarcodeFilterData> createDataFromHU(
final @Nullable String barcode,
final @Nullable I_M_HU hu)
{
if (hu == null)
{
return Optional.empty();
}
final ImmutableSet<ProductId> productIds = extractProductIds(hu);
if (productIds.isEmpty())
{
return Optional.empty();
}
|
final ICompositeQueryFilter<I_M_Packageable_V> filter = queryBL.createCompositeQueryFilter(I_M_Packageable_V.class)
.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Product_ID, productIds);
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu);
if (warehouseId != null)
{
filter.addInArrayFilter(I_M_Packageable_V.COLUMNNAME_M_Warehouse_ID, null, warehouseId);
}
final BPartnerId bpartnerId = IHandlingUnitsBL.extractBPartnerIdOrNull(hu);
if (bpartnerId != null)
{
filter.addEqualsFilter(I_M_Packageable_V.COLUMNNAME_C_BPartner_Customer_ID, bpartnerId);
}
return Optional.of(ProductBarcodeFilterData.builder()
.barcode(barcode)
.huId(HuId.ofRepoId(hu.getM_HU_ID()))
.sqlWhereClause(toSqlAndParams(filter))
.build());
}
private ImmutableSet<ProductId> extractProductIds(@NonNull final I_M_HU hu)
{
final IMutableHUContext huContext = handlingUnitsBL.createMutableHUContext(PlainContextAware.newWithThreadInheritedTrx());
return huContext.getHUStorageFactory()
.getStorage(hu)
.getProductStorages()
.stream()
.map(IHUProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\filters\ProductBarcodeFilterServicesFacade.java
| 1
|
请完成以下Java代码
|
public class CompositeVariableContext implements VariableContext {
protected final VariableContext[] delegateContexts;
public CompositeVariableContext(VariableContext[] delegateContexts) {
this.delegateContexts = delegateContexts;
}
public TypedValue resolve(String variableName) {
for (VariableContext variableContext : delegateContexts) {
TypedValue resolvedValue = variableContext.resolve(variableName);
if(resolvedValue != null) {
return resolvedValue;
}
}
return null;
}
public boolean containsVariable(String name) {
for (VariableContext variableContext : delegateContexts) {
if(variableContext.containsVariable(name)) {
return true;
}
|
}
return false;
}
public Set<String> keySet() {
Set<String> keySet = new HashSet<String>();
for (VariableContext variableContext : delegateContexts) {
keySet.addAll(variableContext.keySet());
}
return keySet;
}
public static CompositeVariableContext compose(VariableContext... variableContexts) {
return new CompositeVariableContext(variableContexts);
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\context\CompositeVariableContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LoggingGatewayFilterFactory extends AbstractGatewayFilterFactory<LoggingGatewayFilterFactory.Config> {
final Logger logger = LoggerFactory.getLogger(LoggingGatewayFilterFactory.class);
public static final String BASE_MSG = "baseMessage";
public static final String PRE_LOGGER = "preLogger";
public static final String POST_LOGGER = "postLogger";
public LoggingGatewayFilterFactory() {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList(BASE_MSG, PRE_LOGGER, POST_LOGGER);
}
@Override
public GatewayFilter apply(Config config) {
return new OrderedGatewayFilter((exchange, chain) -> {
if (config.isPreLogger())
logger.info("Pre GatewayFilter logging: " + config.getBaseMessage());
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
if (config.isPostLogger())
logger.info("Post GatewayFilter logging: " + config.getBaseMessage());
}));
}, 1);
}
public static class Config {
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
public Config() {
};
public Config(String baseMessage, boolean preLogger, boolean postLogger) {
super();
this.baseMessage = baseMessage;
this.preLogger = preLogger;
this.postLogger = postLogger;
}
public String getBaseMessage() {
|
return this.baseMessage;
}
public boolean isPreLogger() {
return preLogger;
}
public boolean isPostLogger() {
return postLogger;
}
public void setBaseMessage(String baseMessage) {
this.baseMessage = baseMessage;
}
public void setPreLogger(boolean preLogger) {
this.preLogger = preLogger;
}
public void setPostLogger(boolean postLogger) {
this.postLogger = postLogger;
}
}
}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\LoggingGatewayFilterFactory.java
| 2
|
请完成以下Java代码
|
public I_K_Topic getK_Topic() throws RuntimeException
{
return (I_K_Topic)MTable.get(getCtx(), I_K_Topic.Table_Name)
.getPO(getK_Topic_ID(), get_TrxName()); }
/** Set Knowledge Topic.
@param K_Topic_ID
Knowledge Topic
*/
public void setK_Topic_ID (int K_Topic_ID)
{
if (K_Topic_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_Topic_ID, Integer.valueOf(K_Topic_ID));
}
/** Get Knowledge Topic.
@return Knowledge Topic
*/
public int getK_Topic_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_Topic_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Rating.
@param Rating
Classification or Importance
*/
public void setRating (int Rating)
{
set_Value (COLUMNNAME_Rating, Integer.valueOf(Rating));
}
/** Get Rating.
@return Classification or Importance
*/
public int getRating ()
{
|
Integer ii = (Integer)get_Value(COLUMNNAME_Rating);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Entry.java
| 1
|
请完成以下Java代码
|
public static LocatorId ofRecord(@NonNull final I_M_Locator locatorRecord)
{
return ofRepoId(
WarehouseId.ofRepoId(locatorRecord.getM_Warehouse_ID()),
locatorRecord.getM_Locator_ID());
}
public static int toRepoId(@Nullable final LocatorId locatorId)
{
return locatorId != null ? locatorId.getRepoId() : -1;
}
public static Set<Integer> toRepoIds(final Collection<LocatorId> locatorIds)
{
if (locatorIds.isEmpty())
{
return ImmutableSet.of();
}
return locatorIds.stream().map(LocatorId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
public static boolean equals(@Nullable final LocatorId id1, @Nullable final LocatorId id2)
{
return Objects.equals(id1, id2);
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public static boolean equalsByRepoId(final int repoId1, final int repoId2)
{
final int repoId1Norm = repoId1 > 0 ? repoId1 : -1;
final int repoId2Norm = repoId2 > 0 ? repoId2 : -1;
return repoId1Norm == repoId2Norm;
}
private LocatorId(final int repoId, @NonNull final WarehouseId warehouseId)
{
Check.assumeGreaterThanZero(repoId, "M_Locator_ID");
this.repoId = repoId;
this.warehouseId = warehouseId;
}
@JsonValue
public String toJson()
|
{
return warehouseId.getRepoId() + "_" + repoId;
}
@JsonCreator
public static LocatorId fromJson(final String json)
{
final String[] parts = json.split("_");
if (parts.length != 2)
{
throw new IllegalArgumentException("Invalid json: " + json);
}
final int warehouseId = Integer.parseInt(parts[0]);
final int locatorId = Integer.parseInt(parts[1]);
return ofRepoId(warehouseId, locatorId);
}
public void assetWarehouseId(@NonNull final WarehouseId expectedWarehouseId)
{
if (!WarehouseId.equals(this.warehouseId, expectedWarehouseId))
{
throw new AdempiereException("Expected " + expectedWarehouseId + " for " + this);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\LocatorId.java
| 1
|
请完成以下Java代码
|
public class DeadlockExample {
private Lock lock1 = new ReentrantLock(true);
private Lock lock2 = new ReentrantLock(true);
public static void main(String[] args) {
DeadlockExample deadlock = new DeadlockExample();
new Thread(deadlock::operation1, "T1").start();
new Thread(deadlock::operation2, "T2").start();
}
public void operation1() {
lock1.lock();
print("lock1 acquired, waiting to acquire lock2.");
sleep(50);
lock2.lock();
print("lock2 acquired");
print("executing first operation.");
lock2.unlock();
lock1.unlock();
}
public void operation2() {
lock2.lock();
print("lock2 acquired, waiting to acquire lock1.");
sleep(50);
lock1.lock();
print("lock1 acquired");
|
print("executing second operation.");
lock1.unlock();
lock2.unlock();
}
public void print(String message) {
System.out.println("Thread " + Thread.currentThread()
.getName() + ": " + message);
}
public void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\deadlockAndLivelock\DeadlockExample.java
| 1
|
请完成以下Java代码
|
public MobileAppBundleInfo findInfoById(TenantId tenantId, MobileAppBundleId mobileAppBundleId) {
return DaoUtil.getData(mobileAppBundleRepository.findInfoById(mobileAppBundleId.getId()));
}
@Override
public List<MobileAppBundleOauth2Client> findOauth2ClientsByMobileAppBundleId(TenantId tenantId, MobileAppBundleId mobileAppBundleId) {
return DaoUtil.convertDataList(mobileOauth2ProviderRepository.findAllByMobileAppBundleId(mobileAppBundleId.getId()));
}
@Override
public void addOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) {
mobileOauth2ProviderRepository.save(new MobileAppBundleOauth2ClientEntity(mobileAppBundleOauth2Client));
}
@Override
public void removeOauth2Client(TenantId tenantId, MobileAppBundleOauth2Client mobileAppBundleOauth2Client) {
mobileOauth2ProviderRepository.deleteById(new MobileAppOauth2ClientCompositeKey(mobileAppBundleOauth2Client.getMobileAppBundleId().getId(),
mobileAppBundleOauth2Client.getOAuth2ClientId().getId()));
}
@Override
|
public MobileAppBundle findByPkgNameAndPlatform(TenantId tenantId, String pkgName, PlatformType platform) {
return DaoUtil.getData(mobileAppBundleRepository.findByPkgNameAndPlatformType(pkgName, platform));
}
@Override
public void deleteByTenantId(TenantId tenantId) {
mobileAppBundleRepository.deleteByTenantId(tenantId.getId());
}
@Override
public EntityType getEntityType() {
return EntityType.MOBILE_APP_BUNDLE;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\mobile\JpaMobileAppBundleDao.java
| 1
|
请完成以下Java代码
|
public Batch executeAsync() {
return commandExecutor.execute(new SetRemovalTimeToHistoricProcessInstancesCmd(this));
}
public HistoricProcessInstanceQuery getQuery() {
return query;
}
public List<String> getIds() {
return ids;
}
public Date getRemovalTime() {
return removalTime;
}
public Mode getMode() {
return mode;
}
public boolean isHierarchical() {
return isHierarchical;
}
|
public boolean isUpdateInChunks() {
return updateInChunks;
}
public Integer getChunkSize() {
return chunkSize;
}
public static enum Mode
{
CALCULATED_REMOVAL_TIME,
ABSOLUTE_REMOVAL_TIME,
CLEARED_REMOVAL_TIME;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\SetRemovalTimeToHistoricProcessInstancesBuilderImpl.java
| 1
|
请完成以下Java代码
|
public Map<Class<? extends CmmnElement>, CmmnElementHandler<? extends CmmnElement, ? extends CmmnActivity>> getDefinitionElementHandlers() {
return definitionElementHandlers;
}
public void setDefinitionElementHandlers(Map<Class<? extends CmmnElement>, CmmnElementHandler<? extends CmmnElement, ? extends CmmnActivity>> definitionElementHandlers) {
this.definitionElementHandlers = definitionElementHandlers;
}
public Map<Class<? extends PlanItemDefinition>, ItemHandler> getPlanItemElementHandlers() {
return planItemElementHandlers;
}
public void setPlanItemElementHandlers(Map<Class<? extends PlanItemDefinition>, ItemHandler> planItemElementHandlers) {
this.planItemElementHandlers = planItemElementHandlers;
}
public Map<Class<? extends PlanItemDefinition>, ItemHandler> getDiscretionaryElementHandlers() {
return discretionaryElementHandlers;
|
}
public void setDiscretionaryElementHandlers(Map<Class<? extends PlanItemDefinition>, ItemHandler> discretionaryElementHandlers) {
this.discretionaryElementHandlers = discretionaryElementHandlers;
}
public SentryHandler getSentryHandler() {
return sentryHandler;
}
public void setSentryHandler(SentryHandler sentryHandler) {
this.sentryHandler = sentryHandler;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\DefaultCmmnElementHandlerRegistry.java
| 1
|
请完成以下Java代码
|
public void validate(Object target, Errors errors) {
User user = (User) target;
if (StringUtils.isEmpty(user.getName())) {
errors.rejectValue("name", "name.required");
}
if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required");
}
// Add more validation rules as needed
}
public void validate(Object target, Errors errors, Object... validationHints) {
User user = (User) target;
if (validationHints.length > 0) {
if (validationHints[0] == "create") {
if (StringUtils.isEmpty(user.getName())) {
errors.rejectValue("name", "name.required","Name cannot be empty");
}
if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required" , "Invalid email format");
|
}
if (user.getAge() < 18 || user.getAge() > 65) {
errors.rejectValue("age", "user.age.outOfRange", new Object[]{18, 65}, "Age must be between 18 and 65");
}
} else if (validationHints[0] == "update") {
// Perform update-specific validation
if (StringUtils.isEmpty(user.getName()) && StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("name", "name.or.email.required", "Name or email cannot be empty");
}
}
} else {
// Perform default validation
if (StringUtils.isEmpty(user.getName())) {
errors.rejectValue("name", "name.required");
}
if (StringUtils.isEmpty(user.getEmail())) {
errors.rejectValue("email", "email.required");
}
}
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-validation\src\main\java\com\baeldung\springvalidator\UserValidator.java
| 1
|
请完成以下Java代码
|
public void setHR_Payroll_ID (int HR_Payroll_ID)
{
if (HR_Payroll_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_Payroll_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_Payroll_ID, Integer.valueOf(HR_Payroll_ID));
}
/** Get Payroll.
@return Payroll */
public int getHR_Payroll_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Payroll_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Payroll Year.
@param HR_Year_ID Payroll Year */
public void setHR_Year_ID (int HR_Year_ID)
{
if (HR_Year_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_Year_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_Year_ID, Integer.valueOf(HR_Year_ID));
}
/** Get Payroll Year.
@return Payroll Year */
public int getHR_Year_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Year_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Net Days.
@param NetDays
Net Days in which payment is due
*/
public void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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 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 Quantity.
@param Qty
Quantity
*/
public void setQty (int Qty)
{
set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty));
}
/** Get Quantity.
@return Quantity
*/
public int getQty ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Qty);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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\eevolution\model\X_HR_Year.java
| 1
|
请完成以下Java代码
|
public class ProductJsonNode {
private String name;
private String category;
private JsonNode details;
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 JsonNode getDetails() {
return details;
}
public void setDetails(JsonNode details) {
this.details = details;
}
}
|
repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\dynamicobject\ProductJsonNode.java
| 1
|
请完成以下Java代码
|
public ReferrerAddressType getReferrer() {
return referrer;
}
/**
* Sets the value of the referrer property.
*
* @param value
* allowed object is
* {@link ReferrerAddressType }
*
*/
public void setReferrer(ReferrerAddressType value) {
this.referrer = value;
}
/**
* Gets the value of the employer property.
*
* @return
* possible object is
* {@link EmployerAddressType }
*
*/
public EmployerAddressType getEmployer() {
return employer;
}
/**
* Sets the value of the employer property.
*
* @param value
* allowed object is
* {@link EmployerAddressType }
*
*/
public void setEmployer(EmployerAddressType value) {
this.employer = value;
}
/**
* Gets the value of the balance property.
*
* @return
|
* possible object is
* {@link BalanceTGType }
*
*/
public BalanceTGType getBalance() {
return balance;
}
/**
* Sets the value of the balance property.
*
* @param value
* allowed object is
* {@link BalanceTGType }
*
*/
public void setBalance(BalanceTGType value) {
this.balance = value;
}
/**
* Gets the value of the paymentPeriod property.
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getPaymentPeriod() {
return paymentPeriod;
}
/**
* Sets the value of the paymentPeriod property.
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setPaymentPeriod(Duration value) {
this.paymentPeriod = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\GarantType.java
| 1
|
请完成以下Java代码
|
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
@Override
public void setUI_ApplicationId (final @Nullable java.lang.String UI_ApplicationId)
{
set_Value (COLUMNNAME_UI_ApplicationId, UI_ApplicationId);
}
@Override
public java.lang.String getUI_ApplicationId()
{
return get_ValueAsString(COLUMNNAME_UI_ApplicationId);
}
@Override
public void setUI_DeviceId (final @Nullable java.lang.String UI_DeviceId)
{
set_Value (COLUMNNAME_UI_DeviceId, UI_DeviceId);
}
@Override
public java.lang.String getUI_DeviceId()
{
return get_ValueAsString(COLUMNNAME_UI_DeviceId);
}
@Override
public void setUI_TabId (final @Nullable java.lang.String UI_TabId)
{
set_Value (COLUMNNAME_UI_TabId, UI_TabId);
}
@Override
public java.lang.String getUI_TabId()
{
return get_ValueAsString(COLUMNNAME_UI_TabId);
}
@Override
public void setUI_Trace_ID (final int UI_Trace_ID)
|
{
if (UI_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, null);
else
set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, UI_Trace_ID);
}
@Override
public int getUI_Trace_ID()
{
return get_ValueAsInt(COLUMNNAME_UI_Trace_ID);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setUserAgent (final @Nullable java.lang.String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
@Override
public java.lang.String getUserAgent()
{
return get_ValueAsString(COLUMNNAME_UserAgent);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_UI_Trace.java
| 1
|
请完成以下Java代码
|
private Polyline2D createRectangle(GraphicInfo graphicInfo) {
Polyline2D rectangle = new Polyline2D(
new Point2D(graphicInfo.getX(), graphicInfo.getY()),
new Point2D(graphicInfo.getX() + graphicInfo.getWidth(), graphicInfo.getY()),
new Point2D(graphicInfo.getX() + graphicInfo.getWidth(), graphicInfo.getY() + graphicInfo.getHeight()),
new Point2D(graphicInfo.getX(), graphicInfo.getY() + graphicInfo.getHeight()),
new Point2D(graphicInfo.getX(), graphicInfo.getY())
);
return rectangle;
}
private Polyline2D createGateway(GraphicInfo graphicInfo) {
double middleX = graphicInfo.getX() + (graphicInfo.getWidth() / 2);
double middleY = graphicInfo.getY() + (graphicInfo.getHeight() / 2);
Polyline2D gatewayRectangle = new Polyline2D(
new Point2D(graphicInfo.getX(), middleY),
new Point2D(middleX, graphicInfo.getY()),
new Point2D(graphicInfo.getX() + graphicInfo.getWidth(), middleY),
new Point2D(middleX, graphicInfo.getY() + graphicInfo.getHeight()),
new Point2D(graphicInfo.getX(), middleY)
);
return gatewayRectangle;
}
private GraphicInfo createGraphicInfo(double x, double y) {
GraphicInfo graphicInfo = new GraphicInfo();
graphicInfo.setX(x);
graphicInfo.setY(y);
return graphicInfo;
}
class FlowWithContainer {
protected SequenceFlow sequenceFlow;
protected FlowElementsContainer flowContainer;
|
public FlowWithContainer(SequenceFlow sequenceFlow, FlowElementsContainer flowContainer) {
this.sequenceFlow = sequenceFlow;
this.flowContainer = flowContainer;
}
public SequenceFlow getSequenceFlow() {
return sequenceFlow;
}
public void setSequenceFlow(SequenceFlow sequenceFlow) {
this.sequenceFlow = sequenceFlow;
}
public FlowElementsContainer getFlowContainer() {
return flowContainer;
}
public void setFlowContainer(FlowElementsContainer flowContainer) {
this.flowContainer = flowContainer;
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\BpmnJsonConverter.java
| 1
|
请完成以下Java代码
|
public Date getLockExpirationBefore() {
return lockExpirationBefore;
}
public Date getLockExpirationAfter() {
return lockExpirationAfter;
}
public String getTopicName() {
return topicName;
}
public Boolean getLocked() {
return locked;
}
public Boolean getNotLocked() {
return notLocked;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
|
return activityId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getRetriesLeft() {
return retriesLeft;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java
| 1
|
请完成以下Java代码
|
public boolean contains(MessageListenerContainer container) {
return this.containers.contains(container);
}
/**
* Return true if all containers in this group are stopped.
* @return true if all are stopped.
*/
public boolean allStopped() {
return this.containers.stream()
.allMatch(container -> !container.isRunning());
}
/**
* Add one or more containers to the group.
* @param theContainers the container(s).
*/
public void addContainers(MessageListenerContainer... theContainers) {
for (MessageListenerContainer container : theContainers) {
this.containers.add(container);
}
}
/**
* Remove a container from the group.
* @param container the container.
* @return true if the container was removed.
*/
public boolean removeContainer(MessageListenerContainer container) {
return this.containers.remove(container);
}
@Override
public synchronized void start() {
if (!this.running) {
this.containers.forEach(container -> {
LOGGER.debug(() -> "Starting: " + container);
container.start();
});
this.running = true;
}
}
|
@Override
public synchronized void stop() {
if (this.running) {
this.containers.forEach(container -> container.stop());
this.running = false;
}
}
@Override
public synchronized boolean isRunning() {
return this.running;
}
@Override
public String toString() {
return "ContainerGroup [name=" + this.name + ", containers=" + this.containers + "]";
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\ContainerGroup.java
| 1
|
请完成以下Java代码
|
public void createRequestIfConfigured(final I_M_InOut inout)
{
if (docTypeBL.hasRequestType(DocTypeId.ofRepoId(inout.getC_DocType_ID())))
{
inOutBL.createRequestFromInOut(inout);
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE })
public void forbidReactivateOnCompletedShipmentDeclaration(final I_M_InOut inout)
{
try (final MDCCloseable inoutRecordMDC = TableRecordMDC.putTableRecordReference(inout))
{
if (!inout.isSOTrx())
{
// Only applies to shipments
return;
}
final InOutId shipmentId = InOutId.ofRepoId(inout.getM_InOut_ID());
if (shipmentDeclarationRepo.existCompletedShipmentDeclarationsForShipmentId(shipmentId))
{
throw new AdempiereException(ERR_ShipmentDeclaration).markAsUserValidationError();
}
}
}
|
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE,
}, ifColumnsChanged = {
I_M_InOut.COLUMNNAME_DropShip_Location_ID, I_M_InOut.COLUMNNAME_C_BPartner_Location_ID
})
public void onBPartnerLocation(final I_M_InOut inout)
{
if (InterfaceWrapperHelper.isUIAction(inout))
{
inOutBL.setShipperId(inout);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipment\model\interceptor\M_InOut.java
| 1
|
请完成以下Java代码
|
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getDepartment() {
return department;
}
|
public void setDepartment(String department) {
this.department = department;
}
public Employee() {
}
public Employee(Long id, String fullName, String department) {
this.id = id;
this.fullName = fullName;
this.department = department;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-5\src\main\java\com\baeldung\jakarta\Employee.java
| 1
|
请完成以下Java代码
|
public class GenericEntry<T> {
private T data;
private int rank;
// non-generic constructor
public GenericEntry(int rank) {
this.rank = rank;
}
// generic constructor
public GenericEntry(T data, int rank) {
this.data = data;
this.rank = rank;
}
// generic constructor with different type
public <E extends Rankable & Serializable> GenericEntry(E element) {
this.data = (T) element;
this.rank = element.getRank();
}
// generic constructor with different type and wild card
public GenericEntry(Optional<? extends Rankable> optional) {
if (optional.isPresent()) {
this.data = (T) optional.get();
|
this.rank = optional.get()
.getRank();
}
}
// getters and setters
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-generics-2\src\main\java\com\baeldung\generics\GenericEntry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setTransientVariable(String variableName, Object variableValue) {
throw new UnsupportedOperationException("No execution active, no variables can be set");
}
@Override
public Object getTransientVariableLocal(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
return null;
}
@Override
public Object getTransientVariable(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariables() {
return null;
}
@Override
public void removeTransientVariableLocal(String variableName) {
|
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException("No execution active, no variables can be removed");
}
@Override
public String getTenantId() {
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\el\NoExecutionVariableScope.java
| 2
|
请完成以下Java代码
|
private void setReferenceSource(ModelElementInstance referenceSourceParent, Source referenceSource) {
getReferenceSourceChild().setChild(referenceSourceParent, referenceSource);
}
@SuppressWarnings("unchecked")
public Target getReferenceTargetElement(ModelElementInstanceImpl referenceSourceParentElement) {
Source referenceSource = getReferenceSource(referenceSourceParentElement);
if (referenceSource != null) {
String identifier = getReferenceIdentifier(referenceSource);
ModelElementInstance referenceTargetElement = referenceSourceParentElement.getModelInstance().getModelElementById(identifier);
if (referenceTargetElement != null) {
return (Target) referenceTargetElement;
}
else {
throw new ModelException("Unable to find a model element instance for id " + identifier);
}
}
else {
return null;
}
}
public void setReferenceTargetElement(ModelElementInstanceImpl referenceSourceParentElement, Target referenceTargetElement) {
ModelInstanceImpl modelInstance = referenceSourceParentElement.getModelInstance();
String identifier = referenceTargetAttribute.getValue(referenceTargetElement);
|
ModelElementInstance existingElement = modelInstance.getModelElementById(identifier);
if (existingElement == null || !existingElement.equals(referenceTargetElement)) {
throw new ModelReferenceException("Cannot create reference to model element " + referenceTargetElement
+": element is not part of model. Please connect element to the model first.");
}
else {
Source referenceSourceElement = modelInstance.newInstance(getReferenceSourceElementType());
setReferenceSource(referenceSourceParentElement, referenceSourceElement);
setReferenceIdentifier(referenceSourceElement, identifier);
}
}
public void clearReferenceTargetElement(ModelElementInstanceImpl referenceSourceParentElement) {
getReferenceSourceChild().removeChild(referenceSourceParentElement);
}
}
|
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ElementReferenceImpl.java
| 1
|
请完成以下Java代码
|
public String toString() {
return getRoot().getStructuralId(null);
}
/**
* Create a bindings.
* @param fnMapper the function mapper to use
* @param varMapper the variable mapper to use
* @return tree bindings
*/
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper) {
return bind(fnMapper, varMapper, null);
}
/**
* Create a bindings.
* @param fnMapper the function mapper to use
* @param varMapper the variable mapper to use
* @param converter custom type converter
* @return tree bindings
*/
public Bindings bind(FunctionMapper fnMapper, VariableMapper varMapper, TypeConverter converter) {
Method[] methods = null;
if (!functions.isEmpty()) {
if (fnMapper == null) {
throw new ELException(LocalMessages.get("error.function.nomapper"));
}
methods = new Method[functions.size()];
for (int i = 0; i < functions.size(); i++) {
FunctionNode node = functions.get(i);
String image = node.getName();
Method method = null;
int colon = image.indexOf(':');
if (colon < 0) {
method = fnMapper.resolveFunction("", image);
} else {
method = fnMapper.resolveFunction(image.substring(0, colon), image.substring(colon + 1));
}
if (method == null) {
throw new ELException(LocalMessages.get("error.function.notfound", image));
}
if (node.isVarArgs() && method.isVarArgs()) {
if (method.getParameterTypes().length > node.getParamCount() + 1) {
|
throw new ELException(LocalMessages.get("error.function.params", image));
}
} else {
if (method.getParameterTypes().length != node.getParamCount()) {
throw new ELException(LocalMessages.get("error.function.params", image));
}
}
methods[node.getIndex()] = method;
}
}
ValueExpression[] expressions = null;
if (identifiers.size() > 0) {
expressions = new ValueExpression[identifiers.size()];
for (int i = 0; i < identifiers.size(); i++) {
IdentifierNode node = identifiers.get(i);
ValueExpression expression = null;
if (varMapper != null) {
expression = varMapper.resolveVariable(node.getName());
}
expressions[node.getIndex()] = expression;
}
}
return new Bindings(methods, expressions, converter);
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Tree.java
| 1
|
请完成以下Java代码
|
public void stop() {
synchronized (this.lifeCycleMonitor) {
if (this.running) {
logger.info("Stopping...");
doStop();
this.running = false;
logger.info("Stopped.");
}
}
}
@Override
public void stop(Runnable callback) {
synchronized (this.lifeCycleMonitor) {
|
stop();
callback.run();
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public void destroy() {
stop();
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.hbm2ddl.auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.show-sql= true
# REDIS
# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09
spring.redis.database=0
# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=localhost
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=
# \u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-active=8
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4
|
\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-wait=-1
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.max-idle=8
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.min-idle=0
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=10000
|
repos\spring-boot-leaning-master\1.x\第09课:如何玩转 Redis\spring-boot-redis\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public int getAD_Image_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workbench.
@param AD_Workbench_ID
Collection of windows, reports
*/
public void setAD_Workbench_ID (int AD_Workbench_ID)
{
if (AD_Workbench_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workbench_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workbench_ID, Integer.valueOf(AD_Workbench_ID));
}
/** Get Workbench.
@return Collection of windows, reports
*/
public int getAD_Workbench_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workbench_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
|
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workbench.java
| 1
|
请完成以下Java代码
|
public int getProxyPort ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ProxyPort);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Require CreditCard Verification Code.
@param RequireVV
Require 3/4 digit Credit Verification Code
*/
@Override
public void setRequireVV (boolean RequireVV)
{
set_Value (COLUMNNAME_RequireVV, Boolean.valueOf(RequireVV));
}
/** Get Require CreditCard Verification Code.
@return Require 3/4 digit Credit Verification Code
*/
@Override
public boolean isRequireVV ()
{
Object oo = get_Value(COLUMNNAME_RequireVV);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set User ID.
@param UserID
User ID or account number
*/
@Override
public void setUserID (java.lang.String UserID)
|
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/** Set Vendor ID.
@param VendorID
Vendor ID for the Payment Processor
*/
@Override
public void setVendorID (java.lang.String VendorID)
{
set_Value (COLUMNNAME_VendorID, VendorID);
}
/** Get Vendor ID.
@return Vendor ID for the Payment Processor
*/
@Override
public java.lang.String getVendorID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VendorID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java
| 1
|
请完成以下Java代码
|
public static BufferedImage generateUPCABarcodeImage(String barcodeText) throws Exception {
Barcode barcode = BarcodeFactory.createUPCA(barcodeText); //checksum is automatically added
barcode.setFont(BARCODE_TEXT_FONT);
barcode.setResolution(400);
return BarcodeImageHandler.getImage(barcode);
}
public static BufferedImage generateEAN13BarcodeImage(String barcodeText) throws Exception {
Barcode barcode = BarcodeFactory.createEAN13(barcodeText); //checksum is automatically added
barcode.setFont(BARCODE_TEXT_FONT);
return BarcodeImageHandler.getImage(barcode);
}
|
public static BufferedImage generateCode128BarcodeImage(String barcodeText) throws Exception {
Barcode barcode = BarcodeFactory.createCode128(barcodeText);
barcode.setFont(BARCODE_TEXT_FONT);
return BarcodeImageHandler.getImage(barcode);
}
public static BufferedImage generatePDF417BarcodeImage(String barcodeText) throws Exception {
Barcode barcode = BarcodeFactory.createPDF417(barcodeText);
barcode.setFont(BARCODE_TEXT_FONT);
return BarcodeImageHandler.getImage(barcode);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\generators\BarbecueBarcodeGenerator.java
| 1
|
请完成以下Java代码
|
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Revaluation Date.
@param DateReval
Date of Revaluation
*/
public void setDateReval (Timestamp DateReval)
{
set_Value (COLUMNNAME_DateReval, DateReval);
}
/** Get Revaluation Date.
@return Date of Revaluation
*/
public Timestamp getDateReval ()
{
return (Timestamp)get_Value(COLUMNNAME_DateReval);
}
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Grand Total.
@param GrandTotal
Total amount of document
*/
public void setGrandTotal (BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Grand Total.
@return Total amount of document
*/
public BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Include All Currencies.
@param IsAllCurrencies
Report not just foreign currency Invoices
*/
public void setIsAllCurrencies (boolean IsAllCurrencies)
|
{
set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies));
}
/** Get Include All Currencies.
@return Report not just foreign currency Invoices
*/
public boolean isAllCurrencies ()
{
Object oo = get_Value(COLUMNNAME_IsAllCurrencies);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_InvoiceGL.java
| 1
|
请完成以下Java代码
|
public class ProtoTransportPayloadConfiguration implements TransportPayloadTypeConfiguration {
public static final Location LOCATION = new Location("", "", -1, -1);
public static final String ATTRIBUTES_PROTO_SCHEMA = "attributes proto schema";
public static final String TELEMETRY_PROTO_SCHEMA = "telemetry proto schema";
public static final String RPC_RESPONSE_PROTO_SCHEMA = "rpc response proto schema";
public static final String RPC_REQUEST_PROTO_SCHEMA = "rpc request proto schema";
private static final String PROTO_3_SYNTAX = "proto3";
private String deviceTelemetryProtoSchema;
private String deviceAttributesProtoSchema;
private String deviceRpcRequestProtoSchema;
private String deviceRpcResponseProtoSchema;
private boolean enableCompatibilityWithJsonPayloadFormat;
private boolean useJsonPayloadFormatForDefaultDownlinkTopics;
@Override
public TransportPayloadType getTransportPayloadType() {
return TransportPayloadType.PROTOBUF;
}
public Descriptors.Descriptor getTelemetryDynamicMessageDescriptor(String deviceTelemetryProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceTelemetryProtoSchema, TELEMETRY_PROTO_SCHEMA);
}
public Descriptors.Descriptor getAttributesDynamicMessageDescriptor(String deviceAttributesProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceAttributesProtoSchema, ATTRIBUTES_PROTO_SCHEMA);
}
public Descriptors.Descriptor getRpcResponseDynamicMessageDescriptor(String deviceRpcResponseProtoSchema) {
return DynamicProtoUtils.getDescriptor(deviceRpcResponseProtoSchema, RPC_RESPONSE_PROTO_SCHEMA);
}
public DynamicMessage.Builder getRpcRequestDynamicMessageBuilder(String deviceRpcRequestProtoSchema) {
|
return DynamicProtoUtils.getDynamicMessageBuilder(deviceRpcRequestProtoSchema, RPC_REQUEST_PROTO_SCHEMA);
}
public String getDeviceRpcResponseProtoSchema() {
if (StringUtils.isNotEmpty(deviceRpcResponseProtoSchema)) {
return deviceRpcResponseProtoSchema;
} else {
return "syntax =\"proto3\";\n" +
"package rpc;\n" +
"\n" +
"message RpcResponseMsg {\n" +
" optional string payload = 1;\n" +
"}";
}
}
public String getDeviceRpcRequestProtoSchema() {
if (StringUtils.isNotEmpty(deviceRpcRequestProtoSchema)) {
return deviceRpcRequestProtoSchema;
} else {
return "syntax =\"proto3\";\n" +
"package rpc;\n" +
"\n" +
"message RpcRequestMsg {\n" +
" optional string method = 1;\n" +
" optional int32 requestId = 2;\n" +
" optional string params = 3;\n" +
"}";
}
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\device\profile\ProtoTransportPayloadConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getLabelFontName() {
return labelFontName;
}
public void setLabelFontName(String labelFontName) {
this.labelFontName = labelFontName;
}
public String getAnnotationFontName() {
return annotationFontName;
}
public void setAnnotationFontName(String annotationFontName) {
this.annotationFontName = annotationFontName;
}
public boolean isFormFieldValidationEnabled() {
return formFieldValidationEnabled;
}
public void setFormFieldValidationEnabled(boolean formFieldValidationEnabled) {
this.formFieldValidationEnabled = formFieldValidationEnabled;
}
public Duration getLockPollRate() {
return lockPollRate;
}
public void setLockPollRate(Duration lockPollRate) {
this.lockPollRate = lockPollRate;
}
public Duration getSchemaLockWaitTime() {
return schemaLockWaitTime;
}
public void setSchemaLockWaitTime(Duration schemaLockWaitTime) {
this.schemaLockWaitTime = schemaLockWaitTime;
}
public boolean isEnableHistoryCleaning() {
return enableHistoryCleaning;
}
public void setEnableHistoryCleaning(boolean enableHistoryCleaning) {
this.enableHistoryCleaning = enableHistoryCleaning;
}
public String getHistoryCleaningCycle() {
return historyCleaningCycle;
}
public void setHistoryCleaningCycle(String historyCleaningCycle) {
this.historyCleaningCycle = historyCleaningCycle;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration")
public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) {
|
this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays);
}
public Duration getHistoryCleaningAfter() {
return historyCleaningAfter;
}
public void setHistoryCleaningAfter(Duration historyCleaningAfter) {
this.historyCleaningAfter = historyCleaningAfter;
}
public int getHistoryCleaningBatchSize() {
return historyCleaningBatchSize;
}
public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) {
this.historyCleaningBatchSize = historyCleaningBatchSize;
}
public String getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(String variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
| 2
|
请完成以下Java代码
|
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setOffsetDays (final int OffsetDays)
{
set_Value (COLUMNNAME_OffsetDays, OffsetDays);
}
@Override
public int getOffsetDays()
{
return get_ValueAsInt(COLUMNNAME_OffsetDays);
}
@Override
public void setPercent (final int Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public int getPercent()
{
return get_ValueAsInt(COLUMNNAME_Percent);
}
/**
* ReferenceDateType AD_Reference_ID=541989
* Reference name: ReferenceDateType
*/
public static final int REFERENCEDATETYPE_AD_Reference_ID=541989;
/** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV";
/** BLDate = BL */
|
public static final String REFERENCEDATETYPE_BLDate = "BL";
/** OrderDate = OD */
public static final String REFERENCEDATETYPE_OrderDate = "OD";
/** LCDate = LC */
public static final String REFERENCEDATETYPE_LCDate = "LC";
/** ETADate = ET */
public static final String REFERENCEDATETYPE_ETADate = "ET";
@Override
public void setReferenceDateType (final java.lang.String ReferenceDateType)
{
set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType);
}
@Override
public java.lang.String getReferenceDateType()
{
return get_ValueAsString(COLUMNNAME_ReferenceDateType);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentTerm_Break.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean isAllowRefresh(I_AD_Table_MView mview, PO sourcePO, RefreshMode refreshMode)
{
if (refreshMode == RefreshMode.Complete)
{
return true;
}
else if (refreshMode == RefreshMode.Partial)
{
MViewMetadata mdata = getMetadata(mview);
if (mdata == null)
{
log.debug("No metadata found for " + mview + " => return false");
return false;
}
String relationWhereClause = mdata.getRelationWhereClause(sourcePO.get_TableName(), mdata.getTargetTableName());
if (Check.isEmpty(relationWhereClause, true))
{
return false;
}
else
{
return true;
}
}
log.warn("Unknown refreshMode=" + refreshMode + " => returning false");
return false;
}
@Override
public void refreshEx(I_AD_Table_MView mview, PO sourcePO, RefreshMode refreshMode, String trxName)
{
if (refreshMode == RefreshMode.Complete)
{
updateComplete(mview);
}
else if (refreshMode == RefreshMode.Partial)
{
updatePartial(mview, sourcePO, trxName);
}
else
{
throw new AdempiereException("RefreshMode " + refreshMode + " not supported");
}
}
/**
* Try to update the materialized view. This method is not throwing an exception in case it fails but it logs it and
* return false. This is useful because we don't want to condition the update of triggering PO to updating the
* MView. That can be solved later
*
* @return true if updated, false if failed
*/
@Override
public boolean refresh(final I_AD_Table_MView mview, final PO sourcePO, final RefreshMode refreshMode, final String trxName)
{
final boolean[] ok = new boolean[] { false };
Services.get(ITrxManager.class).run(trxName, new TrxRunnable2()
{
@Override
public void run(String trxName)
|
{
refreshEx(mview, sourcePO, refreshMode, trxName);
ok[0] = true;
}
@Override
public boolean doCatch(Throwable e)
{
// log the error, return true to rollback the transaction but don't throw it forward
log.error(e.getLocalizedMessage() + ", mview=" + mview + ", sourcePO=" + sourcePO + ", trxName=" + trxName, e);
ok[0] = false;
return true;
}
@Override
public void doFinally()
{
}
});
return ok[0];
}
@Override
public boolean isSourceChanged(MViewMetadata mdata, PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName();
final Set<String> sourceColumns = mdata.getSourceColumns(sourceTableName);
if (sourceColumns == null || sourceColumns.isEmpty())
return false;
if (changeType == ModelValidator.TYPE_AFTER_NEW || changeType == ModelValidator.TYPE_AFTER_DELETE)
{
return true;
}
for (String sourceColumn : sourceColumns)
{
if (sourcePO.is_ValueChanged(sourceColumn))
{
return true;
}
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableMViewBL.java
| 2
|
请完成以下Java代码
|
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
OAuth2AccessToken accessToken;
try {
accessToken = restTemplate.getAccessToken();
} catch (final OAuth2Exception e) {
throw new BadCredentialsException("Could not obtain access token", e);
}
try {
final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
String kid = JwtHelper.headers(idToken)
.get("kid");
final Jwt tokenDecoded = JwtHelper.decodeAndVerify(idToken, verifier(kid));
final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);
verifyClaims(authInfo);
final OpenIdConnectUserDetails user = new OpenIdConnectUserDetails(authInfo, accessToken);
return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
} catch (final Exception e) {
throw new BadCredentialsException("Could not obtain user details from token", e);
}
}
public void verifyClaims(Map claims) {
int exp = (int) claims.get("exp");
Date expireDate = new Date(exp * 1000L);
Date now = new Date();
if (expireDate.before(now) || !claims.get("iss").equals(issuer) || !claims.get("aud").equals(clientId)) {
throw new RuntimeException("Invalid claims");
}
}
|
private RsaVerifier verifier(String kid) throws Exception {
JwkProvider provider = new UrlJwkProvider(new URI(jwkUrl).toURL());
Jwk jwk = provider.get(kid);
return new RsaVerifier((RSAPublicKey) jwk.getPublicKey());
}
public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
restTemplate = restTemplate2;
}
private static class NoopAuthenticationManager implements AuthenticationManager {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
}
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\java\com\baeldung\openid\oidc\OpenIdConnectFilter.java
| 1
|
请完成以下Java代码
|
public String getTableName()
{
return po.get_TableName();
}
@Override
public int getAD_Table_ID()
{
return po.get_Table_ID();
}
@Override
public String getKeyColumnNameOrNull()
{
return keyColumnName;
}
@Override
public int getRecord_ID()
{
return po.get_ID();
}
@Override
public boolean isSingleKeyRecord()
{
return keyColumnName != null;
}
@Override
public Properties getCtx()
{
return po.getCtx();
}
@Override
public String getTrxName()
{
return po.get_TrxName();
}
@Override
public Evaluatee createEvaluationContext()
{
final Properties privateCtx = Env.deriveCtx(getCtx());
final PO po = getPO();
final POInfo poInfo = po.getPOInfo();
|
for (int i = 0; i < poInfo.getColumnCount(); i++)
{
final Object val;
final int dispType = poInfo.getColumnDisplayType(i);
if (DisplayType.isID(dispType))
{
// make sure we get a 0 instead of a null for foreign keys
val = po.get_ValueAsInt(i);
}
else
{
val = po.get_Value(i);
}
if (val == null)
{
continue;
}
if (val instanceof Integer)
{
Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (Integer)val);
}
else if (val instanceof String)
{
Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (String)val);
}
}
return Evaluatees.ofCtx(privateCtx, Env.WINDOW_None, false);
}
@Override
public boolean hasField(final String columnName)
{
return po.getPOInfo().hasColumnName(columnName);
}
@Override
public Object getFieldValue(final String columnName)
{
return po.get_Value(columnName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\POZoomSource.java
| 1
|
请完成以下Java代码
|
public class Vehicle {
static String defaultValue = "DEFAULT";
private String make = defaultValue;
private String model = defaultValue;
private String color = defaultValue;
private int weight = 0;
private boolean statusNew = true;
public Vehicle() {
super();
}
public Vehicle(String make, String model, String color, int weight, boolean statusNew) {
this.make = make;
|
this.model = model;
this.color = color;
this.weight = weight;
this.statusNew = statusNew;
}
public Vehicle(Vehicle vehicle) {
this(vehicle.make, vehicle.model, vehicle.color, vehicle.weight, vehicle.statusNew);
}
@Override
public String toString() {
return "Vehicle [make=" + make + ", model=" + model + ", color=" + color + ", weight=" + weight + ", statusNew=" + statusNew + "]";
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\Vehicle.java
| 1
|
请完成以下Java代码
|
public class Items {
@GET
@Path("/cookie")
public String readCookieParam(@CookieParam("cookieParamToRead") String cookieParamToRead) {
return "Cookie parameter value is [" + cookieParamToRead + "]";
}
@GET
@Path("/header")
public String readHeaderParam(@HeaderParam("headerParamToRead") String headerParamToRead) {
return "Header parameter value is [" + headerParamToRead + "]";
}
@GET
@Path("/path/{pathParamToRead}")
public String readPathParam(@PathParam("pathParamToRead") String pathParamToRead) {
return "Path parameter value is [" + pathParamToRead + "]";
}
@GET
@Path("/query")
public String readQueryParam(@QueryParam("queryParamToRead") String queryParamToRead) {
return "Query parameter value is [" + queryParamToRead + "]";
}
|
@POST
@Path("/form")
public String readFormParam(@FormParam("formParamToRead") String formParamToRead) {
return "Form parameter value is [" + formParamToRead + "]";
}
@GET
@Path("/matrix")
public String readMatrixParam(@MatrixParam("matrixParamToRead") String matrixParamToRead) {
return "Matrix parameter value is [" + matrixParamToRead + "]";
}
@POST
@Path("/bean/{pathParam}")
public String readBeanParam(@BeanParam ItemParam itemParam) {
return itemParam.toString();
}
}
|
repos\tutorials-master\web-modules\jersey\src\main\java\com\baeldung\jersey\server\Items.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UaaProperties {
private KeyStore keyStore = new KeyStore();
public KeyStore getKeyStore() {
return keyStore;
}
private WebClientConfiguration webClientConfiguration = new WebClientConfiguration();
public WebClientConfiguration getWebClientConfiguration() {
return webClientConfiguration;
}
/**
* Keystore configuration for signing and verifying JWT tokens.
*/
public static class KeyStore {
//name of the keystore in the classpath
private String name = "config/tls/keystore.p12";
//password used to access the key
private String password = "password";
//name of the alias to fetch
private String alias = "selfsigned";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
}
|
public static class WebClientConfiguration {
//validity of the short-lived access token in secs (min: 60), don't make it too long
private int accessTokenValidityInSeconds = 5 * 60;
//validity of the refresh token in secs (defines the duration of "remember me")
private int refreshTokenValidityInSecondsForRememberMe = 7 * 24 * 60 * 60;
private String clientId = "web_app";
private String secret = "changeit";
public int getAccessTokenValidityInSeconds() {
return accessTokenValidityInSeconds;
}
public void setAccessTokenValidityInSeconds(int accessTokenValidityInSeconds) {
this.accessTokenValidityInSeconds = accessTokenValidityInSeconds;
}
public int getRefreshTokenValidityInSecondsForRememberMe() {
return refreshTokenValidityInSecondsForRememberMe;
}
public void setRefreshTokenValidityInSecondsForRememberMe(int refreshTokenValidityInSecondsForRememberMe) {
this.refreshTokenValidityInSecondsForRememberMe = refreshTokenValidityInSecondsForRememberMe;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\uaa\src\main\java\com\baeldung\jhipster\uaa\config\UaaProperties.java
| 2
|
请完成以下Java代码
|
public String[] getActivityIdIn() {
return activityIdIn;
}
@CamundaQueryParam(value="activityIdIn", converter = StringArrayConverter.class)
public void setActivityIdIn(String[] activityIdIn) {
this.activityIdIn = activityIdIn;
}
public String getBusinessKey() {
return businessKey;
}
@CamundaQueryParam(value="businessKey")
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
@CamundaQueryParam(value = "variables", converter = VariableListConverter.class)
public void setVariables(List<VariableQueryParameterDto> variables) {
this.variables = variables;
}
public List<QueryVariableValue> getQueryVariableValues() {
return queryVariableValues;
}
public void initQueryVariableValues(VariableSerializers variableTypes, String dbType) {
queryVariableValues = createQueryVariableValues(variableTypes, variables, dbType);
}
@Override
protected String getOrderByValue(String sortBy) {
return super.getOrderBy();
}
@Override
protected boolean isValidSortByValue(String value) {
return false;
}
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
|
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>();
if (variables == null) {
return values;
}
for (VariableQueryParameterDto variable : variables) {
QueryVariableValue value = new QueryVariableValue(
variable.getName(),
resolveVariableValue(variable.getValue()),
ConditionQueryParameterDto.getQueryOperator(variable.getOperator()),
false);
value.initialize(variableTypes, dbType);
values.add(value);
}
return values;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionQueryDto.java
| 1
|
请完成以下Java代码
|
private I_R_Request createEmptyRequest()
{
final I_R_Request request = requestDAO.createEmptyRequest();
request.setR_RequestType_ID(requestTypeDAO.retrieveDefaultRequestTypeIdOrFirstActive().getRepoId());
final Timestamp date = SystemTime.asDayTimestamp();
request.setDateTrx(date);
request.setStartTime(date);
return request;
}
private I_R_Request createRequestFromBPartner(final I_C_BPartner bpartner)
{
final I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bpartner, I_AD_User.class);
final I_R_Request request = createEmptyRequest();
request.setSalesRep_ID(getAD_User_ID());
request.setC_BPartner_ID(bpartner.getC_BPartner_ID());
if (defaultContact != null)
{
request.setAD_User_ID(defaultContact.getAD_User_ID());
}
return request;
}
private I_R_Request createRequestFromShipment(final I_M_InOut shipment)
{
final I_C_BPartner bPartner = bPartnerDAO.getById(shipment.getC_BPartner_ID());
final I_AD_User defaultContact = Services.get(IBPartnerDAO.class).retrieveDefaultContactOrNull(bPartner, I_AD_User.class);
|
final I_R_Request request = createEmptyRequest();
request.setSalesRep_ID(getAD_User_ID());
request.setC_BPartner_ID(shipment.getC_BPartner_ID());
request.setM_InOut_ID(shipment.getM_InOut_ID());
request.setDateDelivered(shipment.getMovementDate());
if (defaultContact != null)
{
request.setAD_User_ID(defaultContact.getAD_User_ID());
}
return request;
}
private I_R_Request createRequestFromUser(final I_AD_User user)
{
final I_R_Request request = createEmptyRequest();
request.setAD_User_ID(user.getAD_User_ID());
request.setC_BPartner_ID(user.getC_BPartner_ID());
return request;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\request\process\WEBUI_CreateRequest.java
| 1
|
请完成以下Java代码
|
public CaseFileItem getContext() {
return contextRefAttribute.getReferenceTargetElement(this);
}
public void setContext(CaseFileItem context) {
contextRefAttribute.setReferenceTargetElement(this, context);
}
public ConditionExpression getCondition() {
return conditionChild.getChild(this);
}
public void setCondition(ConditionExpression expression) {
conditionChild.setChild(this, expression);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ApplicabilityRule.class, CMMN_ELEMENT_APPLICABILITY_RULE)
.namespaceUri(CMMN11_NS)
.extendsType(CmmnElement.class)
.instanceProvider(new ModelTypeInstanceProvider<ApplicabilityRule>() {
public ApplicabilityRule newInstance(ModelTypeInstanceContext instanceContext) {
|
return new ApplicabilityRuleImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME)
.build();
contextRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CONTEXT_REF)
.idAttributeReference(CaseFileItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
conditionChild = sequenceBuilder.element(ConditionExpression.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\ApplicabilityRuleImpl.java
| 1
|
请完成以下Java代码
|
protected void closeSpecific()
{
currentFile = null;
currentFiles = null;
}
private FileInputStream currentStream;
@Override
public InputStream connectNext(final boolean lastWasSuccess)
{
if (currentStream != null)
{
try
{
// note: close alone didn't suffice (at least in WinXP when
// running in eclipse debug session)
currentStream.getFD().sync();
currentStream.close();
}
catch (IOException e)
{
throw new AdempiereException(e);
}
}
if (lastWasSuccess && currentFile != null)
{
final String archiveFolder = (String)getCurrentParams().get(
IInboundProcessorBL.ARCHIVE_FOLDER).getValue();
inboundProcessorBL.moveToArchive(currentFile, archiveFolder);
}
if (currentFiles.hasNext())
{
currentFile = currentFiles.next();
|
try
{
currentStream = new FileInputStream(currentFile);
return currentStream;
}
catch (FileNotFoundException e)
{
ConfigException.throwNew(ConfigException.FILE_ACCESS_FAILED_2P,
currentFile.getAbsolutePath(), e.getMessage());
}
}
return null;
}
@Override
public List<Parameter> getParameters()
{
final List<Parameter> result = new ArrayList<Parameter>();
result.add(new Parameter(IInboundProcessorBL.LOCAL_FOLDER,
"Import-Ordner", "Name of the folder to import from",
DisplayType.FilePath, 1));
result.add(new Parameter(IInboundProcessorBL.ARCHIVE_FOLDER,
"Archiv-Ordner",
"Name of the folder to move files to after import",
DisplayType.FilePath, 2));
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\spi\impl\FileImporter.java
| 1
|
请完成以下Java代码
|
public ListenableFuture<Rpc> findRpcByIdAsync(TenantId tenantId, RpcId rpcId) {
log.trace("Executing findRpcByIdAsync, tenantId [{}], rpcId: [{}]", tenantId, rpcId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validateId(rpcId, id -> INCORRECT_RPC_ID + id);
return rpcDao.findByIdAsync(tenantId, rpcId.getId());
}
@Override
public PageData<Rpc> findAllByDeviceIdAndStatus(TenantId tenantId, DeviceId deviceId, RpcStatus rpcStatus, PageLink pageLink) {
log.trace("Executing findAllByDeviceIdAndStatus, tenantId [{}], deviceId [{}], rpcStatus [{}], pageLink [{}]", tenantId, deviceId, rpcStatus, pageLink);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validatePageLink(pageLink);
return rpcDao.findAllByDeviceIdAndStatus(tenantId, deviceId, rpcStatus, pageLink);
}
@Override
public PageData<Rpc> findAllByDeviceId(TenantId tenantId, DeviceId deviceId, PageLink pageLink) {
log.trace("Executing findAllByDeviceIdAndStatus, tenantId [{}], deviceId [{}], pageLink [{}]", tenantId, deviceId, pageLink);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
validatePageLink(pageLink);
return rpcDao.findAllByDeviceId(tenantId, deviceId, pageLink);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findById(tenantId, new RpcId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(findRpcByIdAsync(tenantId, new RpcId(entityId.getId())))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.RPC;
|
}
private final PaginatedRemover<TenantId, Rpc> tenantRpcRemover = new PaginatedRemover<>() {
@Override
protected PageData<Rpc> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return rpcDao.findAllRpcByTenantId(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, Rpc entity) {
deleteRpc(tenantId, entity.getId());
}
};
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\rpc\BaseRpcService.java
| 1
|
请完成以下Java代码
|
public LocatorId getSinglePickFromLocatorIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getPickFromLocatorId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
public Optional<LocatorInfo> getSinglePickFromLocator()
{
return lines.stream()
.map(DistributionJobLine::getPickFromLocator)
.distinct()
.collect(GuavaCollectors.singleElementOrEmpty());
}
@Nullable
public LocatorId getSingleDropToLocatorIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getDropToLocatorId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
public Optional<LocatorInfo> getSingleDropToLocator()
{
return lines.stream()
.map(DistributionJobLine::getDropToLocator)
.distinct()
.collect(GuavaCollectors.singleElementOrEmpty());
|
}
@Nullable
public ProductId getSingleProductIdOrNull()
{
return lines.stream()
.map(DistributionJobLine::getProductId)
.distinct()
.collect(GuavaCollectors.singleElementOrNull());
}
@Nullable
public Quantity getSingleUnitQuantityOrNull()
{
final MixedQuantity qty = lines.stream()
.map(DistributionJobLine::getQtyToMove)
.distinct()
.collect(MixedQuantity.collectAndSum());
return qty.toNoneOrSingleValue().orElse(null);
}
public Optional<DistributionJobLineId> getNextEligiblePickFromLineId(@NonNull final ProductId productId)
{
return lines.stream()
.filter(line -> ProductId.equals(line.getProductId(), productId))
.filter(DistributionJobLine::isEligibleForPicking)
.map(DistributionJobLine::getId)
.findFirst();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\model\DistributionJob.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class Application {
/**
* Name scheme how Immutables generates implementations from interface/class definitions.
*/
public static final String IMMUTABLE_IMPLEMENTATION_CLASS = "%s.Immutable%s";
@Configuration
static class ImmutablesJdbcConfiguration extends AbstractJdbcConfiguration {
private final ResourceLoader resourceLoader;
public ImmutablesJdbcConfiguration(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* {@link JdbcConverter} that redirects entities to be instantiated towards the implementation. See
* {@link #IMMUTABLE_IMPLEMENTATION_CLASS} and
* {@link #getImplementationEntity(JdbcMappingContext, RelationalPersistentEntity)}.
*
* @param mappingContext
* @param operations
* @param relationResolver
* @param conversions
* @param dialect
* @return
*/
@Override
public JdbcConverter jdbcConverter(JdbcMappingContext mappingContext, NamedParameterJdbcOperations operations,
@Lazy RelationResolver relationResolver, JdbcCustomConversions conversions, Dialect dialect) {
var jdbcTypeFactory = new DefaultJdbcTypeFactory(operations.getJdbcOperations());
return new MappingJdbcConverter(mappingContext, relationResolver, conversions, jdbcTypeFactory) {
@Override
@SuppressWarnings("all")
protected <S> S readAggregate(ConversionContext context, RowDocumentAccessor documentAccessor,
TypeInformation<? extends S> typeHint) {
RelationalPersistentEntity<?> implementationEntity = getImplementationEntity(mappingContext,
mappingContext.getRequiredPersistentEntity(typeHint));
return (S) super.readAggregate(context, documentAccessor, implementationEntity.getTypeInformation());
}
};
}
|
/**
* Returns if the entity passed as an argument is an interface the implementation provided by Immutable is provided
* instead. In all other cases the entity passed as an argument is returned.
*/
@SuppressWarnings("unchecked")
private <T> RelationalPersistentEntity<T> getImplementationEntity(JdbcMappingContext mappingContext,
RelationalPersistentEntity<T> entity) {
Class<T> type = entity.getType();
if (type.isInterface()) {
var immutableClass = String.format(IMMUTABLE_IMPLEMENTATION_CLASS, type.getPackageName(), type.getSimpleName());
if (ClassUtils.isPresent(immutableClass, resourceLoader.getClassLoader())) {
return (RelationalPersistentEntity<T>) mappingContext
.getPersistentEntity(ClassUtils.resolveClassName(immutableClass, resourceLoader.getClassLoader()));
}
}
return entity;
}
}
}
|
repos\spring-data-examples-main\jdbc\immutables\src\main\java\example\springdata\jdbc\immutables\Application.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void increaseCount(String request, int status) {
increaseMainMetric(request, status);
increaseStatusMetric(status);
updateTimeMap(status);
}
public Map<String, Map<Integer, Integer>> getFullMetric() {
return metricMap;
}
public Map<Integer, Integer> getStatusMetric() {
return statusMetric;
}
public Object[][] getGraphData() {
final int colCount = statusMetric.keySet().size() + 1;
final Set<Integer> allStatus = statusMetric.keySet();
final int rowCount = timeMap.keySet().size() + 1;
final Object[][] result = new Object[rowCount][colCount];
result[0][0] = "Time";
int j = 1;
for (final int status : allStatus) {
result[0][j] = status;
j++;
}
int i = 1;
Map<Integer, Integer> tempMap;
for (final Entry<String, Map<Integer, Integer>> entry : timeMap.entrySet()) {
result[i][0] = entry.getKey();
tempMap = entry.getValue();
for (j = 1; j < colCount; j++) {
result[i][j] = tempMap.get((Integer) result[0][j]);
if (result[i][j] == null) {
result[i][j] = 0;
}
}
i++;
}
for (int k = 1; k < result[0].length; k++) {
result[0][k] = result[0][k].toString();
}
return result;
}
private void increaseMainMetric(String request, int status) {
Map<Integer, Integer> statusMap = metricMap.get(request);
if (statusMap == null) {
statusMap = new ConcurrentHashMap<>();
}
Integer count = statusMap.get(status);
if (count == null) {
count = 1;
} else {
count++;
|
}
statusMap.put(status, count);
metricMap.put(request, statusMap);
}
private void increaseStatusMetric(int status) {
statusMetric.merge(status, 1, Integer::sum);
}
private void updateTimeMap(int status) {
final String time = DATE_FORMAT.format(new Date());
Map<Integer, Integer> statusMap = timeMap.get(time);
if (statusMap == null) {
statusMap = new ConcurrentHashMap<>();
}
Integer count = statusMap.get(status);
if (count == null) {
count = 1;
} else {
count++;
}
statusMap.put(status, count);
timeMap.put(time, statusMap);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-actuator\src\main\java\com\baeldung\metrics\service\InMemoryMetricService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void redisLock3(int i) {
RedisLock3 redisLock3 = new RedisLock3(redisTemplate, "redisLock:" + i % 10, 5 * 60, 50000);
try {
long now = System.currentTimeMillis();
if (redisLock3.tryLock()) {
logger.info("=" + (System.currentTimeMillis() - now));
// TODO 获取到锁要执行的代码块
logger.info("j:" + j++);
} else {
logger.info("k:" + k++);
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock3.unlock();
}
}
public String set(final String key, final String value, final String nxxx, final String expx,
|
final long seconds) {
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
return redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
String command = Command.SET.name();
byte[] keys = SafeEncoder.encode(key);
byte[] values = SafeEncoder.encode(value);
byte[] nxs = SafeEncoder.encode("NX");
byte[] exs = SafeEncoder.encode("EX");
byte[] secondsByte = SafeEncoder.encode(String.valueOf(seconds));
Object result = connection.execute(command, keys, values, nxs, exs, secondsByte);
if (result == null) {
return null;
}
return new String((byte[]) result);
}
});
}
}
|
repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\service\PersonService.java
| 2
|
请完成以下Java代码
|
public class ExecuteShellUtil {
private Vector<String> stdout;
Session session;
public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
|
stdout.add(line);
System.out.println(line);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public void close(){
if (session != null) {
session.disconnect();
}
}
public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\util\ExecuteShellUtil.java
| 1
|
请完成以下Java代码
|
public void close() throws Exception
{
removeTemporaryCustomizer(connectionCustomizer);
}
};
}
private void removeTemporaryCustomizer(@NonNull final ITemporaryConnectionCustomizer dlmConnectionCustomizer)
{
final boolean wasInTheList = temporaryCustomizers.get().remove(dlmConnectionCustomizer);
Check.errorIf(!wasInTheList, "ITemporaryConnectionCustomizer={} was not in the thread-local list of temperary customizers; this={}", dlmConnectionCustomizer, this);
}
@Override
public void fireRegisteredCustomizers(@NonNull final Connection c)
{
getRegisteredCustomizers().forEach(
customizer ->
{
invokeIfNotYetInvoked(customizer, c);
});
}
@Override
public String toString()
{
return "ConnectionCustomizerService [permanentCustomizers=" + permanentCustomizers + ", (thread-local-)temporaryCustomizers=" + temporaryCustomizers.get() + ", (thread-local-)currentlyInvokedCustomizers=" + currentlyInvokedCustomizers + "]";
}
private List<IConnectionCustomizer> getRegisteredCustomizers()
{
return new ImmutableList.Builder<IConnectionCustomizer>()
.addAll(permanentCustomizers)
|
.addAll(temporaryCustomizers.get())
.build();
}
/**
* Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish.
* So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}.
*
* @param customizer
* @param connection
*/
private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection)
{
try
{
if (currentlyInvokedCustomizers.get().add(customizer))
{
customizer.customizeConnection(connection);
currentlyInvokedCustomizers.get().remove(customizer);
}
}
finally
{
currentlyInvokedCustomizers.get().remove(customizer);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getVersionGt() {
return versionGt;
}
public Integer getVersionGte() {
return versionGte;
}
public Integer getVersionLt() {
return versionLt;
}
public Integer getVersionLte() {
return versionLte;
}
public boolean isLatest() {
return latest;
}
public String getCategory() {
return category;
}
public String getCategoryLike() {
return categoryLike;
}
public String getResourceName() {
|
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
void setAuthenticationManagerPostProcessor(
Map<String, ObjectPostProcessor<ReactiveAuthenticationManager>> postProcessors) {
if (postProcessors.size() == 1) {
this.postProcessor = postProcessors.values().iterator().next();
}
this.postProcessor = postProcessors.get("rSocketAuthenticationManagerPostProcessor");
}
@Bean(name = RSOCKET_SECURITY_BEAN_NAME)
@Scope("prototype")
RSocketSecurity rsocketSecurity(ApplicationContext context) {
RSocketSecurity security = new RSocketSecurity().authenticationManager(authenticationManager());
security.setApplicationContext(context);
return security;
}
private ReactiveAuthenticationManager authenticationManager() {
|
if (this.authenticationManager != null) {
return this.authenticationManager;
}
if (this.reactiveUserDetailsService != null) {
UserDetailsRepositoryReactiveAuthenticationManager manager = new UserDetailsRepositoryReactiveAuthenticationManager(
this.reactiveUserDetailsService);
if (this.passwordEncoder != null) {
manager.setPasswordEncoder(this.passwordEncoder);
}
return this.postProcessor.postProcess(manager);
}
return null;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\rsocket\RSocketSecurityConfiguration.java
| 2
|
请完成以下Java代码
|
public static boolean isAvailableForBPartnerId(@NonNull final I_M_PickingSlot pickingSlot, @Nullable final BPartnerId bpartnerId)
{
//
// General use Picking Slot, accept it right away
if (isAvailableForAnyBPartner(pickingSlot))
{
return true;
}
//
// Check BPartner
final BPartnerId pickingSlotBPartnerId = extractBPartnerId(pickingSlot);
// Any BPartner Picking Slot
if (pickingSlotBPartnerId == null)
{
// accept any partner
}
// Picking slot specific for BP
else
{
if (bpartnerId == null)
{
// no particular partner was requested, (i.e. M_HU_PI_Item_Product does not have a BP set), accept it
}
else if (BPartnerId.equals(bpartnerId, pickingSlotBPartnerId))
{
// same BP, accept it
}
|
else
{
// not same BP, don't accept it
return false;
}
}
// If we reach this point, we passed all validation rules
return true;
}
@Nullable
private static BPartnerId extractBPartnerId(final @NonNull I_M_PickingSlot pickingSlot)
{
return BPartnerId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotUtils.java
| 1
|
请完成以下Java代码
|
public void evictFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
MutableAcl acl = getFromCache(pk);
if (acl != null) {
this.cache.evict(acl.getId());
this.cache.evict(acl.getObjectIdentity());
}
}
@Override
public void evictFromCache(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
MutableAcl acl = getFromCache(objectIdentity);
if (acl != null) {
this.cache.evict(acl.getId());
this.cache.evict(acl.getObjectIdentity());
}
}
@Override
public MutableAcl getFromCache(ObjectIdentity objectIdentity) {
Assert.notNull(objectIdentity, "ObjectIdentity required");
return getFromCache((Object) objectIdentity);
}
@Override
public MutableAcl getFromCache(Serializable pk) {
Assert.notNull(pk, "Primary key (identifier) required");
return getFromCache((Object) pk);
}
@Override
public void putInCache(MutableAcl acl) {
Assert.notNull(acl, "Acl required");
|
Assert.notNull(acl.getObjectIdentity(), "ObjectIdentity required");
Assert.notNull(acl.getId(), "ID required");
if ((acl.getParentAcl() != null) && (acl.getParentAcl() instanceof MutableAcl)) {
putInCache((MutableAcl) acl.getParentAcl());
}
this.cache.put(acl.getObjectIdentity(), acl);
this.cache.put(acl.getId(), acl);
}
private MutableAcl getFromCache(Object key) {
Cache.ValueWrapper element = this.cache.get(key);
if (element == null) {
return null;
}
return initializeTransientFields((MutableAcl) element.get());
}
private MutableAcl initializeTransientFields(MutableAcl value) {
if (value instanceof AclImpl) {
FieldUtils.setProtectedFieldValue("aclAuthorizationStrategy", value, this.aclAuthorizationStrategy);
FieldUtils.setProtectedFieldValue("permissionGrantingStrategy", value, this.permissionGrantingStrategy);
}
if (value.getParentAcl() != null) {
initializeTransientFields((MutableAcl) value.getParentAcl());
}
return value;
}
@Override
public void clearCache() {
this.cache.clear();
}
}
|
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\SpringCacheBasedAclCache.java
| 1
|
请完成以下Java代码
|
public void mouseReleased(MouseEvent me)
{
if (startModel != null && moved)
{
Point p = me.getPoint();
JList<ListItem> endList = yesList;
DefaultListModel<ListItem> endModel = yesModel;
if (me.getComponent() == yesList)
{
if (!yesList.contains (p))
{
endList = noList;
endModel = noModel;
}
}
else
{
if (noList.contains (p))
{
setCursor(Cursor.getDefaultCursor());
moved = false;
return; // move within noList
}
p = SwingUtilities.convertPoint (noList, p, yesList);
}
int index = endList.locationToIndex(p);
|
if (index > -1) // && endList.getCellBounds(index, index).contains(p))
{
startModel.removeElement(selObject);
endModel.add(index, selObject);
//
startList.clearSelection();
endList.clearSelection();
endList.setSelectedValue(selObject, true);
//
setIsChanged(true);
}
}
startList = null;
startModel = null;
selObject = null;
moved = false;
setCursor(Cursor.getDefaultCursor());
} // mouseReleased
}
} // VSortTab
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VSortTab.java
| 1
|
请完成以下Java代码
|
public AbstractDataAssociation createDataInputAssociation(BpmnParse bpmnParse, DataAssociation dataAssociationElement) {
if (dataAssociationElement.getAssignments().isEmpty()) {
return new MessageImplicitDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
} else {
SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(
dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
for (org.flowable.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (StringUtils.isNotEmpty(assignmentElement.getFrom()) && StringUtils.isNotEmpty(assignmentElement.getTo())) {
Expression from = bpmnParse.getExpressionManager().createExpression(assignmentElement.getFrom());
Expression to = bpmnParse.getExpressionManager().createExpression(assignmentElement.getTo());
Assignment assignment = new Assignment(from, to);
dataAssociation.addAssignment(assignment);
}
}
|
return dataAssociation;
}
}
public AbstractDataAssociation createDataOutputAssociation(BpmnParse bpmnParse, DataAssociation dataAssociationElement) {
if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) {
return new MessageImplicitDataOutputAssociation(dataAssociationElement.getTargetRef(), dataAssociationElement.getSourceRef());
} else {
Expression transformation = bpmnParse.getExpressionManager().createExpression(dataAssociationElement.getTransformation());
AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(null, dataAssociationElement.getTargetRef(), transformation);
return dataOutputAssociation;
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\AbstractExternalInvocationBpmnParseHandler.java
| 1
|
请完成以下Java代码
|
public void setQtyPromised (java.math.BigDecimal QtyPromised)
{
set_Value (COLUMNNAME_QtyPromised, QtyPromised);
}
/** Get Zusagbar.
@return Zusagbar */
@Override
public java.math.BigDecimal getQtyPromised ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyPromised);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
*/
|
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponseLineQty.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected boolean hasExcludingConditions() {
return super.hasExcludingConditions() || CompareUtil.elementIsNotContainedInArray(id, ids);
}
//results ////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionCountByQueryCriteria(this);
}
return 0;
}
@Override
public List<CaseDefinition> executeList(CommandContext commandContext, Page page) {
if (isCmmnEnabled(commandContext)) {
checkQueryOk();
return commandContext
.getCaseDefinitionManager()
.findCaseDefinitionsByQueryCriteria(this, page);
}
return Collections.emptyList();
}
@Override
public void checkQueryOk() {
super.checkQueryOk();
// latest() makes only sense when used with key() or keyLike()
if (latest && ( (id != null) || (name != null) || (nameLike != null) || (version != null) || (deploymentId != null) ) ){
throw new NotValidException("Calling latest() can only be used in combination with key(String) and keyLike(String)");
}
}
private boolean isCmmnEnabled(CommandContext commandContext) {
return commandContext
.getProcessEngineConfiguration()
.isCmmnEnabled();
}
// getters ////////////////////////////////////////////
public String getId() {
return id;
}
public String[] getIds() {
return ids;
}
public String getCategory() {
return category;
}
|
public String getCategoryLike() {
return categoryLike;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getDeploymentId() {
return deploymentId;
}
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
public boolean isLatest() {
return latest;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\repository\CaseDefinitionQueryImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PPOrderBOMLineId implements RepoIdAware
{
@JsonCreator
public static PPOrderBOMLineId ofRepoId(final int repoId)
{
return new PPOrderBOMLineId(repoId);
}
@Nullable
public static PPOrderBOMLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PPOrderBOMLineId(repoId) : null;
}
public static Optional<PPOrderBOMLineId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final PPOrderBOMLineId id)
{
return id != null ? id.getRepoId() : -1;
}
int repoId;
|
private PPOrderBOMLineId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_BOMLine_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final PPOrderBOMLineId id1, @Nullable final PPOrderBOMLineId id2)
{
return Objects.equals(id1, id2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\eevolution\api\PPOrderBOMLineId.java
| 2
|
请完成以下Java代码
|
class OrderPayScheduleCreateCommand
{
@NonNull private final ITrxManager trxManager = Services.get(ITrxManager.class);
@NonNull private final OrderPayScheduleService orderPayScheduleService;
@NonNull private final PaymentTermService paymentTermService;
@NonNull private final I_C_Order orderRecord;
public void execute()
{
trxManager.runInThreadInheritedTrx(this::execute0);
}
private void execute0()
{
orderPayScheduleService.deleteByOrderId(OrderId.ofRepoId(orderRecord.getC_Order_ID()));
final OrderSchedulingContext context = orderPayScheduleService.extractContext(orderRecord);
if (context == null)
{
return; // Nothing to schedule
}
if (!context.getPaymentTerm().isComplex() )
{
return; // Nothing to schedule
}
final List<PaymentTermBreak> termBreaks = context.getPaymentTerm().getSortedBreaks();
final ImmutableList.Builder<OrderPayScheduleCreateRequest.Line> linesBuilder = ImmutableList.builder();
Money totalScheduledAmount = Money.zero(context.getGrandTotal().getCurrencyId());
for (int i = 0; i < termBreaks.size() - 1; i++)
{
final PaymentTermBreak termBreak = termBreaks.get(i);
// Calculate amount by percent
final Money lineDueAmount = context.getGrandTotal().multiply(termBreak.getPercent(), context.getPrecision());
final OrderPayScheduleCreateRequest.Line line = toOrderPayScheduleCreateRequestLine(
context,
termBreak,
lineDueAmount
);
linesBuilder.add(line);
totalScheduledAmount = totalScheduledAmount.add(lineDueAmount);
|
}
final PaymentTermBreak lastTermBreak = termBreaks.get(termBreaks.size() - 1);
// Calculate the exact amount needed for the last line: Grand Total - accumulated total
final Money lastLineDueAmount = context.getGrandTotal().subtract(totalScheduledAmount);
final OrderPayScheduleCreateRequest.Line lastLine = toOrderPayScheduleCreateRequestLine(
context,
lastTermBreak,
lastLineDueAmount
);
linesBuilder.add(lastLine);
final OrderPayScheduleCreateRequest request = OrderPayScheduleCreateRequest.builder()
.orderId(context.getOrderId())
.lines(linesBuilder.build())
.build();
orderPayScheduleService.create(request);
}
private static OrderPayScheduleCreateRequest.Line toOrderPayScheduleCreateRequestLine(
@NonNull final OrderSchedulingContext context,
@NonNull final PaymentTermBreak termBreak,
@NonNull final Money dueAmount)
{
final DueDateAndStatus result = context.computeDueDate(termBreak);
return OrderPayScheduleCreateRequest.Line.builder()
.dueDate(result.getDueDate())
.dueAmount(dueAmount)
.paymentTermBreakId(termBreak.getId())
.referenceDateType(termBreak.getReferenceDateType())
.percent(termBreak.getPercent())
.orderPayScheduleStatus(result.getStatus())
.offsetDays(termBreak.getOffsetDays())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleCreateCommand.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LDAPConfigurator extends IdmEngineConfigurator {
protected LDAPConfiguration ldapConfiguration;
@Override
public void beforeInit(AbstractEngineConfiguration engineConfiguration) {
// Nothing to do
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
this.idmEngineConfiguration = new LdapIdmEngineConfiguration();
if (ldapConfiguration == null) {
throw new FlowableException("ldapConfiguration is not set");
}
LDAPGroupCache ldapGroupCache = null;
if (ldapConfiguration.getGroupCacheSize() > 0) {
ldapGroupCache = new LDAPGroupCache(ldapConfiguration.getGroupCacheSize(),
ldapConfiguration.getGroupCacheExpirationTime(), engineConfiguration.getClock());
if (ldapConfiguration.getGroupCacheListener() != null) {
ldapGroupCache.setLdapCacheListener(ldapConfiguration.getGroupCacheListener());
}
}
super.configure(engineConfiguration);
getIdmEngineConfiguration(engineConfiguration)
.setIdmIdentityService(new LDAPIdentityServiceImpl(ldapConfiguration, ldapGroupCache, idmEngineConfiguration));
|
}
// Getters and Setters //////////////////////////////////////////////////
public LDAPConfiguration getLdapConfiguration() {
return ldapConfiguration;
}
public void setLdapConfiguration(LDAPConfiguration ldapConfiguration) {
this.ldapConfiguration = ldapConfiguration;
}
protected static IdmEngineConfiguration getIdmEngineConfiguration(AbstractEngineConfiguration engineConfiguration) {
return (IdmEngineConfiguration) engineConfiguration.getEngineConfigurations().get(EngineConfigurationConstants.KEY_IDM_ENGINE_CONFIG);
}
}
|
repos\flowable-engine-main\modules\flowable-ldap-configurator\src\main\java\org\flowable\ldap\LDAPConfigurator.java
| 2
|
请完成以下Java代码
|
public java.lang.String getClient_Id()
{
return get_ValueAsString(COLUMNNAME_Client_Id);
}
@Override
public void setClient_Secret (final @Nullable java.lang.String Client_Secret)
{
set_Value (COLUMNNAME_Client_Secret, Client_Secret);
}
@Override
public java.lang.String getClient_Secret()
{
return get_ValueAsString(COLUMNNAME_Client_Secret);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
|
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setServiceLevel (final @Nullable java.lang.String ServiceLevel)
{
set_Value (COLUMNNAME_ServiceLevel, ServiceLevel);
}
@Override
public java.lang.String getServiceLevel()
{
return get_ValueAsString(COLUMNNAME_ServiceLevel);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Config.java
| 1
|
请完成以下Java代码
|
public PayPalConfig getConfig()
{
return payPalConfigProvider.getConfig();
}
private <T> PayPalClientResponse<T, PayPalErrorResponse> executeRequest(
@NonNull final HttpRequest<T> request,
@NonNull final PayPalClientExecutionContext context)
{
final PayPalCreateLogRequestBuilder log = PayPalCreateLogRequest.builder()
.paymentReservationId(context.getPaymentReservationId())
.paymentReservationCaptureId(context.getPaymentReservationCaptureId())
//
.salesOrderId(context.getSalesOrderId())
.salesInvoiceId(context.getSalesInvoiceId())
.paymentId(context.getPaymentId())
//
.internalPayPalOrderId(context.getInternalPayPalOrderId());
try
{
log.request(request);
final PayPalHttpClient httpClient = createPayPalHttpClient(getConfig());
final HttpResponse<T> response = httpClient.execute(request);
log.response(response);
return PayPalClientResponse.ofResult(response.result());
}
catch (final HttpException httpException)
{
log.response(httpException);
final String errorAsJson = httpException.getMessage();
try
{
final PayPalErrorResponse error = JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(errorAsJson, PayPalErrorResponse.class);
return PayPalClientResponse.ofError(error, httpException);
}
catch (final Exception jsonException)
{
throw AdempiereException.wrapIfNeeded(httpException)
.suppressing(jsonException);
}
}
|
catch (final IOException ex)
{
log.response(ex);
throw AdempiereException.wrapIfNeeded(ex);
}
finally
{
logsRepo.log(log.build());
}
}
public Capture captureOrder(
@NonNull final PayPalOrderAuthorizationId authId,
@NonNull final Amount amount,
@Nullable final Boolean finalCapture,
@NonNull final PayPalClientExecutionContext context)
{
final AuthorizationsCaptureRequest request = new AuthorizationsCaptureRequest(authId.getAsString())
.requestBody(new CaptureRequest()
.amount(new com.paypal.payments.Money()
.currencyCode(amount.getCurrencyCode().toThreeLetterCode())
.value(amount.getAsBigDecimal().toPlainString()))
.finalCapture(finalCapture));
return executeRequest(request, context)
.getResult();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalClientService.java
| 1
|
请完成以下Java代码
|
public String toString()
{
final ToStringHelper helper = MoreObjects.toStringHelper(this)
.omitNullValues()
.add("documentPath", documentPath)
.add("fieldName", fieldName);
if (valueSet)
{
helper.add("value", value == null ? "<NULL>" : value);
}
return helper.toString();
}
@Override
public DocumentPath getDocumentPath()
{
return documentPath;
}
@Override
public String getFieldName()
{
return fieldName;
}
|
@Override
public DocumentFieldWidgetType getWidgetType()
{
return widgetType;
}
@Override
public boolean isValueSet()
{
return valueSet;
}
@Override
public Object getValue()
{
return value;
}
public MutableDocumentFieldChangedEvent setValue(final Object value)
{
this.value = value;
valueSet = true;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\MutableDocumentFieldChangedEvent.java
| 1
|
请完成以下Java代码
|
public Object getOperand1()
{
return operand1;
}
/**
* @return {@link CtxName} or {@link String}; never returns null
*/
public Object getOperand2()
{
return operand2;
}
/**
* @return operator; never returns null
*/
public String getOperator()
|
{
return operator;
}
@Override
public String toString()
{
return getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return getExpressionString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicTuple.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
final class ShipmentCandidateRowsRepository
{
private final IShipmentScheduleBL shipmentScheduleBL;
private final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class);
private final LookupDataSource salesOrdersLookup;
private final LookupDataSource customersLookup;
private final LookupDataSource warehousesLookup;
private final LookupDataSource productsLookup;
private final LookupDataSource asiLookup;
private final LookupDataSource catchUOMsLookup;
@Builder
private ShipmentCandidateRowsRepository(
@NonNull final IShipmentScheduleBL shipmentScheduleBL,
@NonNull final LookupDataSourceFactory lookupDataSourceFactory)
{
this.shipmentScheduleBL = shipmentScheduleBL;
salesOrdersLookup = lookupDataSourceFactory.searchInTableLookup(I_C_Order.Table_Name);
customersLookup = lookupDataSourceFactory.searchInTableLookup(I_C_BPartner.Table_Name);
warehousesLookup = lookupDataSourceFactory.searchInTableLookup(I_M_Warehouse.Table_Name);
productsLookup = lookupDataSourceFactory.searchInTableLookup(I_M_Product.Table_Name);
|
asiLookup = lookupDataSourceFactory.productAttributes();
catchUOMsLookup = lookupDataSourceFactory.searchInTableLookup(I_C_UOM.Table_Name);
}
public ShipmentCandidateRows getByShipmentScheduleIds(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
return ShipmentCandidateRowsLoader.builder()
.shipmentScheduleBL(shipmentScheduleBL)
.shipmentScheduleEffectiveBL(shipmentScheduleEffectiveBL)
.salesOrdersLookup(salesOrdersLookup)
.customersLookup(customersLookup)
.warehousesLookup(warehousesLookup)
.productsLookup(productsLookup)
.asiLookup(asiLookup)
.catchUOMsLookup(catchUOMsLookup)
//
.shipmentScheduleIds(shipmentScheduleIds)
//
.load();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRowsRepository.java
| 2
|
请完成以下Java代码
|
public class TestObject {
private int dataPointOne;
private int dataPointTwo;
public TestObject() {
dataPointOne = 10;
}
public int getDataPointOne() {
return dataPointOne;
}
public void setDataPointOne(int dataPointOne) {
this.dataPointOne = dataPointOne;
|
}
public int getDataPointTwo() {
return dataPointTwo;
}
public void setDataPointTwo(int dataPointTwo) {
this.dataPointTwo = dataPointTwo;
}
@Override
public String toString() {
return "TestObject{" + "dataPointOne=" + dataPointOne + ", dataPointTwo=" + dataPointTwo + '}';
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-basic-4\src\main\java\com\baeldung\concurrent\futurevscompletablefuturevsrxjava\TestObject.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
|
}
public TimePeriod getPeriod() {
return period;
}
public void setPeriod(TimePeriod period) {
this.period = period;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
}
|
repos\piggymetrics-master\account-service\src\main\java\com\piggymetrics\account\domain\Item.java
| 2
|
请完成以下Java代码
|
public TaskListener getTimeoutTaskListener(String timeoutId) {
return timeoutTaskListeners.get(timeoutId);
}
public void addTaskListener(String eventName, TaskListener taskListener) {
CollectionUtil.addToMapOfLists(taskListeners, eventName, taskListener);
// re-calculate combined map to ensure order of listener execution
populateAllTaskListeners();
}
public void addBuiltInTaskListener(String eventName, TaskListener taskListener) {
CollectionUtil.addToMapOfLists(builtinTaskListeners, eventName, taskListener);
// re-calculate combined map to ensure order of listener execution
populateAllTaskListeners();
}
public void addTimeoutTaskListener(String timeoutId, TaskListener taskListener) {
timeoutTaskListeners.put(timeoutId, taskListener);
}
public FormDefinition getFormDefinition() {
return formDefinition;
}
public void setFormDefinition(FormDefinition formDefinition) {
this.formDefinition = formDefinition;
}
public Expression getFormKey() {
return formDefinition.getFormKey();
}
public void setFormKey(Expression formKey) {
this.formDefinition.setFormKey(formKey);
}
public Expression getCamundaFormDefinitionKey() {
return formDefinition.getCamundaFormDefinitionKey();
}
|
public String getCamundaFormDefinitionBinding() {
return formDefinition.getCamundaFormDefinitionBinding();
}
public Expression getCamundaFormDefinitionVersion() {
return formDefinition.getCamundaFormDefinitionVersion();
}
// helper methods ///////////////////////////////////////////////////////////
protected void populateAllTaskListeners() {
// reset allTaskListeners to build it from zero
allTaskListeners = new HashMap<>();
// ensure builtinTaskListeners are executed before regular taskListeners
CollectionUtil.mergeMapsOfLists(allTaskListeners, builtinTaskListeners);
CollectionUtil.mergeMapsOfLists(allTaskListeners, taskListeners);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\task\TaskDefinition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Vehicle addVehicle(String vin, Integer year, String make, String model, String trim, Location location) {
Optional<Vehicle> existingVehicle = this.inventoryRepository.findById(vin);
if (existingVehicle.isPresent()) {
Map<String, Object> params = new HashMap<>();
params.put("vin", vin);
throw new VehicleAlreadyPresentException("Failed to add vehicle. Vehicle with vin already present.", params);
}
Vehicle vehicle = Vehicle.builder()
.vin(vin)
.year(year)
.make(make)
.model(model)
.location(location)
.trim(trim)
.build();
this.locationRepository.save(location);
return this.inventoryRepository.save(vehicle);
}
public List<Vehicle> searchAll() {
return this.inventoryRepository.findAll();
}
|
public List<Vehicle> searchByLocation(String zipcode) {
if (StringUtils.hasText(zipcode) || zipcode.length() != 5) {
throw new InvalidInputException("Invalid zipcode " + zipcode + " provided.");
}
return this.locationRepository.findById(zipcode)
.map(Location::getVehicles)
.orElse(new ArrayList<>());
}
public Vehicle searchByVin(String vin) {
return this.inventoryRepository.findById(vin)
.orElseThrow(() -> new VehicleNotFoundException("Vehicle with vin: " + vin + " not found."));
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql\src\main\java\com\baeldung\graphql\error\handling\service\InventoryService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class AD_Menu
{
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_DELETE })
public void logSqlMigrationContextInfo(final I_AD_Menu record)
{
if (MigrationScriptFileLoggerHolder.isDisabled())
{
return;
}
MigrationScriptFileLoggerHolder.logComment("Name: " + record.getName());
final String action = record.getAction();
MigrationScriptFileLoggerHolder.logComment("Action Type: " + action);
if (X_AD_Menu.ACTION_Window.equals(action))
{
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(record.getAD_Window_ID());
if (adWindowId != null)
{
final ADWindowName windowName = Names.ADWindowName_Loader.retrieve(adWindowId);
MigrationScriptFileLoggerHolder.logComment("Window: " + windowName.toShortString());
}
|
}
else if (X_AD_Menu.ACTION_Process.equals(action))
{
final AdProcessId adProcessId = AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID());
if (adProcessId != null)
{
final ADProcessName processName = Names.ADProcessName_Loader.retrieve(adProcessId);
MigrationScriptFileLoggerHolder.logComment("Process: " + processName.toShortString());
}
}
else if (X_AD_Menu.ACTION_Report.equals(action))
{
final AdProcessId adProcessId = AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID());
if (adProcessId != null)
{
final ADProcessName processName = Names.ADProcessName_Loader.retrieve(adProcessId);
MigrationScriptFileLoggerHolder.logComment("Report: " + processName.toShortString());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\interceptor\AD_Menu.java
| 2
|
请完成以下Java代码
|
public boolean isTree()
{
Object oo = get_Value(COLUMNNAME_IsTree);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsTree(boolean IsTree)
{
set_Value (COLUMNNAME_IsTree, Boolean.valueOf(IsTree));
}
@Override
public boolean isParameterNextLine()
{
Object oo = get_Value(COLUMNNAME_IsParameterNextLine);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsParameterNextLine(boolean IsParameterNextLine)
{
set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine));
}
public void setParameterSeqNo (int ParameterSeqNo)
{
set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo));
}
public int getParameterSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
public void setParameterDisplayLogic (String ParameterDisplayLogic)
{
set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic);
}
|
public String getParameterDisplayLogic ()
{
return (String)get_Value(COLUMNNAME_ParameterDisplayLogic);
}
public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Query Criteria Function.
@param QueryCriteriaFunction
column used for adding a sql function to query criteria
*/
public void setQueryCriteriaFunction (String QueryCriteriaFunction)
{
set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction);
}
/** Get Query Criteria Function.
@return column used for adding a sql function to query criteria
*/
public String getQueryCriteriaFunction ()
{
return (String)get_Value(COLUMNNAME_QueryCriteriaFunction);
}
@Override
public void setDefaultValue (String DefaultValue)
{
set_Value (COLUMNNAME_DefaultValue, DefaultValue);
}
@Override
public String getDefaultValue ()
{
return (String)get_Value(COLUMNNAME_DefaultValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java
| 1
|
请完成以下Java代码
|
public static PriceAndTax calculatePriceAndTaxAndUpdate(
@NonNull final I_C_Invoice_Candidate icRecord,
final org.compiere.model.I_M_InOutLine fromInOutLine)
{
try
{
final PriceAndTax priceAndTax = calculatePriceAndTax(icRecord, fromInOutLine);
IInvoiceCandInvalidUpdater.updatePriceAndTax(icRecord, priceAndTax);
return priceAndTax;
}
catch (final Exception e)
{
if (icRecord.getC_Tax_ID() <= 0)
{
icRecord.setC_Tax_ID(Tax.C_TAX_ID_NO_TAX_FOUND); // make sure that we will be able to save the icRecord
}
setError(icRecord, e);
|
return null;
}
}
private static void setError(
@NonNull final I_C_Invoice_Candidate ic,
@NonNull final Exception ex)
{
logger.debug("Set IsInDispute=true, because an error occured");
ic.setIsInDispute(true); // 07193 - Mark's request
final boolean askForDeleteRegeneration = false; // default; don't ask for re-generation
final I_AD_Note note = null; // we don't have a note
Services.get(IInvoiceCandBL.class).setError(ic, ex.getLocalizedMessage(), note, askForDeleteRegeneration);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inout\invoicecandidate\M_InOutLine_Handler.java
| 1
|
请完成以下Java代码
|
public void setName (String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
|
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_ValueNoCheck (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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_ReportStatement.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.