instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}
@Override
@Scheduled(cron = "${remind.cron}")
public void sendRemindNotifications() {
|
final NotificationType type = NotificationType.REMIND;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for remind notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
emailService.send(type, recipient, null);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during remind notification for {}", recipient, t);
}
}));
}
}
|
repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\NotificationServiceImpl.java
| 2
|
请完成以下Spring Boot application配置
|
tf:
frozenModelPath: inception-v3/inception_v3_2016_08_28_frozen.pb
labelsPath: inception-v3/imagenet_slim_labels.txt
outputLayer: InceptionV3/Predictions/Reshape_1
image:
width: 299
height: 299
mean: 0
|
scale: 255
logging.level.net.sf.jmimemagic: WARN
spring:
servlet:
multipart:
max-file-size: 5MB
|
repos\springboot-demo-master\Tensorflow\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public HeadersConfigurer<H> and() {
return HeadersConfigurer.this;
}
}
public final class PermissionsPolicyConfig {
private PermissionsPolicyHeaderWriter writer;
private PermissionsPolicyConfig() {
}
/**
* Sets the policy to be used in the response header.
* @param policy a permissions policy
* @return the {@link PermissionsPolicyConfig} for additional configuration
* @throws IllegalArgumentException if policy is null
*/
public PermissionsPolicyConfig policy(String policy) {
this.writer.setPolicy(policy);
return this;
}
}
public final class CrossOriginOpenerPolicyConfig {
private CrossOriginOpenerPolicyHeaderWriter writer;
public CrossOriginOpenerPolicyConfig() {
}
/**
* Sets the policy to be used in the {@code Cross-Origin-Opener-Policy} header
* @param openerPolicy a {@code Cross-Origin-Opener-Policy}
* @return the {@link CrossOriginOpenerPolicyConfig} for additional configuration
* @throws IllegalArgumentException if openerPolicy is null
*/
public CrossOriginOpenerPolicyConfig policy(
CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy openerPolicy) {
this.writer.setPolicy(openerPolicy);
return this;
}
}
public final class CrossOriginEmbedderPolicyConfig {
private CrossOriginEmbedderPolicyHeaderWriter writer;
public CrossOriginEmbedderPolicyConfig() {
}
/**
* Sets the policy to be used in the {@code Cross-Origin-Embedder-Policy} header
* @param embedderPolicy a {@code Cross-Origin-Embedder-Policy}
* @return the {@link CrossOriginEmbedderPolicyConfig} for additional
|
* configuration
* @throws IllegalArgumentException if embedderPolicy is null
*/
public CrossOriginEmbedderPolicyConfig policy(
CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy embedderPolicy) {
this.writer.setPolicy(embedderPolicy);
return this;
}
}
public final class CrossOriginResourcePolicyConfig {
private CrossOriginResourcePolicyHeaderWriter writer;
public CrossOriginResourcePolicyConfig() {
}
/**
* Sets the policy to be used in the {@code Cross-Origin-Resource-Policy} header
* @param resourcePolicy a {@code Cross-Origin-Resource-Policy}
* @return the {@link CrossOriginResourcePolicyConfig} for additional
* configuration
* @throws IllegalArgumentException if resourcePolicy is null
*/
public CrossOriginResourcePolicyConfig policy(
CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy resourcePolicy) {
this.writer.setPolicy(resourcePolicy);
return this;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\HeadersConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Age
{
int ageInMonths;
public static Age ZERO = new Age(0);
@NonNull
public static Age ofAgeInMonths(final int ageInMonths)
{
if (ageInMonths == ZERO.ageInMonths)
{
return ZERO;
}
return new Age(ageInMonths);
}
private Age(final int ageInMonths)
{
this.ageInMonths = ageInMonths;
}
@NonNull
public Age add(final @NonNull Age other)
{
if (other.isZero())
{
return this;
}
if (isZero())
{
return other;
}
return ofAgeInMonths(this.ageInMonths + other.ageInMonths);
|
}
public boolean isZero()
{
return ageInMonths == 0;
}
@Override
public String toString() {return toStringValue();}
public String toStringValue()
{
return String.valueOf(ageInMonths);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\age\Age.java
| 2
|
请完成以下Java代码
|
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public int getRevision() {
return revision;
|
}
@Override
public int getRevisionNext() {
return revision + 1;
}
@Override
public void setRevision(int revision) {
this.revision = revision;
}
public String getInfoJsonId() {
return infoJsonId;
}
public void setInfoJsonId(String infoJsonId) {
this.infoJsonId = infoJsonId;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionInfoEntity.java
| 1
|
请完成以下Java代码
|
public void completeForwardAndBackwardDDOrders(final I_DD_Order ddOrder)
{
//
// Complete Forward and Backward DD Orders, if they are on the same plant (08059)
processForwardAndBackwardDraftDDOrders(ddOrder, this::completeDDOrderIfNeeded);
}
public void disallowMRPCleanupOnForwardAndBackwardDDOrders(final I_DD_Order ddOrder)
{
processForwardAndBackwardDraftDDOrders(ddOrder, ddOrderToProcess -> {
// Skip this DD_Order if flag was already set to false
if (!ddOrderToProcess.isMRP_AllowCleanup())
{
return;
}
// Set MRP_AlowCleanup to false and save it
ddOrderToProcess.setMRP_AllowCleanup(false);
ddOrderLowLevelDAO.save(ddOrderToProcess);
});
}
public void completeBackwardDDOrders(final I_M_Forecast forecast)
{
//
// Retrive backward DD Orders
final List<I_DD_Order> ddOrders = ddOrderLowLevelDAO.retrieveBackwardDDOrderLinesQuery(forecast)
//
// Not already processed lines
// NOTE: to avoid recursions, we relly on the fact that current DD Order which is about to be completed,
// even if the DocStatus was not already set in database,
// it's lines were already flagged as processed
.addEqualsFilter(I_DD_OrderLine.COLUMN_Processed, false)
//
// Collect DD_Orders
.andCollect(I_DD_OrderLine.COLUMN_DD_Order_ID)
.addEqualsFilter(I_DD_Order.COLUMN_Processed, false) // only not processed DD_Orders
//
// Retrieve them
.create()
.list();
completeDDOrdersIfNeeded(ddOrders);
}
public void save(final I_DD_Order ddOrder)
{
ddOrderLowLevelDAO.save(ddOrder);
}
public void save(final I_DD_OrderLine ddOrderline)
{
ddOrderLowLevelDAO.save(ddOrderline);
}
public void save(final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlternative)
{
ddOrderLowLevelDAO.save(ddOrderLineOrAlternative);
|
}
public List<I_DD_OrderLine> retrieveLines(final I_DD_Order order)
{
return ddOrderLowLevelDAO.retrieveLines(order);
}
public List<I_DD_OrderLine_Alternative> retrieveAllAlternatives(final I_DD_OrderLine ddOrderLine)
{
return ddOrderLowLevelDAO.retrieveAllAlternatives(ddOrderLine);
}
public void updateUomFromProduct(final I_DD_OrderLine ddOrderLine)
{
final ProductId productId = ProductId.ofRepoIdOrNull(ddOrderLine.getM_Product_ID());
if (productId == null)
{
// nothing to do
return;
}
final UomId stockingUomId = productBL.getStockUOMId(productId);
ddOrderLine.setC_UOM_ID(stockingUomId.getRepoId());
}
public void deleteOrders(@NonNull final DeleteOrdersQuery deleteOrdersQuery)
{
ddOrderLowLevelDAO.deleteOrders(deleteOrdersQuery);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\DDOrderLowLevelService.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Set<Student> getLikes() {
return likes;
}
public void setLikes(Set<Student> likes) {
this.likes = likes;
}
public Set<CourseRating> getRatings() {
return ratings;
}
public void setRatings(Set<CourseRating> ratings) {
this.ratings = ratings;
}
public Set<CourseRegistration> getRegistrations() {
return registrations;
}
public void setRegistrations(Set<CourseRegistration> registrations) {
this.registrations = registrations;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Course other = (Course) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\Course.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InMemoryRelyingPartyRegistrationRepository implements IterableRelyingPartyRegistrationRepository {
private final Map<String, RelyingPartyRegistration> byRegistrationId;
private final Map<String, List<RelyingPartyRegistration>> byAssertingPartyEntityId;
public InMemoryRelyingPartyRegistrationRepository(RelyingPartyRegistration... registrations) {
this(Arrays.asList(registrations));
}
public InMemoryRelyingPartyRegistrationRepository(Collection<RelyingPartyRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be empty");
this.byRegistrationId = createMappingToIdentityProvider(registrations);
this.byAssertingPartyEntityId = createMappingByAssertingPartyEntityId(registrations);
}
private static Map<String, RelyingPartyRegistration> createMappingToIdentityProvider(
Collection<RelyingPartyRegistration> rps) {
LinkedHashMap<String, RelyingPartyRegistration> result = new LinkedHashMap<>();
for (RelyingPartyRegistration rp : rps) {
Assert.notNull(rp, "relying party collection cannot contain null values");
String key = rp.getRegistrationId();
Assert.notNull(key, "relying party identifier cannot be null");
Assert.isNull(result.get(key), () -> "relying party duplicate identifier '" + key + "' detected.");
result.put(key, rp);
}
return Collections.unmodifiableMap(result);
}
private static Map<String, List<RelyingPartyRegistration>> createMappingByAssertingPartyEntityId(
Collection<RelyingPartyRegistration> rps) {
MultiValueMap<String, RelyingPartyRegistration> result = new LinkedMultiValueMap<>();
for (RelyingPartyRegistration rp : rps) {
result.add(rp.getAssertingPartyMetadata().getEntityId(), rp);
}
return Collections.unmodifiableMap(result);
}
|
@Override
public RelyingPartyRegistration findByRegistrationId(String id) {
return this.byRegistrationId.get(id);
}
@Override
public RelyingPartyRegistration findUniqueByAssertingPartyEntityId(String entityId) {
Collection<RelyingPartyRegistration> registrations = this.byAssertingPartyEntityId.get(entityId);
if (registrations == null) {
return null;
}
if (registrations.size() > 1) {
return null;
}
return registrations.iterator().next();
}
@Override
public Iterator<RelyingPartyRegistration> iterator() {
return this.byRegistrationId.values().iterator();
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\registration\InMemoryRelyingPartyRegistrationRepository.java
| 2
|
请完成以下Java代码
|
public GenericEventListenerInstanceQuery stateAvailable() {
innerQuery.planItemInstanceStateAvailable();
return this;
}
@Override
public GenericEventListenerInstanceQuery stateSuspended() {
innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED);
return this;
}
@Override
public GenericEventListenerInstanceQuery orderByName() {
innerQuery.orderByName();
return this;
}
@Override
public GenericEventListenerInstanceQuery asc() {
innerQuery.asc();
return this;
}
@Override
public GenericEventListenerInstanceQuery desc() {
innerQuery.desc();
return this;
}
@Override
public GenericEventListenerInstanceQuery orderBy(QueryProperty property) {
innerQuery.orderBy(property);
return this;
}
@Override
public GenericEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
innerQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
|
return innerQuery.count();
}
@Override
public GenericEventListenerInstance singleResult() {
PlanItemInstance instance = innerQuery.singleResult();
return GenericEventListenerInstanceImpl.fromPlanItemInstance(instance);
}
@Override
public List<GenericEventListenerInstance> list() {
return convertPlanItemInstances(innerQuery.list());
}
@Override
public List<GenericEventListenerInstance> listPage(int firstResult, int maxResults) {
return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults));
}
protected List<GenericEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) {
if (instances == null) {
return null;
}
return instances.stream().map(GenericEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\GenericEventListenerInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public java.lang.String getLastname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Lastname);
}
/** Set Login.
@param Login
Used for login. See Help.
*/
@Override
public void setLogin (java.lang.String Login)
{
set_Value (COLUMNNAME_Login, Login);
}
/** Get Login.
@return Used for login. See Help.
*/
@Override
public java.lang.String getLogin ()
{
return (java.lang.String)get_Value(COLUMNNAME_Login);
}
/** Set Handynummer.
@param MobilePhone Handynummer */
@Override
public void setMobilePhone (java.lang.String MobilePhone)
{
set_Value (COLUMNNAME_MobilePhone, MobilePhone);
}
/** Get Handynummer.
@return Handynummer */
@Override
public java.lang.String getMobilePhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_MobilePhone);
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
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 Role name.
@param RoleName Role name */
@Override
public void setRoleName (java.lang.String RoleName)
{
set_Value (COLUMNNAME_RoleName, RoleName);
}
/** Get Role name.
@return Role name */
@Override
public java.lang.String getRoleName ()
{
return (java.lang.String)get_Value(COLUMNNAME_RoleName);
}
/** Set UserValue.
@param UserValue UserValue */
@Override
public void setUserValue (java.lang.String UserValue)
{
set_Value (COLUMNNAME_UserValue, UserValue);
}
/** Get UserValue.
@return UserValue */
@Override
public java.lang.String getUserValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserValue);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_User.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return m_html.toString();
} // toString
/**
* Output Document
* @param out out
*/
public void output (OutputStream out)
{
m_html.output(out);
} // output
/**
* Output Document
* @param out out
*/
public void output (PrintWriter out)
{
m_html.output(out);
} // output
/**
|
* Add Popup Center
* @param nowrap set nowrap in td
* @return null or center single td
*/
public td addPopupCenter(boolean nowrap)
{
if (m_table == null)
return null;
//
td center = new td ("popupCenter", AlignType.CENTER, AlignType.MIDDLE, nowrap);
center.setColSpan(2);
m_table.addElement(new tr()
.addElement(center));
return center;
} // addPopupCenter
} // WDoc
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebDoc.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public XMLGregorianCalendar getLastASNDeliveryDate() {
return lastASNDeliveryDate;
}
/**
* Sets the value of the lastASNDeliveryDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setLastASNDeliveryDate(XMLGregorianCalendar value) {
this.lastASNDeliveryDate = value;
}
/**
* Gets the value of the lastReceivedQuantity property.
*
* @return
* possible object is
* {@link ConditionalUnitType }
*
*/
public ConditionalUnitType getLastReceivedQuantity() {
return lastReceivedQuantity;
}
/**
* Sets the value of the lastReceivedQuantity property.
*
* @param value
* allowed object is
* {@link ConditionalUnitType }
*
*/
public void setLastReceivedQuantity(ConditionalUnitType value) {
this.lastReceivedQuantity = value;
}
/**
* Gets the value of the lastASNDispatchDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getLastASNDispatchDate() {
|
return lastASNDispatchDate;
}
/**
* Sets the value of the lastASNDispatchDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setLastASNDispatchDate(XMLGregorianCalendar value) {
this.lastASNDispatchDate = value;
}
/**
* Gets the value of the lastDispatchedQuantity property.
*
* @return
* possible object is
* {@link ConditionalUnitType }
*
*/
public ConditionalUnitType getLastDispatchedQuantity() {
return lastDispatchedQuantity;
}
/**
* Sets the value of the lastDispatchedQuantity property.
*
* @param value
* allowed object is
* {@link ConditionalUnitType }
*
*/
public void setLastDispatchedQuantity(ConditionalUnitType value) {
this.lastDispatchedQuantity = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ForecastASNReferenceType.java
| 2
|
请完成以下Java代码
|
public static PickingSlotId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PickingSlotId(repoId) : null;
}
public static Optional<PickingSlotId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final PickingSlotId pickingSlotId)
{
return pickingSlotId != null ? pickingSlotId.getRepoId() : -1;
}
int repoId;
|
private PickingSlotId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "M_PickingSlot_ID");
}
public static boolean equals(final PickingSlotId o1, final PickingSlotId o2)
{
return Objects.equals(o1, o2);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\PickingSlotId.java
| 1
|
请完成以下Java代码
|
public class BatchInformation2 {
@XmlElement(name = "MsgId")
protected String msgId;
@XmlElement(name = "PmtInfId")
protected String pmtInfId;
@XmlElement(name = "NbOfTxs")
protected String nbOfTxs;
@XmlElement(name = "TtlAmt")
protected ActiveOrHistoricCurrencyAndAmount ttlAmt;
@XmlElement(name = "CdtDbtInd")
@XmlSchemaType(name = "string")
protected CreditDebitCode cdtDbtInd;
/**
* Gets the value of the msgId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMsgId() {
return msgId;
}
/**
* Sets the value of the msgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMsgId(String value) {
this.msgId = value;
}
/**
* Gets the value of the pmtInfId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPmtInfId() {
return pmtInfId;
}
/**
* Sets the value of the pmtInfId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPmtInfId(String value) {
this.pmtInfId = value;
}
/**
* Gets the value of the nbOfTxs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfTxs() {
return nbOfTxs;
}
/**
* Sets the value of the nbOfTxs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfTxs(String value) {
|
this.nbOfTxs = value;
}
/**
* Gets the value of the ttlAmt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getTtlAmt() {
return ttlAmt;
}
/**
* Sets the value of the ttlAmt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.ttlAmt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BatchInformation2.java
| 1
|
请完成以下Java代码
|
public boolean isHandled(final Method method)
{
if (!method.isAnnotationPresent(annotationClass))
{
return false;
}
return true;
}
});
final MethodHandler handler = new MethodHandler()
{
@Override
public Object invoke(final Object self, final Method thisMethod, final Method proceed, final Object[] methodArgs) throws Throwable
{
@SuppressWarnings("unchecked")
final T serviceInstance = (T)self;
return invokeForJavassist0(interceptorInstance, serviceInstance, thisMethod, proceed, methodArgs);
}
};
// check out the deprecation notice.
// also note that we don't need the caching that badly since we are intercepting singletons, and that right now we have all the setup in this method (ofc we can retain that advantage, but it's more effort).
// for now I think if is OK this way. If we change it, we should at any rate make sure to still keep the interceptor's code localized in this class.
factory.setHandler(handler);
@SuppressWarnings("unchecked")
final Class<T> serviceInstanceInterceptedClass = (Class<T>) factory.createClass();
return serviceInstanceInterceptedClass;
}
// there were no registered interceptors
return serviceInstanceClass;
|
}
catch (Exception e)
{
throw ServicesException.wrapIfNeeded(e);
}
}
/**
* Called when there we got an error/warning while creating the intercepted class.
*
* @param ex
*/
private final void onException(final ServicesException ex)
{
if (FAIL_ON_ERROR)
{
throw ex;
}
else
{
ex.printStackTrace(System.err);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\JavaAssistInterceptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result edit(@RequestBody SysCheckRule sysCheckRule) {
sysCheckRuleService.updateById(sysCheckRule);
return Result.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@AutoLog(value = "编码校验规则-通过id删除")
@Operation(summary = "编码校验规则-通过id删除")
@DeleteMapping(value = "/delete")
public Result delete(@RequestParam(name = "id", required = true) String id) {
sysCheckRuleService.removeById(id);
return Result.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@AutoLog(value = "编码校验规则-批量删除")
@Operation(summary = "编码校验规则-批量删除")
@DeleteMapping(value = "/deleteBatch")
public Result deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
this.sysCheckRuleService.removeByIds(Arrays.asList(ids.split(",")));
return Result.ok("批量删除成功!");
}
/**
* 通过id查询
*
|
* @param id
* @return
*/
@AutoLog(value = "编码校验规则-通过id查询")
@Operation(summary = "编码校验规则-通过id查询")
@GetMapping(value = "/queryById")
public Result queryById(@RequestParam(name = "id", required = true) String id) {
SysCheckRule sysCheckRule = sysCheckRuleService.getById(id);
return Result.ok(sysCheckRule);
}
/**
* 导出excel
*
* @param request
* @param sysCheckRule
*/
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysCheckRule sysCheckRule) {
return super.exportXls(request, sysCheckRule, SysCheckRule.class, "编码校验规则");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysCheckRule.class);
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysCheckRuleController.java
| 2
|
请完成以下Java代码
|
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public boolean isExclusive() {
return isExclusive;
}
public void setExclusive(boolean isExclusive) {
this.isExclusive = isExclusive;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
|
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AcquirableJobEntity other = (AcquirableJobEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", lockOwner=" + lockOwner
+ ", lockExpirationTime=" + lockExpirationTime
+ ", duedate=" + duedate
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", processInstanceId=" + processInstanceId
+ ", isExclusive=" + isExclusive
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AcquirableJobEntity.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getSubjectId() {
return subjectId;
}
public void setSubjectId(Long subjectId) {
this.subjectId = subjectId;
}
public String getMemberNickName() {
return memberNickName;
}
public void setMemberNickName(String memberNickName) {
this.memberNickName = memberNickName;
}
public String getMemberIcon() {
return memberIcon;
}
public void setMemberIcon(String memberIcon) {
this.memberIcon = memberIcon;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreateTime() {
return createTime;
}
|
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
@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(", subjectId=").append(subjectId);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", content=").append(content);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectComment.java
| 1
|
请完成以下Java代码
|
public void setHR_ListVersion_ID (int HR_ListVersion_ID)
{
if (HR_ListVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID));
}
/** Get Payroll List Version.
@return Payroll List Version */
public int getHR_ListVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_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 Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
|
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListVersion.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String listFileNames(String dir) {
return gateway.nlstFile(dir);
}
@Override
public File getFile(String dir) {
return null;
}
@Override
public List<File> mgetFile(String dir) {
return null;
}
@Override
public boolean rmFile(String file) {
return false;
}
@Override
public boolean mv(String sourceFile, String targetFile) {
return false;
}
@Override
public File putFile(String dir) {
return null;
}
@Override
public List<File> mputFile(String dir) {
return null;
}
@Override
public String nlstFile(String dir) {
return gateway.nlstFile(dir);
}
private static File convertInputStreamToFile(InputStream inputStream, String savePath) {
OutputStream outputStream = null;
File file = new File(savePath);
|
try {
outputStream = new FileOutputStream(file);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
log.info("convert InputStream to file done, savePath is : {}", savePath);
} catch (IOException e) {
log.error("error:", e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("error:", e);
}
}
}
return file;
}
private static File convert(MultipartFile file) throws IOException {
File convertFile = new File(file.getOriginalFilename());
convertFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convertFile);
fos.write(file.getBytes());
fos.close();
return convertFile;
}
}
|
repos\springboot-demo-master\sftp\src\main\java\com\et\sftp\service\impl\SftpServiceImpl.java
| 2
|
请完成以下Java代码
|
public final boolean isNumeric()
{
return TYPES_ALL_NUMERIC.contains(this);
}
public final boolean isBigDecimal()
{
return isNumeric() && BigDecimal.class.equals(getValueClassOrNull());
}
public final boolean isStrictText()
{
return this == Text || this == LongText;
}
public final boolean isText()
{
return isStrictText() || this == URL || this == Password;
}
public final boolean isButton()
{
return this == Button || this == ActionButton || this == ProcessButton || this == ZoomIntoButton;
}
public final boolean isLookup()
{
return this == Lookup || this == List;
}
public final boolean isSupportZoomInto()
{
return isLookup() || this == DocumentFieldWidgetType.ZoomIntoButton
// || this == DocumentFieldWidgetType.Labels // not implemented yet
;
}
public final boolean isBoolean()
|
{
return this == YesNo || this == Switch;
}
/**
* Same as {@link #getValueClassOrNull()} but it will throw exception in case there is no valueClass.
*
* @return value class
*/
public Class<?> getValueClass()
{
if (valueClass == null)
{
throw new IllegalStateException("valueClass is unknown for " + this);
}
return valueClass;
}
/**
* Gets the standard value class to be used for this widget.
* In case there are multiple value classes which can be used for this widget, the method will return null.
*
* @return value class or <code>null</code>
*/
public Class<?> getValueClassOrNull()
{
return valueClass;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldWidgetType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VariableServiceImpl extends CommonServiceImpl<VariableServiceConfiguration> implements VariableService {
public VariableServiceImpl(VariableServiceConfiguration variableServiceConfiguration) {
super(variableServiceConfiguration);
}
@Override
public InternalVariableInstanceQuery createInternalVariableInstanceQuery() {
return getVariableInstanceEntityManager().createInternalVariableInstanceQuery();
}
@Override
public VariableInstanceEntity createVariableInstance(String name) {
return getVariableInstanceEntityManager().create(name);
}
@Override
public void insertVariableInstance(VariableInstanceEntity variable) {
getVariableInstanceEntityManager().insert(variable);
}
@Override
public void insertVariableInstanceWithValue(VariableInstanceEntity variable, Object value, String tenantId) {
getVariableInstanceEntityManager().insertWithValue(variable, value, tenantId);
}
|
@Override
public void deleteVariableInstance(VariableInstanceEntity variable) {
getVariableInstanceEntityManager().delete(variable);
}
@Override
public void deleteVariablesByExecutionId(String executionId) {
getVariableInstanceEntityManager().deleteVariablesByExecutionId(executionId);
}
@Override
public void deleteVariablesByTaskId(String taskId) {
getVariableInstanceEntityManager().deleteVariablesByTaskId(taskId);
}
public VariableInstanceEntityManager getVariableInstanceEntityManager() {
return configuration.getVariableInstanceEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\VariableServiceImpl.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public double getCityCentreLatitude() {
return cityCentreLattitude;
}
public double getCityCentreLongitude() {
return cityCentreLongitude;
}
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
City city = (City) o;
if (Double.compare(city.cityCentreLattitude, cityCentreLattitude) != 0) return false;
if (Double.compare(city.cityCentreLongitude, cityCentreLongitude) != 0) return false;
if (!Objects.equals(id, city.id)) return false;
return Objects.equals(name, city.name);
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\ttl\model\City.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
// Get raw bean type
Class<?> rawBeanType = getUserClass(beanType);
if (isAssignable(ServiceConfig.class, rawBeanType)) { // ServiceConfig type or sub-type
String interfaceName = (String) beanDefinition.getPropertyValues().get("interface");
String mappedBeanName = interfaceNamesToBeanNames.putIfAbsent(interfaceName, beanName);
// If mapped bean name exists and does not equal current bean name
if (mappedBeanName != null && !mappedBeanName.equals(beanName)) {
// conflictedBeanNames will record current bean name.
conflictedBeanNames.add(beanName);
}
}
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (conflictedBeanNames.contains(beanName) && bean instanceof ServiceConfig) {
ServiceConfig serviceConfig = (ServiceConfig) bean;
if (isConflictedServiceConfig(serviceConfig)) {
// Set id as the bean name
serviceConfig.setId(beanName);
}
}
return bean;
}
|
private boolean isConflictedServiceConfig(ServiceConfig serviceConfig) {
return Objects.equals(serviceConfig.getId(), serviceConfig.getInterface());
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* Keep the order being higher than {@link CommonAnnotationBeanPostProcessor#getOrder()} that is
* {@link Ordered#LOWEST_PRECEDENCE}
*
* @return {@link Ordered#LOWEST_PRECEDENCE} +1
*/
@Override
public int getOrder() {
return LOWEST_PRECEDENCE + 1;
}
@Override
public void destroy() throws Exception {
interfaceNamesToBeanNames.clear();
conflictedBeanNames.clear();
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\autoconfigure\src\main\java\org\apache\dubbo\spring\boot\beans\factory\config\ServiceBeanIdConflictProcessor.java
| 2
|
请完成以下Java代码
|
public class MailObject {
@Email
@NotNull
@Size(min = 1, message = "Please, set an email address to send the message to it")
private String to;
private String recipientName;
private String subject;
private String text;
private String senderName;
private String templateEngine;
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRecipientName() {
return recipientName;
}
|
public void setRecipientName(String recipientName) {
this.recipientName = recipientName;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getTemplateEngine() {
return templateEngine;
}
public void setTemplateEngine(String templateEngine) {
this.templateEngine = templateEngine;
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\domain\MailObject.java
| 1
|
请完成以下Java代码
|
public SpinXmlAttribute attribute() {
try {
ensureNotDocumentRootExpression(expression);
Attr attribute = (Attr) query.evaluate(expression, domElement.unwrap(), XPathConstants.NODE);
ensureXPathNotNull(attribute, expression);
return dataFormat.createAttributeWrapper(attribute);
} catch (XPathExpressionException e) {
throw LOG.unableToEvaluateXPathExpressionOnElement(domElement, e);
} catch (ClassCastException e) {
throw LOG.unableToCastXPathResultTo(Attr.class, e);
}
}
public SpinList<SpinXmlAttribute> attributeList() {
try {
ensureNotDocumentRootExpression(expression);
NodeList nodeList = (NodeList) query.evaluate(expression, domElement.unwrap(), XPathConstants.NODESET);
ensureXPathNotEmpty(nodeList, expression);
return new SpinListImpl<SpinXmlAttribute>(new DomXmlAttributeIterable(nodeList, dataFormat));
} catch (XPathExpressionException e) {
throw LOG.unableToEvaluateXPathExpressionOnElement(domElement, e);
} catch (ClassCastException e) {
throw LOG.unableToCastXPathResultTo(NodeList.class, e);
}
}
public String string() {
try {
ensureNotDocumentRootExpression(expression);
return (String) query.evaluate(expression, domElement.unwrap(), XPathConstants.STRING);
} catch (XPathExpressionException e) {
throw LOG.unableToEvaluateXPathExpressionOnElement(domElement, e);
} catch (ClassCastException e) {
throw LOG.unableToCastXPathResultTo(String.class, e);
}
}
public Double number() {
try {
ensureNotDocumentRootExpression(expression);
return (Double) query.evaluate(expression, domElement.unwrap(), XPathConstants.NUMBER);
} catch (XPathExpressionException e) {
|
throw LOG.unableToEvaluateXPathExpressionOnElement(domElement, e);
} catch (ClassCastException e) {
throw LOG.unableToCastXPathResultTo(Double.class, e);
}
}
public Boolean bool() {
try {
ensureNotDocumentRootExpression(expression);
return (Boolean) query.evaluate(expression, domElement.unwrap(), XPathConstants.BOOLEAN);
} catch (XPathExpressionException e) {
throw LOG.unableToEvaluateXPathExpressionOnElement(domElement, e);
} catch (ClassCastException e) {
throw LOG.unableToCastXPathResultTo(Boolean.class, e);
}
}
public SpinXPathQuery ns(String prefix, String namespace) {
resolver.setNamespace(prefix, namespace);
query.setNamespaceContext(resolver);
return this;
}
public SpinXPathQuery ns(Map<String, String> namespaces) {
resolver.setNamespaces(namespaces);
query.setNamespaceContext(resolver);
return this;
}
}
|
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\query\DomXPathQuery.java
| 1
|
请完成以下Java代码
|
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
// We can't use constructor injection of the application context because
// it causes eager factory bean initialization
this.registry = (BeanDefinitionRegistry) this.applicationContext.getAutowireCapableBeanFactory();
this.binder = ConfigurationPropertiesBinder.get(this.applicationContext);
}
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE + 1;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (!hasBoundValueObject(beanName)) {
bind(ConfigurationPropertiesBean.get(this.applicationContext, bean, beanName));
}
return bean;
}
private boolean hasBoundValueObject(String beanName) {
return BindMethod.VALUE_OBJECT.equals(BindMethodAttribute.get(this.registry, beanName));
}
private void bind(@Nullable ConfigurationPropertiesBean bean) {
if (bean == null) {
return;
|
}
Assert.state(bean.asBindTarget().getBindMethod() != BindMethod.VALUE_OBJECT,
"Cannot bind @ConfigurationProperties for bean '" + bean.getName()
+ "'. Ensure that @ConstructorBinding has not been applied to regular bean");
try {
this.binder.bind(bean);
}
catch (Exception ex) {
throw new ConfigurationPropertiesBindException(bean, ex);
}
}
/**
* Register a {@link ConfigurationPropertiesBindingPostProcessor} bean if one is not
* already registered.
* @param registry the bean definition registry
* @since 2.2.0
*/
public static void register(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "'registry' must not be null");
if (!registry.containsBeanDefinition(BEAN_NAME)) {
BeanDefinition definition = BeanDefinitionBuilder
.rootBeanDefinition(ConfigurationPropertiesBindingPostProcessor.class)
.getBeanDefinition();
definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
registry.registerBeanDefinition(BEAN_NAME, definition);
}
ConfigurationPropertiesBinder.register(registry);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesBindingPostProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JasperDataSourceProvider
{
private final SqlDataSource sqlDataSource;
private final JsonDataSource jsonDataSource;
private final RemoteRestAPIDataSource remoteRestAPIDataSource;
public JasperDataSourceProvider(
@NonNull final SqlDataSource sqlDataSource,
@NonNull final JsonDataSource jsonDataSource,
@NonNull final RemoteRestAPIDataSource remoteRestAPIDataSource
)
{
this.sqlDataSource = sqlDataSource;
this.jsonDataSource = jsonDataSource;
this.remoteRestAPIDataSource = remoteRestAPIDataSource;
}
public ReportDataSource getDataSource(@NonNull final ReportContext reportContext)
{
final ProcessType reportType = reportContext.getType();
if (reportType == ProcessType.JasperReportsSQL)
{
return sqlDataSource;
}
else if (reportType == ProcessType.JasperReportsJSON)
{
final String jsonPath = StringUtils.trimBlankToNull(reportContext.getJSONPath());
|
if (jsonPath == null || "-".equals(jsonPath))
{
return jsonDataSource;
}
else
{
return remoteRestAPIDataSource;
}
}
else
{
throw new AdempiereException("Cannot determine data source for " + reportContext);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\data_source\JasperDataSourceProvider.java
| 2
|
请完成以下Java代码
|
public I_M_ChangeNotice getM_ChangeNotice() throws RuntimeException
{
return (I_M_ChangeNotice)MTable.get(getCtx(), I_M_ChangeNotice.Table_Name)
.getPO(getM_ChangeNotice_ID(), get_TrxName()); }
/** Set Change Notice.
@param M_ChangeNotice_ID
Bill of Materials (Engineering) Change Notice (Version)
*/
public void setM_ChangeNotice_ID (int M_ChangeNotice_ID)
{
if (M_ChangeNotice_ID < 1)
set_Value (COLUMNNAME_M_ChangeNotice_ID, null);
else
set_Value (COLUMNNAME_M_ChangeNotice_ID, Integer.valueOf(M_ChangeNotice_ID));
}
/** Get Change Notice.
@return Bill of Materials (Engineering) Change Notice (Version)
*/
public int getM_ChangeNotice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeNotice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set Name.
@param Name
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 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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_BOM.java
| 1
|
请完成以下Java代码
|
public Operator getOperator() {
return operator;
}
@Override
public Object eval(Bindings bindings, ELContext context) {
return operator.eval(bindings, context, left, right);
}
@Override
public String toString() {
return "'" + operator.toString() + "'";
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
|
left.appendStructure(b, bindings);
b.append(' ');
b.append(operator);
b.append(' ');
right.appendStructure(b, bindings);
}
public int getCardinality() {
return 2;
}
public AstNode getChild(int i) {
return i == 0 ? left : i == 1 ? right : null;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBinary.java
| 1
|
请完成以下Java代码
|
protected void lockJob(AcquirableJobEntity job) {
String lockOwner = jobExecutor.getLockOwner();
job.setLockOwner(lockOwner);
int lockTimeInMillis = jobExecutor.getLockTimeInMillis();
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(ClockUtil.getCurrentTime());
gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
job.setLockExpirationTime(gregorianCalendar.getTime());
}
@Override
public Class<? extends DbEntity> getEntityType() {
return AcquirableJobEntity.class;
}
@Override
public OptimisticLockingResult failedOperation(DbOperation operation) {
if (operation instanceof DbEntityOperation) {
DbEntityOperation entityOperation = (DbEntityOperation) operation;
// could not lock the job -> remove it from list of acquired jobs
acquiredJobs.removeJobId(entityOperation.getEntity().getId());
// When the job that failed the lock with an OLE is removed,
// we suppress the OLE.
|
return OptimisticLockingResult.IGNORE;
}
// If none of the conditions are satisfied, this might indicate a bug,
// so we throw the OLE.
return OptimisticLockingResult.THROW;
}
protected boolean isAcquireExclusiveOverProcessHierarchies(CommandContext context) {
var engineConfig = context.getProcessEngineConfiguration();
return engineConfig != null && engineConfig.isJobExecutorAcquireExclusiveOverProcessHierarchies();
}
protected String selectProcessInstanceId(AcquirableJobEntity job, boolean isAcquireExclusiveOverProcessHierarchies) {
if (isAcquireExclusiveOverProcessHierarchies && job.getRootProcessInstanceId() != null) {
return job.getRootProcessInstanceId();
}
return job.getProcessInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AcquireJobsCmd.java
| 1
|
请完成以下Java代码
|
public int getC_RevenueRecognition_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_RevenueRecognition_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Time based.
@param IsTimeBased
Time based Revenue Recognition rather than Service Level based
*/
public void setIsTimeBased (boolean IsTimeBased)
{
set_Value (COLUMNNAME_IsTimeBased, Boolean.valueOf(IsTimeBased));
}
/** Get Time based.
@return Time based Revenue Recognition rather than Service Level based
*/
public boolean isTimeBased ()
{
Object oo = get_Value(COLUMNNAME_IsTimeBased);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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 Number of Months.
@param NoMonths Number of Months */
public void setNoMonths (int NoMonths)
{
set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths));
}
/** Get Number of Months.
@return Number of Months */
public int getNoMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** RecognitionFrequency AD_Reference_ID=196 */
public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196;
/** Month = M */
public static final String RECOGNITIONFREQUENCY_Month = "M";
/** Quarter = Q */
public static final String RECOGNITIONFREQUENCY_Quarter = "Q";
/** Year = Y */
public static final String RECOGNITIONFREQUENCY_Year = "Y";
/** Set Recognition frequency.
@param RecognitionFrequency Recognition frequency */
public void setRecognitionFrequency (String RecognitionFrequency)
{
set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency);
}
/** Get Recognition frequency.
@return Recognition frequency */
public String getRecognitionFrequency ()
{
return (String)get_Value(COLUMNNAME_RecognitionFrequency);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java
| 1
|
请完成以下Java代码
|
public class IdmEngineImpl implements IdmEngine {
private static final Logger LOGGER = LoggerFactory.getLogger(IdmEngineImpl.class);
protected String name;
protected IdmIdentityService identityService;
protected IdmManagementService managementService;
protected IdmEngineConfiguration engineConfiguration;
protected CommandExecutor commandExecutor;
public IdmEngineImpl(IdmEngineConfiguration engineConfiguration) {
this.engineConfiguration = engineConfiguration;
this.name = engineConfiguration.getEngineName();
this.identityService = engineConfiguration.getIdmIdentityService();
this.managementService = engineConfiguration.getIdmManagementService();
this.commandExecutor = engineConfiguration.getCommandExecutor();
if (engineConfiguration.getSchemaManagementCmd() != null) {
engineConfiguration.getCommandExecutor().execute(engineConfiguration.getSchemaCommandConfig(), engineConfiguration.getSchemaManagementCmd());
}
if (name == null) {
LOGGER.info("default flowable IdmEngine created");
} else {
LOGGER.info("IdmEngine {} created", name);
}
IdmEngines.registerIdmEngine(this);
if (engineConfiguration.getEngineLifecycleListeners() != null) {
for (EngineLifecycleListener engineLifecycleListener : engineConfiguration.getEngineLifecycleListeners()) {
engineLifecycleListener.onEngineBuilt(this);
}
}
}
@Override
public void close() {
IdmEngines.unregister(this);
engineConfiguration.close();
if (engineConfiguration.getEngineLifecycleListeners() != null) {
for (EngineLifecycleListener engineLifecycleListener : engineConfiguration.getEngineLifecycleListeners()) {
engineLifecycleListener.onEngineClosed(this);
}
}
}
// getters and setters
|
// //////////////////////////////////////////////////////
@Override
public String getName() {
return name;
}
@Override
public IdmIdentityService getIdmIdentityService() {
return identityService;
}
@Override
public IdmManagementService getIdmManagementService() {
return managementService;
}
@Override
public IdmEngineConfiguration getIdmEngineConfiguration() {
return engineConfiguration;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\IdmEngineImpl.java
| 1
|
请完成以下Java代码
|
boolean isTranslated()
{
return this.IsTranslated;
}
public String getColumnSQL()
{
return this.ColumnSQL;
}
public boolean isVirtualColumn()
{
return this.virtualColumn;
}
public String getColumnSqlForSelect()
{
return sqlColumnForSelect;
}
public ReferenceId getAD_Reference_Value_ID()
{
return AD_Reference_Value_ID;
}
public boolean isSelectionColumn()
{
return IsSelectionColumn;
}
public boolean isMandatory()
{
return IsMandatory;
}
public boolean isKey()
{
return IsKey;
}
public boolean isParent()
{
return IsParent;
}
public boolean isStaleable()
{
return IsStaleable;
}
public boolean isLookup()
{
return org.compiere.util.DisplayType.isLookup(displayType);
}
public int getAD_Sequence_ID()
{
return AD_Sequence_ID;
}
|
public boolean isIdentifier()
{
return IsIdentifier;
}
@Nullable
public String getReferencedTableNameOrNull()
{
return _referencedTableName.orElse(null);
}
private static Optional<String> computeReferencedTableName(
final int displayType,
@Nullable final TableName adReferenceValueTableName)
{
// Special lookups (Location, Locator etc)
final String refTableName = DisplayType.getTableName(displayType);
if (refTableName != null)
{
return Optional.of(refTableName);
}
if (DisplayType.isLookup(displayType) && adReferenceValueTableName != null)
{
return Optional.of(adReferenceValueTableName.getAsString());
}
return Optional.empty();
}
public boolean isPasswordColumn()
{
return DisplayType.isPassword(ColumnName, displayType);
}
} // POInfoColumn
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\POInfoColumn.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
application:
name: Report Service
datasource:
url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/${MYSQL_DB:seedapp}?useUnicode=true&allowPublicKeyRetrieval=true
username: ${MYSQL_USERNAME:root}
password: ${MYSQL_PASSWORD:password}
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://${KEYCLOAK_HOST:localhost}:${KEYCLOAK_PORT:8080}/realms/seedapp
server:
port: 8086
logging:
level:
org.springframework.web: INFO
org.hibernate: INFO
|
ROOT: WARN
gt: DEBUG
management:
tracing:
sampling:
probability: 1.0
zipkin:
export:
tracing:
endpoint: http://${ZIPKIN_HOST:localhost}:${ZIPKIN_PORT:9411}/api/v2/spans
|
repos\spring-boot-web-application-sample-master\main-app\report-service\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public abstract class AbstractBaseDevice implements IDevice
{
/**
* The constructor registers a handler for the {@link DeviceRequestGetConfigParams} request. That handler returns the result of {@link #getRequiredConfigParams()}. This way each subclass can be
* queried for its config params and can be configured with after is was instantiated.
*/
public AbstractBaseDevice()
{
// registering the the handler that returns out required configuration info
registerHandler(DeviceRequestGetConfigParams.class, request -> getRequiredConfigParams());
registerHandler(DeviceRequestConfigureDevice.class, getConfigureDeviceHandler());
}
@SuppressWarnings("rawtypes")
private final ConcurrentHashMap<Class<?>, IDeviceRequestHandler> requestType2Handler = new ConcurrentHashMap<>();
protected final <O extends IDeviceResponse, I extends IDeviceRequest<O>, H extends IDeviceRequestHandler<I, O>> void registerHandler(final Class<I> requestType, final H handler)
{
requestType2Handler.put(requestType, handler);
}
@Override
public final <O extends IDeviceResponse, I extends IDeviceRequest<O>> O accessDevice(final I input)
{
@SuppressWarnings("unchecked")
final IDeviceRequestHandler<IDeviceRequest<IDeviceResponse>, IDeviceResponse> deviceRequestHandler = requestType2Handler.get(input.getClass());
|
@SuppressWarnings("unchecked")
final O response = (O)deviceRequestHandler.handleRequest((IDeviceRequest<IDeviceResponse>)input);
return response;
}
/**
* Currently this method is called from the device's default constructor, so it must work without making any assumption about the device's initialization state.
*/
public abstract IDeviceResponseGetConfigParams getRequiredConfigParams();
/**
* Returns that particular request handler which is in charge of configuring the device using parameters from the "outside world".
*/
public abstract IDeviceRequestHandler<DeviceRequestConfigureDevice, IDeviceResponse> getConfigureDeviceHandler();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.api\src\main\java\de\metas\device\api\AbstractBaseDevice.java
| 1
|
请完成以下Java代码
|
private void printUsage(Command command) {
try {
int maxOptionsLength = 0;
List<OptionHelpLine> optionHelpLines = new ArrayList<>();
for (OptionHelp optionHelp : command.getOptionsHelp()) {
OptionHelpLine optionHelpLine = new OptionHelpLine(optionHelp);
optionHelpLines.add(optionHelpLine);
maxOptionsLength = Math.max(maxOptionsLength, optionHelpLine.getOptions().length());
}
this.console.println();
this.console.println("Usage:");
this.console.println(command.getName() + " " + command.getUsageHelp());
for (OptionHelpLine optionHelpLine : optionHelpLines) {
this.console.println(String.format("\t%" + maxOptionsLength + "s: %s", optionHelpLine.getOptions(),
optionHelpLine.getUsage()));
}
this.console.drawLine();
}
catch (IOException ex) {
Log.error(ex.getMessage() + " (" + ex.getClass().getName() + ")");
}
}
|
/**
* Encapsulated options and usage help.
*/
private static class OptionHelpLine {
private final String options;
private final String usage;
OptionHelpLine(OptionHelp optionHelp) {
this.options = String.join(", ", optionHelp.getOptions());
this.usage = optionHelp.getUsageHelp();
}
String getOptions() {
return this.options;
}
String getUsage() {
return this.usage;
}
}
}
|
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\CommandCompleter.java
| 1
|
请完成以下Java代码
|
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEntered (final BigDecimal QtyEntered)
{
|
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderSummary.java
| 1
|
请完成以下Java代码
|
public void check(HealthCheckRequest request, StreamObserver<HealthCheckResponse> responseObserver) {
if (!request.getService().isEmpty()) {
HealthComponent health = healthEndpoint.healthForPath(request.getService());
if (health == null) {
responseObserver.onError(
new StatusException(NOT_FOUND.withDescription("unknown service " + request.getService())));
return;
}
Status status = health.getStatus();
HealthCheckResponse.ServingStatus result = resolveStatus(status);
HealthCheckResponse response = HealthCheckResponse.newBuilder().setStatus(result).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
} else {
Status status = healthEndpoint.health().getStatus();
HealthCheckResponse.ServingStatus result = resolveStatus(status);
|
HealthCheckResponse response = HealthCheckResponse.newBuilder().setStatus(result).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
private HealthCheckResponse.ServingStatus resolveStatus(Status status) {
if (Status.UP.equals(status)) {
return HealthCheckResponse.ServingStatus.SERVING;
}
if (Status.DOWN.equals(status) || Status.OUT_OF_SERVICE.equals(status)) {
return HealthCheckResponse.ServingStatus.NOT_SERVING;
}
return HealthCheckResponse.ServingStatus.UNKNOWN;
}
}
|
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\health\ActuatorGrpcHealth.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BusinessRuleRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, BusinessRulesCollection> cache = CCache.<Integer, BusinessRulesCollection>builder()
.tableName(I_AD_BusinessRule.Table_Name)
.additionalTableNameToResetFor(I_AD_BusinessRule_Precondition.Table_Name)
.additionalTableNameToResetFor(I_AD_BusinessRule_Trigger.Table_Name)
.additionalTableNameToResetFor(I_AD_BusinessRule_WarningTarget.Table_Name)
.build();
public void addCacheResetListener(@NonNull final BusinessRulesChangedListener listener)
{
final ICacheResetListener cacheResetListener = (request) -> {
listener.onRulesChanged();
return 1L;
};
final CacheMgt cacheMgt = CacheMgt.get();
cacheMgt.addCacheResetListener(I_AD_BusinessRule.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_Precondition.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_Trigger.Table_Name, cacheResetListener);
cacheMgt.addCacheResetListener(I_AD_BusinessRule_WarningTarget.Table_Name, cacheResetListener);
}
public BusinessRulesCollection getAll()
{
return cache.getOrLoad(0, this::retrieveAll);
}
private BusinessRulesCollection retrieveAll() {return newLoader().retrieveAll();}
|
private BusinessRuleLoader newLoader()
{
return BusinessRuleLoader.builder()
.queryBL(queryBL)
.build();
}
public void validate(final I_AD_BusinessRule record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_Precondition record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_Trigger record) {newLoader().validate(record);}
public void validate(final I_AD_BusinessRule_WarningTarget record) {newLoader().validate(record);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\business_rule\descriptor\BusinessRuleRepository.java
| 2
|
请完成以下Java代码
|
public int getAD_AlertRecipient_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_AlertRecipient_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_Role getAD_Role() throws RuntimeException
{
return (I_AD_Role)MTable.get(getCtx(), I_AD_Role.Table_Name)
.getPO(getAD_Role_ID(), get_TrxName()); }
/** Set Role.
@param AD_Role_ID
Responsibility Role
*/
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_Value (COLUMNNAME_AD_Role_ID, null);
else
set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Role.
@return Responsibility Role
*/
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_Value (COLUMNNAME_AD_User_ID, null);
|
else
set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertRecipient.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Dict yun(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return Dict.create().set("code", 400).set("message", "文件内容为空");
}
String fileName = file.getOriginalFilename();
String rawFileName = StrUtil.subBefore(fileName, ".", true);
String fileType = StrUtil.subAfter(fileName, ".", true);
String localFilePath = StrUtil.appendIfMissing(fileTempPath, "/") + rawFileName + "-" + DateUtil.current(false) + "." + fileType;
try {
file.transferTo(new File(localFilePath));
Response response = qiNiuService.uploadFile(new File(localFilePath));
if (response.isOK()) {
JSONObject jsonObject = JSONUtil.parseObj(response.bodyString());
String yunFileName = jsonObject.getStr("key");
String yunFilePath = StrUtil.appendIfMissing(prefix, "/") + yunFileName;
|
FileUtil.del(new File(localFilePath));
log.info("【文件上传至七牛云】绝对路径:{}", yunFilePath);
return Dict.create().set("code", 200).set("message", "上传成功").set("data", Dict.create().set("fileName", yunFileName).set("filePath", yunFilePath));
} else {
log.error("【文件上传至七牛云】失败,{}", JSONUtil.toJsonStr(response));
FileUtil.del(new File(localFilePath));
return Dict.create().set("code", 500).set("message", "文件上传失败");
}
} catch (IOException e) {
log.error("【文件上传至七牛云】失败,绝对路径:{}", localFilePath);
return Dict.create().set("code", 500).set("message", "文件上传失败");
}
}
}
|
repos\spring-boot-demo-master\demo-upload\src\main\java\com\xkcoding\upload\controller\UploadController.java
| 2
|
请完成以下Java代码
|
private List<ProductsProposalRow> updateLastShipmentDays(final List<ProductsProposalRow> rows)
{
final Set<ProductId> productIds = rows.stream().map(ProductsProposalRow::getProductId).collect(ImmutableSet.toImmutableSet());
if (productIds.isEmpty())
{
return rows;
}
final Map<ProductId, BPartnerProductStats> statsByProductId = bpartnerProductStatsService.getByPartnerAndProducts(bpartnerId, productIds);
return rows.stream()
.map(row -> updateRowFromStats(row, statsByProductId.get(row.getProductId())))
.collect(ImmutableList.toImmutableList());
}
private ProductsProposalRow updateRowFromStats(
@NonNull final ProductsProposalRow row,
@Nullable final BPartnerProductStats stats)
{
final Integer lastShipmentOrReceiptInDays = calculateLastShipmentOrReceiptInDays(stats);
return row.withLastShipmentDays(lastShipmentOrReceiptInDays);
|
}
@Nullable
private Integer calculateLastShipmentOrReceiptInDays(@Nullable final BPartnerProductStats stats)
{
if (stats == null)
{
return null;
}
else if (soTrx.isSales())
{
return stats.getLastShipmentInDays();
}
else
{
return stats.getLastReceiptInDays();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowsLoader.java
| 1
|
请完成以下Java代码
|
private int getWindowNo()
{
return windowNo;
}
/**
* ActionListener
*
* @param e
*/
@Override
public void actionPerformed(final ActionEvent e)
{
if (e.getSource() == fileButton)
{
cmd_file();
}
//
// OK: caller shall take the new image
else if (ConfirmPanel.A_OK.equals(e.getActionCommand()))
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
InterfaceWrapperHelper.save(m_mImage);
canceled = false;
dispose();
}
catch (final Exception ex)
{
clientUI.error(getWindowNo(), ex);
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
//
// Reset: caller shall reset the field value
else if (ConfirmPanel.A_RESET.equals(e.getActionCommand()))
{
m_mImage = null; // reset
canceled = false;
dispose();
}
} // actionPerformed
/**
* Load file & display
*/
private void cmd_file()
{
// Show File Open Dialog
final JFileChooser jfc = new JFileChooser();
jfc.setMultiSelectionEnabled(false);
jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
jfc.showOpenDialog(this);
// Get File Name
final File imageFile = jfc.getSelectedFile();
if (imageFile == null || imageFile.isDirectory() || !imageFile.exists())
{
return;
}
final String fileName = imageFile.getAbsolutePath();
//
// See if we can load & display it
final byte[] data;
final ImageIcon image;
try
{
data = Util.readBytes(imageFile);
|
image = new ImageIcon(data, fileName);
}
catch (final Exception e)
{
clientUI.error(getWindowNo(), e);
return;
}
//
// Update UI
fileButton.setText(imageFile.getAbsolutePath());
imagePreviewLabel.setIcon(image);
confirmPanel.getOKButton().setEnabled(true);
pack();
// Save info
m_mImage.setName(fileName);
m_mImage.setImageURL(fileName);
m_mImage.setBinaryData(data);
} // cmd_file
/**
* Get Image ID
*
* @return ID or -1
*/
public int getAD_Image_ID()
{
if (m_mImage != null && m_mImage.getAD_Image_ID() > 0)
{
return m_mImage.getAD_Image_ID();
}
return -1;
}
/**
* @return true if the window was canceled and the caller shall ignore the result
*/
public boolean isCanceled()
{
return canceled;
}
} // VImageDialog
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VImageDialog.java
| 1
|
请完成以下Java代码
|
private void validateQueueProcessorAssignment(@NonNull final IQueueProcessor queueProcessor)
{
if (!getSupportedQueueProcessors().contains(queueProcessor.getClass()))
{
final String supportedClassNames = getSupportedQueueProcessors().stream().map(Class::getName).collect(Collectors.joining(","));
throw new AdempiereException("QueueProcessorPlanner can only take: [" + supportedClassNames + "]! but received: " + queueProcessor.getClass().getName());
}
}
@NonNull
private Integer getPollIntervalMillis()
{
return sysConfigBL.getIntValue(SYSCONFIG_POLLINTERVAL_MILLIS, SYSCONFIG_POLLINTERVAL_DEFAULT_MS);
}
@NonNull
private List<IQueueProcessor> getQueueProcessorsAvailableToWork()
{
return queueProcessors
.values()
.stream()
.filter(IQueueProcessor::isAvailableToWork)
.collect(ImmutableList.toImmutableList());
}
private static boolean isValid(final I_C_Queue_WorkPackage workPackage)
{
if (workPackage == null)
{
return false;
}
if (workPackage.isProcessed())
{
return false;
}
if (workPackage.isError())
{
return false;
}
return true;
}
|
private static void setupNewCtxForWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage, @NonNull final Properties commonCtx)
{
final Properties newCtx = Env.copyCtx(commonCtx);
InterfaceWrapperHelper.setCtx(workPackage, newCtx);
WorkPackageQueue.setupWorkPackageContext(newCtx, workPackage);
}
protected abstract boolean handleWorkPackageProcessing(@NonNull final IQueueProcessor queueProcessor, @NonNull final I_C_Queue_WorkPackage workPackage);
protected abstract void startPlanner();
protected abstract void shutdownPlanner();
protected abstract Set<Class<? extends AbstractQueueProcessor>> getSupportedQueueProcessors();
protected abstract boolean isStopOnFailedRun();
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\planner\QueueProcessorPlanner.java
| 1
|
请完成以下Java代码
|
public boolean isConfigChanged()
{
return configChanged;
}
public int getTargetDLMLevel()
{
return targetDLMLevel;
}
public int getCurrentDLMLevel()
{
return currentDLMLevel;
}
public Timestamp getNextInspectionDate()
{
return nextInspectionDate;
}
public int getDLM_Partition_ID()
{
return DLM_Partition_ID;
}
public boolean isAborted()
{
return aborted;
}
@Override
public String toString()
{
return "Partition [DLM_Partition_ID=" + DLM_Partition_ID + ", records.size()=" + records.size() + ", recordsChanged=" + recordsChanged + ", configChanged=" + configChanged + ", targetDLMLevel=" + targetDLMLevel + ", currentDLMLevel=" + currentDLMLevel + ", nextInspectionDate=" + nextInspectionDate + "]";
}
public static class WorkQueue
{
public static WorkQueue of(final I_DLM_Partition_Workqueue workqueueDB)
{
final ITableRecordReference tableRecordRef = TableRecordReference.ofReferencedOrNull(workqueueDB);
final WorkQueue result = new WorkQueue(tableRecordRef);
result.setDLM_Partition_Workqueue_ID(workqueueDB.getDLM_Partition_Workqueue_ID());
return result;
}
|
public static WorkQueue of(final ITableRecordReference tableRecordRef)
{
return new WorkQueue(tableRecordRef);
}
private final ITableRecordReference tableRecordReference;
private int dlmPartitionWorkqueueId;
private WorkQueue(final ITableRecordReference tableRecordReference)
{
this.tableRecordReference = tableRecordReference;
}
public ITableRecordReference getTableRecordReference()
{
return tableRecordReference;
}
public int getDLM_Partition_Workqueue_ID()
{
return dlmPartitionWorkqueueId;
}
public void setDLM_Partition_Workqueue_ID(final int dlm_Partition_Workqueue_ID)
{
dlmPartitionWorkqueueId = dlm_Partition_Workqueue_ID;
}
@Override
public String toString()
{
return "Partition.WorkQueue [DLM_Partition_Workqueue_ID=" + dlmPartitionWorkqueueId + ", tableRecordReference=" + tableRecordReference + "]";
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\Partition.java
| 1
|
请完成以下Java代码
|
public class ConsumerPausedEvent extends KafkaEvent {
private static final long serialVersionUID = 1L;
private final @Nullable String reason;
private transient Collection<TopicPartition> partitions;
/**
* Construct an instance with the provided source and partitions.
* @param source the container instance that generated the event.
* @param container the container or the parent container if the container is a child.
* @param partitions the partitions.
* @since 2.2.1
*/
public ConsumerPausedEvent(Object source, Object container, Collection<TopicPartition> partitions) {
super(source, container);
this.partitions = partitions;
this.reason = null;
}
/**
* Construct an instance with the provided source and partitions.
* @param source the container instance that generated the event.
* @param container the container or the parent container if the container is a child.
* @param partitions the partitions.
* @param reason the reason for the pause.
* @since 2.8.9
*/
public ConsumerPausedEvent(Object source, Object container, Collection<TopicPartition> partitions,
String reason) {
super(source, container);
|
this.partitions = partitions;
this.reason = reason;
}
/**
* Return the paused partitions.
* @return the partitions.
*/
public Collection<TopicPartition> getPartitions() {
return this.partitions;
}
@Override
public String toString() {
return "ConsumerPausedEvent [reason=" + this.reason + ", partitions=" + this.partitions + "]";
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\ConsumerPausedEvent.java
| 1
|
请完成以下Java代码
|
public ExplainedOptional<AggregatedCostAmount> getCreateCosts(final AcctSchema as)
{
final AcctSchemaId acctSchemaId = as.getId();
if (isReversalLine())
{
return services.createReversalCostDetailsOrEmpty(
CostDetailReverseRequest.builder()
.acctSchemaId(acctSchemaId)
.reversalDocumentRef(CostingDocumentRef.ofCostCollectorId(get_ID()))
.initialDocumentRef(CostingDocumentRef.ofCostCollectorId(getReversalLine_ID()))
.date(getDateAcctAsInstant())
.build())
.map(CostDetailCreateResultsList::toAggregatedCostAmount);
}
else
{
|
return services.createCostDetailOrEmpty(
CostDetailCreateRequest.builder()
.acctSchemaId(acctSchemaId)
.clientId(getClientId())
.orgId(getOrgId())
.productId(getProductId())
.attributeSetInstanceId(getAttributeSetInstanceId())
.documentRef(CostingDocumentRef.ofCostCollectorId(get_ID()))
.qty(getQty())
.amt(CostAmount.zero(as.getCurrencyId())) // N/A
.date(getDateAcctAsInstant())
.build())
.map(CostDetailCreateResultsList::toAggregatedCostAmount);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\acct\DocLine_CostCollector.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Optional<Comment> findById(long id) {
return repository.findById(id)
.map(commentMapper::toDomain);
}
@Override
public Optional<CommentAssembly> findAssemblyById(Long userId, long id) {
return assemblyRepository.findById(id, userId)
.map(commentMapper::toDomain);
}
@Override
public List<CommentAssembly> findAllAssemblyByArticleId(Long userId, long articleId) {
return assemblyRepository.findAllByArticleId(articleId, userId).stream()
.map(commentMapper::toDomain)
.toList();
}
@Override
public Comment save(Comment comment) {
var entity = commentMapper.fromDomain(comment);
var saved = repository.save(entity);
return commentMapper.toDomain(saved);
}
@Override
public void deleteById(long id) {
repository.deleteById(id);
}
@Override
public void deleteAllByArticleId(long articleId) {
repository.deleteAllByArticleId(articleId);
}
@Mapper(config = MappingConfig.class)
interface CommentMapper {
|
Comment toDomain(CommentJdbcEntity source);
CommentJdbcEntity fromDomain(Comment source);
@Mapping(target = "author", source = "source")
CommentAssembly toDomain(CommentAssemblyJdbcEntity source);
default Profile profile(CommentAssemblyJdbcEntity source) {
return new Profile(source.authorUsername(),
source.authorBio(),
source.authorImage(),
source.authorFollowing());
}
}
}
|
repos\realworld-backend-spring-master\service\src\main\java\com\github\al\realworld\infrastructure\db\jdbc\CommentJdbcRepositoryAdapter.java
| 2
|
请完成以下Java代码
|
public void close() throws IOException {
doOnResponseCommitted();
this.delegate.close();
}
@Override
public void print(boolean b) throws IOException {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) throws IOException {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(double d) throws IOException {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(float f) throws IOException {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(int i) throws IOException {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) throws IOException {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(String s) throws IOException {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void println() throws IOException {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean b) throws IOException {
trackContentLength(b);
trackContentLengthLn();
this.delegate.println(b);
}
@Override
public void println(char c) throws IOException {
trackContentLength(c);
trackContentLengthLn();
this.delegate.println(c);
}
@Override
public void println(double d) throws IOException {
trackContentLength(d);
trackContentLengthLn();
this.delegate.println(d);
}
@Override
public void println(float f) throws IOException {
trackContentLength(f);
trackContentLengthLn();
this.delegate.println(f);
}
@Override
public void println(int i) throws IOException {
trackContentLength(i);
trackContentLengthLn();
this.delegate.println(i);
}
@Override
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
|
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
@Override
public boolean equals(Object obj) {
return this.delegate.equals(obj);
}
@Override
public int hashCode() {
return this.delegate.hashCode();
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\OnCommittedResponseWrapper.java
| 1
|
请完成以下Java代码
|
public IQueryFilter<I_M_HU> createHUOnPickingSlotQueryFilter(final Object contextProvider)
{
final ICompositeQueryFilter<I_M_HU> filters = queryBL.createCompositeQueryFilter(I_M_HU.class);
filters.setJoinOr();
//
// Filter HUs which are open on Picking Slot
{
final IQuery<I_M_PickingSlot> pickingSlotsQuery = queryBL.createQueryBuilder(I_M_PickingSlot.class, contextProvider)
.addOnlyActiveRecordsFilter()
// NOTE: make sure that we are considering only those picking slots where M_HU_ID is set
// If not, well, postgresql will be confused and will evaluate this expression like always false
.addNotEqualsFilter(I_M_PickingSlot.COLUMNNAME_M_HU_ID, null)
.create();
filters.addInSubQueryFilter(I_M_HU.COLUMNNAME_M_HU_ID,
I_M_PickingSlot.COLUMNNAME_M_HU_ID,
pickingSlotsQuery);
}
//
// Filter HUs which are in Picking Slot queue
{
final IQuery<I_M_PickingSlot_HU> pickingSlotsQueueQuery = queryBL.createQueryBuilder(I_M_PickingSlot_HU.class, contextProvider)
.addOnlyActiveRecordsFilter()
.addNotEqualsFilter(I_M_PickingSlot_HU.COLUMN_M_HU_ID, null) // M_HU_ID IS NOT NULL
.create();
filters.addInSubQueryFilter(I_M_HU.COLUMNNAME_M_HU_ID,
I_M_PickingSlot_HU.COLUMNNAME_M_HU_ID,
pickingSlotsQueueQuery);
}
return filters;
|
}
@Override
public boolean isEmpty(final de.metas.picking.model.I_M_PickingSlot pickingSlot)
{
return !queryPickingSlotHUs(pickingSlot).anyMatch();
}
private IQuery<I_M_PickingSlot_HU> queryPickingSlotHUs(final de.metas.picking.model.I_M_PickingSlot pickingSlot)
{
return queryBL.createQueryBuilder(I_M_PickingSlot_HU.class, pickingSlot)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_PickingSlot_HU.COLUMNNAME_M_PickingSlot_ID, pickingSlot.getM_PickingSlot_ID())
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotDAO.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<PageResult<DatabaseDto>> queryDatabase(DatabaseQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(databaseService.queryAll(criteria,pageable),HttpStatus.OK);
}
@Log("新增数据库")
@ApiOperation(value = "新增数据库")
@PostMapping
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> createDatabase(@Validated @RequestBody Database resources){
databaseService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改数据库")
@ApiOperation(value = "修改数据库")
@PutMapping
@PreAuthorize("@el.check('database:edit')")
public ResponseEntity<Object> updateDatabase(@Validated @RequestBody Database resources){
databaseService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除数据库")
@ApiOperation(value = "删除数据库")
@DeleteMapping
@PreAuthorize("@el.check('database:del')")
public ResponseEntity<Object> deleteDatabase(@RequestBody Set<String> ids){
databaseService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
|
@Log("测试数据库链接")
@ApiOperation(value = "测试数据库链接")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('database:testConnect')")
public ResponseEntity<Object> testConnect(@Validated @RequestBody Database resources){
return new ResponseEntity<>(databaseService.testConnection(resources),HttpStatus.CREATED);
}
@Log("执行SQL脚本")
@ApiOperation(value = "执行SQL脚本")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('database:add')")
public ResponseEntity<Object> uploadDatabase(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
String id = request.getParameter("id");
DatabaseDto database = databaseService.findById(id);
String fileName;
if(database != null){
fileName = FileUtil.verifyFilename(file.getOriginalFilename());
File executeFile = new File(fileSavePath + fileName);
FileUtil.del(executeFile);
file.transferTo(executeFile);
String result = SqlUtils.executeFile(database.getJdbcUrl(), database.getUserName(), database.getPwd(), executeFile);
return new ResponseEntity<>(result,HttpStatus.OK);
}else{
throw new BadRequestException("Database not exist");
}
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\DatabaseController.java
| 1
|
请完成以下Java代码
|
private void registerLinks(List<Link> links, Function<List<Link>, String> defaultDescription,
Supplier<BulletedSection<GettingStartedSection.Link>> section) {
if (ObjectUtils.isEmpty(links)) {
return;
}
links.forEach((link) -> {
if (link.getHref() != null) {
String description = (link.getDescription() != null) ? link.getDescription()
: defaultDescription.apply(links);
if (description != null) {
String url = link.getHref().replace("{bootVersion}", this.platformVersion);
section.get().addItem(new GettingStartedSection.Link(url, description));
}
}
});
}
private Function<List<Link>, String> defaultLinkDescription(Dependency dependency) {
return (links) -> (links.size() == 1) ? dependency.getName() : null;
}
private MultiValueMap<GuideType, Link> indexLinks(Dependency dependency) {
MultiValueMap<GuideType, Link> links = new LinkedMultiValueMap<>();
dependency.getLinks().forEach((link) -> {
if ("reference".equals(link.getRel())) {
links.add(GuideType.REFERENCE, link);
}
|
else if ("guide".equals(link.getRel())) {
links.add(GuideType.GUIDE, link);
}
else {
links.add(GuideType.OTHER, link);
}
});
return links;
}
private enum GuideType {
REFERENCE, GUIDE, OTHER
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\RequestedDependenciesHelpDocumentCustomizer.java
| 1
|
请完成以下Java代码
|
public class BankInfo {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int sellerId;
private String firstName;
private String lastName;
private String bankName;
private String routingNumber;
|
private String accountNumber;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private AddressInfo addressInfo;
//Contact
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "contact_id")
private ContactInfo contactInfo;
//Customer
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id")
@JsonIgnore
private Customer customer;
}
|
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-5.Spring-ReactJS-Ecommerce-Shopping\fullstack\backend\model\src\main\java\com\urunov\entity\info\BankInfo.java
| 1
|
请完成以下Java代码
|
public Properties get()
{
final Properties ctx = super.get();
listener.onContextCheckOut(ctx);
return ctx;
};
@Override
public void set(final Properties ctx)
{
final Properties ctxOld = super.get();
super.set(ctx);
listener.onContextCheckIn(ctx, ctxOld);
};
};
@Override
protected Properties getDelegate()
{
return threadLocalContext.get();
}
public ThreadLocalServerContext()
{
super();
}
/**
* Temporarily switches the context in the current thread.
*/
public IAutoCloseable switchContext(final Properties ctx)
{
Check.assumeNotNull(ctx, "ctx not null");
// Avoid StackOverflowException caused by setting the same context
if (ctx == this)
{
return NullAutoCloseable.instance;
}
final long threadIdOnSet = Thread.currentThread().getId();
final Properties ctxOld = threadLocalContext.get();
threadLocalContext.set(ctx);
return new IAutoCloseable()
{
|
private boolean closed = false;
@Override
public void close()
{
// Do nothing if already closed
if (closed)
{
return;
}
// Assert we are restoring the ctx in same thread.
// Because else, we would set the context "back" in another thread which would lead to huge inconsistencies.
if (Thread.currentThread().getId() != threadIdOnSet)
{
throw new IllegalStateException("Error: setting back the context shall be done in the same thread as it was set initially");
}
threadLocalContext.set(ctxOld);
closed = true;
}
};
}
/**
* Dispose the context from current thread
*/
public void dispose()
{
final Properties ctx = threadLocalContext.get();
ctx.clear();
threadLocalContext.remove();
}
public void setListener(@NonNull final IContextProviderListener listener)
{
this.listener = listener;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\context\ThreadLocalServerContext.java
| 1
|
请完成以下Java代码
|
protected void notifyTransformListeners(Decision decision, DmnDecision dmnDecision) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecision(decision, dmnDecision);
}
}
protected void notifyTransformListeners(Input input, DmnDecisionTableInputImpl dmnInput) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableInput(input, dmnInput);
}
}
protected void notifyTransformListeners(Definitions definitions, DmnDecisionRequirementsGraphImpl dmnDecisionRequirementsGraph) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionRequirementsGraph(definitions, dmnDecisionRequirementsGraph);
}
}
protected void notifyTransformListeners(Output output, DmnDecisionTableOutputImpl dmnOutput) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableOutput(output, dmnOutput);
}
}
protected void notifyTransformListeners(Rule rule, DmnDecisionTableRuleImpl dmnRule) {
for (DmnTransformListener transformListener : transformListeners) {
transformListener.transformDecisionTableRule(rule, dmnRule);
}
}
// context //////////////////////////////////////////////////////////////////
public DmnModelInstance getModelInstance() {
return modelInstance;
}
|
public Object getParent() {
return parent;
}
public DmnDecision getDecision() {
return decision;
}
public DmnDataTypeTransformerRegistry getDataTypeTransformerRegistry() {
return dataTypeTransformerRegistry;
}
public DmnHitPolicyHandlerRegistry getHitPolicyHandlerRegistry() {
return hitPolicyHandlerRegistry;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DefaultDmnTransform.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String serialNumber;
private String description;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
|
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
InvoiceEntity that = (InvoiceEntity) o;
return Objects.equals(serialNumber, that.serialNumber);
}
@Override
public int hashCode() {
return Objects.hash(serialNumber);
}
}
|
repos\tutorials-master\persistence-modules\spring-jpa-3\src\main\java\com\baeldung\continuetransactionafterexception\model\InvoiceEntity.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void configureDefaultActivitiRegistry(String registryBeanName, BeanDefinitionRegistry registry) {
if (!beanAlreadyConfigured(registry, registryBeanName, ActivitiStateHandlerRegistry.class)) {
String registryName =ActivitiStateHandlerRegistry.class.getName();
log.info( "registering a " + registryName + " instance under bean name "+ ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME+ ".");
RootBeanDefinition rootBeanDefinition = new RootBeanDefinition();
rootBeanDefinition.setBeanClassName( registryName );
rootBeanDefinition.getPropertyValues().addPropertyValue("processEngine", this.processEngine);
BeanDefinitionHolder holder = new BeanDefinitionHolder(rootBeanDefinition, registryBeanName);
BeanDefinitionReaderUtils.registerBeanDefinition(holder, registry);
}
}
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
configureDefaultActivitiRegistry(ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME, registry);
|
} else {
log.info("BeanFactory is not a BeanDefinitionRegistry. The default '"
+ ActivitiContextUtils.ACTIVITI_REGISTRY_BEAN_NAME + "' cannot be configured.");
}
}
private boolean beanAlreadyConfigured(BeanDefinitionRegistry registry, String beanName, Class clz) {
if (registry.isBeanNameInUse(beanName)) {
BeanDefinition bDef = registry.getBeanDefinition(beanName);
if (bDef.getBeanClassName().equals(clz.getName())) {
return true; // so the beans already registered, and of the right type. so we assume the user is overriding our configuration
} else {
throw new IllegalStateException("The bean name '" + beanName + "' is reserved.");
}
}
return false;
}
}
|
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\components\config\xml\StateHandlerAnnotationBeanFactoryPostProcessor.java
| 2
|
请完成以下Java代码
|
public static Permission[] getPermissionsByResourceType(int givenResourceType) {
Class<? extends Enum<? extends Permission>> clazz = PERMISSION_ENUMS.get(givenResourceType);
if (clazz == null) {
return Permissions.values();
}
return ((Permission[]) clazz.getEnumConstants());
}
/**
* Currently used only in the Rest API
* Returns a {@link Permission} based on the specified <code>permissionName</code> and <code>resourceType</code>
* @throws BadUserRequestException in case the permission is not valid for the specified resource type
*/
public static Permission getPermissionByNameAndResourceType(String permissionName, int resourceType) {
for (Permission permission : getPermissionsByResourceType(resourceType)) {
if (permission.getName().equals(permissionName)) {
return permission;
}
}
throw new BadUserRequestException(
String.format("The permission '%s' is not valid for '%s' resource type.", permissionName, getResourceByType(resourceType))
|
);
}
/**
* Iterates over the {@link Resources} and
* returns either the resource with specified <code>resourceType</code> or <code>null</code>.
*/
public static Resource getResourceByType(int resourceType) {
for (Resource resource : Resources.values()) {
if (resource.resourceType() == resourceType) {
return resource;
}
}
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ResourceTypeUtil.java
| 1
|
请完成以下Java代码
|
public class PrintingClientDelegate implements IPrintingClientDelegate
{
private static final transient Logger logger = LogManager.getLogger(PrintingClientDelegate.class);
/**
* The actual printing client. Will be initialized in constructor
*/
private PrintingClient client;
public PrintingClientDelegate()
{
client = createPrintingClient();
}
private PrintingClient createPrintingClient()
{
final Context ctx = Context.getContext();
ctx.addSource(new EnvContext());
ctx.addSource(new SysConfigContext());
// the swing client can always use the loopback endpoint, as it has direct (DB-)access to the server
ctx.setProperty(Context.CTX_PrintConnectionEndpoint, LoopbackPrintConnectionEndpoint.class.getName());
// ctx.setProperty(Context.CTX_UserInterface, new SwingUserInterface(this));
logger.info("Context: " + ctx);
//
// Create printing client, but don't start it by default
final boolean start = false;
final PrintingClient client = new PrintingClient(start);
return client;
}
@Override
public boolean isStarted()
{
return client.isStarted();
|
}
@Override
public void start()
{
client.start();
}
@Override
public void stop()
{
client.stop();
}
@Override
public void destroy()
{
if (client != null)
{
client.destroy();
}
client = null;
}
@Override
public void restart()
{
stop();
start();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.embedded-client\src\main\java\de\metas\printing\client\impl\PrintingClientDelegate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class InvoiceToExport
{
public static final String CURRENCY_CHF = "CHF";
@NonNull
InvoiceId id;
@NonNull
DocBaseAndSubType docBaseAndSubType;
@NonNull
MetasfreshVersion metasfreshVersion;
@NonNull
GregorianCalendar invoiceDate;
@NonNull
Instant invoiceTimestamp;
@NonNull
String documentNumber;
@NonNull
BPartner biller;
@NonNull
BPartner recipient;
boolean isReversal;
@NonNull
|
Money amount;
@NonNull
Money alreadyPaidAmount;
@Nullable
CustomInvoicePayload customInvoicePayload;
@Singular("invoiceTax")
List<InvoiceTax> invoiceTaxes;
@Singular
List<InvoiceLine> invoiceLines;
@Singular
List<InvoiceAttachment> invoiceAttachments;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.invoice_gateway.spi\src\main\java\de\metas\invoice_gateway\spi\model\export\InvoiceToExport.java
| 2
|
请完成以下Java代码
|
public String qty(final ICalloutField calloutField)
{
if (isCalloutActive())
{// prevent recursive
return NO_ERROR;
}
if (isDoInvocation(calloutField))
{
return new CalloutOrder().qty(calloutField);
}
return NO_ERROR;
}
private boolean isDoInvocation(final ICalloutField calloutField)
{
if (!I_C_OrderLine.COLUMNNAME_QtyEntered.equals(calloutField.getColumnName()))
{
// execute the callout
return true;
}
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
// don't execute the callout
if(subscriptionBL.isSubscription(ol))
{
return false;
}
//execute the callout
return true;
}
// metas
public String subscriptionLocation(final ICalloutField calloutField)
{
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
final I_C_Order order = ol.getC_Order();
final boolean IsSOTrx = order.isSOTrx();
final boolean isSubscription = ol.isSubscription();
if (IsSOTrx && !isSubscription)
{
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
final Quantity qty = orderLineBL.getQtyEntered(ol);
final BigDecimal qtyOrdered = orderLineBL.convertQtyEnteredToStockUOM(ol).toBigDecimal();
ol.setQtyOrdered(qtyOrdered);
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder()
.orderLine(ol)
.qtyOverride(qty)
.resultUOM(ResultUOM.CONTEXT_UOM)
.updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true)
.updateLineNetAmt(true)
.build());
}
if (IsSOTrx && isSubscription)
{
final int C_BPartner_ID = order.getC_BPartner_ID();
|
PreparedStatement pstmt = null;
ResultSet rs = null;
final String sql = "SELECT C_BPartner_Location_ID FROM C_BPartner_Location "
+ " WHERE C_BPartner_ID = ? "
+ " ORDER BY IsSubscriptionToDefault DESC";
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
final int bpartnerLocationId = rs.getInt(1);
order.setC_BPartner_Location_ID(bpartnerLocationId);
log.debug("C_BPartner_Location_ID for Subscription changed -> " + bpartnerLocationId);
}
}
catch (final SQLException e)
{
log.error(sql, e);
return e.getLocalizedMessage();
}
finally
{
DB.close(rs, pstmt);
}
}
return NO_ERROR;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\callout\OrderLine.java
| 1
|
请完成以下Java代码
|
public class Product {
private long id;
private String title;
private LocalDateTime createdTs;
private BigDecimal price;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public LocalDateTime getCreatedTs() {
return createdTs;
}
public void setCreatedTs(LocalDateTime createdTs) {
this.createdTs = createdTs;
|
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Product{");
sb.append("id=").append(id);
sb.append(", title='").append(title).append('\'');
sb.append(", createdTs=").append(createdTs);
sb.append(", price=").append(price);
sb.append('}');
return sb.toString();
}
}
|
repos\tutorials-master\persistence-modules\spring-jdbc\src\main\java\com\baeldung\spring\jdbc\batch\model\Product.java
| 1
|
请完成以下Java代码
|
private void updateTranslationsForElement(final I_AD_Window window)
{
final AdElementId windowElementId = AdElementId.ofRepoIdOrNull(window.getAD_Element_ID());
if (windowElementId == null)
{
// nothing to do. It was not yet set
return;
}
elementTranslationBL.updateWindowTranslationsFromElement(windowElementId);
}
private void recreateElementLinkForWindow(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(window.getAD_Window_ID());
if (adWindowId != null)
|
{
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.recreateADElementLinkForWindowId(adWindowId);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onBeforeWindowDelete(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoId(window.getAD_Window_ID());
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.deleteExistingADElementLinkForWindowId(adWindowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\model\interceptor\AD_Window.java
| 1
|
请完成以下Java代码
|
public void setIsTranslated (final boolean IsTranslated)
{
set_Value (COLUMNNAME_IsTranslated, IsTranslated);
}
@Override
public boolean isTranslated()
{
return get_ValueAsBoolean(COLUMNNAME_IsTranslated);
}
@Override
public org.compiere.model.I_M_HazardSymbol getM_HazardSymbol()
{
return get_ValueAsPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class);
}
@Override
public void setM_HazardSymbol(final org.compiere.model.I_M_HazardSymbol M_HazardSymbol)
{
set_ValueFromPO(COLUMNNAME_M_HazardSymbol_ID, org.compiere.model.I_M_HazardSymbol.class, M_HazardSymbol);
}
@Override
public void setM_HazardSymbol_ID (final int M_HazardSymbol_ID)
{
if (M_HazardSymbol_ID < 1)
|
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HazardSymbol_ID, M_HazardSymbol_ID);
}
@Override
public int getM_HazardSymbol_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HazardSymbol_ID);
}
@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_M_HazardSymbol_Trl.java
| 1
|
请完成以下Java代码
|
public int getRecord_ID()
{
return prospect.getR_Group_ID();
}
@Override
public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder()
.clientId(getClientId())
.orgId(getOrgId())
.adProcessId(getProcessInfo().getAdProcessId())
.fromUserId(UserId.ofRepoId(from.getAD_User_ID()))
.build());
return mailService.sendEMail(EMailRequest.builder()
.mailbox(mailbox)
.toList(toEMailAddresses(toEmail))
.subject(text.getSubject())
.message(text.getTextSnippetParsed(attributes))
.html(true)
.build());
}
|
});
}
private void notifyLetter(MADBoilerPlate text, MRGroupProspect prospect)
{
throw new UnsupportedOperationException();
}
private List<MRGroupProspect> getProspects(int R_Group_ID)
{
final String whereClause = MRGroupProspect.COLUMNNAME_R_Group_ID + "=?";
return new Query(getCtx(), MRGroupProspect.Table_Name, whereClause, get_TrxName())
.setParameters(R_Group_ID)
.list(MRGroupProspect.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToGroup.java
| 1
|
请完成以下Java代码
|
public void uncheckPath(TreePath path) {
// uncheck is propagated to children
this.model.uncheckSubTree(path);
TreePath parentPath = path;
// check all the ancestors with subtrees checked
while ((parentPath = parentPath.getParentPath()) != null) {
switch (this.model.getChildrenChecking(parentPath)) {
case HALF_CHECKED:
this.model.addToCheckedPathsSet(parentPath);
this.model.addToGreyedPathsSet(parentPath);
break;
case ALL_UNCHECKED:
this.model.removeFromCheckedPathsSet(parentPath);
this.model.removeFromGreyedPathsSet(parentPath);
break;
case ALL_CHECKED:
System.err.println("This should not happen (PropagatePreservingUncheckTreeCheckingMode)");
break;
default:
case NO_CHILDREN:
System.err.println("This should not happen (PropagatePreservingCheckTreeCheckingMode)");
break;
}
}
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenInserted(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterChildrenInserted(TreePath parent) {
if (this.model.isPathChecked(parent)) {
this.model.checkSubTree(parent);
} else {
this.model.uncheckSubTree(parent);
}
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterChildrenRemoved(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterChildrenRemoved(TreePath parent) {
if (this.model.isPathChecked(parent)) {
// System.out.println(parent +" was removed (not checked)");
|
if (this.model.getChildrenPath(parent).length != 0) {
if (!this.model.pathHasChildrenWithValue(parent, true)) {
// System.out.println("uncheking it");
uncheckPath(parent);
}
}
}
this.model.updatePathGreyness(parent);
this.model.updateAncestorsGreyness(parent);
}
/*
* (non-Javadoc)
*
* @see it.cnr.imaa.essi.lablib.gui.checkboxtree.TreeCheckingMode#updateCheckAfterStructureChanged(javax.swing.tree.TreePath)
*/
@Override
public void updateCheckAfterStructureChanged(TreePath parent) {
if (this.model.isPathChecked(parent)) {
checkPath(parent);
} else {
uncheckPath(parent);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\PropagatePreservingUncheckTreeCheckingMode.java
| 1
|
请完成以下Java代码
|
abstract class AbstractVariableEvaluationContextPostProcessor
implements EvaluationContextPostProcessor<FilterInvocation> {
@Override
public final EvaluationContext postProcess(EvaluationContext context, FilterInvocation invocation) {
return new VariableEvaluationContext(context, invocation.getHttpRequest());
}
abstract Map<String, String> extractVariables(HttpServletRequest request);
/**
* {@link DelegatingEvaluationContext} to expose variable.
*/
class VariableEvaluationContext extends DelegatingEvaluationContext {
private final HttpServletRequest request;
private @Nullable Map<String, String> variables;
|
VariableEvaluationContext(EvaluationContext delegate, HttpServletRequest request) {
super(delegate);
this.request = request;
}
@Override
public @Nullable Object lookupVariable(String name) {
Object result = super.lookupVariable(name);
if (result != null) {
return result;
}
if (this.variables == null) {
this.variables = extractVariables(this.request);
}
return this.variables.get(name);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\expression\AbstractVariableEvaluationContextPostProcessor.java
| 1
|
请完成以下Java代码
|
public BigDecimal getPointsSum_Invoiced()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_Settled (final BigDecimal PointsSum_Settled)
{
set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled);
}
@Override
public BigDecimal getPointsSum_Settled()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled);
|
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle)
{
set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle);
}
@Override
public BigDecimal getPointsSum_ToSettle()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OpenViewGlobalActionHandlerResult implements GlobalActionHandlerResult
{
private static final String SEPARATOR = "#";
public static final OpenViewGlobalActionHandlerResult ofPayload(final String payload)
{
Check.assumeNotEmpty(payload, "payload is not empty");
final int idx = payload.indexOf(SEPARATOR);
if (idx > 0)
{
final ViewId viewId = ViewId.ofViewIdString(payload.substring(0, idx));
final ViewProfileId viewProfileId = ViewProfileId.fromJson(payload.substring(idx + SEPARATOR.length()));
return of(viewId, viewProfileId);
}
else
{
final ViewId viewId = ViewId.ofViewIdString(payload);
final ViewProfileId viewProfileId = null;
return of(viewId, viewProfileId);
}
}
public String toPayloadString()
|
{
if (viewProfileId != null)
{
return viewId.toJson() + SEPARATOR + viewProfileId.toJson();
}
else
{
return viewId.toJson();
}
}
@NonNull
ViewId viewId;
@Nullable
ViewProfileId viewProfileId;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\globalaction\OpenViewGlobalActionHandlerResult.java
| 2
|
请完成以下Java代码
|
public void setMetasfreshBPartnerId(final JsonMetasfreshId metasfreshBPartnerId)
{
this.metasfreshBPartnerId = metasfreshBPartnerId;
this.metasfreshBPartnerIdSet = true;
}
public void setCode(final String code)
{
this.code = code;
this.codeSet = true;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
public void setName(final String name)
{
this.name = name;
this.nameSet = true;
}
public void setFirstName(final String firstName)
{
this.firstName = firstName;
this.firstNameSet = true;
}
public void setLastName(final String lastName)
{
this.lastName = lastName;
this.lastNameSet = true;
}
public void setEmail(final String email)
{
this.email = email;
this.emailSet = true;
}
public void setPhone(final String phone)
{
this.phone = phone;
this.phoneSet = true;
}
public void setFax(final String fax)
{
this.fax = fax;
this.faxSet = true;
}
public void setMobilePhone(final String mobilePhone)
{
this.mobilePhone = mobilePhone;
this.mobilePhoneSet = true;
}
public void setDefaultContact(final Boolean defaultContact)
{
this.defaultContact = defaultContact;
this.defaultContactSet = true;
}
public void setShipToDefault(final Boolean shipToDefault)
{
this.shipToDefault = shipToDefault;
this.shipToDefaultSet = true;
}
public void setBillToDefault(final Boolean billToDefault)
{
this.billToDefault = billToDefault;
this.billToDefaultSet = true;
}
|
public void setNewsletter(final Boolean newsletter)
{
this.newsletter = newsletter;
this.newsletterSet = true;
}
public void setDescription(final String description)
{
this.description = description;
this.descriptionSet = true;
}
public void setSales(final Boolean sales)
{
this.sales = sales;
this.salesSet = true;
}
public void setSalesDefault(final Boolean salesDefault)
{
this.salesDefault = salesDefault;
this.salesDefaultSet = true;
}
public void setPurchase(final Boolean purchase)
{
this.purchase = purchase;
this.purchaseSet = true;
}
public void setPurchaseDefault(final Boolean purchaseDefault)
{
this.purchaseDefault = purchaseDefault;
this.purchaseDefaultSet = true;
}
public void setSubjectMatter(final Boolean subjectMatter)
{
this.subjectMatter = subjectMatter;
this.subjectMatterSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestContact.java
| 1
|
请完成以下Java代码
|
class RomanArabicConverter {
public static int romanToArabic(String input) {
String romanNumeral = input.toUpperCase();
int result = 0;
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
int i = 0;
while ((romanNumeral.length() > 0) && (i < romanNumerals.size())) {
RomanNumeral symbol = romanNumerals.get(i);
if (romanNumeral.startsWith(symbol.name())) {
result += symbol.getValue();
romanNumeral = romanNumeral.substring(symbol.name().length());
} else {
i++;
}
}
if (romanNumeral.length() > 0) {
throw new IllegalArgumentException(input + " cannot be converted to a Roman Numeral");
}
return result;
}
|
public static String arabicToRoman(int number) {
if ((number <= 0) || (number > 4000)) {
throw new IllegalArgumentException(number + " is not in range (0,4000]");
}
List<RomanNumeral> romanNumerals = RomanNumeral.getReverseSortedValues();
int i = 0;
StringBuilder sb = new StringBuilder();
while (number > 0 && i < romanNumerals.size()) {
RomanNumeral currentSymbol = romanNumerals.get(i);
if (currentSymbol.getValue() <= number) {
sb.append(currentSymbol.name());
number -= currentSymbol.getValue();
} else {
i++;
}
}
return sb.toString();
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-3\src\main\java\com\baeldung\algorithms\romannumerals\RomanArabicConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class M_CostRevaluation implements ITabCallout
{
private final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class);
@PostConstruct
public void postConstruct()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@Override
public void onNew(@NonNull final ICalloutRecord calloutRecord)
{
final I_M_CostRevaluation costRevaluation = calloutRecord.getModel(I_M_CostRevaluation.class);
setDocTypeId(costRevaluation);
}
@CalloutMethod(columnNames = I_M_CostRevaluation.COLUMNNAME_C_DocType_ID)
public void onDocTypeChanged(@NonNull final I_M_CostRevaluation costRevaluation)
{
setDocumentNo(costRevaluation);
}
private void setDocTypeId(final I_M_CostRevaluation costRevaluation)
{
final DocTypeId docTypeId = docTypeDAO.getDocTypeIdOrNull(DocTypeQuery.builder()
.docBaseType(DocBaseType.CostRevaluation)
.docSubType(DocTypeQuery.DOCSUBTYPE_Any)
.adClientId(costRevaluation.getAD_Client_ID())
.adOrgId(costRevaluation.getAD_Org_ID())
.build());
if (docTypeId == null)
{
return;
}
|
costRevaluation.setC_DocType_ID(docTypeId.getRepoId());
}
private void setDocumentNo(final I_M_CostRevaluation costRevaluation)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(costRevaluation.getC_DocType_ID());
if (docTypeId == null)
{
return;
}
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(docTypeDAO.getById(docTypeId))
.setOldDocumentNo(costRevaluation.getDocumentNo())
.setDocumentModel(costRevaluation)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
costRevaluation.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\callout\M_CostRevaluation.java
| 2
|
请完成以下Java代码
|
public AttributeValueId getAttributeValueIdOrNull(final Object valueKey)
{
final String valueKeyNormalized = normalizeValueKey(valueKey);
return getAttributeValuesMap().getAttributeValueId(valueKeyNormalized);
}
private NamePair findValueDirectly(final String valueKey)
{
return attributeValuesNP_HighVolumeCache.computeIfAbsent(valueKey, key -> {
final AttributeListValue av = attributeDAO.retrieveAttributeValueOrNull(attribute, valueKey);
return av == null ? null : toValueNamePair(av);
});
}
@Override
public NamePair getNullValue()
{
return getAttributeValuesMap().getNullValue();
}
@Override
public boolean isHighVolume()
{
if (_highVolume == null)
{
_highVolume = attribute.isHighVolumeValuesList();
}
return _highVolume;
}
@Immutable
private static final class AttributeValuesMap
{
@Getter private final NamePair nullValue;
private final ImmutableMap<String, NamePair> valuesByKey;
private final ImmutableList<NamePair> valuesList;
private final ImmutableMap<String, AttributeValueId> attributeValueIdByKey;
private AttributeValuesMap(final Attribute attribute, final Collection<AttributeListValue> attributeValues)
{
final ImmutableMap.Builder<String, NamePair> valuesByKey = ImmutableMap.builder();
final ImmutableMap.Builder<String, AttributeValueId> attributeValueIdByKey = ImmutableMap.builder();
NamePair nullValue = null;
for (final AttributeListValue av : attributeValues)
{
if (!av.isActive())
{
continue;
}
final ValueNamePair vnp = toValueNamePair(av);
valuesByKey.put(vnp.getValue(), vnp);
attributeValueIdByKey.put(vnp.getValue(), av.getId());
//
|
// Null placeholder value (if defined)
if (av.isNullFieldValue())
{
Check.assumeNull(nullValue, "Only one null value shall be defined for {}, but we found: {}, {}",
attribute.getDisplayName().getDefaultValue(), nullValue, av);
nullValue = vnp;
}
}
this.valuesByKey = valuesByKey.build();
this.valuesList = ImmutableList.copyOf(this.valuesByKey.values());
this.attributeValueIdByKey = attributeValueIdByKey.build();
this.nullValue = nullValue;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("values", valuesList)
.add("nullValue", nullValue)
.toString();
}
public List<NamePair> getValues()
{
return valuesList;
}
public NamePair getValueByKeyOrNull(final String key)
{
return valuesByKey.get(key);
}
public AttributeValueId getAttributeValueId(final String valueKey)
{
final AttributeValueId attributeValueId = attributeValueIdByKey.get(valueKey);
if (attributeValueId == null)
{
throw new AdempiereException("No M_AttributeValue_ID found for '" + valueKey + "'");
}
return attributeValueId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\impl\DefaultAttributeValuesProvider.java
| 1
|
请完成以下Java代码
|
protected List<QueryTable> getQueryTableInfo(String dictCodeString) {
//针对转义字符进行解码
try {
if (dictCodeString.contains("%")) {
dictCodeString = URLDecoder.decode(dictCodeString, "UTF-8");
}
} catch (Exception e) {
//e.printStackTrace();
}
dictCodeString = dictCodeString.trim();
// 无论什么场景 第二、三个元素一定是表的字段,直接add
if (dictCodeString != null && dictCodeString.indexOf(SymbolConstant.COMMA) > 0) {
String[] arr = dictCodeString.split(SymbolConstant.COMMA);
if (arr.length != 3 && arr.length != 4) {
return null;
}
//获取表名
String tableName = getTableName(arr[0]);
QueryTable table = new QueryTable(tableName, "");
// 无论什么场景 第二、三个元素一定是表的字段,直接add
//参数字段1
table.addField(arr[1].trim());
//参数字段2
String filed = arr[2].trim();
if (oConvertUtils.isNotEmpty(filed)) {
table.addField(filed);
}
List<QueryTable> list = new ArrayList<>();
list.add(table);
return list;
}
return null;
}
|
/**
* 取where前面的为:table name
*
* @param str
* @return
*/
private String getTableName(String str) {
String[] arr = str.split("\\s+(?i)where\\s+");
String tableName = arr[0].trim();
//【20230814】解决使用参数tableName=sys_user t&复测,漏洞仍然存在
if (tableName.contains(".")) {
tableName = tableName.substring(tableName.indexOf(".")+1, tableName.length()).trim();
}
if (tableName.contains(" ")) {
tableName = tableName.substring(0, tableName.indexOf(" ")).trim();
}
//【issues/4393】 sys_user , (sys_user), sys_user%20, %60sys_user%60
String reg = "\\s+|\\(|\\)|`";
return tableName.replaceAll(reg, "");
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\security\DictQueryBlackListHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class VariableInstanceDataResource extends VariableInstanceBaseResource {
@GetMapping(value = "/cmmn-runtime/variable-instances/{varInstanceId}/data")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the variable instance was found and the requested variable data is returned."),
@ApiResponse(code = 404, message = "Indicates the requested variable instance was not found or the variable instance does not have a variable with the given name or the variable does not have a binary stream available. Status message provides additional information.") })
@ApiOperation(value = "Get the binary data for a variable instance", tags = {
"Runtime" }, nickname = "getVariableInstanceData", notes = "The response body contains the binary value of the variable. When the variable is of type binary, the content-type of the response is set to application/octet-stream, regardless of the content of the variable or the request accept-type header. In case of serializable, application/x-java-serialized-object is used as content-type.")
@ResponseBody
public byte[] getVariableData(@ApiParam(name = "varInstanceId") @PathVariable("varInstanceId") String varInstanceId, HttpServletResponse response) {
try {
byte[] result = null;
RestVariable variable = getVariableFromRequest(true, varInstanceId);
if (CmmnRestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
result = (byte[]) variable.getValue();
response.setContentType("application/octet-stream");
} else if (CmmnRestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) {
|
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(buffer);
outputStream.writeObject(variable.getValue());
outputStream.close();
result = buffer.toByteArray();
response.setContentType("application/x-java-serialized-object");
} else {
throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null);
}
return result;
} catch (IOException ioe) {
// Re-throw IOException
throw new FlowableException("Unexpected exception getting variable data", ioe);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\variable\VariableInstanceDataResource.java
| 2
|
请完成以下Java代码
|
public class Pair<K,V> implements Serializable {
/**
* Key of this <code>Pair</code>.
*/
private K key;
/**
* Gets the key for this pair.
* @return key for this pair
*/
public K getKey() { return key; }
/**
* Value of this this <code>Pair</code>.
*/
private V value;
/**
* Gets the value for this pair.
* @return value for this pair
*/
public V getValue() { return value; }
/**
* Creates a new pair
* @param key The key for this pair
* @param value The value to use for this pair
*/
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* <p><code>String</code> representation of this
* <code>Pair</code>.</p>
*
* <p>The default name/value delimiter '=' is always used.</p>
*
* @return <code>String</code> representation of this <code>Pair</code>
*/
@Override
public String toString() {
return key + "=" + value;
}
/**
* <p>Generate a hash code for this <code>Pair</code>.</p>
*
* <p>The hash code is calculated using both the name and
* the value of the <code>Pair</code>.</p>
*
* @return hash code for this <code>Pair</code>
*/
@Override
public int hashCode() {
// name's hashCode is multiplied by an arbitrary prime number (13)
// in order to make sure there is a difference in the hashCode between
|
// these two parameters:
// name: a value: aa
// name: aa value: a
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
/**
* <p>Test this <code>Pair</code> for equality with another
* <code>Object</code>.</p>
*
* <p>If the <code>Object</code> to be tested is not a
* <code>Pair</code> or is <code>null</code>, then this method
* returns <code>false</code>.</p>
*
* <p>Two <code>Pair</code>s are considered equal if and only if
* both the names and values are equal.</p>
*
* @param o the <code>Object</code> to test for
* equality with this <code>Pair</code>
* @return <code>true</code> if the given <code>Object</code> is
* equal to this <code>Pair</code> else <code>false</code>
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
return true;
}
return false;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Pair.java
| 1
|
请完成以下Java代码
|
public String toString()
{
StringBuffer sb = new StringBuffer("MDocType[");
sb.append(get_ID()).append("-").append(getName())
.append(",DocNoSequence_ID=").append(getDocNoSequence_ID())
.append("]");
return sb.toString();
} // toString
/**
* Get Print Name
* @param AD_Language language
* @return print Name if available translated
*/
public String getPrintName (String AD_Language)
{
if (AD_Language == null || AD_Language.length() == 0)
{
return super.getPrintName();
}
return get_Translation (COLUMNNAME_PrintName, AD_Language);
} // getPrintName
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success)
{
// Add doctype/docaction access to all roles of client
String sqlDocAction = "INSERT INTO AD_Document_Action_Access "
+ "(AD_Client_ID,AD_Org_ID,IsActive,Created,CreatedBy,Updated,UpdatedBy,"
+ "C_DocType_ID , AD_Ref_List_ID, AD_Role_ID) "
+ "(SELECT "
+ getAD_Client_ID() + ",0,'Y', now(),"
+ getUpdatedBy() + ", now()," + getUpdatedBy()
+ ", doctype.C_DocType_ID, action.AD_Ref_List_ID, rol.AD_Role_ID "
+ "FROM AD_Client client "
+ "INNER JOIN C_DocType doctype ON (doctype.AD_Client_ID=client.AD_Client_ID) "
+ "INNER JOIN AD_Ref_List action ON (action.AD_Reference_ID=135) "
+ "INNER JOIN AD_Role rol ON (rol.AD_Client_ID=client.AD_Client_ID) "
|
+ "WHERE client.AD_Client_ID=" + getAD_Client_ID()
+ " AND doctype.C_DocType_ID=" + get_ID()
+ " AND rol.IsManual='N'"
+ ")";
int docact = DB.executeUpdateAndSaveErrorOnFail(sqlDocAction, get_TrxName());
log.debug("AD_Document_Action_Access=" + docact);
}
return success;
} // afterSave
/**
* Executed after Delete operation.
* @param success true if record deleted
* @return true if delete is a success
*/
@Override
protected boolean afterDelete (boolean success)
{
if(success) {
//delete access records
int docactDel = DB.executeUpdateAndSaveErrorOnFail("DELETE FROM AD_Document_Action_Access WHERE C_DocType_ID=" + get_IDOld(), get_TrxName());
log.debug("Deleting AD_Document_Action_Access=" + docactDel + " for C_DocType_ID: " + get_IDOld());
}
return success;
} // afterDelete
} // MDocType
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MDocType.java
| 1
|
请完成以下Java代码
|
public colgroup addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public colgroup addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
|
@param hashcode the name of the element to be removed.
*/
public colgroup removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\colgroup.java
| 1
|
请完成以下Java代码
|
public class Error {
private String id;
private String name;
private String errorCode;
public Error(String id, String name, String errorCode) {
this.id = id;
this.name = name;
this.errorCode = errorCode;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
|
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Error.java
| 1
|
请完成以下Java代码
|
public SuspensionState getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(SuspensionState suspensionState) {
this.suspensionState = suspensionState;
}
public List<EventSubscriptionQueryValue> getEventSubscriptions() {
return eventSubscriptions;
}
public void setEventSubscriptions(List<EventSubscriptionQueryValue> eventSubscriptions) {
this.eventSubscriptions = eventSubscriptions;
}
|
public String getIncidentId() {
return incidentId;
}
public String getIncidentType() {
return incidentType;
}
public String getIncidentMessage() {
return incidentMessage;
}
public String getIncidentMessageLike() {
return incidentMessageLike;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExecutionQueryImpl.java
| 1
|
请完成以下Java代码
|
protected CEditor createLookupEditor(final String columnName, final Lookup lookup, final Object defaultValue)
{
final VLookup vl = new VLookup(columnName, false, false, true, lookup);
vl.setName(columnName);
if (defaultValue != null)
{
vl.setValue(defaultValue);
}
vl.addVetoableChangeListener(fieldChangedListener);
return vl;
}
@Override
protected CEditor createStringEditor(final String defaultValue)
{
final VString field = new VString();
field.setBackground(AdempierePLAF.getInfoBackground());
if (defaultValue != null)
{
field.setText(defaultValue);
}
field.addVetoableChangeListener(fieldChangedListener);
return field;
}
@Override
protected CEditor createNumberEditor(final String columnName, final String title, final int displayType)
|
{
final VNumber vn = new VNumber(columnName, false, false, true, displayType, title);
vn.setName(columnName);
vn.addVetoableChangeListener(fieldChangedListener);
return vn;
}
@Override
protected CEditor createDateEditor(final String columnName, final String title, final int displayType)
{
final VDate vd = new VDate(columnName, false, false, true, displayType, title);
vd.setName(columnName);
vd.addVetoableChangeListener(fieldChangedListener);
return vd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoQueryCriteriaGeneral.java
| 1
|
请完成以下Java代码
|
public Document getAddressDocumentForReading(final int addressDocIdInt)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
return getInnerAddressDocument(addressDocId).copy(CopyMode.CheckInReadonly, NullDocumentChangesCollector.instance);
}
private Document getAddressDocumentForWriting(final DocumentId addressDocId, final IDocumentChangesCollector changesCollector)
{
return getInnerAddressDocument(addressDocId).copy(CopyMode.CheckOutWritable, changesCollector);
}
public void processAddressDocumentChanges(final int addressDocIdInt, final List<JSONDocumentChangedEvent> events, final IDocumentChangesCollector changesCollector)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, changesCollector);
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit().newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> putAddressDocument(addressDoc));
}
public LookupValue complete(final int addressDocIdInt, @Nullable final List<JSONDocumentChangedEvent> events)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, NullDocumentChangesCollector.instance);
if (events != null && !events.isEmpty())
{
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
}
final I_C_Location locationRecord = createC_Location(addressDoc);
|
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> removeAddressDocumentById(addressDocId));
final String locationStr = locationBL.mkAddress(locationRecord);
return IntegerLookupValue.of(locationRecord.getC_Location_ID(), locationStr);
}
private I_C_Location createC_Location(final Document locationDoc)
{
final I_C_Location locationRecord = InterfaceWrapperHelper.create(Env.getCtx(), I_C_Location.class, ITrx.TRXNAME_ThreadInherited);
locationDoc.getFieldViews()
.forEach(locationField -> locationField
.getDescriptor()
.getDataBindingNotNull(AddressFieldBinding.class)
.writeValue(locationRecord, locationField));
locationDAO.save(locationRecord);
return locationRecord;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRepository.java
| 1
|
请完成以下Java代码
|
public ImmutableSet<ResourceId> getActivePlantIds()
{
return getResourcesMap().getActivePlantIds();
}
//
//
//
//
//
private static final class ResourcesMap
{
@Getter private final ImmutableList<Resource> allActive;
private final ImmutableMap<ResourceId, Resource> byId;
ResourcesMap(final List<Resource> list)
{
this.allActive = list.stream().filter(Resource::isActive).collect(ImmutableList.toImmutableList());
this.byId = Maps.uniqueIndex(list, Resource::getResourceId);
}
public Resource getById(@NonNull final ResourceId id)
{
final Resource resource = byId.get(id);
if (resource == null)
{
throw new AdempiereException("Resource not found by ID: " + id);
}
return resource;
}
public Stream<Resource> streamAllActive()
{
return allActive.stream();
}
|
public List<Resource> getByIds(final Set<ResourceId> ids)
{
return ids.stream()
.map(byId::get)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
public ImmutableSet<ResourceId> getActivePlantIds()
{
return streamAllActive()
.filter(resource -> resource.isActive() && resource.isPlant())
.map(Resource::getResourceId)
.collect(ImmutableSet.toImmutableSet());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\ResourceRepository.java
| 1
|
请完成以下Java代码
|
public TbResourceInfo findSystemOrTenantResourceByEtag(TenantId tenantId, ResourceType resourceType, String etag) {
if (StringUtils.isEmpty(etag)) {
return null;
}
log.trace("Executing findSystemOrTenantResourceByEtag [{}] [{}] [{}]", tenantId, resourceType, etag);
return resourceInfoDao.findSystemOrTenantResourceByEtag(tenantId, resourceType, etag);
}
protected String encode(String data) {
return encode(data.getBytes(StandardCharsets.UTF_8));
}
protected String encode(byte[] data) {
if (data == null || data.length == 0) {
return "";
}
return Base64.getEncoder().encodeToString(data);
}
protected String decode(String value) {
if (value == null) {
return null;
}
return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8);
}
private final PaginatedRemover<TenantId, TbResourceId> tenantResourcesRemover = new PaginatedRemover<>() {
@Override
protected PageData<TbResourceId> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return resourceDao.findIdsByTenantId(id.getId(), pageLink);
}
|
@Override
protected void removeEntity(TenantId tenantId, TbResourceId resourceId) {
deleteResource(tenantId, resourceId, true);
}
};
@TransactionalEventListener(classes = ResourceInfoEvictEvent.class)
@Override
public void handleEvictEvent(ResourceInfoEvictEvent event) {
if (event.getResourceId() != null) {
cache.evict(new ResourceInfoCacheKey(event.getResourceId()));
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\resource\BaseResourceService.java
| 1
|
请完成以下Java代码
|
public void setFitness(double fitness) {
this.fitness = fitness;
}
/**
* Sets the {@link #bestPosition}.
*
* @param bestPosition
* the new {@link #bestPosition}
*/
public void setBestPosition(long[] bestPosition) {
this.bestPosition = bestPosition;
}
/**
* Sets the {@link #bestFitness}.
*
* @param bestFitness
* the new {@link #bestFitness}
*/
public void setBestFitness(double bestFitness) {
this.bestFitness = bestFitness;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
|
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Particle.java
| 1
|
请完成以下Java代码
|
public Task assign(AssignTaskPayload assignTaskPayload) {
String assignee = assignTaskPayload.getAssignee();
String taskId = assignTaskPayload.getTaskId();
assertAssigneeIsACandidateUser(taskId, assignee);
reassignTask(taskId, assignee);
return reassignedTask(taskId);
}
private List<IdentityLink> getIdentityLinks(String taskId) {
String authenticatedUserId = securityManager.getAuthenticatedUserId();
if (authenticatedUserId != null && !authenticatedUserId.isEmpty()) {
List<String> userRoles = securityManager.getAuthenticatedUserRoles();
List<String> userGroups = securityManager.getAuthenticatedUserGroups();
org.activiti.engine.task.Task internalTask = taskService
.createTaskQuery()
.taskCandidateOrAssigned(authenticatedUserId, userGroups)
.taskId(taskId)
.singleResult();
if (internalTask == null) {
throw new NotFoundException(
"Unable to find task for the given id: " +
taskId +
" for user: " +
authenticatedUserId +
" (with groups: " +
userGroups +
" & with roles: " +
userRoles +
")"
);
}
return taskService.getIdentityLinksForTask(taskId);
}
throw new IllegalStateException("There is no authenticated user, we need a user authenticated to find tasks");
}
private void assertAssigneeIsACandidateUser(String taskId, String assignee) {
List<String> userCandidates = userCandidates(taskId);
if (!userCandidates.contains(assignee)) {
|
throw new IllegalStateException(
"You cannot assign a task to " + assignee + " due it is not a candidate for it"
);
}
}
private void reassignTask(String taskId, String assignee) {
releaseTask(taskId);
taskService.claim(taskId, assignee);
}
private void releaseTask(String taskId) {
assertCanReleaseTask(taskId);
taskService.unclaim(taskId);
}
private void assertCanReleaseTask(String taskId) {
Task task = task(taskId);
if (task.getAssignee() == null || task.getAssignee().isEmpty()) {
throw new IllegalStateException("You cannot release a task that is not claimed");
}
String authenticatedUserId = securityManager.getAuthenticatedUserId();
if (!task.getAssignee().equals(authenticatedUserId)) {
throw new IllegalStateException("You cannot release a task where you are not the assignee");
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskRuntimeImpl.java
| 1
|
请完成以下Java代码
|
public DeepSeekModelResponse convert(@NonNull String text) {
if (!StringUtils.hasText(text)) {
throw new IllegalArgumentException("Text cannot be blank");
}
int openingThinkTagIndex = text.indexOf(OPENING_THINK_TAG);
int closingThinkTagIndex = text.indexOf(CLOSING_THINK_TAG);
if (openingThinkTagIndex != -1 && closingThinkTagIndex != -1 && closingThinkTagIndex > openingThinkTagIndex) {
String chainOfThought = text.substring(openingThinkTagIndex + OPENING_THINK_TAG.length(), closingThinkTagIndex);
String answer = text.substring(closingThinkTagIndex + CLOSING_THINK_TAG.length());
return new DeepSeekModelResponse(chainOfThought, answer);
} else {
logger.debug("No <think> tags found in the response. Treating entire text as answer.");
return new DeepSeekModelResponse(null, text);
}
}
|
/**
* This method is used to define instructions for formatting the AI model's response,
* which are appended to the user prompt.
* See {@link org.springframework.ai.converter.BeanOutputConverter#getFormat()} for reference.
*
* However, in the current implementation, we extract only the AI response and its chain of thought,
* so no formatting instructions are needed.
*/
@Override
public String getFormat() {
return null;
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai\src\main\java\com\baeldung\springai\deepseek\DeepSeekModelOutputConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onExchangeBegin(@NonNull final Route route, @NonNull final Exchange exchange)
{
stopWaitLoop.set(false);
boolean masterDataFileExists = checkForMasterDataFiles(exchange);
while (masterDataFileExists && !stopWaitLoop.get())
{
LockSupport.parkNanos(fileEndpointConfig.getPollingFrequency().toNanos());
masterDataFileExists = checkForMasterDataFiles(exchange);
}
}
private boolean checkForMasterDataFiles(@NonNull final Exchange exchange)
{
final FileSystem fileSystem = FileSystems.getDefault();
final PathMatcher bpartnerFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternBPartner());
final PathMatcher warehouseFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternWarehouse());
final PathMatcher productFileMatcher = fileSystem.getPathMatcher("glob:" + fileEndpointConfig.getFileNamePatternProduct());
final Path rootLocation = Paths.get(fileEndpointConfig.getRootLocation());
final EnumSet<FileVisitOption> options = EnumSet.noneOf(FileVisitOption.class);
final Path[] existingMasterDataFile = new Path[1];
final SimpleFileVisitor<Path> visitor = new SimpleFileVisitor<>()
{
@Override
public FileVisitResult visitFile(@NonNull final Path currentFile, final BasicFileAttributes attrs)
{
if (bpartnerFileMatcher.matches(currentFile.getFileName()))
{
existingMasterDataFile[0] = currentFile;
return FileVisitResult.TERMINATE;
}
if (warehouseFileMatcher.matches(currentFile.getFileName()))
{
existingMasterDataFile[0] = currentFile;
return FileVisitResult.TERMINATE;
}
if (productFileMatcher.matches(currentFile.getFileName()))
{
existingMasterDataFile[0] = currentFile;
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
};
|
try
{
Files.walkFileTree(rootLocation, options, 1, visitor); // maxDepth=1 means to check the folder and its included files
}
catch (final IOException e)
{
throw new RuntimeCamelException("Caught exception while checking for existing master data files", e);
}
final boolean atLEastOneFileFound = existingMasterDataFile[0] != null;
if (atLEastOneFileFound)
{
final String fileName = exchange.getIn().getBody(GenericFile.class).getFileName();
pInstanceLogger.logMessage("There is at least the masterdata file " + existingMasterDataFile[0].getFileName() + " which has to be processed first => stall the processing of orders file " + fileName + " for now");
}
return atLEastOneFileFound;
}
@Override
protected void doStop()
{
stopWaitLoop.set(true);
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\purchaseorder\StallWhileMasterdataFilesExistPolicy.java
| 2
|
请完成以下Java代码
|
class DataSnapshot {
private volatile boolean ready;
@Getter
@Setter
private long ts;
private final Set<AlarmConditionFilterKey> keys;
private final Map<AlarmConditionFilterKey, EntityKeyValue> values = new ConcurrentHashMap<>();
DataSnapshot(Set<AlarmConditionFilterKey> entityKeysToFetch) {
this.keys = entityKeysToFetch;
}
static AlarmConditionFilterKey toConditionKey(EntityKey key) {
return new AlarmConditionFilterKey(toConditionKeyType(key.getType()), key.getKey());
}
static AlarmConditionKeyType toConditionKeyType(EntityKeyType keyType) {
switch (keyType) {
case ATTRIBUTE:
case SERVER_ATTRIBUTE:
case SHARED_ATTRIBUTE:
case CLIENT_ATTRIBUTE:
return AlarmConditionKeyType.ATTRIBUTE;
case TIME_SERIES:
return AlarmConditionKeyType.TIME_SERIES;
case ENTITY_FIELD:
return AlarmConditionKeyType.ENTITY_FIELD;
default:
throw new RuntimeException("Not supported entity key: " + keyType.name());
}
|
}
void removeValue(EntityKey key) {
values.remove(toConditionKey(key));
}
boolean putValue(AlarmConditionFilterKey key, long newTs, EntityKeyValue value) {
return putIfKeyExists(key, value, ts != newTs);
}
private boolean putIfKeyExists(AlarmConditionFilterKey key, EntityKeyValue value, boolean updateOfTs) {
if (keys.contains(key)) {
EntityKeyValue oldValue = values.put(key, value);
if (updateOfTs) {
return true;
} else {
return oldValue == null || !oldValue.equals(value);
}
} else {
return false;
}
}
EntityKeyValue getValue(AlarmConditionFilterKey key) {
return values.get(key);
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\profile\DataSnapshot.java
| 1
|
请完成以下Java代码
|
public void setIsEsrAccount (final boolean IsEsrAccount)
{
set_Value (COLUMNNAME_IsEsrAccount, IsEsrAccount);
}
@Override
public boolean isEsrAccount()
{
return get_ValueAsBoolean(COLUMNNAME_IsEsrAccount);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQR_IBAN (final @Nullable java.lang.String QR_IBAN)
{
set_Value (COLUMNNAME_QR_IBAN, QR_IBAN);
}
@Override
public java.lang.String getQR_IBAN()
{
return get_ValueAsString(COLUMNNAME_QR_IBAN);
}
/**
* R_AvsAddr AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSADDR_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSADDR_Match = "Y";
/** NoMatch = N */
public static final String R_AVSADDR_NoMatch = "N";
/** Unavailable = X */
public static final String R_AVSADDR_Unavailable = "X";
@Override
public void setR_AvsAddr (final @Nullable java.lang.String R_AvsAddr)
{
set_ValueNoCheck (COLUMNNAME_R_AvsAddr, R_AvsAddr);
}
|
@Override
public java.lang.String getR_AvsAddr()
{
return get_ValueAsString(COLUMNNAME_R_AvsAddr);
}
/**
* R_AvsZip AD_Reference_ID=213
* Reference name: C_Payment AVS
*/
public static final int R_AVSZIP_AD_Reference_ID=213;
/** Match = Y */
public static final String R_AVSZIP_Match = "Y";
/** NoMatch = N */
public static final String R_AVSZIP_NoMatch = "N";
/** Unavailable = X */
public static final String R_AVSZIP_Unavailable = "X";
@Override
public void setR_AvsZip (final @Nullable java.lang.String R_AvsZip)
{
set_ValueNoCheck (COLUMNNAME_R_AvsZip, R_AvsZip);
}
@Override
public java.lang.String getR_AvsZip()
{
return get_ValueAsString(COLUMNNAME_R_AvsZip);
}
@Override
public void setRoutingNo (final @Nullable java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSEPA_CreditorIdentifier (final @Nullable java.lang.String SEPA_CreditorIdentifier)
{
set_Value (COLUMNNAME_SEPA_CreditorIdentifier, SEPA_CreditorIdentifier);
}
@Override
public java.lang.String getSEPA_CreditorIdentifier()
{
return get_ValueAsString(COLUMNNAME_SEPA_CreditorIdentifier);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount.java
| 1
|
请完成以下Java代码
|
public ReceiveTaskBuilder builder() {
return new ReceiveTaskBuilder((BpmnModelInstance) modelInstance, this);
}
public String getImplementation() {
return implementationAttribute.getValue(this);
}
public void setImplementation(String implementation) {
implementationAttribute.setValue(this, implementation);
}
public boolean instantiate() {
return instantiateAttribute.getValue(this);
}
public void setInstantiate(boolean instantiate) {
instantiateAttribute.setValue(this, instantiate);
}
|
public Message getMessage() {
return messageRefAttribute.getReferenceTargetElement(this);
}
public void setMessage(Message message) {
messageRefAttribute.setReferenceTargetElement(this, message);
}
public Operation getOperation() {
return operationRefAttribute.getReferenceTargetElement(this);
}
public void setOperation(Operation operation) {
operationRefAttribute.setReferenceTargetElement(this, operation);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ReceiveTaskImpl.java
| 1
|
请完成以下Java代码
|
private void readUnicode() throws IOException {
this.character = 0;
for (int i = 0; i < 4; i++) {
int digit = this.reader.read();
if (digit >= '0' && digit <= '9') {
this.character = (this.character << 4) + digit - '0';
}
else if (digit >= 'a' && digit <= 'f') {
this.character = (this.character << 4) + digit - 'a' + 10;
}
else if (digit >= 'A' && digit <= 'F') {
this.character = (this.character << 4) + digit - 'A' + 10;
}
else {
throw new IllegalStateException("Malformed \\uxxxx encoding.");
}
}
}
boolean isWhiteSpace() {
return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f');
}
boolean isEndOfFile() {
return this.character == -1;
}
boolean isEndOfLine() {
return this.character == -1 || (!this.escaped && this.character == '\n');
}
boolean isListDelimiter() {
return !this.escaped && this.character == ',';
}
boolean isPropertyDelimiter() {
return !this.escaped && (this.character == '=' || this.character == ':');
}
char getCharacter() {
return (char) this.character;
}
Location getLocation() {
return new Location(this.reader.getLineNumber(), this.columnNumber);
}
|
boolean isSameLastLineCommentPrefix() {
return this.lastLineCommentPrefixCharacter == this.character;
}
boolean isCommentPrefixCharacter() {
return this.character == '#' || this.character == '!';
}
boolean isHyphenCharacter() {
return this.character == '-';
}
}
/**
* A single document within the properties file.
*/
static class Document {
private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) {
if (!key.isEmpty()) {
this.values.put(key, value);
}
}
boolean isEmpty() {
return this.values.isEmpty();
}
Map<String, OriginTrackedValue> asMap() {
return this.values;
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java
| 1
|
请完成以下Java代码
|
public class SetHuPackingInstructionIdCommand
{
private final ITrxManager trxManager = Services.get(ITrxManager.class);
private final PickingCandidateRepository pickingCandidateRepository;
private final Set<PickingCandidateId> pickingCandidateIds;
private final PackToSpec packToSpec;
@Builder
private SetHuPackingInstructionIdCommand(
@NonNull final PickingCandidateRepository pickingCandidateRepository,
@NonNull final Set<PickingCandidateId> pickingCandidateIds,
@NonNull final PackToSpec packToSpec)
{
Check.assumeNotEmpty(pickingCandidateIds, "pickingCandidateIds is not empty");
this.pickingCandidateRepository = pickingCandidateRepository;
this.pickingCandidateIds = pickingCandidateIds;
this.packToSpec = packToSpec;
}
public List<PickingCandidate> perform()
{
return trxManager.callInThreadInheritedTrx(this::performInTrx);
}
|
private List<PickingCandidate> performInTrx()
{
final List<PickingCandidate> pickingCandidates = pickingCandidateRepository.getByIds(pickingCandidateIds);
pickingCandidates.forEach(PickingCandidate::assertDraft);
pickingCandidates.forEach(this::processPickingCandidate);
return pickingCandidates;
}
private void processPickingCandidate(final PickingCandidate pickingCandidate)
{
pickingCandidate.packTo(packToSpec);
pickingCandidateRepository.save(pickingCandidate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\SetHuPackingInstructionIdCommand.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQtyOnHand()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setT_MD_Stock_WarehouseAndProduct_ID (final int T_MD_Stock_WarehouseAndProduct_ID)
{
if (T_MD_Stock_WarehouseAndProduct_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID, T_MD_Stock_WarehouseAndProduct_ID);
}
@Override
|
public int getT_MD_Stock_WarehouseAndProduct_ID()
{
return get_ValueAsInt(COLUMNNAME_T_MD_Stock_WarehouseAndProduct_ID);
}
@Override
public void setUUID (final java.lang.String UUID)
{
set_Value (COLUMNNAME_UUID, UUID);
}
@Override
public java.lang.String getUUID()
{
return get_ValueAsString(COLUMNNAME_UUID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_T_MD_Stock_WarehouseAndProduct.java
| 1
|
请完成以下Java代码
|
UserRolePermissionsBuilder setAlreadyIncludedRolePermissions(final UserRolePermissionsIncludesList userRolePermissionsAlreadyIncluded)
{
Check.assumeNotNull(userRolePermissionsAlreadyIncluded, "included not null");
Check.assumeNull(this.userRolePermissionsAlreadyIncluded, "already included permissions were not configured before");
this.userRolePermissionsAlreadyIncluded = userRolePermissionsAlreadyIncluded;
return this;
}
UserRolePermissionsIncludesList getUserRolePermissionsIncluded()
{
Check.assumeNotNull(userRolePermissionsIncluded, "userRolePermissionsIncluded not null");
return userRolePermissionsIncluded;
}
public UserRolePermissionsBuilder setMenuInfo(final UserMenuInfo menuInfo)
{
this._menuInfo = menuInfo;
return this;
}
public UserMenuInfo getMenuInfo()
{
if (_menuInfo == null)
{
_menuInfo = findMenuInfo();
}
return _menuInfo;
}
|
private UserMenuInfo findMenuInfo()
{
final Role adRole = getRole();
final AdTreeId roleMenuTreeId = adRole.getMenuTreeId();
if (roleMenuTreeId != null)
{
return UserMenuInfo.of(roleMenuTreeId, adRole.getRootMenuId());
}
final I_AD_ClientInfo adClientInfo = getAD_ClientInfo();
final AdTreeId adClientMenuTreeId = AdTreeId.ofRepoIdOrNull(adClientInfo.getAD_Tree_Menu_ID());
if (adClientMenuTreeId != null)
{
return UserMenuInfo.of(adClientMenuTreeId, adRole.getRootMenuId());
}
// Fallback: when role has NO menu and there is no menu defined on AD_ClientInfo level - shall not happen
return UserMenuInfo.DEFAULT_MENU;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsBuilder.java
| 1
|
请完成以下Java代码
|
public void setIsIncludeOtherGroup (boolean IsIncludeOtherGroup)
{
set_Value (COLUMNNAME_IsIncludeOtherGroup, Boolean.valueOf(IsIncludeOtherGroup));
}
/** Get inkl. "sonstige"-Eintrag.
@return Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll
*/
@Override
public boolean isIncludeOtherGroup ()
{
Object oo = get_Value(COLUMNNAME_IsIncludeOtherGroup);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
|
}
/** Set Name.
@param Name Name */
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Name */
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Management {
/**
* Whether Spring Integration components should perform logging in the main
* message flow. When disabled, such logging will be skipped without checking the
* logging level. When enabled, such logging is controlled as normal by the
* logging system's log level configuration.
*/
private boolean defaultLoggingEnabled = true;
/**
* List of simple patterns to match against the names of Spring Integration
* components. When matched, observation instrumentation will be performed for the
* component. Please refer to the javadoc of the smartMatch method of Spring
* Integration's PatternMatchUtils for details of the pattern syntax.
*/
private List<String> observationPatterns = new ArrayList<>();
|
public boolean isDefaultLoggingEnabled() {
return this.defaultLoggingEnabled;
}
public void setDefaultLoggingEnabled(boolean defaultLoggingEnabled) {
this.defaultLoggingEnabled = defaultLoggingEnabled;
}
public List<String> getObservationPatterns() {
return this.observationPatterns;
}
public void setObservationPatterns(List<String> observationPatterns) {
this.observationPatterns = observationPatterns;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationProperties.java
| 2
|
请完成以下Java代码
|
public void setES_FTS_Filter_ID (final int ES_FTS_Filter_ID)
{
if (ES_FTS_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_ID, ES_FTS_Filter_ID);
}
@Override
public int getES_FTS_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_ID);
}
@Override
public void setES_FTS_Filter_JoinColumn_ID (final int ES_FTS_Filter_JoinColumn_ID)
{
if (ES_FTS_Filter_JoinColumn_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Filter_JoinColumn_ID, ES_FTS_Filter_JoinColumn_ID);
}
@Override
|
public int getES_FTS_Filter_JoinColumn_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Filter_JoinColumn_ID);
}
@Override
public void setIsNullable (final boolean IsNullable)
{
set_Value (COLUMNNAME_IsNullable, IsNullable);
}
@Override
public boolean isNullable()
{
return get_ValueAsBoolean(COLUMNNAME_IsNullable);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Filter_JoinColumn.java
| 1
|
请完成以下Java代码
|
public class GridTabModelInternalAccessor implements IModelInternalAccessor
{
private final GridTabWrapper gridTabWrapper;
public GridTabModelInternalAccessor(final GridTabWrapper gridTabWrapper)
{
super();
this.gridTabWrapper = gridTabWrapper;
}
private final GridTab getGridTab()
{
return gridTabWrapper.getGridTab();
}
private final GridField getGridField(final String columnName)
{
return getGridTab().getField(columnName);
}
@Override
public Set<String> getColumnNames()
{
final ImmutableSet.Builder<String> columnNames = ImmutableSet.builder();
for (final GridField gridField : getGridTab().getFields())
{
columnNames.add(gridField.getColumnName());
}
return columnNames.build();
}
@Override
public int getColumnIndex(final String columnName)
{
throw new UnsupportedOperationException("GridTabWrapper has no supported for column indexes");
}
@Override
public boolean isVirtualColumn(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.isVirtualColumn();
}
@Override
public boolean isKeyColumnName(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.isKey();
}
@Override
public boolean isCalculated(final String columnName)
{
final GridField field = getGridField(columnName);
return field != null && field.getVO().isCalculated();
}
@Override
public boolean hasColumnName(final String columnName)
{
return gridTabWrapper.hasColumnName(columnName);
}
@Override
public Object getValue(final String columnName, final int columnIndex, final Class<?> returnType)
{
return gridTabWrapper.getValue(columnName, returnType);
}
@Override
public Object getValue(final String columnName, final Class<?> returnType)
{
|
return gridTabWrapper.getValue(columnName, returnType);
}
@Override
public boolean setValue(final String columnName, final Object value)
{
gridTabWrapper.setValue(columnName, value);
return true;
}
@Override
public boolean setValueNoCheck(final String columnName, final Object value)
{
gridTabWrapper.setValue(columnName, value);
return true;
}
@Override
public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public boolean invokeEquals(final Object[] methodArgs)
{
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception
{
// TODO: implement
throw new UnsupportedOperationException();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\GridTabModelInternalAccessor.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.