instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
AcceptPaymentDisputeRequest acceptPaymentDisputeRequest = (AcceptPaymentDisputeRequest)o;
return Objects.equals(this.returnAddress, acceptPaymentDisputeRequest.returnAddress) &&
Objects.equals(this.revision, acceptPaymentDisputeRequest.revision);
}
@Override
public int hashCode()
{
return Objects.hash(returnAddress, revision);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class AcceptPaymentDisputeRequest {\n");
|
sb.append(" returnAddress: ").append(toIndentedString(returnAddress)).append("\n");
sb.append(" revision: ").append(toIndentedString(revision)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\AcceptPaymentDisputeRequest.java
| 2
|
请完成以下Java代码
|
public void setDefaultAuthenticationManager(AuthenticationManager defaultAuthenticationManager) {
Assert.notNull(defaultAuthenticationManager, "defaultAuthenticationManager cannot be null");
this.defaultAuthenticationManager = defaultAuthenticationManager;
}
/**
* Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}.
* @return the new {@link RequestMatcherDelegatingAuthorizationManager.Builder}
* instance
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link RequestMatcherDelegatingAuthenticationManagerResolver}.
*/
public static final class Builder {
private final List<RequestMatcherEntry<AuthenticationManager>> entries = new ArrayList<>();
private Builder() {
}
/**
|
* Maps a {@link RequestMatcher} to an {@link AuthorizationManager}.
* @param matcher the {@link RequestMatcher} to use
* @param manager the {@link AuthenticationManager} to use
* @return the {@link Builder} for further
* customizationServerWebExchangeDelegatingReactiveAuthenticationManagerResolvers
*/
public Builder add(RequestMatcher matcher, AuthenticationManager manager) {
Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null");
this.entries.add(new RequestMatcherEntry<>(matcher, manager));
return this;
}
/**
* Creates a {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance.
* @return the {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance
*/
public RequestMatcherDelegatingAuthenticationManagerResolver build() {
return new RequestMatcherDelegatingAuthenticationManagerResolver(this.entries);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\RequestMatcherDelegatingAuthenticationManagerResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getProtocols() {
return this.protocols;
}
public void setProtocols(@Nullable String protocols) {
this.protocols = protocols;
}
public DataSize getMaxFramePayloadLength() {
return this.maxFramePayloadLength;
}
public void setMaxFramePayloadLength(DataSize maxFramePayloadLength) {
this.maxFramePayloadLength = maxFramePayloadLength;
}
public boolean isHandlePing() {
return this.handlePing;
}
|
public void setHandlePing(boolean handlePing) {
this.handlePing = handlePing;
}
public boolean isCompress() {
return this.compress;
}
public void setCompress(boolean compress) {
this.compress = compress;
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static Saml2Error malformedResponseData(String description) {
return new Saml2Error(Saml2ErrorCodes.MALFORMED_RESPONSE_DATA, description);
}
/**
* Construct an {@link Saml2ErrorCodes#DECRYPTION_ERROR} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error decryptionError(String description) {
return new Saml2Error(Saml2ErrorCodes.DECRYPTION_ERROR, description);
}
/**
* Construct an {@link Saml2ErrorCodes#RELYING_PARTY_REGISTRATION_NOT_FOUND} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error relyingPartyRegistrationNotFound(String description) {
return new Saml2Error(Saml2ErrorCodes.RELYING_PARTY_REGISTRATION_NOT_FOUND, description);
}
/**
* Construct an {@link Saml2ErrorCodes#SUBJECT_NOT_FOUND} error
* @param description the error description
* @return the resulting {@link Saml2Error}
* @since 7.0
*/
public static Saml2Error subjectNotFound(String description) {
return new Saml2Error(Saml2ErrorCodes.SUBJECT_NOT_FOUND, description);
}
/**
* Returns the error code.
* @return the error code
*/
public final String getErrorCode() {
|
return this.errorCode;
}
/**
* Returns the error description.
* @return the error description
*/
public final String getDescription() {
return this.description;
}
@Override
public String toString() {
return "[" + this.getErrorCode() + "] " + ((this.getDescription() != null) ? this.getDescription() : "");
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\Saml2Error.java
| 2
|
请完成以下Java代码
|
public boolean isCalculated()
{
return get_ValueAsBoolean(COLUMNNAME_IsCalculated);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
|
return get_ValueAsInt(COLUMNNAME_M_CostElement_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_CostElement.java
| 1
|
请完成以下Java代码
|
public class Association extends CmmnElement {
protected String sourceRef;
protected BaseElement sourceElement;
protected String targetRef;
protected BaseElement targetElement;
protected String transitionEvent;
public String getSourceRef() {
return sourceRef;
}
public void setSourceRef(String sourceRef) {
this.sourceRef = sourceRef;
}
public BaseElement getSourceElement() {
return sourceElement;
}
public void setSourceElement(BaseElement sourceElement) {
this.sourceElement = sourceElement;
}
public String getTargetRef() {
return targetRef;
}
public void setTargetRef(String targetRef) {
this.targetRef = targetRef;
}
public BaseElement getTargetElement() {
return targetElement;
}
|
public void setTargetElement(BaseElement targetElement) {
this.targetElement = targetElement;
}
public String getTransitionEvent() {
return transitionEvent;
}
public void setTransitionEvent(String transitionEvent) {
this.transitionEvent = transitionEvent;
}
@Override
public Association clone() {
Association clone = new Association();
clone.setValues(this);
return clone;
}
public void setValues(Association otherElement) {
super.setValues(otherElement);
setSourceRef(otherElement.getSourceRef());
setTargetRef(otherElement.getTargetRef());
setTransitionEvent(otherElement.getTransitionEvent());
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Association.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setProcessedTimestamp(@NonNull final I_S_Issue record)
{
final I_S_Issue oldRecord = InterfaceWrapperHelper.createOld(record, I_S_Issue.class);
if (oldRecord != null && oldRecord.isProcessed())
{
return;//nothing to do; it means the processed timestamp was already set
}
if (record.isProcessed())
{
record.setProcessedDate(TimeUtil.asTimestamp(Instant.now()));
}
}
private boolean isParentAlreadyInHierarchy(@NonNull final I_S_Issue record)
{
final IssueId currentIssueID = IssueId.ofRepoIdOrNull(record.getS_Issue_ID());
if (currentIssueID == null)
{
return false; //means it's a new record so it doesn't have any children
}
final IssueId parentIssueID = IssueId.ofRepoIdOrNull(record.getS_Parent_Issue_ID());
if (parentIssueID != null)
{
final IssueHierarchy issueHierarchy = issueRepository.buildUpStreamIssueHierarchy(parentIssueID);
return issueHierarchy.hasNodeForId(currentIssueID);
}
return false;
}
|
private boolean parentAlreadyHasAnEffortIssueAssigned(@NonNull final I_S_Issue record)
{
if (record.isEffortIssue())
{
final I_S_Issue parentIssue = record.getS_Parent_Issue();
if (parentIssue != null && !parentIssue.isEffortIssue())
{
return issueRepository.getDirectlyLinkedSubIssues(IssueId.ofRepoId(parentIssue.getS_Issue_ID()))
.stream()
.anyMatch(IssueEntity::isEffortIssue);
}
}
return false;
}
private boolean isBudgetChildForParentEffort(@NonNull final I_S_Issue record)
{
return !record.isEffortIssue()
&& record.getS_Parent_Issue() != null
&& record.getS_Parent_Issue().isEffortIssue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\issue\interceptor\S_Issue.java
| 2
|
请完成以下Spring Boot application配置
|
server.port=80
logging.level.root=info
#application.properties\u4E2D\u7684\u914D\u7F6E\u9879\u4F18\u5148\u7EA7\u9AD8\u4E8Elogback.xml\u6587\u4EF6\u4E2D\u7684\u914D\u7F6E\u
|
9879
#logging.level.com.xiaolyuh=debug
logging.file=d:/ssb-student-log.log
|
repos\spring-boot-student-master\spring-boot-student-log\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private static final class PlainClientUIInstance extends AbstractClientUIInstance
{
private static final Logger logger = LogManager.getLogger(ClientUI.PlainClientUIInstance.class);
@Override
public void info(int WindowNo, String AD_Message)
{
logger.info(AD_Message);
}
@Override
public void info(int WindowNo, String AD_Message, String message)
{
logger.info("" + AD_Message + ": " + message);
}
@Override
public IAskDialogBuilder ask()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean ask(int WindowNo, String AD_Message)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean ask(int WindowNo, String AD_Message, String message)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void warn(int WindowNo, String AD_Message)
{
logger.warn(AD_Message);
}
@Override
public void warn(int WindowNo, String AD_Message, String message)
{
logger.warn("" + AD_Message + ": " + message);
}
@Override
public void error(int WIndowNo, String AD_Message)
{
logger.warn("" + AD_Message);
}
@Override
public void error(int WIndowNo, String AD_Message, String message)
|
{
logger.error("" + AD_Message + ": " + message);
}
@Override
public void download(byte[] data, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void downloadNow(InputStream content, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public String getClientInfo()
{
// implementation basically copied from SwingClientUI
final String javaVersion = System.getProperty("java.version");
return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString();
}
@Override
public void showWindow(Object model)
{
throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()");
}
@Override
public IClientUIInvoker invoke()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void showURL(String url)
{
System.err.println("Showing URL is not supported on server side: " + url);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class DiscordNotifierConfiguration {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties("spring.boot.admin.notify.discord")
public DiscordNotifier discordNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) {
return new DiscordNotifier(repository, createNotifierRestTemplate(proxyProperties));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.boot.admin.notify.dingtalk", name = "webhook-url")
@AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class })
@Lazy(false)
public static class DingTalkNotifierConfiguration {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties("spring.boot.admin.notify.dingtalk")
public DingTalkNotifier dingTalkNotifier(InstanceRepository repository,
NotifierProxyProperties proxyProperties) {
return new DingTalkNotifier(repository, createNotifierRestTemplate(proxyProperties));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.boot.admin.notify.rocketchat", name = "url")
@AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class })
@Lazy(false)
public static class RocketChatNotifierConfiguration {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties("spring.boot.admin.notify.rocketchat")
public RocketChatNotifier rocketChatNotifier(InstanceRepository repository,
|
NotifierProxyProperties proxyProperties) {
return new RocketChatNotifier(repository, createNotifierRestTemplate(proxyProperties));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.boot.admin.notify.feishu", name = "webhook-url")
@AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class })
@Lazy(false)
public static class FeiShuNotifierConfiguration {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties("spring.boot.admin.notify.feishu")
public FeiShuNotifier feiShuNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) {
return new FeiShuNotifier(repository, createNotifierRestTemplate(proxyProperties));
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnProperty(prefix = "spring.boot.admin.notify.webex", name = "auth-token")
@AutoConfigureBefore({ NotifierTriggerConfiguration.class, CompositeNotifierConfiguration.class })
@Lazy(false)
public static class WebexNotifierConfiguration {
@Bean
@ConditionalOnMissingBean
@ConfigurationProperties("spring.boot.admin.notify.webex")
public WebexNotifier webexNotifier(InstanceRepository repository, NotifierProxyProperties proxyProperties) {
return new WebexNotifier(repository, createNotifierRestTemplate(proxyProperties));
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\config\AdminServerNotifierAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("processDefinitionId", this.processDefinitionId);
persistentState.put("infoJsonId", this.infoJsonId);
return persistentState;
}
// getters and setters //////////////////////////////////////////////////////
@Override
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 setR_InterestArea_ID (int R_InterestArea_ID)
{
if (R_InterestArea_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID));
}
/** Get Interest Area.
@return Interest Area or Topic
*/
public int getR_InterestArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Subscribe Date.
@param SubscribeDate
|
Date the contact actively subscribed
*/
public void setSubscribeDate (Timestamp SubscribeDate)
{
set_ValueNoCheck (COLUMNNAME_SubscribeDate, SubscribeDate);
}
/** Get Subscribe Date.
@return Date the contact actively subscribed
*/
public Timestamp getSubscribeDate ()
{
return (Timestamp)get_Value(COLUMNNAME_SubscribeDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_ContactInterest.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractScriptScanner implements IScriptScanner
{
private final IScriptScanner parentScanner;
private IScriptScannerFactory scriptScannerFactory;
private IScriptFactory scriptFactory;
public AbstractScriptScanner(final IScriptScanner parentScanner)
{
super();
this.parentScanner = parentScanner;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
@Override
public void setScriptScannerFactory(final IScriptScannerFactory scriptScannerFactory)
{
// NOTE: null is allowed
this.scriptScannerFactory = scriptScannerFactory;
}
@Override
public IScriptScannerFactory getScriptScannerFactory()
{
return scriptScannerFactory;
}
@Override
public IScriptScannerFactory getScriptScannerFactoryToUse()
{
if (scriptScannerFactory != null)
{
return scriptScannerFactory;
}
if (parentScanner != null)
{
return parentScanner.getScriptScannerFactoryToUse();
}
throw new ScriptException(" No " + IScriptScannerFactory.class + " defined for " + this + ".");
}
@Override
public IScriptFactory getScriptFactory()
{
return scriptFactory;
|
}
@Override
public void setScriptFactory(final IScriptFactory scriptFactory)
{
this.scriptFactory = scriptFactory;
}
@Override
public IScriptFactory getScriptFactoryToUse()
{
//
// If there is an script factory defined on this level, return it
{
final IScriptFactory scriptFactory = getScriptFactory();
if (scriptFactory != null)
{
return scriptFactory;
}
}
//
// Ask parent script scanner
if (parentScanner != null)
{
final IScriptFactory scriptFactory = parentScanner.getScriptFactoryToUse();
if (scriptFactory != null)
{
return scriptFactory;
}
}
//
// Ask Script Scanner Factory for IScriptFactory
{
final IScriptScannerFactory scriptScannerFactory = getScriptScannerFactoryToUse();
final IScriptFactory scriptFactory = scriptScannerFactory.getScriptFactoryToUse();
return scriptFactory;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\AbstractScriptScanner.java
| 1
|
请完成以下Java代码
|
public class QtyDemand_QtySupply_V_to_Forecast extends JavaProcess implements IProcessPrecondition
{
private final QtyDemandSupplyRepository demandSupplyRepository = SpringContextHolder.instance.getBean(QtyDemandSupplyRepository.class);
private final IForecastDAO forecastDAO = Services.get(IForecastDAO.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
|
{
final QtyDemandQtySupply currentRow = demandSupplyRepository.getById(QtyDemandQtySupplyId.ofRepoId(getRecord_ID()));
final ForecastQuery forecastQuery = ForecastQuery.builder()
.warehouseId(currentRow.getWarehouseId())
.orgId(currentRow.getOrgId())
.productId(currentRow.getProductId())
.attributesKey(currentRow.getAttributesKey())
.onlyNonZeroQty(true)
.build();
final List<TableRecordReference> recordReferences = forecastDAO.listIdsByQuery(forecastQuery)
.stream()
.map(id -> TableRecordReference.of(I_M_Forecast.Table_Name, id))
.collect(Collectors.toList());
getResult().setRecordsToOpen(recordReferences);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\material\process\QtyDemand_QtySupply_V_to_Forecast.java
| 1
|
请完成以下Java代码
|
private VerfuegbarkeitSubstitution toJAXB(final StockAvailabilitySubstitution substitution)
{
if (substitution == null)
{
return null;
}
final VerfuegbarkeitSubstitution soap = jaxbObjectFactory.createVerfuegbarkeitSubstitution();
soap.setLieferPzn(substitution.getPzn().getValueAsLong());
soap.setGrund(substitution.getReason().getV1SoapCode());
soap.setSubstitutionsgrund(substitution.getType().getV1SoapCode());
return soap;
}
private StockAvailabilitySubstitution fromJAXBorNull(@Nullable final VerfuegbarkeitSubstitution soap)
{
if (soap == null)
{
return null;
}
return StockAvailabilitySubstitution.builder()
.pzn(PZN.of(soap.getLieferPzn()))
.reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund()))
.type(StockAvailabilitySubstitutionType.fromV1SoapCode(soap.getSubstitutionsgrund()))
.build();
}
private VerfuegbarkeitAnteil toJAXB(final StockAvailabilityResponseItemPart itemPart)
{
final VerfuegbarkeitAnteil soap = jaxbObjectFactory.createVerfuegbarkeitAnteil();
soap.setMenge(itemPart.getQty().getValueAsInt());
|
soap.setTyp(itemPart.getType().getV1SoapCode());
soap.setLieferzeitpunkt(itemPart.getDeliveryDate() != null ? JAXBDateUtils.toXMLGregorianCalendar(itemPart.getDeliveryDate()) : null);
soap.setTour(itemPart.getTour());
soap.setGrund(itemPart.getReason() != null ? itemPart.getReason().getV1SoapCode() : null);
// soap.setTourabweichung(itemPart.isTourDeviation());
return soap;
}
private StockAvailabilityResponseItemPart fromJAXB(@NonNull final VerfuegbarkeitAnteil soap)
{
return StockAvailabilityResponseItemPart.builder()
.qty(Quantity.of(soap.getMenge()))
.type(StockAvailabilityResponseItemPartType.fromV1SoapCode(soap.getTyp()))
.deliveryDate(JAXBDateUtils.toZonedDateTime(soap.getLieferzeitpunkt()))
.reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund()))
.tour(soap.getTour())
// .tourDeviation(soap.isTourabweichung())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\stockAvailability\v1\StockAvailabilityJAXBConvertersV1.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public V put(K key, V value) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.put(key, value);
}
@Override
public V remove(Object key) {
if (!this.loaders.containsKey(key)) {
throw new IllegalArgumentException(
"This map only supports the following keys: " + this.loaders.keySet());
}
return this.loaded.remove(key);
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
@Override
public void clear() {
this.loaded.clear();
}
@Override
public boolean containsValue(Object value) {
return this.loaded.containsValue(value);
}
@Override
public Collection<V> values() {
return this.loaded.values();
}
@Override
public Set<Entry<K, V>> entrySet() {
return this.loaded.entrySet();
}
|
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadingMap<?, ?> that = (LoadingMap<?, ?>) o;
return this.loaded.equals(that.loaded);
}
@Override
public int hashCode() {
return this.loaded.hashCode();
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java
| 2
|
请完成以下Java代码
|
protected void prepareMqttClientConfig(MqttClientConfig config) {
config.setUsername(AzureIotHubUtil.buildUsername(mqttNodeConfiguration.getHost(), config.getClientId()));
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (CredentialsType.SAS == credentials.getType()) {
config.setPassword(AzureIotHubUtil.buildSasToken(mqttNodeConfiguration.getHost(), ((AzureIotHubSasCredentials) credentials).getSasKey(), clock));
}
}
MqttClient initAzureClient(TbContext ctx) throws Exception {
return initClient(ctx);
}
@VisibleForTesting
void setClock(Clock clock) {
this.clock = clock;
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
|
boolean hasChanges = false;
switch (fromVersion) {
case 0:
String protocolVersion = "protocolVersion";
if (!oldConfiguration.has(protocolVersion)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(protocolVersion, MqttVersion.MQTT_3_1_1.name());
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mqtt\azure\TbAzureIotHubNode.java
| 1
|
请完成以下Java代码
|
public static String concatenateUsingStringBuilder(String[] values) {
StringBuilder result = new StringBuilder();
for (String value : values) {
result = result.append(getNonNullString(value));
}
return result.toString();
}
public static String concatenateUsingHelperMethod(String[] values) {
String result = "";
for (String value : values) {
result = result + getNonNullString(value);
}
return result;
|
}
public static String concatenateUsingPlusOperator(String[] values) {
String result = "";
for (String value : values) {
result = result + (value == null ? "" : value);
}
return result;
}
private static String getNonNullString(String value) {
return value == null ? "" : value;
}
}
|
repos\tutorials-master\core-java-modules\core-java-string-operations-4\src\main\java\com\baeldung\concatenation\ConcatenatingNull.java
| 1
|
请完成以下Java代码
|
public de.metas.printing.model.I_AD_PrinterHW_MediaTray getAD_PrinterHW_MediaTray()
{
return get_ValueAsPO(COLUMNNAME_AD_PrinterHW_MediaTray_ID, de.metas.printing.model.I_AD_PrinterHW_MediaTray.class);
}
@Override
public void setAD_PrinterHW_MediaTray(de.metas.printing.model.I_AD_PrinterHW_MediaTray AD_PrinterHW_MediaTray)
{
set_ValueFromPO(COLUMNNAME_AD_PrinterHW_MediaTray_ID, de.metas.printing.model.I_AD_PrinterHW_MediaTray.class, AD_PrinterHW_MediaTray);
}
@Override
public void setAD_PrinterHW_MediaTray_ID (int AD_PrinterHW_MediaTray_ID)
{
if (AD_PrinterHW_MediaTray_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_MediaTray_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_MediaTray_ID, Integer.valueOf(AD_PrinterHW_MediaTray_ID));
}
@Override
public int getAD_PrinterHW_MediaTray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaTray_ID);
}
@Override
public de.metas.printing.model.I_AD_Printer_Matching getAD_Printer_Matching()
{
return get_ValueAsPO(COLUMNNAME_AD_Printer_Matching_ID, de.metas.printing.model.I_AD_Printer_Matching.class);
}
@Override
public void setAD_Printer_Matching(de.metas.printing.model.I_AD_Printer_Matching AD_Printer_Matching)
{
set_ValueFromPO(COLUMNNAME_AD_Printer_Matching_ID, de.metas.printing.model.I_AD_Printer_Matching.class, AD_Printer_Matching);
}
@Override
public void setAD_Printer_Matching_ID (int AD_Printer_Matching_ID)
{
if (AD_Printer_Matching_ID < 1)
set_Value (COLUMNNAME_AD_Printer_Matching_ID, null);
else
set_Value (COLUMNNAME_AD_Printer_Matching_ID, Integer.valueOf(AD_Printer_Matching_ID));
}
|
@Override
public int getAD_Printer_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Matching_ID);
}
@Override
public de.metas.printing.model.I_AD_Printer_Tray getAD_Printer_Tray()
{
return get_ValueAsPO(COLUMNNAME_AD_Printer_Tray_ID, de.metas.printing.model.I_AD_Printer_Tray.class);
}
@Override
public void setAD_Printer_Tray(de.metas.printing.model.I_AD_Printer_Tray AD_Printer_Tray)
{
set_ValueFromPO(COLUMNNAME_AD_Printer_Tray_ID, de.metas.printing.model.I_AD_Printer_Tray.class, AD_Printer_Tray);
}
@Override
public void setAD_Printer_Tray_ID (int AD_Printer_Tray_ID)
{
if (AD_Printer_Tray_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, Integer.valueOf(AD_Printer_Tray_ID));
}
@Override
public int getAD_Printer_Tray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Tray_ID);
}
@Override
public void setAD_PrinterTray_Matching_ID (int AD_PrinterTray_Matching_ID)
{
if (AD_PrinterTray_Matching_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrinterTray_Matching_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrinterTray_Matching_ID, Integer.valueOf(AD_PrinterTray_Matching_ID));
}
@Override
public int getAD_PrinterTray_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterTray_Matching_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterTray_Matching.java
| 1
|
请完成以下Java代码
|
public static int updateHandleInfoAndFinish(XxlJobLog xxlJobLog) {
// finish
finishJob(xxlJobLog);
// text最大64kb 避免长度过长
if (xxlJobLog.getHandleMsg().length() > 15000) {
xxlJobLog.setHandleMsg( xxlJobLog.getHandleMsg().substring(0, 15000) );
}
// fresh handle
return XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateHandleInfo(xxlJobLog);
}
/**
* do somethind to finish job
*/
private static void finishJob(XxlJobLog xxlJobLog){
// 1、handle success, to trigger child job
String triggerChildMsg = null;
if (XxlJobContext.HANDLE_CODE_SUCCESS == xxlJobLog.getHandleCode()) {
XxlJobInfo xxlJobInfo = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(xxlJobLog.getJobId());
if (xxlJobInfo!=null && xxlJobInfo.getChildJobId()!=null && xxlJobInfo.getChildJobId().trim().length()>0) {
triggerChildMsg = "<br><br><span style=\"color:#00c0ef;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_child_run") +"<<<<<<<<<<< </span><br>";
String[] childJobIds = xxlJobInfo.getChildJobId().split(",");
for (int i = 0; i < childJobIds.length; i++) {
int childJobId = (childJobIds[i]!=null && childJobIds[i].trim().length()>0 && isNumeric(childJobIds[i]))?Integer.valueOf(childJobIds[i]):-1;
if (childJobId > 0) {
JobTriggerPoolHelper.trigger(childJobId, TriggerTypeEnum.PARENT, -1, null, null, null);
ReturnT<String> triggerChildResult = ReturnT.SUCCESS;
// add msg
triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg1"),
(i+1),
childJobIds.length,
childJobIds[i],
(triggerChildResult.getCode()==ReturnT.SUCCESS_CODE?I18nUtil.getString("system_success"):I18nUtil.getString("system_fail")),
|
triggerChildResult.getMsg());
} else {
triggerChildMsg += MessageFormat.format(I18nUtil.getString("jobconf_callback_child_msg2"),
(i+1),
childJobIds.length,
childJobIds[i]);
}
}
}
}
if (triggerChildMsg != null) {
xxlJobLog.setHandleMsg( xxlJobLog.getHandleMsg() + triggerChildMsg );
}
// 2、fix_delay trigger next
// on the way
}
private static boolean isNumeric(String str){
try {
int result = Integer.valueOf(str);
return true;
} catch (NumberFormatException e) {
return false;
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\complete\XxlJobCompleter.java
| 1
|
请完成以下Java代码
|
public int enqueue()
{
final IQuery<I_PMM_PurchaseCandidate> query = createRecordsToProcessQuery();
if (!confirmRecordsToProcess(query))
{
return 0;
}
final List<I_PMM_PurchaseCandidate> candidates = query.list();
if (candidates.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName());
final ILockCommand elementsLocker = lockManager.lock()
.setOwner(lockOwner)
.setAutoCleanup(false);
workPackageQueueFactory
.getQueueForEnqueuing(Env.getCtx(), PMM_GenerateOrders.class)
.newWorkPackage()
.setElementsLocker(elementsLocker)
.addElements(candidates)
.buildAndEnqueue();
return candidates.size();
}
private boolean confirmRecordsToProcess(final IQuery<I_PMM_PurchaseCandidate> query)
{
if (confirmationCallback == null)
{
return true; // OK, autoconfirmed
}
//
// Fail if there is nothing to update
final int countToProcess = query.count();
if (countToProcess <= 0)
{
throw new AdempiereException("@NoSelection@");
}
//
// Ask the callback if we shall process
|
return confirmationCallback.confirmRecordsToProcess(countToProcess);
}
private IQuery<I_PMM_PurchaseCandidate> createRecordsToProcessQuery()
{
final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder = queryBL.createQueryBuilder(I_PMM_PurchaseCandidate.class);
if (candidatesFilter != null)
{
queryBuilder.filter(candidatesFilter);
}
return queryBuilder
.addOnlyActiveRecordsFilter()
.filter(lockManager.getNotLockedFilter(I_PMM_PurchaseCandidate.class))
.addCompareFilter(I_PMM_PurchaseCandidate.COLUMNNAME_QtyToOrder, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO)
.orderBy()
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_AD_Org_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_Warehouse_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_BPartner_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_M_PricingSystem_ID)
.addColumn(I_PMM_PurchaseCandidate.COLUMNNAME_C_Currency_ID)
.endOrderBy()
//
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\async\PMM_GenerateOrdersEnqueuer.java
| 1
|
请完成以下Java代码
|
public class ResourceLoadingProcessEnginesFilter extends ProcessEnginesFilter implements ResourceLoaderDependingFilter {
protected static final String DEFAULT_REDIRECT_APP = "tasklist";
protected ResourceLoader resourceLoader;
protected WebappProperty webappProperty;
@Override
protected void applyFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String contextPath = request.getContextPath();
String requestUri = request.getRequestURI().substring(contextPath.length());
String applicationPath = webappProperty.getApplicationPath();
requestUri = trimChar(requestUri, '/');
String appPath = trimChar(applicationPath, '/');
if (requestUri.equals(appPath)) {
// only redirect from index ("/") if index redirect is enabled
if(!requestUri.isEmpty() || webappProperty.isIndexRedirectEnabled()) {
response.sendRedirect(String.format("%s%s/app/%s/", contextPath, applicationPath, DEFAULT_REDIRECT_APP));
return;
}
}
super.applyFilter(request, response, chain);
}
@Override
protected String getWebResourceContents(String name) throws IOException {
InputStream is = null;
try {
Resource resource = resourceLoader.getResource("classpath:"+webappProperty.getWebjarClasspath() + name);
is = resource.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringWriter writer = new StringWriter();
String line = null;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.append("\n");
}
return writer.toString();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
/**
* @return the resourceLoader
*/
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
|
/**
* @param resourceLoader
* the resourceLoader to set
*/
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* @return the webappProperty
*/
public WebappProperty getWebappProperty() {
return webappProperty;
}
/**
* @param webappProperty
* webappProperty to set
*/
public void setWebappProperty(WebappProperty webappProperty) {
this.webappProperty = webappProperty;
}
/**
* @param input - String to trim
* @param charachter - Char to trim
* @return the trimmed String
*/
protected String trimChar(String input, char charachter) {
input = StringUtils.trimLeadingCharacter(input, charachter);
input = StringUtils.trimTrailingCharacter(input, charachter);
return input;
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\ResourceLoadingProcessEnginesFilter.java
| 1
|
请完成以下Java代码
|
public void setDateAcct (java.sql.Timestamp DateAcct)
{
set_ValueNoCheck (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Buchungsdatum.
@return Accounting Date
*/
@Override
public java.sql.Timestamp getDateAcct ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct);
}
@Override
public org.compiere.model.I_Fact_Acct getFact_Acct()
{
return get_ValueAsPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class);
}
@Override
public void setFact_Acct(org.compiere.model.I_Fact_Acct Fact_Acct)
{
set_ValueFromPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class, Fact_Acct);
}
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
@Override
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_Value (COLUMNNAME_Fact_Acct_ID, null);
else
set_Value (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
@Override
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* PostingType AD_Reference_ID=125
* Reference name: _Posting Type
*/
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Actual Year End = Y */
public static final String POSTINGTYPE_ActualYearEnd = "Y";
/** Set Buchungsart.
@param PostingType
Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public void setPostingType (java.lang.String PostingType)
{
|
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Processing Tag.
@param ProcessingTag Processing Tag */
@Override
public void setProcessingTag (java.lang.String ProcessingTag)
{
set_Value (COLUMNNAME_ProcessingTag, ProcessingTag);
}
/** Get Processing Tag.
@return Processing Tag */
@Override
public java.lang.String getProcessingTag ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProcessingTag);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_Log.java
| 1
|
请完成以下Java代码
|
public static Timestamp toTimestamp(
@Nullable final LocalDateAndOrgId localDateAndOrgId,
@NonNull final Function<OrgId, ZoneId> orgMapper)
{
return localDateAndOrgId != null ? localDateAndOrgId.toTimestamp(orgMapper) : null;
}
public static long daysBetween(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2)
{
assertSameOrg(d2, d2);
return ChronoUnit.DAYS.between(d1.toLocalDate(), d2.toLocalDate());
}
private static void assertSameOrg(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2)
{
Check.assumeEquals(d1.getOrgId(), d2.getOrgId(), "Dates have the same org: {}, {}", d1, d2);
}
public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper)
{
return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant();
}
public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) {
return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant();
}
public LocalDate toLocalDate() {
return localDate;
}
public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) {
return Timestamp.from(toInstant(orgMapper));
}
@Override
public int compareTo(final @Nullable LocalDateAndOrgId o) {
return compareToByLocalDate(o);
}
|
/**
* In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes.
* A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?"
* That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s.
*
* @see #compareTo(LocalDateAndOrgId)
*/
private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o)
{
if (o == null)
{
return 1;
}
return this.localDate.compareTo(o.localDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ResponseEntity<Object> getUsers(HttpServletRequest request) {
Map<String, Object> map = CommonUtil.getParameterMap(request);
String username = (String) map.get("username");
return new ResponseEntity<>(userService.getByUsernameContaining(username), HttpStatus.OK);
}
/**
* 添加用户啊
* api :localhost:8099/users
*
* @param user
* @return
*/
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiModelProperty(value="user",notes = "用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> saveUser(@RequestBody User user) {
return new ResponseEntity<>(userService.saveUser(user), HttpStatus.OK);
}
/**
* 修改用户信息
* api :localhost:8099/users
* @param user
* @return
*/
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
@ApiModelProperty(value="user",notes = "修改后用户信息的json串")
@ApiOperation(value = "新增用户", notes="返回新增的用户信息")
public ResponseEntity<Object> updateUser(@RequestBody User user) {
return new ResponseEntity<>(userService.updateUser(user), HttpStatus.OK);
|
}
/**
* 通过ID删除用户
* api :localhost:8099/users/2
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseBody
@ApiOperation(value = "通过id删除用户信息", notes="返回删除状态1 成功 0 失败")
public ResponseEntity<Object> deleteUser(@PathVariable Integer id) {
return new ResponseEntity<>(userService.removeUser(id.longValue()), HttpStatus.OK);
}
}
|
repos\springBoot-master\springboot-swagger-ui\src\main\java\com\abel\example\controller\UserController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public EdgeInstructions getEdgeInstallInstructions(
@Parameter(description = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("edgeId") String strEdgeId,
@Parameter(description = "Installation method ('docker', 'ubuntu' or 'centos')", schema = @Schema(allowableValues = {"docker", "ubuntu", "centos"}))
@PathVariable("method") String installationMethod,
HttpServletRequest request) throws ThingsboardException {
if (isEdgesEnabled() && edgeInstallServiceOpt.isPresent()) {
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
edgeId = checkNotNull(edgeId);
Edge edge = checkEdgeId(edgeId, Operation.READ);
return checkNotNull(edgeInstallServiceOpt.get().getInstallInstructions(edge, installationMethod, request));
} else {
throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
}
}
@ApiOperation(value = "Get Edge Upgrade Instructions (getEdgeUpgradeInstructions)",
notes = "Get an upgrade instructions for provided edge version." + TENANT_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
@GetMapping(value = "/edge/instructions/upgrade/{edgeVersion}/{method}")
public EdgeInstructions getEdgeUpgradeInstructions(
@Parameter(description = "Edge version", required = true)
@PathVariable("edgeVersion") String edgeVersion,
@Parameter(description = "Upgrade method ('docker', 'ubuntu' or 'centos')", schema = @Schema(allowableValues = {"docker", "ubuntu", "centos"}))
@PathVariable("method") String method) throws Exception {
if (isEdgesEnabled() && edgeUpgradeServiceOpt.isPresent()) {
return checkNotNull(edgeUpgradeServiceOpt.get().getUpgradeInstructions(edgeVersion, method));
|
} else {
throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
}
}
@ApiOperation(value = "Is edge upgrade enabled (isEdgeUpgradeAvailable)",
notes = "Returns 'true' if upgrade available for connected edge, 'false' - otherwise.")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN')")
@GetMapping(value = "/edge/{edgeId}/upgrade/available")
public boolean isEdgeUpgradeAvailable(
@Parameter(description = EDGE_ID_PARAM_DESCRIPTION, required = true)
@PathVariable("edgeId") String strEdgeId) throws Exception {
if (isEdgesEnabled() && edgeUpgradeServiceOpt.isPresent()) {
EdgeId edgeId = new EdgeId(toUUID(strEdgeId));
edgeId = checkNotNull(edgeId);
Edge edge = checkEdgeId(edgeId, Operation.READ);
return edgeUpgradeServiceOpt.get().isUpgradeAvailable(edge.getTenantId(), edge.getId());
} else {
throw new ThingsboardException("Edges support disabled", ThingsboardErrorCode.GENERAL);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\EdgeController.java
| 2
|
请完成以下Java代码
|
public class ScriptTaskActivityBehavior extends TaskActivityBehavior {
protected ScriptServiceTask scriptTask;
public ScriptTaskActivityBehavior(ScriptServiceTask scriptTask) {
super(scriptTask.isBlocking(), scriptTask.getBlockingExpression());
this.scriptTask = scriptTask;
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
ScriptingEngines scriptingEngines = CommandContextUtil.getCmmnEngineConfiguration().getScriptingEngines();
if (scriptingEngines == null) {
throw new FlowableException("Could not execute script task instance: no scripting engines found. For " + planItemInstanceEntity);
}
String scriptFormat = scriptTask.getScriptFormat() != null ? scriptTask.getScriptFormat() : ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE;
try {
ScriptEngineRequest.Builder request = ScriptEngineRequest.builder()
.language(scriptFormat)
.script(scriptTask.getScript())
.scopeContainer(planItemInstanceEntity)
.traceEnhancer(trace -> trace.addTraceTag("type", "scriptTask"));
if (scriptTask.isAutoStoreVariables()) {
request.storeScriptVariables();
}
List<IOParameter> inParameters = scriptTask.getInParameters();
|
if (inParameters != null && !inParameters.isEmpty()) {
MapDelegateVariableContainer inputVariableContainer = new MapDelegateVariableContainer();
IOParameterUtil.processInParameters(inParameters, planItemInstanceEntity, inputVariableContainer,
CommandContextUtil.getExpressionManager(commandContext));
request.inputVariableContainer(inputVariableContainer);
} else if (scriptTask.isDoNotIncludeVariables()) {
request.inputVariableContainer(VariableContainer.empty());
}
Object result = scriptingEngines.evaluate(request.build()).getResult();
String resultVariableName = scriptTask.getResultVariableName();
if (StringUtils.isNotBlank(scriptTask.getResultVariableName())) {
planItemInstanceEntity.setVariable(resultVariableName.trim(), result);
}
CommandContextUtil.getAgenda(commandContext).planCompletePlanItemInstanceOperation(planItemInstanceEntity);
} catch (FlowableException e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause instanceof FlowableException) {
throw (FlowableException) rootCause;
} else {
throw e;
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\ScriptTaskActivityBehavior.java
| 1
|
请完成以下Java代码
|
public void setParent_ID (int Parent_ID)
{
if (Parent_ID < 1)
set_Value (COLUMNNAME_Parent_ID, null);
else
set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID));
}
/** Get Parent.
@return Parent of Entity
*/
public int getParent_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
|
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_TreeNode.java
| 1
|
请完成以下Java代码
|
public <ValueType, AggregatedValueType> ValueType aggregateBottomUp(final BottomUpAggregator<ValueType, AggregatedValueType> aggregator)
{
final LinkedHashMap<RoleId, RolesTreeNode> trace = new LinkedHashMap<>();
return aggregateBottomUp(aggregator, trace);
}
private <ValueType, AggregatedValueType> ValueType aggregateBottomUp(
final BottomUpAggregator<ValueType, AggregatedValueType> aggregator,
final LinkedHashMap<RoleId, RolesTreeNode> trace)
{
// Skip already evaluated notes
final RoleId nodeId = getRoleId();
if (trace.containsKey(nodeId))
{
return null;
}
trace.put(nodeId, this);
//
// If this is a leaf node, return it's leaf value
final List<IRolesTreeNode> children = getChildren();
final boolean isLeaf = children.isEmpty();
if (isLeaf)
{
ValueType value = aggregator.leafValue(this);
return value;
|
}
final AggregatedValueType valueAgg = aggregator.initialValue(this);
Check.assumeNotNull(valueAgg, "valueAgg shall not be null");
for (final IRolesTreeNode child : children)
{
final RolesTreeNode childImpl = (RolesTreeNode)child;
final ValueType childValue = childImpl.aggregateBottomUp(aggregator, trace);
if (childValue == null)
{
// do nothing
continue;
}
aggregator.aggregateValue(valueAgg, child, childValue);
}
final ValueType value = aggregator.finalValue(valueAgg);
return value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\RolesTreeNode.java
| 1
|
请完成以下Java代码
|
public final void addChannel(Channel channel, @Nullable Connection connection) {
Assert.notNull(channel, "Channel must not be null");
if (!this.channels.contains(channel)) {
this.channels.add(channel);
if (connection != null) {
List<Channel> channelsForConnection =
this.channelsPerConnection.computeIfAbsent(connection, k -> new LinkedList<>());
channelsForConnection.add(channel);
}
}
}
public boolean containsChannel(Channel channel) {
return this.channels.contains(channel);
}
public @Nullable Connection getConnection() {
return (!this.connections.isEmpty() ? this.connections.get(0) : null);
}
public @Nullable Channel getChannel() {
return (!this.channels.isEmpty() ? this.channels.get(0) : null);
}
public void commitAll() throws AmqpException {
try {
for (Channel channel : this.channels) {
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
channel.basicAck(deliveryTag, false);
}
}
channel.txCommit();
}
}
catch (IOException e) {
throw new AmqpException("failed to commit RabbitMQ transaction", e);
}
}
public void closeAll() {
for (Channel channel : this.channels) {
try {
if (channel != ConsumerChannelRegistry.getConsumerChannel()) { // NOSONAR
channel.close();
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping close of consumer channel: " + channel.toString());
}
}
}
catch (Exception ex) {
logger.debug("Could not close synchronized Rabbit Channel after transaction", ex);
}
}
for (Connection con : this.connections) { //NOSONAR
RabbitUtils.closeConnection(con);
|
}
this.connections.clear();
this.channels.clear();
this.channelsPerConnection.clear();
}
public void addDeliveryTag(Channel channel, long deliveryTag) {
this.deliveryTags.add(channel, deliveryTag);
}
public void rollbackAll() {
for (Channel channel : this.channels) {
if (logger.isDebugEnabled()) {
logger.debug("Rolling back messages to channel: " + channel);
}
RabbitUtils.rollbackIfNecessary(channel);
if (this.deliveryTags.containsKey(channel)) {
for (Long deliveryTag : this.deliveryTags.get(channel)) {
try {
channel.basicReject(deliveryTag, this.requeueOnRollback);
}
catch (IOException ex) {
throw new AmqpIOException(ex);
}
}
// Need to commit the reject (=nack)
RabbitUtils.commitIfNecessary(channel);
}
}
}
}
|
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\RabbitResourceHolder.java
| 1
|
请完成以下Java代码
|
public void setISO_Code (final @Nullable java.lang.String ISO_Code)
{
set_Value (COLUMNNAME_ISO_Code, ISO_Code);
}
@Override
public java.lang.String getISO_Code()
{
return get_ValueAsString(COLUMNNAME_ISO_Code);
}
@Override
public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
@Override
public void setNetDays (final int NetDays)
{
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
|
@Override
public void setsinglevat (final @Nullable BigDecimal singlevat)
{
set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java
| 1
|
请完成以下Java代码
|
public OrganizationUnit getOwner() {
return ownerRef.getReferenceTargetElement(this);
}
public void setOwner(OrganizationUnit owner) {
ownerRef.setReferenceTargetElement(this, owner);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(KnowledgeSource.class, DMN_ELEMENT_KNOWLEDGE_SOURCE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(DrgElement.class)
.instanceProvider(new ModelTypeInstanceProvider<KnowledgeSource>() {
public KnowledgeSource newInstance(ModelTypeInstanceContext instanceContext) {
return new KnowledgeSourceImpl(instanceContext);
}
});
locationUriAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LOCATION_URI)
|
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
authorityRequirementCollection = sequenceBuilder.elementCollection(AuthorityRequirement.class)
.build();
typeChild = sequenceBuilder.element(Type.class)
.build();
ownerRef = sequenceBuilder.element(OwnerReference.class)
.uriElementReference(OrganizationUnit.class)
.build();
typeBuilder.build();
}
}
|
repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\KnowledgeSourceImpl.java
| 1
|
请完成以下Java代码
|
public DeadLetterJobQuery orderByProcessInstanceId() {
return orderBy(JobQueryProperty.PROCESS_INSTANCE_ID);
}
public DeadLetterJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public DeadLetterJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getDeadLetterJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getDeadLetterJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
|
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeadLetterJobQueryImpl.java
| 1
|
请完成以下Java代码
|
public void addBook(Book book) {
this.books.add(book);
book.setAuthor(this);
}
public void removeBook(Book book) {
book.setAuthor(null);
this.books.remove(book);
}
public void removeBooks() {
Iterator<Book> iterator = this.books.iterator();
while (iterator.hasNext()) {
Book book = iterator.next();
book.setAuthor(null);
iterator.remove();
}
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGenre() {
|
return genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\entity\Author.java
| 1
|
请完成以下Java代码
|
public String sbaSettings() {
return "sba-settings.js";
}
@GetMapping(path = "/variables.css", produces = "text/css")
public String variablesCss() {
return "variables.css";
}
@GetMapping(path = "/login", produces = MediaType.TEXT_HTML_VALUE)
public String login() {
return "login";
}
@lombok.Data
@lombok.Builder
public static class Settings {
private final String title;
private final String brand;
private final String loginIcon;
private final String favicon;
private final String faviconDanger;
private final PollTimer pollTimer;
private final UiTheme theme;
private final boolean notificationFilterEnabled;
private final boolean rememberMeEnabled;
private final List<String> availableLanguages;
private final List<String> routes;
private final List<ExternalView> externalViews;
private final List<ViewSettings> viewSettings;
private final Boolean enableToasts;
private final Boolean hideInstanceUrl;
private final Boolean disableInstanceUrl;
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ExternalView {
/**
* Label to be shown in the navbar.
*/
private final String label;
/**
* Url for the external view to be linked
*/
private final String url;
|
/**
* Order in the navbar.
*/
private final Integer order;
/**
* Should the page shown as an iframe or open in a new window.
*/
private final boolean iframe;
/**
* A list of child views.
*/
private final List<ExternalView> children;
public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) {
Assert.hasText(label, "'label' must not be empty");
if (isEmpty(children)) {
Assert.hasText(url, "'url' must not be empty");
}
this.label = label;
this.url = url;
this.order = order;
this.iframe = iframe;
this.children = children;
}
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ViewSettings {
/**
* Name of the view to address.
*/
private final String name;
/**
* Set view enabled.
*/
private boolean enabled;
public ViewSettings(String name, boolean enabled) {
Assert.hasText(name, "'name' must not be empty");
this.name = name;
this.enabled = enabled;
}
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class MSV3StockAvailability
{
private long pzn;
private int qty;
private boolean delete;
@JsonCreator
@Builder(toBuilder = true)
private MSV3StockAvailability(
@JsonProperty("pzn") final long pzn,
@JsonProperty("qty") final int qty,
@JsonProperty("delete") final boolean delete)
{
|
if (pzn <= 0)
{
throw new IllegalArgumentException("pzn shall be > 0");
}
if (qty < 0)
{
throw new IllegalArgumentException("qty shall be >= 0");
}
this.pzn = pzn;
this.qty = qty;
this.delete = delete;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\protocol\MSV3StockAvailability.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Student {
@Id
private Long id;
private String name;
@ManyToMany(mappedBy = "students")
private List<Course> courses;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
|
}
public void setName(String name) {
this.name = name;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-mapping\src\main\java\com\baeldung\associations\biredirectional\Student.java
| 2
|
请完成以下Java代码
|
private DocumentReportInfo getDocumentReportInfo(
@NonNull final DocumentReportAdvisor advisor,
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId printFormatIdToUse,
@Nullable final AdProcessId reportProcessId,
@NonNull final DocumentReportFlavor flavor)
{
final DocumentReportInfo reportInfo = advisor.getDocumentReportInfo(recordRef, printFormatIdToUse, reportProcessId);
return reportInfo.withPrintOptionsFallback(getDocTypePrintOptions(reportInfo.getDocTypeId(), flavor));
}
private DocumentPrintOptions getDocTypePrintOptions(
@Nullable final DocTypeId docTypeId,
@Nullable final DocumentReportFlavor flavor)
{
return docTypeId != null && flavor != null
? docTypePrintOptionsRepository.getByDocTypeAndFlavor(docTypeId, flavor)
|
: DocumentPrintOptions.NONE;
}
public static String getBarcodeServlet(
@NonNull final ClientId clientId,
@NonNull final OrgId orgId)
{
final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class);
return sysConfigBL.getValue(
ReportConstants.SYSCONFIG_BarcodeServlet,
null, // defaultValue,
clientId.getRepoId(),
orgId.getRepoId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportService.java
| 1
|
请完成以下Java代码
|
protected final PaymentsView getPaymentsView()
{
return getView();
}
protected final DocumentIdsSelection getSelectedPaymentRowIdsIncludingDefaultRow()
{
return getSelectedRowIds();
}
protected final InvoicesView getInvoicesView()
{
return getPaymentsView().getInvoicesView();
}
private DocumentIdsSelection getSelectedInvoiceRowIds()
{
return getChildViewSelectedRowIds();
}
//
//
//
protected final ImmutableList<PaymentRow> getPaymentRowsSelectedForAllocation()
{
ImmutableList<PaymentRow> paymentRowsSelectedForAllocation = this._paymentRowsSelectedForAllocation;
if (paymentRowsSelectedForAllocation == null)
{
paymentRowsSelectedForAllocation = this._paymentRowsSelectedForAllocation = computePaymentRowsSelectedForAllocation();
}
return paymentRowsSelectedForAllocation;
}
private ImmutableList<PaymentRow> computePaymentRowsSelectedForAllocation()
{
final DocumentIdsSelection selectedPaymentRowIds = getSelectedPaymentRowIdsIncludingDefaultRow();
return getPaymentsView().streamByIds(selectedPaymentRowIds)
.filter(row -> !row.equals(PaymentRow.DEFAULT_PAYMENT_ROW))
.collect(ImmutableList.toImmutableList());
}
|
protected final ImmutableList<InvoiceRow> getInvoiceRowsSelectedForAllocation()
{
ImmutableList<InvoiceRow> invoiceRowsSelectedForAllocation = this._invoiceRowsSelectedForAllocation;
if (invoiceRowsSelectedForAllocation == null)
{
invoiceRowsSelectedForAllocation = this._invoiceRowsSelectedForAllocation = computeInvoiceRowsSelectedForAllocation();
}
return invoiceRowsSelectedForAllocation;
}
private ImmutableList<InvoiceRow> computeInvoiceRowsSelectedForAllocation()
{
final InvoicesView invoicesView = getInvoicesView();
if (InvoicesViewFactory.isEnablePreparedForAllocationFlag())
{
return invoicesView
.streamByIds(DocumentIdsSelection.ALL)
.filter(InvoiceRow::isPreparedForAllocation)
.collect(ImmutableList.toImmutableList());
}
else
{
return invoicesView
.streamByIds(getSelectedInvoiceRowIds())
.collect(ImmutableList.toImmutableList());
}
}
protected final void invalidatePaymentsAndInvoicesViews()
{
final InvoicesView invoicesView = getInvoicesView();
invoicesView.unmarkPreparedForAllocation(DocumentIdsSelection.ALL);
invalidateView(invoicesView);
invalidateView(getPaymentsView());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\process\PaymentsViewBasedProcess.java
| 1
|
请完成以下Java代码
|
private List<Map<ColumnNamePair, Object>> getSubQueryValues(final T contextModel)
{
if (_subQueryValues != null)
{
return _subQueryValues;
}
final List<?> subQueryResult = subQuery.list();
final List<Map<ColumnNamePair, Object>> subQueryValues = new ArrayList<>(subQueryResult.size());
for (final Object subModel : subQueryResult)
{
final Map<ColumnNamePair, Object> subModelValues = new HashMap<>();
for (final ColumnNamePair matcher : matchers)
{
final String subQueryColumnName = matcher.getSubQueryColumnName();
final IQueryFilterModifier modifier = matcher.getModifier();
final Object value0 = InterfaceWrapperHelper.getValue(subModel, subQueryColumnName).orElse(null);
final Object value = modifier.convertValue(IQueryFilterModifier.COLUMNNAME_Constant, value0, contextModel);
subModelValues.put(matcher, value);
}
subQueryValues.add(subModelValues);
}
this._subQueryValues = subQueryValues;
return subQueryValues;
}
@lombok.Value
@lombok.Builder
private static final class ColumnNamePair
{
@lombok.NonNull
String columnName;
@lombok.NonNull
String subQueryColumnName;
@lombok.NonNull
IQueryFilterModifier modifier;
}
public static final class Builder<T>
{
private String tableName;
private final List<ColumnNamePair> matchers = new ArrayList<>();
private IQuery<?> subQuery;
private Builder()
{
}
|
public InSubQueryFilter<T> build()
{
return new InSubQueryFilter<>(this);
}
public Builder<T> tableName(final String tableName)
{
this.tableName = tableName;
return this;
}
public Builder<T> subQuery(final IQuery<?> subQuery)
{
this.subQuery = subQuery;
return this;
}
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier)
{
matchers.add(ColumnNamePair.builder()
.columnName(columnName)
.subQueryColumnName(subQueryColumnName)
.modifier(modifier)
.build());
return this;
}
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName)
{
return matchingColumnNames(columnName, subQueryColumnName, NullQueryFilterModifier.instance);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilter.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return "TourVersionRange ["
+ "tourVersion=" + tourVersion == null ? null
: tourVersion.getName()
+ ", validFrom=" + validFrom
+ ", validTo=" + validTo
+ "]";
}
@Override
public I_M_TourVersion getM_TourVersion()
{
return tourVersion;
}
@Override
public LocalDate getValidFrom()
{
return validFrom;
}
|
@Override
public LocalDate getValidTo()
{
return validTo;
}
@Override
public Set<LocalDate> generateDeliveryDates()
{
if (dateSequenceGenerator == null)
{
return ImmutableSet.of();
}
return dateSequenceGenerator.generate();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourVersionRange.java
| 1
|
请完成以下Java代码
|
public void dispatchEvent(ActivitiEvent event) {
if (event == null) {
throw new ActivitiIllegalArgumentException("Event cannot be null.");
}
if (event.getType() == null) {
throw new ActivitiIllegalArgumentException("Event type cannot be null.");
}
// Call global listeners
if (!eventListeners.isEmpty()) {
for (ActivitiEventListener listener : eventListeners) {
dispatchEvent(event, listener);
}
}
// Call typed listeners, if any
List<ActivitiEventListener> typed = typedListeners.get(event.getType());
if (typed != null && !typed.isEmpty()) {
for (ActivitiEventListener listener : typed) {
dispatchEvent(event, listener);
}
}
}
protected void dispatchEvent(ActivitiEvent event, ActivitiEventListener listener) {
try {
listener.onEvent(event);
} catch (Throwable t) {
if (listener.isFailOnException()) {
throw new ActivitiException("Exception while executing event-listener", t);
|
} else {
// Ignore the exception and continue notifying remaining listeners. The listener
// explicitly states that the exception should not bubble up
LOG.warn("Exception while executing event-listener, which was ignored", t);
}
}
}
protected synchronized void addTypedEventListener(ActivitiEventListener listener, ActivitiEventType type) {
List<ActivitiEventListener> listeners = typedListeners.get(type);
if (listeners == null) {
// Add an empty list of listeners for this type
listeners = new CopyOnWriteArrayList<ActivitiEventListener>();
typedListeners.put(type, listeners);
}
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiEventSupport.java
| 1
|
请完成以下Java代码
|
public class UnregisterProcessApplicationCmd implements Command<Void> {
protected boolean removeProcessesFromCache;
protected Set<String> deploymentIds;
public UnregisterProcessApplicationCmd(String deploymentId, boolean removeProcessesFromCache) {
this(Collections.singleton(deploymentId), removeProcessesFromCache);
}
public UnregisterProcessApplicationCmd(Set<String> deploymentIds, boolean removeProcessesFromCache) {
this.deploymentIds = deploymentIds;
this.removeProcessesFromCache = removeProcessesFromCache;
}
public Void execute(CommandContext commandContext) {
|
if(deploymentIds == null) {
throw new ProcessEngineException("Deployment Ids cannot be null.");
}
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkUnregisterProcessApplication);
Context.getProcessEngineConfiguration()
.getProcessApplicationManager()
.unregisterProcessApplicationForDeployments(deploymentIds, removeProcessesFromCache);
return null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UnregisterProcessApplicationCmd.java
| 1
|
请完成以下Java代码
|
public String getMonitorJobDefinitionId() {
return monitorJobDefinitionId;
}
public String getBatchJobDefinitionId() {
return batchJobDefinitionId;
}
public boolean isSuspended() {
return suspended;
}
public String getTenantId() {
return tenantId;
}
public String getCreateUserId() {
return createUserId;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(final Date startTime) {
this.startTime = startTime;
}
public Date getExecutionStartTime() {
return executionStartTime;
}
public void setExecutionStartTime(final Date executionStartTime) {
this.executionStartTime = executionStartTime;
}
public static BatchDto fromBatch(Batch batch) {
BatchDto dto = new BatchDto();
|
dto.id = batch.getId();
dto.type = batch.getType();
dto.totalJobs = batch.getTotalJobs();
dto.jobsCreated = batch.getJobsCreated();
dto.batchJobsPerSeed = batch.getBatchJobsPerSeed();
dto.invocationsPerBatchJob = batch.getInvocationsPerBatchJob();
dto.seedJobDefinitionId = batch.getSeedJobDefinitionId();
dto.monitorJobDefinitionId = batch.getMonitorJobDefinitionId();
dto.batchJobDefinitionId = batch.getBatchJobDefinitionId();
dto.suspended = batch.isSuspended();
dto.tenantId = batch.getTenantId();
dto.createUserId = batch.getCreateUserId();
dto.startTime = batch.getStartTime();
dto.executionStartTime = batch.getExecutionStartTime();
return dto;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchDto.java
| 1
|
请完成以下Java代码
|
public boolean isCollapsed()
{
return collapsed;
}
@Override
public boolean isEagerRefresh()
{
return eagerRefresh;
}
public static class Builder
{
private String displayName;
private boolean collapsed = false;
private boolean eagerRefresh = false;
private Builder()
{
super();
}
public FacetCategory build()
{
return new FacetCategory(this);
}
public Builder setDisplayName(final String displayName)
{
this.displayName = displayName;
return this;
|
}
public Builder setDisplayNameAndTranslate(final String displayName)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final Properties ctx = Env.getCtx();
this.displayName = msgBL.translate(ctx, displayName);
return this;
}
public Builder setCollapsed(final boolean collapsed)
{
this.collapsed = collapsed;
return this;
}
public Builder setEagerRefresh()
{
this.eagerRefresh = true;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\FacetCategory.java
| 1
|
请完成以下Java代码
|
public List<I_C_Year> retrieveYearsOfCalendar(final I_C_Calendar calendar)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(calendar);
final String trxName = InterfaceWrapperHelper.getTrxName(calendar);
final String whereClause = I_C_Year.COLUMNNAME_C_Calendar_ID + "=?";
return new Query(ctx, I_C_Year.Table_Name, whereClause, trxName)
.setParameters(calendar.getC_Calendar_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Year.COLUMNNAME_C_Year_ID)
.list(I_C_Year.class);
}
@Override
public I_C_Period retrieveFirstPeriodOfTheYear(final I_C_Year year)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(year);
final String trxName = InterfaceWrapperHelper.getTrxName(year);
return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName)
.setParameters(year.getC_Year_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
|
.setOrderBy(I_C_Period.COLUMNNAME_StartDate)
.first(I_C_Period.class);
}
@Override
public I_C_Period retrieveLastPeriodOfTheYear(final I_C_Year year)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(year);
final String trxName = InterfaceWrapperHelper.getTrxName(year);
return new Query(ctx, I_C_Period.Table_Name, I_C_Period.COLUMNNAME_C_Year_ID + "=?", trxName)
.setParameters(year.getC_Year_ID())
.setOnlyActiveRecords(true)
.setClient_ID()
.setOrderBy(I_C_Period.COLUMNNAME_StartDate + " DESC ")
.first(I_C_Period.class);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\impl\CalendarDAO.java
| 1
|
请完成以下Java代码
|
public class FunctionDelegatesFlowableFunctionResolver implements FlowableFunctionResolver {
protected final Map<String, FlowableFunctionDelegate> functionDelegateMap;
protected final Map<String, Method> functionsCache = new HashMap<>();
public FunctionDelegatesFlowableFunctionResolver(Collection<FlowableFunctionDelegate> functionDelegates) {
functionDelegateMap = new LinkedHashMap<>();
for (FlowableFunctionDelegate functionDelegate : functionDelegates) {
for (String prefix : functionDelegate.prefixes()) {
for (String localName : functionDelegate.localNames()) {
functionDelegateMap.put(prefix + ":" + localName, functionDelegate);
}
}
}
}
|
@Override
public Method resolveFunction(String prefix, String localName) throws NoSuchMethodException {
String functionName = prefix + ":" + localName;
if (functionsCache.containsKey(functionName)) {
return functionsCache.get(functionName);
}
Method functionMethod = resolveFunction(functionDelegateMap.get(functionName), prefix, localName);
functionsCache.put(functionName, functionMethod);
return functionMethod;
}
protected Method resolveFunction(FlowableFunctionDelegate functionDelegate, String prefix, String localName) throws NoSuchMethodException {
return functionDelegate != null ? functionDelegate.functionMethod(prefix, localName) : null;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\FunctionDelegatesFlowableFunctionResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
CacheMetricsRegistrar cacheMetricsRegistrar() {
return this.cacheMetricsRegistrar;
}
private void bindCachesToRegistry() {
this.cacheManagers.forEach(this::bindCacheManagerToRegistry);
}
private void bindCacheManagerToRegistry(String beanName, CacheManager cacheManager) {
cacheManager.getCacheNames().forEach((cacheName) -> {
Cache cache = cacheManager.getCache(cacheName);
Assert.state(cache != null, () -> "'cache' must not be null. 'cacheName' is '%s'".formatted(cacheName));
bindCacheToRegistry(beanName, cache);
});
}
private void bindCacheToRegistry(String beanName, Cache cache) {
Tag cacheManagerTag = Tag.of("cache.manager", getCacheManagerName(beanName));
this.cacheMetricsRegistrar.bindCacheToRegistry(cache, cacheManagerTag);
|
}
/**
* Get the name of a {@link CacheManager} based on its {@code beanName}.
* @param beanName the name of the {@link CacheManager} bean
* @return a name for the given cache manager
*/
private String getCacheManagerName(String beanName) {
if (beanName.length() > CACHE_MANAGER_SUFFIX.length()
&& StringUtils.endsWithIgnoreCase(beanName, CACHE_MANAGER_SUFFIX)) {
return beanName.substring(0, beanName.length() - CACHE_MANAGER_SUFFIX.length());
}
return beanName;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\metrics\CacheMetricsRegistrarConfiguration.java
| 2
|
请完成以下Java代码
|
public String toString() {
return joinOn(this.getClass())
.add("camunda=" + camunda)
.toString();
}
public class Camunda {
private boolean enabled = true;
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param enabled the enabled to set
*/
|
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.toString();
}
}
}
}
|
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\ManagementProperties.java
| 1
|
请完成以下Java代码
|
public String getToken() {
return this.token;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || !(obj instanceof CsrfToken)) {
return false;
}
CsrfToken other = (CsrfToken) obj;
if (!getToken().equals(other.getToken())) {
return false;
|
}
if (!getParameterName().equals(other.getParameterName())) {
return false;
}
return getHeaderName().equals(other.getHeaderName());
}
@Override
public int hashCode() {
int result = getToken().hashCode();
result = 31 * result + getParameterName().hashCode();
result = 31 * result + getHeaderName().hashCode();
return result;
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\DefaultCsrfToken.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Result<List<SysPosition>> queryByIds(@RequestParam(name = "ids") String ids) {
Result<List<SysPosition>> result = new Result<>();
QueryWrapper<SysPosition> queryWrapper = new QueryWrapper<>();
queryWrapper.in(true,"id",ids.split(","));
List<SysPosition> list = sysPositionService.list(queryWrapper);
if (list == null) {
result.error500("未找到对应实体");
} else {
result.setResult(list);
result.setSuccess(true);
}
return result;
}
/**
* 获取职位用户列表
*
* @param pageNo
* @param pageSize
* @param positionId
* @return
*/
@GetMapping("/getPositionUserList")
public Result<IPage<SysUser>> getPositionUserList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
@RequestParam(name = "positionId") String positionId) {
Page<SysUser> page = new Page<>(pageNo, pageSize);
IPage<SysUser> pageList = userPositionService.getPositionUserList(page, positionId);
List<String> userIds = pageList.getRecords().stream().map(SysUser::getId).collect(Collectors.toList());
if (null != userIds && userIds.size() > 0) {
Map<String, String> useDepNames = userService.getDepNamesByUserIds(userIds);
pageList.getRecords().forEach(item -> {
item.setOrgCodeTxt(useDepNames.get(item.getId()));
});
}
return Result.ok(pageList);
}
/**
|
* 添加成员到用户职位关系表
*
* @param userIds
* @param positionId
* @return
*/
@PostMapping("/savePositionUser")
public Result<String> saveUserPosition(@RequestParam(name = "userIds") String userIds,
@RequestParam(name = "positionId") String positionId) {
userPositionService.saveUserPosition(userIds, positionId);
return Result.ok("添加成功");
}
/**
* 职位列表移除成员
*
* @param userIds
* @param positionId
* @return
*/
@DeleteMapping("/removePositionUser")
public Result<String> removeUserPosition(@RequestParam(name = "userIds") String userIds,
@RequestParam(name = "positionId") String positionId) {
userPositionService.removePositionUser(userIds, positionId);
return Result.OK("移除成员成功");
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysPositionController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ComputeSalesRepPriceRequest
{
@NonNull
BPartnerId salesRepId;
@NonNull
SOTrx soTrx;
@NonNull
ProductId productId;
@NonNull
Quantity qty;
@NonNull
CurrencyId customerCurrencyId;
@NonNull
LocalDate commissionDate;
|
@Builder
public ComputeSalesRepPriceRequest(
@NonNull final BPartnerId salesRepId,
@NonNull final SOTrx soTrx,
@NonNull final ProductId productId,
@NonNull final Quantity qty,
@NonNull final CurrencyId customerCurrencyId,
@NonNull final LocalDate commissionDate)
{
this.salesRepId = salesRepId;
this.soTrx = soTrx;
this.productId = productId;
this.qty = qty;
this.customerCurrencyId = customerCurrencyId;
this.commissionDate = commissionDate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\pricing\trade_margin\ComputeSalesRepPriceRequest.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String addUI() {
return "user/info/add";
}
/**
* 函数功能说明 : 保存
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("user:userInfo:add")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, @RequestParam("userName") String userName, @RequestParam("mobile") String mobile, @RequestParam("password") String password, DwzAjax dwz) {
rpUserInfoService.registerOffline(userName, mobile, password);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
|
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 : 查询用户信息 查找带回
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/lookupList", method ={RequestMethod.POST, RequestMethod.GET})
public String lookupList(RpUserInfo rpUserInfo, PageParam pageParam, Model model) {
PageBean pageBean = rpUserInfoService.listPage(pageParam, rpUserInfo);
model.addAttribute("pageBean", pageBean);
model.addAttribute("pageParam", pageParam);
model.addAttribute("rpUserInfo",rpUserInfo);
return "user/info/lookupList";
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\user\UserInfoController.java
| 2
|
请完成以下Java代码
|
public Builder scopes(Set<String> scopes) {
this.scopes = scopes;
return this;
}
/**
* Sets the refresh token associated to the access token.
* @param refreshToken the refresh token associated to the access token.
* @return the {@link Builder}
*/
public Builder refreshToken(String refreshToken) {
this.refreshToken = refreshToken;
return this;
}
/**
* Sets the additional parameters returned in the response.
* @param additionalParameters the additional parameters returned in the response
* @return the {@link Builder}
*/
public Builder additionalParameters(Map<String, Object> additionalParameters) {
this.additionalParameters = additionalParameters;
return this;
}
/**
* Builds a new {@link OAuth2AccessTokenResponse}.
* @return a {@link OAuth2AccessTokenResponse}
*/
public OAuth2AccessTokenResponse build() {
Instant issuedAt = getIssuedAt();
Instant expiresAt = getExpiresAt();
OAuth2AccessTokenResponse accessTokenResponse = new OAuth2AccessTokenResponse();
accessTokenResponse.accessToken = new OAuth2AccessToken(this.tokenType, this.tokenValue, issuedAt,
expiresAt, this.scopes);
if (StringUtils.hasText(this.refreshToken)) {
accessTokenResponse.refreshToken = new OAuth2RefreshToken(this.refreshToken, issuedAt);
}
accessTokenResponse.additionalParameters = Collections
.unmodifiableMap(CollectionUtils.isEmpty(this.additionalParameters) ? Collections.emptyMap()
: this.additionalParameters);
return accessTokenResponse;
}
private Instant getIssuedAt() {
if (this.issuedAt == null) {
|
this.issuedAt = Instant.now();
}
return this.issuedAt;
}
/**
* expires_in is RECOMMENDED, as per spec
* https://tools.ietf.org/html/rfc6749#section-5.1 Therefore, expires_in may not
* be returned in the Access Token response which would result in the default
* value of 0. For these instances, default the expiresAt to +1 second from
* issuedAt time.
* @return
*/
private Instant getExpiresAt() {
if (this.expiresAt == null) {
Instant issuedAt = getIssuedAt();
this.expiresAt = (this.expiresIn > 0) ? issuedAt.plusSeconds(this.expiresIn) : issuedAt.plusSeconds(1);
}
return this.expiresAt;
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AccessTokenResponse.java
| 1
|
请完成以下Java代码
|
public class ArmstrongNumberUtil {
public static boolean isArmstrong(int n) {
if (n < 0) {
return false;
}
List<Integer> digitsList = digitsInList(n);
int len = digitsList.size();
int sum = digitsList.stream()
.mapToInt(d -> (int) Math.pow(d, len))
.sum();
// alternatively, we can use the reduce() method:
// int sum = digits.stream()
// .reduce(0, (subtotal, digit) -> subtotal + (int) Math.pow(digit, len));
return n == sum;
}
private static List<Integer> digitsInList(int n) {
List<Integer> list = new ArrayList<>();
|
while (n > 0) {
list.add(n % 10);
n = n / 10;
}
return list;
}
public static List<Integer> getA005188Sequence(int limit) {
if (limit < 0) {
throw new IllegalArgumentException("The limit cannot be a negative number.");
}
return IntStream.range(0, limit)
.boxed()
.filter(ArmstrongNumberUtil::isArmstrong)
.collect(Collectors.toList());
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-5\src\main\java\com\baeldung\armstrong\ArmstrongNumberUtil.java
| 1
|
请完成以下Spring Boot application配置
|
com:
baeldung:
aws:
access-key: ${AWS_ACCESS_KEY}
secret-key: ${AWS_SECRET_KEY}
athena:
database: ${AMAZON_ATHENA_DATABAS
|
E}
s3-output-location: ${AMAZON_ATHENA_S3_OUTPUT_LOCATION}
|
repos\tutorials-master\aws-modules\amazon-athena\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
class DefaultCalloutProvider implements IDefaultCalloutProvider
{
private static final transient Logger logger = LogManager.getLogger(DefaultCalloutProvider.class);
@Override
public TableCalloutsMap getCallouts(final Properties ctx, final String tableName)
{
//
if(tableName == ANY_TABLE)
{
return TableCalloutsMap.EMPTY;
}
final TableCalloutsMap.Builder tableCalloutsBuilder = TableCalloutsMap.builder();
for (final Entry<String, Supplier<ICalloutInstance>> entry : supplyCallouts(ctx, tableName).entries())
{
final Supplier<ICalloutInstance> columnCalloutSupplier = entry.getValue();
try
{
final ICalloutInstance callout = columnCalloutSupplier.get();
if (callout == null)
{
continue;
}
final String columnName = entry.getKey();
tableCalloutsBuilder.put(columnName, callout);
}
catch (final Exception ex)
{
logger.warn("Failed creating callout instance for {}. Skipped.", columnCalloutSupplier, ex);
}
}
return tableCalloutsBuilder.build();
}
@Cached
public ImmutableListMultimap<String, Supplier<ICalloutInstance>> supplyCallouts(@CacheCtx final Properties ctx, final String tableName)
{
final ListMultimap<String, I_AD_ColumnCallout> calloutsDef = Services.get(IADColumnCalloutDAO.class).retrieveAvailableCalloutsToRun(ctx, tableName);
if (calloutsDef == null || calloutsDef.isEmpty())
{
return ImmutableListMultimap.of();
}
final ImmutableListMultimap.Builder<String, Supplier<ICalloutInstance>> callouts = ImmutableListMultimap.builder();
for (final Entry<String, I_AD_ColumnCallout> entry : calloutsDef.entries())
{
final I_AD_ColumnCallout calloutDef = entry.getValue();
final Supplier<ICalloutInstance> calloutSupplier = supplyCalloutInstanceOrNull(calloutDef);
if (calloutSupplier == null)
{
continue;
}
final String columnName = entry.getKey();
callouts.put(columnName, calloutSupplier);
}
return callouts.build();
}
/**
* @return supplier or <code>null</code> but never throws exception
*/
private Supplier<ICalloutInstance> supplyCalloutInstanceOrNull(final I_AD_ColumnCallout calloutDef)
{
if (calloutDef == null)
{
return null;
|
}
if (!calloutDef.isActive())
{
return null;
}
try
{
final String classname = calloutDef.getClassname();
Check.assumeNotEmpty(classname, "classname is not empty");
final Optional<String> ruleValue = ScriptEngineFactory.extractRuleValueFromClassname(classname);
if(ruleValue.isPresent())
{
return RuleCalloutInstance.supplier(ruleValue.get());
}
else
{
return MethodNameCalloutInstance.supplier(classname);
}
}
catch (final Exception e)
{
// We are just logging and discarding the error because there is nothing that we can do about it
// More, we want to load the other callouts and not just fail
logger.error("Failed creating callout instance for " + calloutDef, e);
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\spi\impl\DefaultCalloutProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Controller {
@GetMapping("/hello")
public Mono<String> hello() {
return Mono.just("world");
}
@GetMapping("/sleep_direct")
public Mono<String> sleepDirect() throws InterruptedException {
Thread.sleep(100L);
return Mono.just("world");
}
@GetMapping("/sleep")
public Mono<String> sleep() {
// System.out.println(Thread.currentThread().getName());
// return Mono.just("world").delayElement(Duration.ofMillis(100));
return Mono.defer(() -> {
// System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(100L);
} catch (InterruptedException ignored) {
}
return Mono.just("world");
}).subscribeOn(Schedulers.parallel());
}
private Map<String, Boolean> MAP = new ConcurrentHashMap<>();
|
@GetMapping("/sleep2")
public Mono<String> sleep2() {
return Mono.defer(() -> {
try {
// System.out.println(Thread.currentThread().getName());
if (!MAP.containsKey(Thread.currentThread().getName())) {
System.out.println(Thread.currentThread().getName());
MAP.put(Thread.currentThread().getName(), true);
}
Thread.sleep(100L);
} catch (InterruptedException ignored) {
}
return Mono.just("world");
}).subscribeOn(Schedulers.elastic());
}
}
|
repos\SpringBoot-Labs-master\lab-06\lab-06-webflux-tomcat\src\main\java\cn\iocoder\springboot\labs\lab06\webflux\Controller.java
| 2
|
请完成以下Java代码
|
public Iterator<T> iterator() {
return this;
}
@Override
public boolean hasNext() {
if (!initialized) {
fetch(new PageLink(fetchSize));
initialized = true;
}
if (currentIdx == currentItems.size()) {
if (hasNextPack) {
fetch(nextPackLink);
}
}
return currentIdx < currentItems.size();
}
|
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return currentItems.get(currentIdx++);
}
private void fetch(PageLink link) {
PageData<T> pageData = fetchPageData(link);
currentIdx = 0;
currentItems = pageData != null ? pageData.getData() : new ArrayList<>();
hasNextPack = pageData != null && pageData.hasNext();
nextPackLink = link.nextPageLink();
}
abstract PageData<T> fetchPageData(PageLink link);
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\BasePageDataIterable.java
| 1
|
请完成以下Java代码
|
public SubProcess newInstance(ModelTypeInstanceContext instanceContext) {
return new SubProcessImpl(instanceContext);
}
});
triggeredByEventAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_TRIGGERED_BY_EVENT)
.defaultValue(false)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
laneSetCollection = sequenceBuilder.elementCollection(LaneSet.class)
.build();
flowElementCollection = sequenceBuilder.elementCollection(FlowElement.class)
.build();
artifactCollection = sequenceBuilder.elementCollection(Artifact.class)
.build();
/** camunda extensions */
camundaAsyncAttribute = typeBuilder.booleanAttribute(CAMUNDA_ATTRIBUTE_ASYNC)
.namespace(CAMUNDA_NS)
.defaultValue(false)
.build();
typeBuilder.build();
}
public SubProcessImpl(ModelTypeInstanceContext context) {
super(context);
}
public SubProcessBuilder builder() {
return new SubProcessBuilder((BpmnModelInstance) modelInstance, this);
}
public boolean triggeredByEvent() {
return triggeredByEventAttribute.getValue(this);
}
public void setTriggeredByEvent(boolean triggeredByEvent) {
triggeredByEventAttribute.setValue(this, triggeredByEvent);
}
public Collection<LaneSet> getLaneSets() {
return laneSetCollection.get(this);
}
|
public Collection<FlowElement> getFlowElements() {
return flowElementCollection.get(this);
}
public Collection<Artifact> getArtifacts() {
return artifactCollection.get(this);
}
/** camunda extensions */
/**
* @deprecated use isCamundaAsyncBefore() instead.
*/
@Deprecated
public boolean isCamundaAsync() {
return camundaAsyncAttribute.getValue(this);
}
/**
* @deprecated use setCamundaAsyncBefore(isCamundaAsyncBefore) instead.
*/
@Deprecated
public void setCamundaAsync(boolean isCamundaAsync) {
camundaAsyncAttribute.setValue(this, isCamundaAsync);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SubProcessImpl.java
| 1
|
请完成以下Java代码
|
public void setIsAllowNegative (boolean IsAllowNegative)
{
set_Value (COLUMNNAME_IsAllowNegative, Boolean.valueOf(IsAllowNegative));
}
/** Get Allow Negative.
@return Allow Negative */
public boolean isAllowNegative ()
{
Object oo = get_Value(COLUMNNAME_IsAllowNegative);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Allow Positive.
@param IsAllowPositive Allow Positive */
public void setIsAllowPositive (boolean IsAllowPositive)
|
{
set_Value (COLUMNNAME_IsAllowPositive, Boolean.valueOf(IsAllowPositive));
}
/** Get Allow Positive.
@return Allow Positive */
public boolean isAllowPositive ()
{
Object oo = get_Value(COLUMNNAME_IsAllowPositive);
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_C_ChargeType_DocType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public EventDeploymentBuilder addEventDefinitionBytes(String resourceName, byte[] eventDefinitionBytes) {
if (eventDefinitionBytes == null) {
throw new FlowableException("event definition bytes is null");
}
EventResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(eventDefinitionBytes);
deployment.addResource(resource);
return this;
}
@Override
public EventDeploymentBuilder addEventDefinition(String resourceName, String eventDefinition) {
addString(resourceName, eventDefinition);
return this;
}
@Override
public EventDeploymentBuilder addChannelDefinitionBytes(String resourceName, byte[] channelDefinitionBytes) {
if (channelDefinitionBytes == null) {
throw new FlowableException("channel definition bytes is null");
}
EventResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(channelDefinitionBytes);
deployment.addResource(resource);
return this;
}
@Override
public EventDeploymentBuilder addChannelDefinition(String resourceName, String channelDefinition) {
addString(resourceName, channelDefinition);
return this;
}
@Override
public EventDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public EventDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public EventDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
|
@Override
public EventDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public EventDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public EventDeployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public EventDeploymentEntity getDeployment() {
return deployment;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\repository\EventDeploymentBuilderImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getResource() {
return resource;
}
@ApiModelProperty(example = "This is a process for testing purposes")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setDiagramResource(String diagramResource) {
this.diagramResource = diagramResource;
}
@ApiModelProperty(example = "http://localhost:8182/repository/deployments/2/resources/testProcess.png", value = "Contains a graphical representation of the process, null when no diagram is available.")
public String getDiagramResource() {
return diagramResource;
}
public void setGraphicalNotationDefined(boolean graphicalNotationDefined) {
this.graphicalNotationDefined = graphicalNotationDefined;
}
@ApiModelProperty(value = "Indicates the process definition contains graphical information (BPMN DI).")
public boolean isGraphicalNotationDefined() {
|
return graphicalNotationDefined;
}
public void setSuspended(boolean suspended) {
this.suspended = suspended;
}
public boolean isSuspended() {
return suspended;
}
public void setStartFormDefined(boolean startFormDefined) {
this.startFormDefined = startFormDefined;
}
public boolean isStartFormDefined() {
return startFormDefined;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionResponse.java
| 2
|
请完成以下Java代码
|
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getName() {
if (localizedName != null && localizedName.length() > 0) {
return localizedName;
} else {
return name;
}
}
public void setName(String name) {
this.name = name;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public String getDescription() {
if (localizedDescription != null && localizedDescription.length() > 0) {
return localizedDescription;
} else {
return description;
}
}
public void setDescription(String description) {
this.description = description;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
|
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]";
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntity.java
| 1
|
请完成以下Java代码
|
public void setEDI_cctop_invoic_v_ID (final int EDI_cctop_invoic_v_ID)
{
if (EDI_cctop_invoic_v_ID < 1)
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, null);
else
set_Value (COLUMNNAME_EDI_cctop_invoic_v_ID, EDI_cctop_invoic_v_ID);
}
@Override
public int getEDI_cctop_invoic_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_invoic_v_ID);
}
@Override
public void setISO_Code (final @Nullable java.lang.String ISO_Code)
{
set_Value (COLUMNNAME_ISO_Code, ISO_Code);
}
@Override
public java.lang.String getISO_Code()
{
return get_ValueAsString(COLUMNNAME_ISO_Code);
}
@Override
public void setnetdate (final @Nullable java.sql.Timestamp netdate)
{
set_Value (COLUMNNAME_netdate, netdate);
}
@Override
public java.sql.Timestamp getnetdate()
{
return get_ValueAsTimestamp(COLUMNNAME_netdate);
}
@Override
public void setNetDays (final int NetDays)
{
|
set_Value (COLUMNNAME_NetDays, NetDays);
}
@Override
public int getNetDays()
{
return get_ValueAsInt(COLUMNNAME_NetDays);
}
@Override
public void setsinglevat (final @Nullable BigDecimal singlevat)
{
set_Value (COLUMNNAME_singlevat, singlevat);
}
@Override
public BigDecimal getsinglevat()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_singlevat);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
}
@Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_120_v.java
| 1
|
请完成以下Java代码
|
private void detectAndCrossLinkCounterAllocationLines()
{
if (allocationLines.size() != 2)
{
return;
}
final I_C_AllocationLine line1 = allocationLines.get(0);
final I_C_AllocationLine line2 = allocationLines.get(1);
if ((line1.getC_Invoice_ID() > 0 && line1.getC_Payment_ID() <= 0)
&& (line2.getC_Invoice_ID() > 0 && line2.getC_Payment_ID() <= 0)
&& line1.getAmount().compareTo(line2.getAmount().negate()) == 0)
{
line1.setCounter_AllocationLine_ID(line2.getC_AllocationLine_ID());
allocationDAO.save(line1);
line2.setCounter_AllocationLine_ID(line1.getC_AllocationLine_ID());
allocationDAO.save(line2);
}
}
public final I_C_AllocationHdr createAndComplete()
{
final boolean complete = true;
return create(complete);
}
private void markAsBuilt()
{
assertNotBuilt();
_built = true;
}
private void assertNotBuilt()
{
Check.assume(!_built, "Not already built");
}
IAllocationDAO getAllocationDAO()
{
return allocationDAO;
}
public final C_AllocationHdr_Builder orgId(@NonNull final OrgId orgId)
{
return orgId(orgId.getRepoId());
}
public final C_AllocationHdr_Builder orgId(final int adOrgId)
{
assertNotBuilt();
allocHdr.setAD_Org_ID(adOrgId);
return this;
}
public final C_AllocationHdr_Builder dateTrx(LocalDate dateTrx)
{
return dateTrx(TimeUtil.asTimestamp(dateTrx));
}
public final C_AllocationHdr_Builder dateTrx(Timestamp dateTrx)
{
assertNotBuilt();
allocHdr.setDateTrx(dateTrx);
return this;
}
public final C_AllocationHdr_Builder dateAcct(LocalDate dateAcct)
{
return dateAcct(TimeUtil.asTimestamp(dateAcct));
|
}
public final C_AllocationHdr_Builder dateAcct(Timestamp dateAcct)
{
assertNotBuilt();
allocHdr.setDateAcct(dateAcct);
return this;
}
public final C_AllocationHdr_Builder currencyId(@NonNull final CurrencyId currencyId)
{
return currencyId(currencyId.getRepoId());
}
public final C_AllocationHdr_Builder currencyId(int currencyId)
{
assertNotBuilt();
allocHdr.setC_Currency_ID(currencyId);
return this;
}
public final C_AllocationHdr_Builder manual(final boolean manual)
{
assertNotBuilt();
allocHdr.setIsManual(manual);
return this;
}
public C_AllocationHdr_Builder description(final String description)
{
assertNotBuilt();
allocHdr.setDescription(description);
return this;
}
public C_AllocationLine_Builder addLine()
{
assertNotBuilt();
final C_AllocationLine_Builder lineBuilder = new C_AllocationLine_Builder(this);
allocationLineBuilders.add(lineBuilder);
return lineBuilder;
}
public final ImmutableList<I_C_AllocationLine> getC_AllocationLines()
{
return ImmutableList.copyOf(allocationLines);
}
public C_AllocationHdr_Builder disableUpdateBPartnerTotalOpenBanace()
{
IBPartnerStatisticsUpdater.DYNATTR_DisableUpdateTotalOpenBalances.setValue(allocHdr, true);
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationHdr_Builder.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public CmmnDeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
String entryName = entry.getName();
byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName);
CmmnResourceEntity resource = resourceEntityManager.create();
resource.setName(entryName);
resource.setBytes(bytes);
deployment.addResource(resource);
}
entry = zipInputStream.getNextEntry();
}
} catch (Exception e) {
throw new FlowableException("problem reading zip input stream", e);
}
return this;
}
public CmmnDeploymentBuilder addCmmnBytes(String resourceName, byte[] cmmnBytes) {
if (cmmnBytes == null) {
throw new FlowableException("cmmn bytes is null");
}
CmmnResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(cmmnBytes);
deployment.addResource(resource);
return this;
}
public CmmnDeploymentBuilder addCmmnModel(String resourceName, CmmnModel cmmnModel) {
// TODO
return null;
}
@Override
public CmmnDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public CmmnDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public CmmnDeploymentBuilder key(String key) {
deployment.setKey(key);
return this;
}
@Override
public CmmnDeploymentBuilder disableSchemaValidation() {
this.isCmmn20XsdValidationEnabled = false;
|
return this;
}
@Override
public CmmnDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public CmmnDeploymentBuilder parentDeploymentId(String parentDeploymentId) {
deployment.setParentDeploymentId(parentDeploymentId);
return this;
}
@Override
public CmmnDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public CmmnDeployment deploy() {
return repositoryService.deploy(this);
}
public CmmnDeploymentEntity getDeployment() {
return deployment;
}
public boolean isCmmnXsdValidationEnabled() {
return isCmmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\repository\CmmnDeploymentBuilderImpl.java
| 2
|
请完成以下Java代码
|
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage_IGNORED, final String localTrxName_IGNORED)
{
final BigDecimal docTypeRepoId = getParameters().getParameterAsBigDecimal(DOC_TYPE_ID);
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(docTypeRepoId != null ? docTypeRepoId.intValue() : 0);
final PurchaseOrderFromItemsAggregator purchaseOrderFromItemsAggregator = //
PurchaseOrderFromItemsAggregator.newInstance(docTypeId);
PurchaseCandidateToOrderWorkflow.builder()
.purchaseCandidateRepo(purchaseCandidateRepo)
.vendorGatewayInvokerFactory(vendorGatewayInvokerFactory)
.purchaseOrderFromItemsAggregator(purchaseOrderFromItemsAggregator)
.build()
.executeForPurchaseCandidates(getPurchaseCandidates());
return Result.SUCCESS;
}
private List<PurchaseCandidate> getPurchaseCandidates()
{
final boolean skipAlreadyScheduledItems = false; // there is just one processor-thread, so there won't be any elements in not yet-processed preceding WPs
final List<I_C_Queue_Element> queueElements = retrieveQueueElements(skipAlreadyScheduledItems);
final Set<PurchaseCandidateId> purchaseCandidateIds = queueElements
.stream()
.map(I_C_Queue_Element::getRecord_ID)
.map(PurchaseCandidateId::ofRepoIdOrNull)
.filter(Objects::nonNull)
|
.collect(ImmutableSet.toImmutableSet());
if (purchaseCandidateIds.isEmpty())
{
throw new AdempiereException("No purchase candidates enqueued");
}
final List<PurchaseCandidate> purchaseCandidates = purchaseCandidateRepo.streamAllByIds(purchaseCandidateIds)
// only those not processed; those locked are OK because *we* locked them
.filter(purchaseCandidate -> !purchaseCandidate.isProcessed())
.collect(ImmutableList.toImmutableList());
if (purchaseCandidates.isEmpty())
{
throw new AdempiereException("No eligible purchase candidates enqueued");
}
return purchaseCandidates;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\async\C_PurchaseCandidates_GeneratePurchaseOrders.java
| 1
|
请完成以下Java代码
|
public class CreateDBFromTemplateScript implements IScript
{
private final String newOwner;
private final String newDBName;
private final String templateDBName;
@Getter
@Setter
private long lastDurationMillis = -1;
@Builder
private CreateDBFromTemplateScript(
final String newOwner,
final String newDBName,
final String templateDBName)
{
this.newOwner = newOwner;
this.newDBName = newDBName;
this.templateDBName = templateDBName;
}
@Override
public String getProjectName()
{
return "000";
}
@Override
|
public String getFileName()
{
return "create_db_" + newDBName + "_with_template_" + templateDBName + ".sql";
}
@Override
public ScriptType getType()
{
return ScriptType.SQL;
}
@Override
public File getLocalFile()
{
final String command = "COMMIT; CREATE DATABASE " + newDBName + " WITH OWNER " + newOwner + " TEMPLATE " + templateDBName;
final InputStream stream = new ByteArrayInputStream(command.getBytes(StandardCharsets.UTF_8));
return FileUtils.createLocalFile(getFileName(), stream);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\impl\CreateDBFromTemplateScript.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
datasource:
url: jdbc:h2:mem:testdb # H2 in-memory DB
username: sa
password: password
driver-class-name: org.h2.Driver
h2:
console:
enabled: true
path: /h2-console
jpa:
hibernate:
ddl-auto: update
show-sql: false
properties:
hibernate.f
|
ormat_sql: true
graphql:
servlet:
enabled: true
path: /graphql
schema:
locations: classpath:pagination/
|
repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\resources\application-pagination.yml
| 2
|
请完成以下Java代码
|
private Optional<I_AD_Issue> getById(@NonNull final AdIssueId adIssueId)
{
return queryBL
.createQueryBuilderOutOfTrx(I_AD_Issue.class)
.addEqualsFilter(I_AD_Issue.COLUMNNAME_AD_Issue_ID, adIssueId)
.create()
.firstOnlyOptional(I_AD_Issue.class);
}
@Override
public IssueCountersByCategory getIssueCountersByCategory(
@NonNull final TableRecordReference recordRef,
final boolean onlyNotAcknowledged)
{
final ArrayList<Object> sqlParams = new ArrayList<>();
final StringBuilder sql = new StringBuilder("SELECT "
+ " " + I_AD_Issue.COLUMNNAME_IssueCategory
+ ", count(1) as count"
+ "\n FROM " + I_AD_Issue.Table_Name
+ "\n WHERE "
+ " " + I_AD_Issue.COLUMNNAME_IsActive + "=?"
+ " AND " + I_AD_Issue.COLUMNNAME_AD_Table_ID + "=?"
+ " AND " + I_AD_Issue.COLUMNNAME_Record_ID + "=?");
sqlParams.add(true); // IsActive
sqlParams.add(recordRef.getAD_Table_ID());
sqlParams.add(recordRef.getRecord_ID());
if (onlyNotAcknowledged)
{
sql.append(" AND ").append(I_AD_Issue.COLUMNNAME_Processed).append("=?");
sqlParams.add(false);
}
sql.append("\n GROUP BY ").append(I_AD_Issue.COLUMNNAME_IssueCategory);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
|
final HashMap<IssueCategory, Integer> counters = new HashMap<>();
while (rs.next())
{
final IssueCategory issueCategory = IssueCategory.ofNullableCodeOrOther(rs.getString(I_AD_Issue.COLUMNNAME_IssueCategory));
final int count = rs.getInt("count");
counters.compute(issueCategory, (k, previousCounter) -> {
return previousCounter != null
? previousCounter + count
: count;
});
}
return IssueCountersByCategory.of(counters);
}
catch (final SQLException ex)
{
throw new DBException(ex, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\error\impl\ErrorManager.java
| 1
|
请完成以下Java代码
|
public I_C_ValidCombination getCB_Expense_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Expense_Acct(), get_TrxName()); }
/** Set Cash Book Expense.
@param CB_Expense_Acct
Cash Book Expense Account
*/
public void setCB_Expense_Acct (int CB_Expense_Acct)
{
set_Value (COLUMNNAME_CB_Expense_Acct, Integer.valueOf(CB_Expense_Acct));
}
/** Get Cash Book Expense.
@return Cash Book Expense Account
*/
public int getCB_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getCB_Receipt_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getCB_Receipt_Acct(), get_TrxName()); }
/** Set Cash Book Receipt.
@param CB_Receipt_Acct
Cash Book Receipts Account
*/
public void setCB_Receipt_Acct (int CB_Receipt_Acct)
{
set_Value (COLUMNNAME_CB_Receipt_Acct, Integer.valueOf(CB_Receipt_Acct));
}
/** Get Cash Book Receipt.
@return Cash Book Receipts Account
*/
public int getCB_Receipt_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CB_Receipt_Acct);
|
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_CashBook getC_CashBook() throws RuntimeException
{
return (I_C_CashBook)MTable.get(getCtx(), I_C_CashBook.Table_Name)
.getPO(getC_CashBook_ID(), get_TrxName()); }
/** Set Cash Book.
@param C_CashBook_ID
Cash Book for recording petty cash transactions
*/
public void setC_CashBook_ID (int C_CashBook_ID)
{
if (C_CashBook_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CashBook_ID, Integer.valueOf(C_CashBook_ID));
}
/** Get Cash Book.
@return Cash Book for recording petty cash transactions
*/
public int getC_CashBook_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CashBook_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashBook_Acct.java
| 1
|
请完成以下Java代码
|
public List<Event> handleUpdateUserCommand(UpdateUserCommand command) {
User user = UserUtility.recreateUserState(writeRepository, command.getUserId());
List<Event> events = new ArrayList<>();
List<Contact> contactsToRemove = user.getContacts()
.stream()
.filter(c -> !command.getContacts()
.contains(c))
.collect(Collectors.toList());
for (Contact contact : contactsToRemove) {
UserContactRemovedEvent contactRemovedEvent = new UserContactRemovedEvent(contact.getType(), contact.getDetail());
events.add(contactRemovedEvent);
writeRepository.addEvent(command.getUserId(), contactRemovedEvent);
}
List<Contact> contactsToAdd = command.getContacts()
.stream()
.filter(c -> !user.getContacts()
.contains(c))
.collect(Collectors.toList());
for (Contact contact : contactsToAdd) {
UserContactAddedEvent contactAddedEvent = new UserContactAddedEvent(contact.getType(), contact.getDetail());
events.add(contactAddedEvent);
writeRepository.addEvent(command.getUserId(), contactAddedEvent);
}
List<Address> addressesToRemove = user.getAddresses()
|
.stream()
.filter(a -> !command.getAddresses()
.contains(a))
.collect(Collectors.toList());
for (Address address : addressesToRemove) {
UserAddressRemovedEvent addressRemovedEvent = new UserAddressRemovedEvent(address.getCity(), address.getState(), address.getPostcode());
events.add(addressRemovedEvent);
writeRepository.addEvent(command.getUserId(), addressRemovedEvent);
}
List<Address> addressesToAdd = command.getAddresses()
.stream()
.filter(a -> !user.getAddresses()
.contains(a))
.collect(Collectors.toList());
for (Address address : addressesToAdd) {
UserAddressAddedEvent addressAddedEvent = new UserAddressAddedEvent(address.getCity(), address.getState(), address.getPostcode());
events.add(addressAddedEvent);
writeRepository.addEvent(command.getUserId(), addressAddedEvent);
}
return events;
}
}
|
repos\tutorials-master\patterns-modules\cqrs-es\src\main\java\com\baeldung\patterns\escqrs\aggregates\UserAggregate.java
| 1
|
请完成以下Java代码
|
public class UserDetail {
private long id;
private long userId;
private String address;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
|
public void setUserId(long userId) {
this.userId = userId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
repos\spring-boot-leaning-master\2.x_data\3-4 解决后期业务变动导致的数据结构不一致的问题\spring-boot-canal-mongodb-cascade\src\main\java\com\neo\model\UserDetail.java
| 1
|
请完成以下Java代码
|
private static DataEntrySubTabId extractDataEntrySubTabId(@NonNull final DetailId detailId)
{
final int subTabId = detailId.getIdInt();
Check.assume(detailId.getIdPrefix().equals(I_DataEntry_SubTab.Table_Name), "The given document.entityDescriptor.detailId needs to have prefix={}", I_DataEntry_SubTab.Table_Name);
final DataEntrySubTabId dataEntrySubTabId = DataEntrySubTabId.ofRepoId(subTabId);
return dataEntrySubTabId;
}
@Override
public void delete(@NonNull final Document document)
{
assertValidState(document);
final DataEntryRecordQuery dataEntryRecordQuery = extractDataEntryRecordQuery(document);
dataEntryRecordRepository.deleteBy(dataEntryRecordQuery);
}
private void assertValidState(@NonNull final Document document)
{
assertThisRepository(document.getEntityDescriptor());
if (Adempiere.isUnitTestMode())
{
return;
}
DocumentPermissionsHelper.assertCanEdit(document);
Services.get(ITrxManager.class).assertThreadInheritedTrxExists();
}
@Override
public String retrieveVersion(DocumentEntityDescriptor entityDescriptor, int documentIdAsInt)
{
return VERSION_DEFAULT;
}
@Override
public int retrieveLastLineNo(DocumentQuery query)
{
return 0;
}
private static final class DataEntryDocumentValuesSupplier implements DocumentValuesSupplier
{
private final DataEntryRecord dataEntryRecord;
|
private final DataEntryWebuiTools dataEntryWebuiTools;
private DataEntryDocumentValuesSupplier(
@NonNull final DataEntryRecord dataEntryRecord,
@NonNull DataEntryWebuiTools dataEntryWebuiTools)
{
this.dataEntryWebuiTools = dataEntryWebuiTools;
this.dataEntryRecord = dataEntryRecord;
}
@Override
public DocumentId getDocumentId()
{
final DocumentId documentId = DataEntrySubTabBindingRepository.createDocumentId(
dataEntryRecord.getDataEntrySubTabId(),
dataEntryRecord.getMainRecord());
return documentId;
}
@Override
public String getVersion()
{
return VERSION_DEFAULT;
}
@Override
public Object getValue(@NonNull final DocumentFieldDescriptor fieldDescriptor)
{
return dataEntryWebuiTools.extractDataEntryValueForField(dataEntryRecord, fieldDescriptor);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntrySubTabBindingRepository.java
| 1
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
final ImmutableList<ExternalSystemParentConfig> configs = externalSystemConfigDAO.getActiveByType(ExternalSystemType.Alberta);
if (configs.size() > 0)
{
return ProcessPreconditionsResolution.accept();
}
return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(MSG_ERR_PROCESS_NOT_AVAILABLE, ExternalSystemType.Alberta.getValue()));
}
@Override
protected String doIt() throws Exception
{
addLog("Calling with params: externalSystemConfigAlbertaId {}, ignoreSelection {}, orgId {}", externalSystemConfigAlbertaId, ignoreSelection, orgId);
final Set<BPartnerId> bPartnerIdSet = (ignoreSelection ? getAllBPartnerRecords() : getSelectedBPartnerRecords())
.stream()
.map(I_C_BPartner::getC_BPartner_ID)
.map(BPartnerId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
final OrgId computedOrgId = orgId > 0 ? OrgId.ofRepoId(orgId) : getProcessInfo().getOrgId();
final ExternalSystemAlbertaConfigId albertaConfigId = ExternalSystemAlbertaConfigId.ofRepoId(externalSystemConfigAlbertaId);
final Stream<JsonExternalSystemRequest> requestList = invokeAlbertaService
.streamSyncExternalRequestsForBPartnerIds(bPartnerIdSet, albertaConfigId, getPinstanceId(), computedOrgId);
final ExternalSystemMessageSender externalSystemMessageSender = SpringContextHolder.instance.getBean(ExternalSystemMessageSender.class);
requestList.forEach(externalSystemMessageSender::send);
return JavaProcess.MSG_OK;
|
}
@NonNull
private List<I_C_BPartner> getAllBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = queryBL.createQueryBuilder(I_C_BPartner.class)
.addOnlyActiveRecordsFilter();
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
}
@NonNull
private List<I_C_BPartner> getSelectedBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class);
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeAlbertaForBPartnerIds.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class LongType implements VariableType {
public static final String TYPE_NAME = "long";
private static final long serialVersionUID = 1L;
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public Object getValue(ValueFields valueFields) {
return valueFields.getLongValue();
|
}
@Override
public void setValue(Object value, ValueFields valueFields) {
valueFields.setLongValue((Long) value);
if (value != null) {
valueFields.setTextValue(value.toString());
} else {
valueFields.setTextValue(null);
}
}
@Override
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return Long.class.isAssignableFrom(value.getClass()) || long.class.isAssignableFrom(value.getClass());
}
}
|
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\LongType.java
| 2
|
请完成以下Java代码
|
public class HRCreateConcept extends JavaProcess
{
private int p_HR_Payroll_ID = 0;
/**
* Prepare
*/
protected void prepare ()
{
p_HR_Payroll_ID = getRecord_ID();
} // prepare
/**
* Process
* @return info
* @throws Exception
*/
protected String doIt () throws Exception
{
int count = 0;
for(MHRConcept concept : MHRConcept.getConcepts(p_HR_Payroll_ID, 0, 0, null))
{
if(!existsPayrollConcept(concept.get_ID()))
{
|
MHRPayrollConcept payrollConcept = new MHRPayrollConcept (concept, p_HR_Payroll_ID, get_TrxName());
payrollConcept.saveEx();
count++;
}
}
return "@Created@/@Updated@ #" + count;
} // doIt
private boolean existsPayrollConcept(int HR_Concept_ID)
{
final String whereClause = "HR_Payroll_ID=? AND HR_Concept_ID=?";
return new Query(getCtx(), MHRPayrollConcept.Table_Name, whereClause, get_TrxName())
.setParameters(new Object[]{p_HR_Payroll_ID, HR_Concept_ID})
.anyMatch();
}
} // Create Concept of the current Payroll
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\process\HRCreateConcept.java
| 1
|
请完成以下Java代码
|
public class FlowableEventDispatcherImpl implements FlowableEventDispatcher {
protected FlowableEventSupport eventSupport;
protected boolean enabled = true;
public FlowableEventDispatcherImpl() {
eventSupport = new FlowableEventSupport();
}
@Override
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public boolean isEnabled() {
return enabled;
}
@Override
public void addEventListener(FlowableEventListener listenerToAdd) {
eventSupport.addEventListener(listenerToAdd);
}
@Override
public void addEventListener(FlowableEventListener listenerToAdd, FlowableEventType... types) {
eventSupport.addEventListener(listenerToAdd, types);
}
@Override
public void removeEventListener(FlowableEventListener listenerToRemove) {
eventSupport.removeEventListener(listenerToRemove);
}
@Override
public void dispatchEvent(FlowableEvent event, String engineType) {
if (enabled) {
eventSupport.dispatchEvent(event);
}
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
|
AbstractEngineConfiguration engineConfiguration = commandContext.getEngineConfigurations().get(engineType);
if (engineConfiguration != null && engineConfiguration.getAdditionalEventDispatchActions() != null) {
for (EventDispatchAction eventDispatchAction : engineConfiguration.getAdditionalEventDispatchActions()) {
eventDispatchAction.dispatchEvent(commandContext, eventSupport, event);
}
}
}
}
public FlowableEventSupport getEventSupport() {
return eventSupport;
}
public void setEventSupport(FlowableEventSupport eventSupport) {
this.eventSupport = eventSupport;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableEventDispatcherImpl.java
| 1
|
请完成以下Java代码
|
public class Employee {
private Integer employeeId;
private Address address;
private String employeeName;
public Employee() {
super();
}
public Employee(Integer employeeId, Address address, String employeeName) {
this.employeeId = employeeId;
this.address = address;
this.employeeName = employeeName;
}
public Integer getEmployeeId() {
return employeeId;
}
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
|
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-maps-4\src\main\java\com\baeldung\nestedhashmaps\Employee.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Routers {
@Bean
public RouterFunction<ServerResponse> route(UserService userService, LoginService loginService) {
return RouterFunctions
//Secured endpoints
.route(GET("/secured/users/{id}").and(accept(APPLICATION_JSON)), request -> {
Mono<UserData> userDataMono = userService.getEmployee(request.pathVariable("id"));
return ServerResponse.ok().body(userDataMono, UserData.class);
})
.andRoute(GET("/secured/users").and(accept(APPLICATION_JSON)), request -> {
Flux<UserData> userDataFlux = userService.getAll();
return ServerResponse.ok().body(userDataFlux, UserData.class);
})
.andRoute(POST("/secured/users").and(accept(APPLICATION_JSON)), request -> {
Mono<CreateUserData> monoBody = request.bodyToMono(CreateUserData.class);
Mono<UserData> userDataMono = monoBody.flatMap(userService::create);
return ServerResponse.ok().body(userDataMono, UserData.class);
})
.andRoute(DELETE("/secured/users/{id}").and(accept(APPLICATION_JSON)), request -> {
Mono<UserData> userDataMono = userService.delete(request.pathVariable("id"));
return ServerResponse.ok().body(userDataMono, UserData.class);
})
.andRoute(PUT("/secured/users").and(accept(APPLICATION_JSON)), request -> {
Mono<UserData> monoBody = request.bodyToMono(UserData.class);
Mono<UserData> userDataMono = monoBody.flatMap(userService::update);
return ServerResponse.ok().body(userDataMono, UserData.class);
})
.andRoute(PUT("/secured/create/{n}").and(accept(APPLICATION_JSON)), request -> {
userService.createUsersBulk(Integer.parseInt(request.pathVariable("n")));
return ServerResponse.ok().build();
})
|
.filter(new ExampleHandlerFilterFunction(loginService))
//Un-Secured Login/Logout endpoints
.andRoute(POST("/secured/login").and(accept(APPLICATION_JSON)), request -> {
Mono<LoginRequest> monoBody = request.bodyToMono(LoginRequest.class);
Mono<Token> tokenMono = monoBody.flatMap(loginService::login);
return ServerResponse.ok().body(tokenMono, Token.class);
})
.andRoute(POST("/secured/logout").and(accept(APPLICATION_JSON)), request -> {
Mono<Token> monoBody = request.bodyToMono(Token.class);
Mono<Void> voidMono = monoBody.flatMap(loginService::logout);
return ServerResponse.ok().body(voidMono, Void.class);
});
}
}
|
repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\config\Routers.java
| 2
|
请完成以下Java代码
|
private Method read(Object base) {
if (this.read == null) {
this.read = Util.getMethod(this.owner, base, getReadMethod());
}
return this.read;
}
abstract Method getWriteMethod();
abstract Method getReadMethod();
abstract String getName();
}
private BeanProperty property(Object base, Object property) {
Class<?> type = base.getClass();
String prop = property.toString();
BeanProperties props = this.cache.get(type.getName());
if (props == null || type != props.getType()) {
props = BeanSupport.getInstance().getBeanProperties(type);
this.cache.put(type.getName(), props);
}
return props.get(prop);
}
private static final class ConcurrentCache<K, V> {
private final int size;
private final Map<K, V> eden;
private final Map<K, V> longterm;
ConcurrentCache(int size) {
this.size = size;
this.eden = new ConcurrentHashMap<>(size);
this.longterm = new WeakHashMap<>(size);
}
|
public V get(K key) {
V value = this.eden.get(key);
if (value == null) {
synchronized (longterm) {
value = this.longterm.get(key);
}
if (value != null) {
this.eden.put(key, value);
}
}
return value;
}
public void put(K key, V value) {
if (this.eden.size() >= this.size) {
synchronized (longterm) {
this.longterm.putAll(this.eden);
}
this.eden.clear();
}
this.eden.put(key, value);
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\BeanELResolver.java
| 1
|
请完成以下Java代码
|
protected boolean sortOptionsValid() {
return (sortBy != null && sortOrder != null) || (sortBy == null && sortOrder == null);
}
public T toQuery(ProcessEngine engine) {
T query = createNewQuery(engine);
applyFilters(query);
if (!sortOptionsValid()) {
throw new InvalidRequestException(Status.BAD_REQUEST, "Only a single sorting parameter specified. sortBy and sortOrder required");
}
applySortingOptions(query, engine);
return query;
}
protected abstract T createNewQuery(ProcessEngine engine);
protected abstract void applyFilters(T query);
protected void applySortingOptions(T query, ProcessEngine engine) {
if (sortBy != null) {
applySortBy(query, sortBy, null, engine);
}
if (sortOrder != null) {
applySortOrder(query, sortOrder);
}
if (sortings != null) {
for (SortingDto sorting : sortings) {
String sortingOrder = sorting.getSortOrder();
String sortingBy = sorting.getSortBy();
if (sortingBy != null) {
applySortBy(query, sortingBy, sorting.getParameters(), engine);
}
if (sortingOrder != null) {
applySortOrder(query, sortingOrder);
}
}
}
}
protected abstract void applySortBy(T query, String sortBy, Map<String, Object> parameters, ProcessEngine engine);
protected void applySortOrder(T query, String sortOrder) {
if (sortOrder != null) {
|
if (sortOrder.equals(SORT_ORDER_ASC_VALUE)) {
query.asc();
} else if (sortOrder.equals(SORT_ORDER_DESC_VALUE)) {
query.desc();
}
}
}
public static String sortOrderValueForDirection(Direction direction) {
if (Direction.ASCENDING.equals(direction)) {
return SORT_ORDER_ASC_VALUE;
}
else if (Direction.DESCENDING.equals(direction)) {
return SORT_ORDER_DESC_VALUE;
}
else {
throw new RestException("Unknown query sorting direction " + direction);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\AbstractQueryDto.java
| 1
|
请完成以下Java代码
|
public class Saldo {
private String sollHabenKennung;
private String waehrung;
private Date buchungsdatum;
private BigDecimal betrag;
public Saldo(String sollHabenKennung, Date buchungsdatum, String waehrung, BigDecimal betrag) {
this.sollHabenKennung = sollHabenKennung;
this.waehrung = waehrung;
this.buchungsdatum = buchungsdatum;
this.betrag = betrag;
}
public String getSollHabenKennung() {
return sollHabenKennung;
}
public void setSollHabenKennung(String sollHabenKennung) {
this.sollHabenKennung = sollHabenKennung;
}
public String getWaehrung() {
return waehrung;
}
public void setWaehrung(String waehrung) {
this.waehrung = waehrung;
}
|
public Date getBuchungsdatum() {
return buchungsdatum;
}
public void setBuchungsdatum(Date buchungsdatum) {
this.buchungsdatum = buchungsdatum;
}
public BigDecimal getBetrag() {
return betrag;
}
public void setBetrag(BigDecimal betrag) {
this.betrag = betrag;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Saldo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class MethodSecurityAspectJAutoProxyRegistrar implements ImportBeanDefinitionRegistrar {
/**
* Register, escalate, and configure the AspectJ auto proxy creator based on the value
* of the @{@link EnableMethodSecurity#proxyTargetClass()} attribute on the importing
* {@code @Configuration} class.
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
registerBeanDefinition("preFilterAuthorizationMethodInterceptor",
"org.springframework.security.authorization.method.aspectj.PreFilterAspect", "preFilterAspect$0",
registry);
registerBeanDefinition("postFilterAuthorizationMethodInterceptor",
"org.springframework.security.authorization.method.aspectj.PostFilterAspect", "postFilterAspect$0",
registry);
registerBeanDefinition("preAuthorizeAuthorizationMethodInterceptor",
"org.springframework.security.authorization.method.aspectj.PreAuthorizeAspect", "preAuthorizeAspect$0",
registry);
registerBeanDefinition("postAuthorizeAuthorizationMethodInterceptor",
|
"org.springframework.security.authorization.method.aspectj.PostAuthorizeAspect",
"postAuthorizeAspect$0", registry);
registerBeanDefinition("securedAuthorizationMethodInterceptor",
"org.springframework.security.authorization.method.aspectj.SecuredAspect", "securedAspect$0", registry);
}
private void registerBeanDefinition(String beanName, String aspectClassName, String aspectBeanName,
BeanDefinitionRegistry registry) {
if (!registry.containsBeanDefinition(beanName)) {
return;
}
BeanDefinition interceptor = registry.getBeanDefinition(beanName);
BeanDefinitionBuilder aspect = BeanDefinitionBuilder.rootBeanDefinition(aspectClassName);
aspect.setFactoryMethod("aspectOf");
aspect.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
aspect.addPropertyValue("securityInterceptor", interceptor);
registry.registerBeanDefinition(aspectBeanName, aspect.getBeanDefinition());
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\MethodSecurityAspectJAutoProxyRegistrar.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Category {
@Id
@GeneratedValue
private Long id;
private String name;
@OneToMany(mappedBy = "category", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Book> books;
public Category() {
}
public Category(String name) {
this.name = name;
}
public Category(String name, Book... books) {
this.name = name;
this.books = Stream.of(books).collect(Collectors.toList());
this.books.forEach(x -> x.setCategory(this));
}
public Category(String name, List<Book> books) {
this.name = name;
this.books = books;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
|
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\datajpadelete\entity\Category.java
| 2
|
请完成以下Java代码
|
public void setUrl(final String url)
{
this.url = url;
this.urlSet = true;
}
public void setUrl2(final String url2)
{
this.url2 = url2;
this.url2Set = true;
}
public void setUrl3(final String url3)
{
this.url3 = url3;
this.url3Set = true;
}
public void setGroup(final String group)
{
this.group = group;
this.groupSet = true;
}
public void setGlobalId(final String globalId)
{
this.globalId = globalId;
|
this.globalIdset = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
public void setVatId(final String vatId)
{
this.vatId = vatId;
this.vatIdSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestBPartner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ContactInfoValidator implements ConstraintValidator<ContactInfo, String> {
private static final Logger LOG = LogManager.getLogger(ContactInfoValidator.class);
@Autowired
private ContactInfoExpressionRepository expressionRepository;
@Value("${contactInfoType}")
String expressionType;
private String pattern;
@Override
public void initialize(final ContactInfo contactInfo) {
if (StringUtils.isEmptyOrWhitespace(expressionType)) {
|
LOG.error("Contact info type missing!");
} else {
pattern = expressionRepository.findById(expressionType).map(ContactInfoExpression::getPattern).orElse("");
}
}
@Override
public boolean isValid(final String value, final ConstraintValidatorContext context) {
if (!StringUtils.isEmptyOrWhitespace(pattern)) {
return Pattern.matches(pattern, value);
}
LOG.error("Contact info pattern missing!");
return false;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\dynamicvalidation\ContactInfoValidator.java
| 2
|
请完成以下Java代码
|
protected String doIt()
{
final I_M_HU tuOrAggregatedHU = getTUOrAggregatedTU();
final QtyTU qtyTU = QtyTU.ofInt(this.qtyTU);
final QtyTU maxQtyTU = handlingUnitsBL.getTUsCount(tuOrAggregatedHU);
if (qtyTU.isGreaterThan(maxQtyTU))
{
throw new AdempiereException("@QtyTU@ <= " + maxQtyTU);
}
final I_M_HU luHU = getTargetLU();
//
// If it's a top level TU then
// first remove it from picking slots
final boolean isTopLevelHU = handlingUnitsBL.isTopLevel(tuOrAggregatedHU);
if (isTopLevelHU)
{
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(tuOrAggregatedHU);
this.huExtractedFromPickingSlotEvent = HUExtractedFromPickingSlotEvent.builder()
.huId(tuOrAggregatedHU.getM_HU_ID())
.bpartnerId(tuOrAggregatedHU.getC_BPartner_ID())
.bpartnerLocationId(tuOrAggregatedHU.getC_BPartner_Location_ID())
.build();
}
final HashSet<HuId> huIdsDestroyedCollector = new HashSet<>();
HUTransformService.builder()
.emptyHUListener(EmptyHUListener.collectDestroyedHUIdsTo(huIdsDestroyedCollector))
.build()
.tuToExistingLU(tuOrAggregatedHU, qtyTU, luHU);
// Remove from picking slots all destroyed HUs
pickingCandidateService.inactivateForHUIds(huIdsDestroyedCollector);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
|
{
if (!success)
{
return;
}
// Invalidate views
final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView();
pickingSlotsClearingView.invalidateAll();
getPackingHUsView().invalidateAll();
if (huExtractedFromPickingSlotEvent != null)
{
pickingSlotsClearingView.handleEvent(huExtractedFromPickingSlotEvent);
}
}
@NonNull
private I_M_HU getTargetLU()
{
final HUEditorRow packingHURow = getSingleSelectedPackingHUsRow();
Check.assume(packingHURow.isLU(), "Pack to HU shall be a LU: {}", packingHURow);
return handlingUnitsBL.getById(packingHURow.getHuId());
}
@NonNull
private I_M_HU getTUOrAggregatedTU()
{
final PickingSlotRow pickingSlotRow = getSingleSelectedPickingSlotRow();
Check.assume(pickingSlotRow.isTU(), "Picking slot HU shall be a TU: {}", pickingSlotRow);
return handlingUnitsBL.getById(pickingSlotRow.getHuId());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutTUAndAddToLU.java
| 1
|
请完成以下Java代码
|
public Collection<KPI> toCollection()
{
return byId.values();
}
@Nullable
public KPI getByIdOrNull(@NonNull final KPIId kpiId)
{
return byId.get(kpiId);
}
}
@Builder
@ToString
private static class KPILoadingContext
|
{
@NonNull private final ImmutableListMultimap<KPIId, I_WEBUI_KPI_Field> kpiFieldDefsMap;
@NonNull private final HashMap<Integer, I_AD_Element> adElementsById = new HashMap<>();
public ImmutableList<I_WEBUI_KPI_Field> getFields(@NonNull final KPIId kpiId)
{
return kpiFieldDefsMap.get(kpiId);
}
public I_AD_Element getAdElementById(final int adElementId, @NonNull final IADElementDAO adElementDAO)
{
return adElementsById.computeIfAbsent(adElementId, adElementDAO::getById);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPIRepository.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_IMP_ProcessorLog> logs = retrieveLogs();
Services.get(IIMPProcessorBL.class).resubmit(logs, false, this);
return "OK";
}
private Iterator<I_IMP_ProcessorLog> retrieveLogs()
{
final StringBuilder whereClause = new StringBuilder("1=1");
final List<Object> params = new ArrayList<Object>();
|
// Window selection
final String processWhereClause = getProcessInfo().getWhereClause();
if (!Check.isEmpty(processWhereClause, true))
{
whereClause.append(" AND (").append(processWhereClause).append(")");
}
// Only those who have errors
whereClause.append(" AND ").append(I_IMP_ProcessorLog.COLUMNNAME_IsError).append("=?");
params.add(true);
return new Query(getCtx(), I_IMP_ProcessorLog.Table_Name, whereClause.toString(), ITrx.TRXNAME_None)
.setParameters(params)
// .setApplyAccessFilterRW(true) // if a user can open the window and see the error-log records, we want to let him/her resubmit them
.setOrderBy(I_IMP_ProcessorLog.COLUMNNAME_IMP_ProcessorLog_ID)
.iterate(I_IMP_ProcessorLog.class, false); // guaranteed=false
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\process\IMP_ProcessorLog_ResubmitXML.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static void initDeployedResourceLists(DeploymentWithDefinitions deployment, DeploymentWithDefinitionsDto dto) {
List<ProcessDefinition> deployedProcessDefinitions = deployment.getDeployedProcessDefinitions();
if (deployedProcessDefinitions != null) {
dto.deployedProcessDefinitions = new HashMap<String, ProcessDefinitionDto>();
for (ProcessDefinition processDefinition : deployedProcessDefinitions) {
dto.deployedProcessDefinitions
.put(processDefinition.getId(), ProcessDefinitionDto.fromProcessDefinition(processDefinition));
}
}
List<CaseDefinition> deployedCaseDefinitions = deployment.getDeployedCaseDefinitions();
if (deployedCaseDefinitions != null) {
dto.deployedCaseDefinitions = new HashMap<String, CaseDefinitionDto>();
for (CaseDefinition caseDefinition : deployedCaseDefinitions) {
dto.deployedCaseDefinitions
.put(caseDefinition.getId(), CaseDefinitionDto.fromCaseDefinition(caseDefinition));
}
}
|
List<DecisionDefinition> deployedDecisionDefinitions = deployment.getDeployedDecisionDefinitions();
if (deployedDecisionDefinitions != null) {
dto.deployedDecisionDefinitions = new HashMap<String, DecisionDefinitionDto>();
for (DecisionDefinition decisionDefinition : deployedDecisionDefinitions) {
dto.deployedDecisionDefinitions
.put(decisionDefinition.getId(), DecisionDefinitionDto.fromDecisionDefinition(decisionDefinition));
}
}
List<DecisionRequirementsDefinition> deployedDecisionRequirementsDefinitions = deployment.getDeployedDecisionRequirementsDefinitions();
if (deployedDecisionRequirementsDefinitions != null) {
dto.deployedDecisionRequirementsDefinitions = new HashMap<String, DecisionRequirementsDefinitionDto>();
for (DecisionRequirementsDefinition drd : deployedDecisionRequirementsDefinitions) {
dto.deployedDecisionRequirementsDefinitions
.put(drd.getId(), DecisionRequirementsDefinitionDto.fromDecisionRequirementsDefinition(drd));
}
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\DeploymentWithDefinitionsDto.java
| 2
|
请完成以下Java代码
|
public boolean accepts(VirtualFile file) {
return ProcessApplicationScanningUtil.isDiagram(file.getName(), process.getName());
}
});
for (VirtualFile diagram : diagrams) {
addResource(diagram, processArchiveRoot, resources);
}
}
}
catch (IOException e) {
LOG.cannotScanVfsRoot(processArchiveRoot, e);
}
}
private void addResource(VirtualFile virtualFile, VirtualFile processArchiveRoot, Map<String, byte[]> resources) {
String resourceName = virtualFile.getPathNameRelativeTo(processArchiveRoot);
try {
InputStream inputStream = virtualFile.openStream();
|
byte[] bytes = IoUtil.readInputStream(inputStream, resourceName);
IoUtil.closeSilently(inputStream);
resources.put(resourceName, bytes);
}
catch (IOException e) {
LOG.cannotReadInputStreamForFile(resourceName, processArchiveRoot, e);
}
}
protected Enumeration<URL> loadClasspathResourceRoots(final ClassLoader classLoader, String strippedPaResourceRootPath) {
try {
return classLoader.getResources(strippedPaResourceRootPath);
}
catch (IOException e) {
throw LOG.exceptionWhileLoadingCpRoots(strippedPaResourceRootPath, classLoader, e);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\scanning\VfsProcessApplicationScanner.java
| 1
|
请完成以下Java代码
|
public void setIsStatement (boolean IsStatement)
{
set_Value (COLUMNNAME_IsStatement, Boolean.valueOf(IsStatement));
}
/** Get Is Statement.
@return Dunning Level is a definition of a statement
*/
@Override
public boolean isStatement ()
{
Object oo = get_Value(COLUMNNAME_IsStatement);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Massenaustritt.
@param IsWriteOff Massenaustritt */
@Override
public void setIsWriteOff (boolean IsWriteOff)
{
set_Value (COLUMNNAME_IsWriteOff, Boolean.valueOf(IsWriteOff));
}
/** Get Massenaustritt.
@return Massenaustritt */
@Override
public boolean isWriteOff ()
{
Object oo = get_Value(COLUMNNAME_IsWriteOff);
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
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Notiz.
@param Note
Optional additional user defined information
*/
@Override
public void setNote (java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
/** Get Notiz.
@return Optional additional user defined information
*/
@Override
public java.lang.String getNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_Note);
}
/** Set Notiz Header.
|
@param NoteHeader
Optional weitere Information für ein Dokument
*/
@Override
public void setNoteHeader (java.lang.String NoteHeader)
{
set_Value (COLUMNNAME_NoteHeader, NoteHeader);
}
/** Get Notiz Header.
@return Optional weitere Information für ein Dokument
*/
@Override
public java.lang.String getNoteHeader ()
{
return (java.lang.String)get_Value(COLUMNNAME_NoteHeader);
}
/** Set Drucktext.
@param PrintName
The label text to be printed on a document or correspondence.
*/
@Override
public void setPrintName (java.lang.String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Drucktext.
@return The label text to be printed on a document or correspondence.
*/
@Override
public java.lang.String getPrintName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DunningLevel.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getTreeColumnName(final I_AD_InfoWindow infoWindow)
{
final I_AD_InfoColumn treeColumn = Services.get(IADInfoWindowDAO.class).retrieveTreeInfoColumn(infoWindow);
if (treeColumn == null)
{
return null;
}
final String treeColumnName = treeColumn.getSelectClause();
return treeColumnName;
}
@Override
// @Cached
public int getAD_Tree_ID(final I_AD_InfoWindow infoWindow)
{
String keyName = getTreeColumnName(infoWindow);
// the keyName is wrong typed in Mtree class
// TODO: HARDCODED
|
if ("M_Product_Category_ID".equals(keyName))
{
keyName = "M_ProductCategory_ID";
}
final Properties ctx = InterfaceWrapperHelper.getCtx(infoWindow);
final int adTreeId = MTree.getDefaultAD_Tree_ID(Env.getAD_Client_ID(ctx), keyName);
return adTreeId;
}
@Override
public boolean isShowTotals(final I_AD_InfoWindow infoWindow)
{
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\ADInfoWindowBL.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private void acquireLock()
{
final boolean lockAcquired = lock.tryLock();
if (!lockAcquired)
{
throw new AdempiereException("The import is already running!");
}
log.debug(" {} GithubImporterService: lock acquired, starting the import!", IMPORT_LOG_MESSAGE_PREFIX);
}
private void releaseLock()
{
lock.unlock();
log.debug(" {} GithubImporterService: lock released!", IMPORT_LOG_MESSAGE_PREFIX);
}
private void processLabels(final List<Label> labelList,
@NonNull final ImportIssueInfo.ImportIssueInfoBuilder importIssueInfoBuilder,
@NonNull final OrgId orgId)
{
final ImmutableList<ProcessedLabel> processedLabels = labelService.processLabels(labelList);
final List<IssueLabel> issueLabelList = new ArrayList<>();
final List<String> deliveryPlatformList = new ArrayList<>();
BigDecimal budget = BigDecimal.ZERO;
BigDecimal estimation = BigDecimal.ZERO;
BigDecimal roughEstimation = BigDecimal.ZERO;
Optional<Status> status = Optional.empty();
Optional<LocalDate> plannedUATDate = Optional.empty();
Optional<LocalDate> deliveredDate = Optional.empty();
for (final ProcessedLabel label : processedLabels)
{
switch (label.getLabelType())
{
case ESTIMATION:
estimation = estimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case ROUGH_EST:
roughEstimation = roughEstimation.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case BUDGET:
budget = budget.add(NumberUtils.asBigDecimal(label.getExtractedValue(), BigDecimal.ZERO));
break;
case STATUS:
status = status.isPresent() ? status : Status.ofCodeOptional(label.getExtractedValue());
break;
case DELIVERY_PLATFORM:
deliveryPlatformList.add(label.getExtractedValue());
break;
case PLANNED_UAT:
|
plannedUATDate = plannedUATDate.isPresent() ? plannedUATDate : getDateFromLabel(label.getExtractedValue());
break;
case DELIVERED_DATE:
deliveredDate = deliveredDate.isPresent() ? deliveredDate : getDateFromLabel(label.getExtractedValue());
break;
default:
// nothing to do for UNKNOWN label types
}
issueLabelList.add(IssueLabel.builder().value(label.getLabel()).orgId(orgId).build());
}
importIssueInfoBuilder.budget(budget);
importIssueInfoBuilder.estimation(estimation);
importIssueInfoBuilder.roughEstimation(roughEstimation);
importIssueInfoBuilder.issueLabels(ImmutableList.copyOf(issueLabelList));
status.ifPresent(importIssueInfoBuilder::status);
plannedUATDate.ifPresent(importIssueInfoBuilder::plannedUATDate);
deliveredDate.ifPresent(importIssueInfoBuilder::deliveredDate);
if (!deliveryPlatformList.isEmpty())
{
importIssueInfoBuilder.deliveryPlatform(Joiner.on(",").join(deliveryPlatformList));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\github\GithubImporterService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public <S extends T> void saveInBatch(Iterable<S> entities) {
if (entities == null) {
throw new IllegalArgumentException("The given Iterable of entities cannot be null!");
}
int i = 0;
for (S entity : entities) {
entityManager.persist(entity);
i++;
// Flush a batch of inserts and release memory
if (i % batchSize() == 0 && i > 0) {
logger.log(Level.INFO,
"Flushing the EntityManager containing {0} entities ...", i);
entityManager.flush();
entityManager.clear();
i = 0;
}
}
if (i > 0) {
logger.log(Level.INFO,
"Flushing the remaining {0} entities ...", i);
entityManager.flush();
entityManager.clear();
}
|
}
private static int batchSize() {
int batchsize = Integer.valueOf(Dialect.DEFAULT_BATCH_SIZE); // default batch size
Properties configuration = new Properties();
try (InputStream inputStream = BatchRepositoryImpl.class.getClassLoader()
.getResourceAsStream("application.properties")) {
configuration.load(inputStream);
} catch (IOException ex) {
logger.log(Level.SEVERE,
"Cannot fetch batch size. Using further Dialect.DEFAULT_BATCH_SIZE{0}", ex);
return batchsize;
}
String batchsizestr = configuration.getProperty(
"spring.jpa.properties.hibernate.jdbc.batch_size");
if (batchsizestr != null) {
batchsize = Integer.valueOf(batchsizestr);
}
return batchsize;
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchInsertOrder\src\main\java\com\bookstore\impl\BatchRepositoryImpl.java
| 2
|
请完成以下Java代码
|
protected boolean isValidSortByValue(String value) {
return false;
}
public void validateAndPrepareQuery() {
if (subscriptionStartDate == null || !subscriptionStartDate.before(ClockUtil.now())) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST,
"subscriptionStartDate parameter has invalid value: " + subscriptionStartDate);
}
if (startDate != null && endDate != null && !endDate.after(startDate)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "endDate parameter must be after startDate");
}
if (!VALID_GROUP_BY_VALUES.contains(groupBy)) {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupBy);
}
if (metrics == null || metrics.isEmpty()) {
metrics = VALID_METRIC_VALUES;
|
}
// convert metrics to internal names
this.metrics = metrics.stream()
.map(MetricsUtil::resolveInternalName)
.collect(Collectors.toSet());
}
public int getSubscriptionMonth() {
return subscriptionMonth;
}
public int getSubscriptionDay() {
return subscriptionDay;
}
}
|
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\admin\impl\plugin\base\dto\MetricsAggregatedQueryDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
@Column(name = "pagecount")
private String pageCount;
public Book(Integer id, String name, String pageCount) {
this.id = id;
this.name = name;
this.pageCount = pageCount;
}
public Book() {
}
public Integer getId() {
return id;
}
|
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPageCount() {
return pageCount;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
}
|
repos\springboot-demo-master\GraphQL\src\main\java\com\et\graphql\model\Book.java
| 2
|
请完成以下Java代码
|
public int hashCode() {
return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions,
this.dltStrategy, this.kafkaOperations);
}
@Override
public String toString() {
return "Properties{" +
"delayMs=" + this.delayMs +
", suffix='" + this.suffix + '\'' +
", type=" + this.type +
", maxAttempts=" + this.maxAttempts +
", numPartitions=" + this.numPartitions +
", dltStrategy=" + this.dltStrategy +
", kafkaOperations=" + this.kafkaOperations +
", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout +
'}';
}
public boolean isMainEndpoint() {
return Type.MAIN.equals(this.type);
}
|
}
enum Type {
MAIN,
RETRY,
/**
* A retry topic reused along sequential retries
* with the same back off interval.
*
* @since 3.0.4
*/
REUSABLE_RETRY_TOPIC,
DLT,
NO_OPS
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.