instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public boolean isDoNotIncludeVariables() {
return doNotIncludeVariables;
}
public void setDoNotIncludeVariables(boolean doNotIncludeVariables) {
this.doNotIncludeVariables = doNotIncludeVariables;
}
@Override
public List<IOParameter> getInParameters() {
return inParameters;
}
@Override
public void setInParameters(List<IOParameter> inParameters) {
this.inParameters = inParameters;
}
@Override
public void addInParameter(IOParameter inParameter) {
this.inParameters.add(inParameter);
}
@Override
public List<IOParameter> getOutParameters() {
return outParameters;
}
@Override
public void setOutParameters(List<IOParameter> outParameters) {
this.outParameters = outParameters;
} | @Override
public void addOutParameter(IOParameter outParameter) {
this.outParameters.add(outParameter);
}
@Override
public ExternalWorkerServiceTask clone() {
ExternalWorkerServiceTask clone = new ExternalWorkerServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ExternalWorkerServiceTask otherElement) {
super.setValues(otherElement);
setTopic(otherElement.getTopic());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ExternalWorkerServiceTask.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CarModel other = (CarModel) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (maker == null) {
if (other.maker != null)
return false;
} else if (!maker.equals(other.maker))
return false;
if (name == null) { | if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (sku == null) {
if (other.sku != null)
return false;
} else if (!sku.equals(other.sku))
return false;
if (year == null) {
if (other.year != null)
return false;
} else if (!year.equals(other.year))
return false;
return true;
}
} | repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarModel.java | 1 |
请完成以下Java代码 | public void error(final int WindowNo, final String AD_Message)
{
getCurrentInstance().error(WindowNo, AD_Message);
}
@Override
public void error(final int WindowNo, final String AD_Message, final String message)
{
getCurrentInstance().error(WindowNo, AD_Message, message);
}
@Override
public void error(int WindowNo, Throwable e)
{
getCurrentInstance().error(WindowNo, e);
}
@Override
public void download(final byte[] data, final String contentType, final String filename)
{
getCurrentInstance().download(data, contentType, filename);
}
@Override
public void downloadNow(final InputStream content, final String contentType, final String filename)
{
getCurrentInstance().downloadNow(content, contentType, filename);
}
@Override
public void invokeLater(final int windowNo, final Runnable runnable)
{
getCurrentInstance().invokeLater(windowNo, runnable);
}
@Override
public Thread createUserThread(final Runnable runnable, final String threadName)
{
return getCurrentInstance().createUserThread(runnable, threadName);
}
@Override
public String getClientInfo()
{
return getCurrentInstance().getClientInfo();
}
/**
* This method does nothing.
*
* @deprecated please check out the deprecation notice in {@link IClientUIInstance#hideBusyDialog()}.
*/
@Deprecated
@Override
public void hideBusyDialog()
{ | // nothing
}
@Override
public void showWindow(final Object model)
{
getCurrentInstance().showWindow(model);
}
@Override
public void executeLongOperation(final Object component, final Runnable runnable)
{
getCurrentInstance().executeLongOperation(component, runnable);
}
@Override
public IClientUIInvoker invoke()
{
return getCurrentInstance().invoke();
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
return getCurrentInstance().invokeAsync();
}
@Override
public void showURL(String url)
{
getCurrentInstance().showURL(url);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\AbstractClientUI.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public List<String> getFields() {
return this.fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
}
}
public static class Propagation {
/**
* Tracing context propagation types produced and consumed by the application.
* Setting this property overrides the more fine-grained propagation type
* properties.
*/
private @Nullable List<PropagationType> type;
/**
* Tracing context propagation types produced by the application.
*/
private List<PropagationType> produce = List.of(PropagationType.W3C);
/**
* Tracing context propagation types consumed by the application.
*/
private List<PropagationType> consume = List.of(PropagationType.values());
public void setType(@Nullable List<PropagationType> type) {
this.type = type;
}
public void setProduce(List<PropagationType> produce) {
this.produce = produce;
}
public void setConsume(List<PropagationType> consume) {
this.consume = consume;
}
public @Nullable List<PropagationType> getType() {
return this.type;
}
public List<PropagationType> getProduce() {
return this.produce;
} | public List<PropagationType> getConsume() {
return this.consume;
}
/**
* Supported propagation types. The declared order of the values matter.
*/
public enum PropagationType {
/**
* <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation.
*/
W3C,
/**
* <a href="https://github.com/openzipkin/b3-propagation#single-header">B3
* single header</a> propagation.
*/
B3,
/**
* <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3
* multiple headers</a> propagation.
*/
B3_MULTI
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java | 2 |
请完成以下Java代码 | private ImmutableList<GeographicalCoordinates> queryAllCoordinates(@NonNull final GeoCoordinatesRequest request)
{
final String formattedAddress = String.format("%s, %s %s, %s",
CoalesceUtil.coalesce(request.getAddress(), ""),
CoalesceUtil.coalesce(request.getPostal(), ""),
CoalesceUtil.coalesce(request.getCity(), ""),
CoalesceUtil.coalesce(request.getCountryCode2(), ""));
logger.trace("Formatted address: {}", formattedAddress);
final GeocodingResult[] results = GeocodingApi
.geocode(context, formattedAddress)
.awaitIgnoreError();
//noinspection ConfusingArgumentToVarargsMethod
logger.trace("Geocoding response from google: {}", results);
if (results == null)
{
return ImmutableList.of(); | }
return Arrays.stream(results)
.map(GoogleMapsGeocodingProviderImpl::toGeographicalCoordinates)
.collect(GuavaCollectors.toImmutableList());
}
private static GeographicalCoordinates toGeographicalCoordinates(@NonNull final GeocodingResult result)
{
final LatLng ll = result.geometry.location;
return GeographicalCoordinates.builder()
.latitude(BigDecimal.valueOf(ll.lat))
.longitude(BigDecimal.valueOf(ll.lng))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\location\geocoding\provider\googlemaps\GoogleMapsGeocodingProviderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setSearchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCompleteTime() {
return completeTime;
}
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@ApiModelProperty(example = "completed") | public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResponse.java | 2 |
请完成以下Java代码 | public boolean isCacheScriptingEngines() {
return cacheScriptingEngines;
}
public ScriptEngineManager getScriptEngineManager() {
return scriptEngineManager;
}
protected class JavaScriptingFlowableScriptEvaluationRequest implements FlowableScriptEvaluationRequest {
protected String language;
protected String script;
protected Resolver resolver;
protected VariableContainer scopeContainer;
protected VariableContainer inputVariableContainer;
protected boolean storeScriptVariables;
@Override
public FlowableScriptEvaluationRequest language(String language) {
if (StringUtils.isEmpty(language)) {
throw new FlowableIllegalArgumentException("language is empty");
}
this.language = language;
return this;
}
@Override
public FlowableScriptEvaluationRequest script(String script) {
if (StringUtils.isEmpty(script)) {
throw new FlowableIllegalArgumentException("script is empty");
}
this.script = script;
return this;
}
@Override
public FlowableScriptEvaluationRequest resolver(Resolver resolver) {
this.resolver = resolver;
return this;
}
@Override
public FlowableScriptEvaluationRequest scopeContainer(VariableContainer scopeContainer) {
this.scopeContainer = scopeContainer;
return this;
}
@Override
public FlowableScriptEvaluationRequest inputVariableContainer(VariableContainer inputVariableContainer) { | this.inputVariableContainer = inputVariableContainer;
return this;
}
@Override
public FlowableScriptEvaluationRequest storeScriptVariables() {
this.storeScriptVariables = true;
return this;
}
@Override
public ScriptEvaluation evaluate() throws FlowableScriptException {
if (StringUtils.isEmpty(language)) {
throw new FlowableIllegalArgumentException("language is required");
}
if (StringUtils.isEmpty(script)) {
throw new FlowableIllegalArgumentException("script is required");
}
ScriptEngine scriptEngine = getEngineByName(language);
Bindings bindings = createBindings();
try {
Object result = scriptEngine.eval(script, bindings);
return new ScriptEvaluationImpl(resolver, result);
} catch (ScriptException e) {
throw new FlowableScriptException(e.getMessage(), e);
}
}
protected Bindings createBindings() {
return new ScriptBindings(Collections.singletonList(resolver), scopeContainer, inputVariableContainer, storeScriptVariables);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\JSR223FlowableScriptEngine.java | 1 |
请完成以下Java代码 | public OperatorOverloader getOperatorOverloader() {
return delegate.getOperatorOverloader();
}
@Override
public void setVariable(String name, Object value) {
delegate.setVariable(name, value);
}
@Override
@Nullable
public Object lookupVariable(String name) {
return delegate.lookupVariable(name);
}
@Override
public List<IndexAccessor> getIndexAccessors() {
return delegate.getIndexAccessors();
}
@Override
public TypedValue assignVariable(String name, Supplier<TypedValue> valueSupplier) {
return delegate.assignVariable(name, valueSupplier);
} | @Override
public boolean isAssignmentEnabled() {
return delegate.isAssignmentEnabled();
}
}
class RestrictivePropertyAccessor extends ReflectivePropertyAccessor {
@Override
public boolean canRead(EvaluationContext context, Object target, String name) {
return false;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\ShortcutConfigurable.java | 1 |
请完成以下Java代码 | Builder handlers(Set<MqttPendingHandler> handlers) {
this.handlers = handlers;
return this;
}
Builder subscribeMessage(MqttSubscribeMessage subscribeMessage) {
this.subscribeMessage = subscribeMessage;
return this;
}
Builder ownerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) {
this.retransmissionConfig = retransmissionConfig; | return this;
}
Builder pendingOperation(PendingOperation pendingOperation) {
this.pendingOperation = pendingOperation;
return this;
}
MqttPendingSubscription build() {
return new MqttPendingSubscription(future, topic, handlers, subscribeMessage, ownerId, retransmissionConfig, pendingOperation);
}
}
} | repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingSubscription.java | 1 |
请完成以下Java代码 | public void setSetupTimeReal (final @Nullable BigDecimal SetupTimeReal)
{
set_Value (COLUMNNAME_SetupTimeReal, SetupTimeReal);
}
@Override
public BigDecimal getSetupTimeReal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SetupTimeReal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUser1_ID (final int User1_ID)
{
if (User1_ID < 1)
set_Value (COLUMNNAME_User1_ID, null);
else
set_Value (COLUMNNAME_User1_ID, User1_ID);
}
@Override
public int getUser1_ID()
{
return get_ValueAsInt(COLUMNNAME_User1_ID);
} | @Override
public void setUser2_ID (final int User2_ID)
{
if (User2_ID < 1)
set_Value (COLUMNNAME_User2_ID, null);
else
set_Value (COLUMNNAME_User2_ID, User2_ID);
}
@Override
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Post {
@Id
@GeneratedValue private Long id;
private String message;
private Instant date;
public Post() {}
public Post(String message) {
this.message = message;
this.date = Instant.now().minus(new Random().nextLong(100), ChronoUnit.MINUTES);
}
public String getMessage() {
return message;
} | public void setMessage(String message) {
this.message = message;
}
public Instant getDate() {
return date;
}
public void setDate(Instant date) {
this.date = date;
}
@Override
public String toString() {
return message;
}
} | repos\spring-data-examples-main\jpa\aot-optimization\src\main\java\example\springdata\aot\Post.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean hasStartFormKey() {
return hasStartFormKey;
}
@Override
public String getName() {
return name;
}
@Override
public int getVersion() {
return version;
}
@Override
public String getResourceName() {
return resourceName;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public String getDiagramResourceName() {
return diagramResourceName;
}
@Override | public boolean isSuspended() {
return suspended;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getVersionTag() {
return versionTag;
}
@Override
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
@Override
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\repository\CalledProcessDefinitionImpl.java | 2 |
请完成以下Java代码 | protected String getEventName() {
return COMPLETE;
}
protected CmmnExecution eventNotificationsStarted(CmmnExecution execution) {
CmmnActivityBehavior behavior = getActivityBehavior(execution);
triggerBehavior(behavior, execution);
execution.setCurrentState(COMPLETED);
return execution;
}
protected void postTransitionNotification(CmmnExecution execution) {
if (!execution.isCaseInstanceExecution()) {
execution.remove();
} else {
CmmnExecution superCaseExecution = execution.getSuperCaseExecution();
PvmExecutionImpl superExecution = execution.getSuperExecution();
if (superCaseExecution != null) {
TransferVariablesActivityBehavior behavior = (TransferVariablesActivityBehavior) getActivityBehavior(superCaseExecution);
behavior.transferVariables(execution, superCaseExecution);
superCaseExecution.complete();
} else if (superExecution != null) {
SubProcessActivityBehavior behavior = (SubProcessActivityBehavior) getActivityBehavior(superExecution);
try {
behavior.passOutputVariables(superExecution, execution);
} catch (RuntimeException e) {
LOG.completingSubCaseError(execution, e);
throw e;
} catch (Exception e) {
LOG.completingSubCaseError(execution, e);
throw LOG.completingSubCaseErrorException(execution, e);
}
// set sub case instance to null
superExecution.setSubCaseInstance(null);
try { | behavior.completed(superExecution);
} catch (RuntimeException e) {
LOG.completingSubCaseError(execution, e);
throw e;
} catch (Exception e) {
LOG.completingSubCaseError(execution, e);
throw LOG.completingSubCaseErrorException(execution, e);
}
}
execution.setSuperCaseExecution(null);
execution.setSuperExecution(null);
}
CmmnExecution parent = execution.getParent();
if (parent != null) {
CmmnActivityBehavior behavior = getActivityBehavior(parent);
if (behavior instanceof CmmnCompositeActivityBehavior) {
CmmnCompositeActivityBehavior compositeBehavior = (CmmnCompositeActivityBehavior) behavior;
compositeBehavior.handleChildCompletion(parent, execution);
}
}
}
protected abstract void triggerBehavior(CmmnActivityBehavior behavior, CmmnExecution execution);
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\operation\AbstractAtomicOperationCaseExecutionComplete.java | 1 |
请完成以下Java代码 | public String getRedirectUrl() {
return this.redirectUrl;
}
@Override
public List<Cookie> getCookies() {
return this.cookies;
}
@Override
public String getMethod() {
return this.method;
}
@Override
public List<String> getHeaderValues(String name) {
return this.headers.getOrDefault(name, new ArrayList<>());
}
@Override
public Collection<String> getHeaderNames() {
return this.headers.keySet();
}
@Override
public List<Locale> getLocales() {
return this.locales;
}
@Override
public String[] getParameterValues(String name) {
return this.parameters.getOrDefault(name, new String[0]);
}
@Override
public Map<String, String[]> getParameterMap() {
return this.parameters;
}
public void setRedirectUrl(String redirectUrl) {
Assert.notNull(redirectUrl, "redirectUrl cannot be null");
this.redirectUrl = redirectUrl;
}
public void setCookies(List<Cookie> cookies) {
Assert.notNull(cookies, "cookies cannot be null"); | this.cookies = cookies;
}
public void setMethod(String method) {
Assert.notNull(method, "method cannot be null");
this.method = method;
}
public void setHeaders(Map<String, List<String>> headers) {
Assert.notNull(headers, "headers cannot be null");
this.headers = headers;
}
public void setLocales(List<Locale> locales) {
Assert.notNull(locales, "locales cannot be null");
this.locales = locales;
}
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "parameters cannot be null");
this.parameters = parameters;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\savedrequest\SimpleSavedRequest.java | 1 |
请完成以下Java代码 | private static SyndFeed createFeed() {
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_1.0");
feed.setTitle("Test title");
feed.setLink("http://www.somelink.com");
feed.setDescription("Basic description");
return feed;
}
private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry"); | entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException, URISyntaxException {
URL feedSource = new URI("http://rssblog.whatisrss.com/feed/").toURL();
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
} | repos\tutorials-master\web-modules\rome\src\main\java\com\baeldung\rome\RSSRomeExample.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UmsMemberCacheServiceImpl implements UmsMemberCacheService {
@Autowired
private RedisService redisService;
@Autowired
private UmsMemberMapper memberMapper;
@Value("${redis.database}")
private String REDIS_DATABASE;
@Value("${redis.expire.common}")
private Long REDIS_EXPIRE;
@Value("${redis.expire.authCode}")
private Long REDIS_EXPIRE_AUTH_CODE;
@Value("${redis.key.member}")
private String REDIS_KEY_MEMBER;
@Value("${redis.key.authCode}")
private String REDIS_KEY_AUTH_CODE;
@Override
public void delMember(Long memberId) {
UmsMember umsMember = memberMapper.selectByPrimaryKey(memberId);
if (umsMember != null) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + umsMember.getUsername();
redisService.del(key);
}
}
@Override
public UmsMember getMember(String username) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + username;
return (UmsMember) redisService.get(key); | }
@Override
public void setMember(UmsMember member) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_MEMBER + ":" + member.getUsername();
redisService.set(key, member, REDIS_EXPIRE);
}
@CacheException
@Override
public void setAuthCode(String telephone, String authCode) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
redisService.set(key,authCode,REDIS_EXPIRE_AUTH_CODE);
}
@CacheException
@Override
public String getAuthCode(String telephone) {
String key = REDIS_DATABASE + ":" + REDIS_KEY_AUTH_CODE + ":" + telephone;
return (String) redisService.get(key);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\UmsMemberCacheServiceImpl.java | 2 |
请完成以下Java代码 | private void registerServices()
{
//
// 07085 - Set storage for invoice history and apply filters
{
Services.registerService(IInvoiceHistoryDAO.class, new HUInvoiceHistoryDAO());
}
// Material tracking (07371)
Services.registerService(IHandlingUnitsInfoFactory.class, new HUHandlingUnitsInfoFactory());
// task 09533
Services.registerService(IPPOrderMInOutLineRetrievalService.class, new de.metas.handlingunits.materialtracking.spi.impl.PPOrderMInOutLineRetrievalService());
}
/**
* Public for testing purposes only!
*/
public static void registerHUSSAggregationKeyDependencies()
{ | final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class);
final String registrationKey = HUShipmentScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY;
//
// Register Handlers
keyRegistry.registerAggregationKeyValueHandler(registrationKey, new HUShipmentScheduleKeyValueHandler());
}
private void registerImportProcesses()
{
final IImportProcessFactory importProcessesFactory = Services.get(IImportProcessFactory.class);
importProcessesFactory.registerImportProcess(I_I_Inventory.class, de.metas.inventory.impexp.InventoryImportProcess.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\Main.java | 1 |
请完成以下Java代码 | public void setES_FTS_Config_Field_ID (final int ES_FTS_Config_Field_ID)
{
if (ES_FTS_Config_Field_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_Field_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_Field_ID, ES_FTS_Config_Field_ID);
}
@Override
public int getES_FTS_Config_Field_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_Field_ID);
}
@Override
public de.metas.elasticsearch.model.I_ES_FTS_Config getES_FTS_Config()
{
return get_ValueAsPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class);
}
@Override | public void setES_FTS_Config(final de.metas.elasticsearch.model.I_ES_FTS_Config ES_FTS_Config)
{
set_ValueFromPO(COLUMNNAME_ES_FTS_Config_ID, de.metas.elasticsearch.model.I_ES_FTS_Config.class, ES_FTS_Config);
}
@Override
public void setES_FTS_Config_ID (final int ES_FTS_Config_ID)
{
if (ES_FTS_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ES_FTS_Config_ID, ES_FTS_Config_ID);
}
@Override
public int getES_FTS_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ES_FTS_Config_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java-gen\de\metas\elasticsearch\model\X_ES_FTS_Config_Field.java | 1 |
请完成以下Java代码 | public class CaseSentryPartImpl extends CmmnSentryPart {
private static final long serialVersionUID = 1L;
protected CaseExecutionImpl caseInstance;
protected CaseExecutionImpl caseExecution;
protected CaseExecutionImpl sourceCaseExecution;
public CaseExecutionImpl getCaseInstance() {
return caseInstance;
}
public void setCaseInstance(CmmnExecution caseInstance) {
this.caseInstance = (CaseExecutionImpl) caseInstance;
}
public CmmnExecution getCaseExecution() {
return caseExecution;
}
public void setCaseExecution(CmmnExecution caseExecution) {
this.caseExecution = (CaseExecutionImpl) caseExecution;
}
public CmmnExecution getSourceCaseExecution() {
return sourceCaseExecution;
}
public void setSourceCaseExecution(CmmnExecution sourceCaseExecution) {
this.sourceCaseExecution = (CaseExecutionImpl) sourceCaseExecution;
}
public String getId() {
return String.valueOf(System.identityHashCode(this));
}
public String getCaseInstanceId() {
if (caseInstance != null) {
return caseInstance.getId();
} | return null;
}
public String getCaseExecutionId() {
if (caseExecution != null) {
return caseExecution.getId();
}
return null;
}
public String getSourceCaseExecutionId() {
if (sourceCaseExecution != null) {
return sourceCaseExecution.getId();
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseSentryPartImpl.java | 1 |
请完成以下Java代码 | public class SerializableGraphQlRequest implements GraphQlRequest {
private @Nullable String query;
private @Nullable String operationName;
private Map<String, Object> variables = Collections.emptyMap();
private Map<String, Object> extensions = Collections.emptyMap();
public void setQuery(String query) {
this.query = query;
}
public @Nullable String getQuery() {
return this.query;
}
public void setOperationName(@Nullable String operationName) {
this.operationName = operationName;
}
@Override
public @Nullable String getOperationName() {
return this.operationName;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
@Override
public Map<String, Object> getVariables() { | return this.variables;
}
public void setExtensions(Map<String, Object> extensions) {
this.extensions = extensions;
}
@Override
public Map<String, Object> getExtensions() {
return this.extensions;
}
@Override
public String getDocument() {
if (this.query == null) {
if (this.extensions.get("persistedQuery") != null) {
return PersistedQuerySupport.PERSISTED_QUERY_MARKER;
}
throw new ServerWebInputException("No 'query'");
}
return this.query;
}
@Override
public Map<String, Object> toMap() {
throw new UnsupportedOperationException();
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\support\SerializableGraphQlRequest.java | 1 |
请完成以下Java代码 | public String getId() {
return formProperty.getId();
}
public String getLabel() {
return formProperty.getName();
}
public FormType getType() {
return formProperty.getType();
}
public String getTypeName() {
return formProperty.getType().getName();
}
public Object getDefaultValue() {
return formProperty.getValue();
}
public List<FormFieldValidationConstraint> getValidationConstraints() {
return validationConstraints;
}
public Map<String, String> getProperties() { | return Collections.emptyMap();
}
@Override
public boolean isBusinessKey() {
return false;
}
public TypedValue getDefaultValueTyped() {
return getValue();
}
public TypedValue getValue() {
return Variables.stringValue(formProperty.getValue());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\engine\FormPropertyAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UtilDate {
/** 年月日时分秒(无下划线) yyyyMMddHHmmss */
public static final String dtLong = "yyyyMMddHHmmss";
/** 完整时间 yyyy-MM-dd HH:mm:ss */
public static final String simple = "yyyy-MM-dd HH:mm:ss";
/** 年月日(无下划线) yyyyMMdd */
public static final String dtShort = "yyyyMMdd";
/**
* 返回系统当前时间(精确到毫秒),作为一个唯一的订单编号
* @return
* 以yyyyMMddHHmmss为格式的当前系统时间
*/
public static String getOrderNum(){
Date date=new Date();
DateFormat df=new SimpleDateFormat(dtLong);
return df.format(date);
}
/**
* 获取系统当前日期(精确到毫秒),格式:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String getDateFormatter(){
Date date=new Date(); | DateFormat df=new SimpleDateFormat(simple);
return df.format(date);
}
/**
* 获取系统当期年月日(精确到天),格式:yyyyMMdd
* @return
*/
public static String getDate(){
Date date=new Date();
DateFormat df=new SimpleDateFormat(dtShort);
return df.format(date);
}
/**
* 产生随机的三位数
* @return
*/
public static String getThree(){
Random rad=new Random();
return rad.nextInt(1000)+"";
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\UtilDate.java | 2 |
请完成以下Java代码 | public class User extends DateAudit {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(max = 40)
private String surname;
@Size(max = 40)
private String name;
@Size(max = 40)
private String lastname;
@Size(max = 30)
private String username = "default";
@NotBlank
@Size(max = 15)
private String phone;
@Size(max = 40)
@Email
private String email;
@Column(name = "password", columnDefinition = "char(60)") | private String password;
@Lob
private byte[] avatar;
private String disposablePassword;
private String city;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id")
)
private Set<Role> roles = new HashSet<>();
@OneToMany(mappedBy = "user", fetch = FetchType.LAZY)
private List<Orders> ordersList;
} | repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\model\User.java | 1 |
请完成以下Java代码 | public String getReferenzId() {
return referenzId;
}
/**
* Sets the value of the referenzId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setReferenzId(String value) {
this.referenzId = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\RuecknahmeangebotAntwort.java | 1 |
请完成以下Java代码 | public <T> Collection<CachedEntity> findInCacheAsCachedObjects(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache != null) {
return classCache.values();
}
return null;
}
@Override
@SuppressWarnings("unchecked")
public <T> List<T> findInCache(Class<T> entityClass) {
Map<String, CachedEntity> classCache = cachedObjects.get(entityClass);
if (classCache == null) {
classCache = findClassCacheByCheckingSubclasses(entityClass);
}
if (classCache != null) {
// Having two ArrayLists and merge them later is faster than doing add(0, element)
ArrayList<T> entities = new ArrayList<>(classCache.size());
ArrayList<T> deletedEntities = new ArrayList<>(classCache.size());
for (CachedEntity cachedObject : classCache.values()) {
if (!cachedObject.getEntity().isDeleted()) {
entities.add((T) cachedObject.getEntity());
} else {
deletedEntities.add((T) cachedObject.getEntity());
}
}
// Non-deleted entities go first in the returned list,
// while deleted ones go at the end.
// This way users of this method will first get the 'active' entities.
entities.addAll(deletedEntities);
return entities;
} | return Collections.emptyList();
}
@Override
public Map<Class<?>, Map<String, CachedEntity>> getAllCachedEntities() {
return cachedObjects;
}
@Override
public void close() {
}
@Override
public void flush() {
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\cache\EntityCacheImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Item insert(Item item) {
if (item.getId() == null) {
item.setId(UUID.randomUUID()
.toString());
}
db.add(item);
return item;
}
public List<Item> findAll() {
return db;
}
public List<Item> findAllByName(String name) {
return db.stream()
.filter(i -> i.getName()
.equals(name))
.toList();
}
public Item findById(String id) {
return db.stream()
.filter(i -> i.getId() | .equals(id))
.findFirst()
.orElseThrow(EntityNotFoundException::new);
}
public void deleteById(String id) {
Item item = findById(id);
db.remove(item);
}
public List<Item> deleteAllByName(String name) {
List<Item> allByName = findAllByName(name);
db.removeAll(allByName);
return allByName;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\cats\service\ItemService.java | 2 |
请完成以下Java代码 | public ConversationLink newInstance(ModelTypeInstanceContext instanceContext) {
return new ConversationLinkImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
sourceRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SOURCE_REF)
.required()
.qNameAttributeReference(InteractionNode.class)
.build();
targetRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TARGET_REF)
.required()
.qNameAttributeReference(InteractionNode.class)
.build();
typeBuilder.build();
}
public ConversationLinkImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
} | public void setName(String name) {
nameAttribute.setValue(this, name);
}
public InteractionNode getSource() {
return sourceRefAttribute.getReferenceTargetElement(this);
}
public void setSource(InteractionNode source) {
sourceRefAttribute.setReferenceTargetElement(this, source);
}
public InteractionNode getTarget() {
return targetRefAttribute.getReferenceTargetElement(this);
}
public void setTarget(InteractionNode target) {
targetRefAttribute.setReferenceTargetElement(this, target);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConversationLinkImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) {
HeaderElementIterator it = new BasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return p.getDefaultKeepAliveTimeMillis();
}
};
}
@Bean
public CloseableHttpClient httpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(p.getRequestTimeout())
.setConnectTimeout(p.getConnectTimeout())
.setSocketTimeout(p.getSocketTimeout()).build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingConnectionManager())
.setKeepAliveStrategy(connectionKeepAliveStrategy())
.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) // 重试次数
.build();
} | @Bean
public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
return new Runnable() {
@Override
@Scheduled(fixedDelay = 10000)
public void run() {
try {
if (connectionManager != null) {
LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections...");
connectionManager.closeExpiredConnections();
connectionManager.closeIdleConnections(p.getCloseIdleConnectionWaitTimeSecs(), TimeUnit.SECONDS);
} else {
LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised");
}
} catch (Exception e) {
LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e);
}
}
};
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("poolScheduler");
scheduler.setPoolSize(50);
return scheduler;
}
} | repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\config\HttpClientConfig.java | 2 |
请完成以下Java代码 | public class IgniteJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
Connection conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
createDatabaseTables(conn);
insertData(conn);
getData(conn);
}
private static void createDatabaseTables(Connection conn) throws SQLException {
Statement sql = conn.createStatement();
sql.executeUpdate("CREATE TABLE Employee (" +
" id INTEGER PRIMARY KEY, name VARCHAR, isEmployed timyint(1)) " +
" WITH \"template=replicated\"");
sql.executeUpdate("CREATE INDEX idx_employee_name ON Employee (name)");
}
private static void insertData(Connection conn) throws SQLException { | PreparedStatement sql =
conn.prepareStatement("INSERT INTO Employee (id, name, isEmployed) VALUES (?, ?, ?)");
sql.setLong(1, 1);
sql.setString(2, "James");
sql.setBoolean(3, true);
sql.executeUpdate();
sql.setLong(1, 2);
sql.setString(2, "Monica");
sql.setBoolean(3, false);
sql.executeUpdate();
}
private static void getData(Connection conn) throws SQLException {
Statement sql = conn.createStatement();
ResultSet rs = sql.executeQuery("SELECT e.name, e.isEmployed " +
" FROM Employee e " +
" WHERE e.isEmployed = TRUE ");
while (rs.next())
System.out.println(rs.getString(1) + ", " + rs.getString(2));
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\ignite\jdbc\IgniteJDBC.java | 1 |
请完成以下Java代码 | public final class ModelTranslation implements IModelTranslation
{
public static IModelTranslation of(final String adLanguage, final Map<String, String> trlMap)
{
return new ModelTranslation(adLanguage, trlMap);
}
private final String adLanguage;
private final ImmutableMap<String, String> trlMap;
public ModelTranslation(final String adLanguage, final Map<String, String> trlMap)
{
this.adLanguage = adLanguage;
if (trlMap == null)
{
this.trlMap = ImmutableMap.of();
}
else
{
this.trlMap = ImmutableMap.copyOf(trlMap);
}
} | @Override
public String getAD_Language()
{
return adLanguage;
}
@Override
public boolean isTranslated(final String columnName)
{
return trlMap.containsKey(columnName);
}
@Override
public String getTranslation(final String columnName)
{
return trlMap.get(columnName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\ModelTranslation.java | 1 |
请完成以下Java代码 | public class Order {
private String orderNo;
private LocalDate date;
private String customerName;
private List<OrderLine> orderLines;
public Order() {
}
public Order(String orderNo, LocalDate date, String customerName, List<OrderLine> orderLines) {
super();
this.orderNo = orderNo;
this.date = date;
this.customerName = customerName;
this.orderLines = orderLines;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public List<OrderLine> getOrderLines() { | if (orderLines == null) {
orderLines = new ArrayList<>();
}
return orderLines;
}
public void setOrderLines(List<OrderLine> orderLines) {
if (orderLines == null) {
orderLines = new ArrayList<>();
}
this.orderLines = orderLines;
}
@Override
public String toString() {
return "Order [orderNo=" + orderNo + ", date=" + date + ", customerName=" + customerName + ", orderLines=" + orderLines + "]";
}
} | repos\tutorials-master\jackson-modules\jackson-conversions\src\main\java\com\baeldung\jackson\yaml\Order.java | 1 |
请完成以下Java代码 | public class ResourceQRCodeJsonConverter
{
public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("RES");
public static String toGlobalQRCodeJsonString(final ResourceQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final ResourceQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static ResourceQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static ResourceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!isTypeMatching(globalQRCode))
{
throw new AdempiereException("Invalid QR Code")
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
} | final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode)
{
return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\resource\qrcode\ResourceQRCodeJsonConverter.java | 1 |
请完成以下Java代码 | public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
return null; // nothing to do
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
// shall never reach this point
throw new IllegalStateException("Not supported: po=" + po + ", type=" + type);
}
@Override
public String docValidate(final PO po, final int timing)
{
// shall never reach this point
throw new IllegalStateException("Not supported: po=" + po + ", timing=" + timing);
}
/**
*
* @return {@link ModelValidationEngine} which was used on registration
*/
public ModelValidationEngine getEngine()
{
return engine;
}
private void registerArchiveAwareTables()
{
final Properties ctx = Env.getCtx();
final List<I_AD_Column> archiveColumns = new Query(ctx, I_AD_Column.Table_Name, I_AD_Column.COLUMNNAME_ColumnName + "=?", ITrx.TRXNAME_None)
.setParameters(org.compiere.model.I_AD_Archive.COLUMNNAME_AD_Archive_ID)
.setOnlyActiveRecords(true)
.list(I_AD_Column.class);
if (archiveColumns.isEmpty())
{
return;
}
//
// Services | final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class);
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClassIfUnique(ExportArchivePDF.class);
if (processId == null)
{
final AdempiereException ex = new AdempiereException("No AD_Process_ID found for " + ExportArchivePDF.class);
Archive_Main_Validator.logger.error(ex.getLocalizedMessage(), ex);
return;
}
for (final I_AD_Column column : archiveColumns)
{
if (!DisplayType.isLookup(column.getAD_Reference_ID()))
{
continue;
}
final AdTableId adTableId = AdTableId.ofRepoId(column.getAD_Table_ID());
adProcessDAO.registerTableProcess(adTableId, processId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\interceptor\Archive_Main_Validator.java | 1 |
请完成以下Java代码 | public class EquivalentAmount2 {
@XmlElement(name = "Amt", required = true)
protected ActiveOrHistoricCurrencyAndAmount amt;
@XmlElement(name = "CcyOfTrf", required = true)
protected String ccyOfTrf;
/**
* Gets the value of the amt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.amt = value;
}
/**
* Gets the value of the ccyOfTrf property. | *
* @return
* possible object is
* {@link String }
*
*/
public String getCcyOfTrf() {
return ccyOfTrf;
}
/**
* Sets the value of the ccyOfTrf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCcyOfTrf(String value) {
this.ccyOfTrf = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\EquivalentAmount2.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static ImmutableMap<String, List<BigDecimal>> getTaxCategoryMappingRules(@NonNull final JsonExternalSystemRequest externalSystemRequest)
{
final String taxCategoryMappings = externalSystemRequest.getParameters().get(ExternalSystemConstants.PARAM_TAX_CATEGORY_MAPPINGS);
if (Check.isBlank(taxCategoryMappings))
{
return ImmutableMap.of();
}
final ObjectMapper mapper = JsonObjectMapperHolder.sharedJsonObjectMapper();
try
{
return mapper.readValue(taxCategoryMappings, JsonTaxCategoryMappings.class)
.getJsonTaxCategoryMappingList()
.stream()
.collect(ImmutableMap.toImmutableMap(JsonTaxCategoryMapping::getTaxCategory, JsonTaxCategoryMapping::getTaxRates));
}
catch (final JsonProcessingException e)
{
throw new RuntimeException(e);
}
} | private static boolean hasMissingFields(@NonNull final ProductRow productRow)
{
return Check.isBlank(productRow.getProductIdentifier())
|| Check.isBlank(productRow.getName())
|| Check.isBlank(productRow.getValue());
}
@NonNull
private static JsonRequestProductUpsert wrapUpsertItem(@NonNull final JsonRequestProductUpsertItem upsertItem)
{
return JsonRequestProductUpsert.builder()
.syncAdvise(SyncAdvise.CREATE_OR_MERGE)
.requestItems(ImmutableList.of(upsertItem))
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\ProductUpsertProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class GetProductVariantParentProcessor implements Processor
{
private final ProcessLogger processLogger;
public GetProductVariantParentProcessor(@NonNull final ProcessLogger processLogger)
{
this.processLogger = processLogger;
}
@Override
public void process(final Exchange exchange) throws Exception
{
final ImportProductsRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_IMPORT_PRODUCTS_CONTEXT, ImportProductsRouteContext.class);
final JsonProduct product = exchange.getIn().getBody(JsonProduct.class);
context.setJsonProduct(product);
final ShopwareClient shopwareClient = context.getShopwareClient();
if (product.getParentId() != null)
{
processLogger.logMessage("Getting variant parent", context.getPInstanceId());
//TODO - maybe add getSingleProduct to shopware client.
final MultiQueryRequest getProductsRequest = buildQueryParentProductRequest(product.getParentId());
final Optional<JsonProducts> jsonProductsOptional = shopwareClient.getProducts(getProductsRequest); | if (jsonProductsOptional.isEmpty())
{
exchange.getIn().setBody(null);
return;
}
final JsonProduct parentProduct = jsonProductsOptional.get().getProductList().get(0);
context.setParentJsonProduct(parentProduct);
}
else
{
exchange.getIn().setBody(null);
return;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\processor\GetProductVariantParentProcessor.java | 2 |
请完成以下Java代码 | public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public String toString() {
return this.getClass().getSimpleName() | + "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", description=" + description
+ ", type=" + type
+ ", taskId=" + taskId
+ ", processInstanceId=" + processInstanceId
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ ", url=" + url
+ ", contentId=" + contentId
+ ", content=" + content
+ ", tenantId=" + tenantId
+ ", createTime=" + createTime
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\AttachmentEntity.java | 1 |
请完成以下Java代码 | public int getRepoId()
{
return repoId;
}
public static int toRepoId(final PickingJobLineId id)
{
return id != null ? id.getRepoId() : -1;
}
public static PickingJobLineId ofRepoId(final int repoId)
{
return new PickingJobLineId(repoId);
}
public static PickingJobLineId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PickingJobLineId(repoId) : null;
}
@NonNull
@JsonCreator
public static PickingJobLineId ofString(@NonNull final String string)
{
try
{ | return ofRepoId(Integer.parseInt(string));
}
catch (final Exception ex)
{
throw new AdempiereException("Invalid id string: `" + string + "`", ex);
}
}
@Nullable
public static PickingJobLineId ofNullableString(@Nullable final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
return stringNorm != null ? ofString(stringNorm) : null;
}
public String getAsString() {return String.valueOf(getRepoId());}
public static boolean equals(@Nullable final PickingJobLineId id1, @Nullable final PickingJobLineId id2) {return Objects.equals(id1, id2);}
public TableRecordReference toTableRecordReference()
{
return TableRecordReference.of(I_M_Picking_Job_Line.Table_Name, repoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\PickingJobLineId.java | 1 |
请完成以下Java代码 | public class OrderLine implements ModelValidator
{
private int ad_Client_ID = -1;
@Override
public int getAD_Client_ID()
{
return ad_Client_ID;
}
@Override
public final void initialize(final ModelValidationEngine engine, final MClient client)
{
if (client != null)
{
ad_Client_ID = client.getAD_Client_ID();
}
engine.addModelChange(I_C_OrderLine.Table_Name, this);
// register this service for callouts and model validators
Services.registerService(IOrderLineBL.class, new OrderLineBL());
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing to do
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
// nothing to do
return null;
}
@Override
public String modelChange(final PO po, int type)
{
onNewAndChangeAndDelete(po, type);
return null;
}
private void onNewAndChangeAndDelete(final PO po, int type)
{
if (!(type == TYPE_AFTER_NEW || type == TYPE_AFTER_CHANGE || type == TYPE_AFTER_DELETE))
{ | return;
}
final I_C_OrderLine ol = InterfaceWrapperHelper.create(po, I_C_OrderLine.class);
//
// updating the freight cost amount, if necessary
final MOrder orderPO = (MOrder)ol.getC_Order();
final String dontUpdateOrder = Env.getContext(po.getCtx(), OrderFastInput.OL_DONT_UPDATE_ORDER + orderPO.get_ID());
if (Check.isEmpty(dontUpdateOrder) || !"Y".equals(dontUpdateOrder))
{
final boolean newOrDelete = type == TYPE_AFTER_NEW || type == TYPE_AFTER_DELETE;
final boolean lineNetAmtChanged = po.is_ValueChanged(I_C_OrderLine.COLUMNNAME_LineNetAmt);
final FreightCostRule freightCostRule = FreightCostRule.ofCode(orderPO.getFreightCostRule());
final boolean isCopy = InterfaceWrapperHelper.isCopy(po); // metas: cg: task US215
if (!isCopy && (lineNetAmtChanged || freightCostRule.isNotFixPrice() || newOrDelete))
{
final OrderFreightCostsService orderFreightCostsService = Adempiere.getBean(OrderFreightCostsService.class);
if (orderFreightCostsService.isFreightCostOrderLine(ol))
{
final I_C_Order order = InterfaceWrapperHelper.create(orderPO, I_C_Order.class);
orderFreightCostsService.updateFreightAmt(order);
orderPO.saveEx();
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\modelvalidator\OrderLine.java | 1 |
请完成以下Java代码 | public class CompleteTaskCmd extends AbstractCompleteTaskCmd {
private static final long serialVersionUID = 1L;
private static final String ASSIGNEE_VARIABLE_NAME = "sys_task_assignee";
protected Map<String, Object> variables;
protected Map<String, Object> transientVariables;
protected Map<String, Object> taskVariables;
protected boolean localScope;
public CompleteTaskCmd(String taskId, Map<String, Object> variables) {
super(taskId);
this.variables = variables;
}
public CompleteTaskCmd(String taskId, Map<String, Object> variables, boolean localScope) {
this(taskId, variables);
this.localScope = localScope;
}
public CompleteTaskCmd(String taskId, Map<String, Object> variables, Map<String, Object> transientVariables) {
this(taskId, variables);
this.transientVariables = transientVariables;
}
protected Void execute(CommandContext commandContext, TaskEntity task) {
if (variables != null) {
if (localScope) {
task.setVariablesLocal(variables);
} else if (task.getExecutionId() != null) {
task.setExecutionVariables(variables);
} else {
task.setVariables(variables);
}
}
if (transientVariables != null) {
if (localScope) { | task.setTransientVariablesLocal(transientVariables);
} else {
task.setTransientVariables(transientVariables);
}
}
Map<String, Object> taskLocalVariables = new HashMap<>(task.getVariablesLocal());
taskLocalVariables.put(ASSIGNEE_VARIABLE_NAME, task.getAssignee());
setTaskVariables(taskLocalVariables);
executeTaskComplete(commandContext, task, variables, localScope);
return null;
}
@Override
protected String getSuspendedTaskException() {
return "Cannot complete a suspended task";
}
public Map<String, Object> getTaskVariables() {
return taskVariables;
}
private void setTaskVariables(Map<String, Object> taskVariables) {
this.taskVariables = taskVariables;
}
public String getTaskId() {
return taskId;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\CompleteTaskCmd.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getPreparationTime_6 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_6);
}
/** Set Bereitstellungszeit So.
@param PreparationTime_7
Preparation time for Sunday
*/
@Override
public void setPreparationTime_7 (java.sql.Timestamp PreparationTime_7)
{
set_Value (COLUMNNAME_PreparationTime_7, PreparationTime_7);
}
/** Get Bereitstellungszeit So.
@return Preparation time for Sunday
*/
@Override
public java.sql.Timestamp getPreparationTime_7 ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PreparationTime_7);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag) | */
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_TourVersion.java | 1 |
请完成以下Java代码 | void clear() {
column = "";
columnMapper = matchAllColumns;
whereFilter = matchAnyString;
}
List<String> search() {
List<String> result = tables.entrySet()
.stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(table))
.flatMap(entry -> Stream.of(entry.getValue()))
.flatMap(Collection::stream)
.map(Row::toString)
.flatMap(columnMapper)
.filter(whereFilter)
.collect(Collectors.toList());
clear();
return result;
} | /**
* Sets column mapper based on {@link #column} attribute.
* Note: If column is unknown, will remain to look for all columns.
*/
private void setColumnMapper() {
switch (column) {
case "*":
colIndex = -1;
break;
case "name":
colIndex = 0;
break;
case "surname":
colIndex = 1;
break;
}
if (colIndex != -1) {
columnMapper = s -> Stream.of(s.split(" ")[colIndex]);
}
}
} | repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\interpreter\Context.java | 1 |
请完成以下Java代码 | public class CommonPage<T> {
/**
* 当前页码
*/
private Integer pageNum;
/**
* 每页数量
*/
private Integer pageSize;
/**
* 总页数
*/
private Integer totalPage;
/**
* 总条数
*/
private Long total;
/**
* 分页数据
*/
private List<T> list;
/**
* 将PageHelper分页后的list转为分页信息
*/
public static <T> CommonPage<T> restPage(List<T> list) {
CommonPage<T> result = new CommonPage<T>();
PageInfo<T> pageInfo = new PageInfo<T>(list);
result.setTotalPage(pageInfo.getPages());
result.setPageNum(pageInfo.getPageNum());
result.setPageSize(pageInfo.getPageSize());
result.setTotal(pageInfo.getTotal());
result.setList(pageInfo.getList());
return result;
}
/**
* 将SpringData分页后的list转为分页信息
*/
public static <T> CommonPage<T> restPage(Page<T> pageInfo) {
CommonPage<T> result = new CommonPage<T>();
result.setTotalPage(pageInfo.getTotalPages());
result.setPageNum(pageInfo.getNumber());
result.setPageSize(pageInfo.getSize());
result.setTotal(pageInfo.getTotalElements());
result.setList(pageInfo.getContent());
return result; | }
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Long getTotal() {
return total;
}
public void setTotal(Long total) {
this.total = total;
}
} | repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonPage.java | 1 |
请完成以下Java代码 | public static boolean isCJKCharacter(char input)
{
Character.UnicodeBlock ub = Character.UnicodeBlock.of(input);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
//全角数字字符和日韩字符
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
//韩文字符集
|| ub == Character.UnicodeBlock.HANGUL_SYLLABLES
|| ub == Character.UnicodeBlock.HANGUL_JAMO
|| ub == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO
//日文字符集
|| ub == Character.UnicodeBlock.HIRAGANA //平假名
|| ub == Character.UnicodeBlock.KATAKANA //片假名
|| ub == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS
)
{
return true;
}
else
{
return false;
}
//其他的CJK标点符号,可以不做处理
//|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
//|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
}
/**
* 进行字符规格化(全角转半角,大写转小写处理)
*
* @param input | * @return char
*/
public static char regularize(char input)
{
if (input == 12288)
{
input = (char) 32;
}
else if (input > 65280 && input < 65375)
{
input = (char) (input - 65248);
}
else if (input >= 'A' && input <= 'Z')
{
input += 32;
}
return input;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\CharacterHelper.java | 1 |
请完成以下Java代码 | public PickingSlotRow getRow(final PickingSlotRowId rowId)
{
return rowsById.get(rowId);
}
@Nullable
public PickingSlotRow getRootRow(final PickingSlotRowId rowId)
{
final PickingSlotRowId rootRowId = getRootRowId(rowId);
if (rootRowId == null)
{
return null;
}
return getRow(rootRowId);
}
public PickingSlotRowId getRootRowId(final PickingSlotRowId rowId)
{ | return rowId2rootRowId.get(rowId);
}
public long size()
{
return rowsById.size();
}
public Stream<PickingSlotRow> stream()
{
return rowsById.values().stream();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRowsCollection.java | 1 |
请完成以下Java代码 | private void update(GatewayMetadata metricsData, long serverReceiveTs) {
long gwLatency = metricsData.publishedTs() - metricsData.receivedTs();
long transportLatency = serverReceiveTs - metricsData.publishedTs();
count.incrementAndGet();
gwLatencySum.addAndGet(gwLatency);
transportLatencySum.addAndGet(transportLatency);
if (minGwLatency == 0 || minGwLatency > gwLatency) {
minGwLatency = gwLatency;
}
if (maxGwLatency < gwLatency) {
maxGwLatency = gwLatency;
}
if (minTransportLatency == 0 || minTransportLatency > transportLatency) {
minTransportLatency = transportLatency;
}
if (maxTransportLatency < transportLatency) { | maxTransportLatency = transportLatency;
}
}
private ConnectorMetricsResult getResult() {
long count = this.count.get();
long avgGwLatency = gwLatencySum.get() / count;
long avgTransportLatency = transportLatencySum.get() / count;
return new ConnectorMetricsResult(avgGwLatency, minGwLatency, maxGwLatency, avgTransportLatency, minTransportLatency, maxTransportLatency);
}
}
public record ConnectorMetricsResult(long avgGwLatency, long minGwLatency, long maxGwLatency,
long avgTransportLatency, long minTransportLatency, long maxTransportLatency) {
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\gateway\metrics\GatewayMetricsState.java | 1 |
请完成以下Java代码 | public void leave(ActivityExecution execution) {
int loopCounter = getLoopVariable(execution, getCollectionElementIndexVariable()) + 1;
int nrOfInstances = getLoopVariable(execution, NUMBER_OF_INSTANCES);
int nrOfCompletedInstances = getLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES) + 1;
int nrOfActiveInstances = getLoopVariable(execution, NUMBER_OF_ACTIVE_INSTANCES);
if (loopCounter != nrOfInstances && !completionConditionSatisfied(execution)) {
callActivityEndListeners(execution);
}
setLoopVariable(execution, getCollectionElementIndexVariable(), loopCounter);
setLoopVariable(execution, NUMBER_OF_COMPLETED_INSTANCES, nrOfCompletedInstances);
logLoopDetails(execution, "instance completed", loopCounter, nrOfCompletedInstances, nrOfActiveInstances, nrOfInstances);
if (loopCounter >= nrOfInstances || completionConditionSatisfied(execution)) {
super.leave(execution);
} else {
try {
executeOriginalBehavior(execution, loopCounter);
} catch (BpmnError error) {
// re-throw business fault so that it can be caught by an Error Intermediate Event or Error Event Sub-Process in the process | throw error;
} catch (Exception e) {
throw new ActivitiException("Could not execute inner activity behavior of multi instance behavior", e);
}
}
}
@Override
public void execute(DelegateExecution execution) {
super.execute(execution);
if (innerActivityBehavior instanceof SubProcessActivityBehavior) {
// ACT-1185: end-event in subprocess may have inactivated execution
if (!execution.isActive() && execution.isEnded() && (execution.getExecutions() == null || execution.getExecutions().isEmpty())) {
execution.setActive(true);
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\SequentialMultiInstanceBehavior.java | 1 |
请完成以下Java代码 | public boolean sendEMail(I_AD_User to, String subject, String message, File attachment, boolean isHtml)
{
if (to == null)
{
log.warn("No To user");
return false;
}
final EMailAddress mailTo = EMailAddress.ofNullableString(to.getEMail());
if (mailTo == null)
{
log.warn("No To address: {}", to);
return false;
}
EMail email = createEMail(mailTo, subject, message, isHtml);
if (email == null)
{
return false;
}
if (attachment != null)
{
email.addAttachment(attachment);
}
try
{
return sendEmailNow(UserId.ofRepoId(to.getAD_User_ID()), email);
}
catch (Exception ex)
{
log.error("Failed sending mail: {}", email, ex);
return false;
}
} // sendEMail
/**
* Send Email Now
*
* @return true if sent
* @deprecated please use {@link de.metas.email.MailService} instead, and extend it as required.
*/
@Deprecated
private boolean sendEmailNow(UserId toUserId, EMail email)
{
final EMailSentStatus emailSentStatus = email.send();
//
X_AD_UserMail um = new X_AD_UserMail(getCtx(), 0, null);
um.setClientOrg(this);
um.setAD_User_ID(toUserId.getRepoId());
um.setSubject(email.getSubject());
um.setMailText(email.getMessageCRLF());
if (emailSentStatus.isSentOK())
{
um.setMessageID(emailSentStatus.getMessageId());
um.setIsDelivered(X_AD_UserMail.ISDELIVERED_Yes);
}
else
{
um.setMessageID(emailSentStatus.getSentMsg());
um.setIsDelivered(X_AD_UserMail.ISDELIVERED_No);
}
um.saveEx();
//
if (emailSentStatus.isSentOK())
{
log.info("Sent Email: {} to {}", email.getSubject(), toUserId);
return true;
} | else
{
log.warn("Could NOT Send Email: {} to {}: {} ({})", email.getSubject(), toUserId, emailSentStatus.getSentMsg(), getName());
return false;
}
} // sendEmailNow
/**
* Create EMail from User
*
* @param to recipient
* @param subject sunject
* @param message nessage
* @return EMail
* @deprecated please use {@link de.metas.email.MailService} instead, and extend it as required.
*/
@Deprecated
public @Nullable EMail createEMail(
final EMailAddress to,
final String subject,
final String message,
final boolean html)
{
try
{
final MailService mailService = SpringContextHolder.instance.getBean(MailService.class);
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.ofClientId(ClientId.ofRepoId(getAD_Client_ID())));
final EMailRequest mailRequest = EMailRequest.builder()
.mailbox(mailbox)
.to(to)
.subject(subject)
.message(message)
.html(html)
.build();
return mailService.createEMail(mailRequest);
}
catch (final Exception ex)
{
log.error("Failed to create the email", ex);
return null;
}
} // createEMail
// metas end
} // MClient | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClient.java | 1 |
请完成以下Java代码 | public @Nullable URI getUri() {
return uri;
}
public void setUri(URI uri) {
this.uri = uri;
}
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
public Map<String, Object> getMetadata() {
return metadata;
}
public void setMetadata(Map<String, Object> metadata) {
this.metadata = metadata;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
RouteDefinition that = (RouteDefinition) o;
return this.order == that.order && Objects.equals(this.id, that.id)
&& Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters)
&& Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata)
&& Objects.equals(this.enabled, that.enabled);
}
@Override
public int hashCode() {
return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order, this.enabled);
}
@Override
public String toString() {
return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters
+ ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + ", enabled=" + enabled + '}';
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\route\RouteDefinition.java | 1 |
请完成以下Java代码 | public List<EntityInfo> findEntityInfosByNamePrefix(TenantId tenantId, String name) {
log.debug("Find asset entity infos by name [{}]", name);
return assetRepository.findEntityInfosByNamePrefix(tenantId.getId(), name);
}
@Override
public Long countByTenantId(TenantId tenantId) {
return assetRepository.countByTenantId(tenantId.getId());
}
@Override
public Asset findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(assetRepository.findByTenantIdAndExternalId(tenantId, externalId));
}
@Override
public Asset findByTenantIdAndName(UUID tenantId, String name) {
return findAssetsByTenantIdAndName(tenantId, name).orElse(null);
}
@Override
public PageData<Asset> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAssetsByTenantId(tenantId, pageLink);
} | @Override
public AssetId getExternalIdByInternal(AssetId internalId) {
return Optional.ofNullable(assetRepository.getExternalIdById(internalId.getId()))
.map(AssetId::new).orElse(null);
}
@Override
public PageData<Asset> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findByTenantId(tenantId.getId(), pageLink);
}
@Override
public List<AssetFields> findNextBatch(UUID uuid, int batchSize) {
return assetRepository.findAllFields(uuid, Limit.of(batchSize));
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\asset\JpaAssetDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SysRole implements Serializable {
@Id
@GeneratedValue
private Integer id;
private String role;
private String description;
private Boolean available = Boolean.FALSE;
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(name="SysRolePermission",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="permissionId")})
private List<SysPermission> permissions;
@ManyToMany
@JoinTable(name="SysUserRole",joinColumns={@JoinColumn(name="roleId")},inverseJoinColumns={@JoinColumn(name="uid")})
private List<UserInfo> userInfos; // 一个角色对应多个用户
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
} | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getAvailable() {
return available;
}
public void setAvailable(Boolean available) {
this.available = available;
}
public List<SysPermission> getPermissions() {
return permissions;
}
public void setPermissions(List<SysPermission> permissions) {
this.permissions = permissions;
}
public List<UserInfo> getUserInfos() {
return userInfos;
}
public void setUserInfos(List<UserInfo> userInfos) {
this.userInfos = userInfos;
}
} | repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\SysRole.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void discardChanges(
@PathVariable("windowId") final String windowIdStr,
@PathVariable("documentId") final String documentIdStr)
{
userSession.assertLoggedIn();
final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), DocumentId.of(documentIdStr));
documentCollection.invalidateRootDocument(documentPath);
}
@PostMapping("/{windowId}/{documentId}/{tabId}/{rowId}/discardChanges")
public void discardChanges(
@PathVariable("windowId") final String windowIdStr,
@PathVariable("documentId") final String documentIdStr,
@PathVariable("tabId") @SuppressWarnings("unused") final String tabIdStr_NOT_USED,
@PathVariable("rowId") @SuppressWarnings("unused") final String rowIdStr_NOT_USED)
{
userSession.assertLoggedIn();
final DocumentPath documentPath = DocumentPath.rootDocumentPath(WindowId.fromJson(windowIdStr), DocumentId.of(documentIdStr));
// For now it's OK if we invalidate the whole root document
documentCollection.invalidateRootDocument(documentPath);
}
@GetMapping("/{windowId}/{documentId}/changeLog")
public JSONDocumentChangeLog getDocumentChangeLog(
@PathVariable("windowId") final String windowIdStr,
@PathVariable("documentId") final String documentIdStr)
{
final WindowId windowId = WindowId.fromJson(windowIdStr);
final DocumentPath documentPath = DocumentPath.rootDocumentPath(windowId, documentIdStr);
return documentChangeLogService.getJSONDocumentChangeLog(documentPath);
}
@GetMapping("/{windowId}/{documentId}/{tabId}/{rowId}/changeLog")
public JSONDocumentChangeLog getDocumentChangeLog(
@PathVariable("windowId") final String windowIdStr,
@PathVariable("documentId") final String documentIdStr,
@PathVariable("tabId") final String tabIdStr,
@PathVariable("rowId") final String rowIdStr)
{
final WindowId windowId = WindowId.fromJson(windowIdStr);
final DocumentId documentId = DocumentId.of(documentIdStr);
final DetailId tabId = DetailId.fromJson(tabIdStr); | final DocumentId rowId = DocumentId.of(rowIdStr);
final DocumentPath documentPath = DocumentPath.singleWindowDocumentPath(windowId, documentId, tabId, rowId);
return documentChangeLogService.getJSONDocumentChangeLog(documentPath);
}
@GetMapping("/health")
public JsonWindowsHealthCheckResponse healthCheck(
@RequestParam(name = "windowIds", required = false) final String windowIdsCommaSeparated
)
{
return healthCheck(JsonWindowHealthCheckRequest.builder()
.onlyAdWindowIds(RepoIdAwares.ofCommaSeparatedSet(windowIdsCommaSeparated, AdWindowId.class))
.checkContextVariables(false)
.build());
}
@PostMapping("/health")
public JsonWindowsHealthCheckResponse healthCheck(@RequestBody JsonWindowHealthCheckRequest request)
{
return WindowHealthCheckCommand.builder()
.documentDescriptorFactory(documentCollection.getDocumentDescriptorFactory())
.request(request)
.build()
.execute();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\WindowRestController.java | 2 |
请完成以下Java代码 | public List<ExternalTask> executeList(CommandContext commandContext, Page page) {
ensureVariablesInitialized();
checkQueryOk();
return commandContext
.getExternalTaskManager()
.findExternalTasksByQueryCriteria(this);
}
public List<String> executeIdsList(CommandContext commandContext) {
ensureVariablesInitialized();
checkQueryOk();
return commandContext
.getExternalTaskManager()
.findExternalTaskIdsByQueryCriteria(this);
}
@Override
public List<ImmutablePair<String, String>> executeDeploymentIdMappingsList(CommandContext commandContext) {
checkQueryOk();
return commandContext
.getExternalTaskManager()
.findDeploymentIdMappingsByQueryCriteria(this);
}
public String getExternalTaskId() {
return externalTaskId;
}
public String getWorkerId() {
return workerId;
}
public Date getLockExpirationBefore() {
return lockExpirationBefore;
}
public Date getLockExpirationAfter() {
return lockExpirationAfter;
}
public String getTopicName() {
return topicName;
}
public Boolean getLocked() {
return locked;
}
public Boolean getNotLocked() {
return notLocked;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
} | public String getProcessDefinitionNameLike() {
return processDefinitionNameLike;
}
public String getActivityId() {
return activityId;
}
public SuspensionState getSuspensionState() {
return suspensionState;
}
public Boolean getRetriesLeft() {
return retriesLeft;
}
public Date getNow() {
return ClockUtil.getCurrentTime();
}
protected void ensureVariablesInitialized() {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue var : variables) {
var.initialize(variableSerializers, dbType);
}
}
public List<QueryVariableValue> getVariables() {
return variables;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ExternalTaskQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void initialize(VariableValueProvider valueProvider) {
if (valueField == null) {
valueType = valueProvider.findVariableType(value);
if (valueType instanceof ByteArrayType) {
throw new FlowableIllegalArgumentException("Variables of type ByteArray cannot be used to query");
} else if (valueType instanceof JPAEntityVariableType && operator != QueryOperator.EQUALS) {
throw new FlowableIllegalArgumentException("JPA entity variables can only be used in 'variableValueEquals'");
} else if (valueType instanceof JPAEntityListVariableType) {
throw new FlowableIllegalArgumentException("Variables containing a list of JPA entities cannot be used to query");
} else {
// Type implementation determines which fields are set on the entity
valueField = valueProvider.createValueFields(name, valueType, value);
}
}
}
public void initialize(VariableServiceConfiguration variableServiceConfiguration) {
initialize(new VariableServiceConfigurationVariableValueProvider(variableServiceConfiguration));
}
public String getName() {
return name;
}
public String getOperator() {
if (operator != null) {
return operator.toString();
}
return QueryOperator.EQUALS.toString();
}
public String getTextValue() {
if (valueField != null) {
return valueField.getTextValue();
}
return null;
}
public Long getLongValue() {
if (valueField != null) {
return valueField.getLongValue();
}
return null;
}
public Double getDoubleValue() {
if (valueField != null) {
return valueField.getDoubleValue();
}
return null;
}
public String getTextValue2() {
if (valueField != null) {
return valueField.getTextValue2();
}
return null;
}
public String getType() { | if (valueType != null) {
return valueType.getTypeName();
}
return null;
}
public boolean needsTypeCheck() {
// When operator is not-equals or type of value is null, type doesn't matter!
if (operator == QueryOperator.NOT_EQUALS || operator == QueryOperator.NOT_EQUALS_IGNORE_CASE) {
return false;
}
if (valueField != null) {
return !NullType.TYPE_NAME.equals(valueType.getTypeName());
}
return false;
}
public boolean isLocal() {
return local;
}
public String getScopeType() {
return scopeType;
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\QueryVariableValue.java | 2 |
请完成以下Java代码 | void setParent(MReportLineSet lineSet)
{
this.parent = lineSet;
}
private MReportLineSet parent = null;
public boolean isInclInParentCalc()
{
return this.get_ValueAsBoolean("IsInclInParentCalc");
}
public static void checkIncludedReportLineSetCycles(MReportLine line)
{
checkIncludedReportLineSetCycles(line, new TreeSet<Integer>(), new StringBuffer());
}
private static void checkIncludedReportLineSetCycles(MReportLine line, Collection<Integer> trace, StringBuffer traceStr)
{
StringBuffer traceStr2 = new StringBuffer(traceStr);
if (traceStr2.length() > 0)
traceStr2.append(" - ");
traceStr2.append(line.getName()); | if (trace.contains(line.getPA_ReportLine_ID()))
{
throw new AdempiereException("@PA_ReportLine_ID@ Loop Detected: "+traceStr2.toString()); // TODO: translate
}
Collection<Integer> trace2 = new TreeSet<Integer>(trace);
trace2.add(line.getPA_ReportLine_ID());
if (line.isLineTypeIncluded() && line.getPA_ReportLineSet() != null)
{
MReportLineSet includedSet = line.getIncluded_ReportLineSet();
traceStr2.append("(").append(includedSet.getName()).append(")");
for (MReportLine includedLine : includedSet.getLiness())
{
checkIncludedReportLineSetCycles(includedLine, trace2, traceStr2);
}
}
}
} // MReportLine | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportLine.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, I_M_HU.class);
}
@Override
public void setM_HU(final I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_Value (COLUMNNAME_M_HU_ID, null);
else
set_Value (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_HU_QRCode_Assignment_ID (final int M_HU_QRCode_Assignment_ID)
{
if (M_HU_QRCode_Assignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_Assignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_QRCode_Assignment_ID, M_HU_QRCode_Assignment_ID);
}
@Override
public int getM_HU_QRCode_Assignment_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_Assignment_ID);
}
@Override
public I_M_HU_QRCode getM_HU_QRCode()
{ | return get_ValueAsPO(COLUMNNAME_M_HU_QRCode_ID, I_M_HU_QRCode.class);
}
@Override
public void setM_HU_QRCode(final I_M_HU_QRCode M_HU_QRCode)
{
set_ValueFromPO(COLUMNNAME_M_HU_QRCode_ID, I_M_HU_QRCode.class, M_HU_QRCode);
}
@Override
public void setM_HU_QRCode_ID (final int M_HU_QRCode_ID)
{
if (M_HU_QRCode_ID < 1)
set_Value (COLUMNNAME_M_HU_QRCode_ID, null);
else
set_Value (COLUMNNAME_M_HU_QRCode_ID, M_HU_QRCode_ID);
}
@Override
public int getM_HU_QRCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_QRCode_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_QRCode_Assignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Set<String> getInclude() {
return this.include;
}
public void setInclude(Set<String> include) {
this.include = include;
}
public Set<String> getExclude() {
return this.exclude;
}
public void setExclude(Set<String> exclude) {
this.exclude = exclude;
}
}
public static class Discovery { | /**
* Whether the discovery page is enabled.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\WebEndpointProperties.java | 2 |
请完成以下Java代码 | public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression()); | fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<CustomProperty>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public static final <T> T unwrap(final T object)
{
if (object == null)
{
return null;
}
final Class<? extends Object> objectClass = object.getClass();
if (Proxy.isProxyClass(objectClass))
{
final InvocationHandler handler = Proxy.getInvocationHandler(object);
if (handler instanceof WeakWrapper)
{
@SuppressWarnings("unchecked")
final WeakWrapper<T> weakWrapper = (WeakWrapper<T>)handler;
return weakWrapper.getDelegate();
}
}
return object;
}
private final WeakReference<T> delegateRef;
private final Class<? extends Object> delegateClass;
private WeakWrapper(final T delegate)
{
super();
Check.assumeNotNull(delegate, "delegate not null");
this.delegateRef = new WeakReference<>(delegate);
this.delegateClass = delegate.getClass();
}
private final T getDelegate()
{
final T delegate = delegateRef.get();
if (delegate == null)
{
throw new RuntimeException("Weak delegate expired for " + this);
}
return delegate;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable
{
final T delegate = getDelegate();
final Method delegateMethod = ProxyMethodsCache.getInstance().getMethodImplementation(method, delegateClass);
if (delegateMethod == null) | {
// shall not happen
throw new IllegalStateException("No delegate method was found for " + method + " in " + delegateClass);
}
if (!delegateMethod.isAccessible())
{
delegateMethod.setAccessible(true);
}
try
{
return delegateMethod.invoke(delegate, args);
}
catch (InvocationTargetException ex)
{
// NOTE: in case of invocation target exception, propagate the parent cause,
// because we don't give a fuck about the exception from reflections API (that's only noise).
throw ex.getCause();
}
}
@Override
public String toString()
{
return "WeakWrapper [delegateClass=" + delegateClass + ", delegateRef=" + delegateRef + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\WeakWrapper.java | 1 |
请完成以下Java代码 | public <T extends ReferenceListAwareEnum> T getValueAsEnum(@NonNull final Class<T> enumType)
{
if (value == null)
{
return null;
}
else if (enumType.isInstance(value))
{
//noinspection unchecked
return (T)value;
}
final String valueStr;
if (value instanceof Map)
{
@SuppressWarnings("unchecked") final Map<String, Object> map = (Map<String, Object>)value;
final LookupValue.StringLookupValue lookupValue = JSONLookupValue.stringLookupValueFromJsonMap(map);
valueStr = lookupValue.getIdAsString();
}
else if (value instanceof JSONLookupValue)
{
final JSONLookupValue json = (JSONLookupValue)value;
valueStr = json.getKey();
}
else
{ | valueStr = value.toString();
}
try
{
return ReferenceListAwareEnums.ofNullableCode(valueStr, enumType);
}
catch (Exception ex)
{
throw new AdempiereException("Failed converting `" + value + "` (" + value.getClass().getSimpleName() + ") to " + enumType.getSimpleName(), ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentChangedEvent.java | 1 |
请完成以下Java代码 | public class ServiceTask extends TaskWithFieldExtensions {
public static final String JAVA_TASK = "java";
public static final String MAIL_TASK = "mail";
protected String implementation;
protected String implementationType;
protected String resultVariableName;
protected String type;
protected boolean storeResultVariableAsTransient;
public String getImplementation() {
return implementation;
}
public void setImplementation(String implementation) {
this.implementation = implementation;
}
public String getImplementationType() {
return implementationType;
}
public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getResultVariableName() {
return resultVariableName;
}
public void setResultVariableName(String resultVariableName) {
this.resultVariableName = resultVariableName;
}
public String getType() {
return type;
}
public void setType(String type) { | this.type = type;
}
public boolean isStoreResultVariableAsTransient() {
return storeResultVariableAsTransient;
}
public void setStoreResultVariableAsTransient(boolean storeResultVariableAsTransient) {
this.storeResultVariableAsTransient = storeResultVariableAsTransient;
}
@Override
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setStoreResultVariableAsTransient(otherElement.isStoreResultVariableAsTransient());
fieldExtensions = new ArrayList<>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public void setQtyScrap (final BigDecimal QtyScrap)
{
set_ValueNoCheck (COLUMNNAME_QtyScrap, QtyScrap);
}
@Override
public BigDecimal getQtyScrap()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyScrap);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyUsageVariance (final BigDecimal QtyUsageVariance)
{
set_Value (COLUMNNAME_QtyUsageVariance, QtyUsageVariance);
}
@Override
public BigDecimal getQtyUsageVariance()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyUsageVariance);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setScrap (final @Nullable BigDecimal Scrap)
{
set_ValueNoCheck (COLUMNNAME_Scrap, Scrap);
}
@Override
public BigDecimal getScrap()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Scrap);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setShowSubBOMIngredients (final boolean ShowSubBOMIngredients)
{
set_Value (COLUMNNAME_ShowSubBOMIngredients, ShowSubBOMIngredients);
}
@Override
public boolean isShowSubBOMIngredients()
{
return get_ValueAsBoolean(COLUMNNAME_ShowSubBOMIngredients);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
} | @Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
/**
* VariantGroup AD_Reference_ID=540490
* Reference name: VariantGroup
*/
public static final int VARIANTGROUP_AD_Reference_ID=540490;
/** 01 = 01 */
public static final String VARIANTGROUP_01 = "01";
/** 02 = 02 */
public static final String VARIANTGROUP_02 = "02";
/** 03 = 03 */
public static final String VARIANTGROUP_03 = "03";
/** 04 = 04 */
public static final String VARIANTGROUP_04 = "04";
/** 05 = 05 */
public static final String VARIANTGROUP_05 = "05";
/** 06 = 06 */
public static final String VARIANTGROUP_06 = "06";
/** 07 = 07 */
public static final String VARIANTGROUP_07 = "07";
/** 08 = 08 */
public static final String VARIANTGROUP_08 = "08";
/** 09 = 09 */
public static final String VARIANTGROUP_09 = "09";
@Override
public void setVariantGroup (final @Nullable java.lang.String VariantGroup)
{
set_Value (COLUMNNAME_VariantGroup, VariantGroup);
}
@Override
public java.lang.String getVariantGroup()
{
return get_ValueAsString(COLUMNNAME_VariantGroup);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_BOMLine.java | 1 |
请完成以下Java代码 | public static Gson getGsonMapper() {
return gsonMapper;
}
public static Gson createGsonMapper() {
return new GsonBuilder()
.serializeNulls()
.registerTypeAdapter(Map.class, new JsonDeserializer<Map<String,Object>>() {
public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
Map<String, Object> map = new HashMap<>();
for (Map.Entry<String, JsonElement> entry : getObject(json).entrySet()) {
if (entry != null) {
String key = entry.getKey();
JsonElement jsonElement = entry.getValue();
if (jsonElement != null && jsonElement.isJsonNull()) {
map.put(key, null);
} else if (jsonElement != null && jsonElement.isJsonPrimitive()) {
Object rawValue = asPrimitiveObject((JsonPrimitive) jsonElement); | if (rawValue != null) {
map.put(key, rawValue);
}
}
}
}
return map;
}
})
.create();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\JsonUtil.java | 1 |
请完成以下Java代码 | public void setReportPrefix (final java.lang.String ReportPrefix)
{
set_Value (COLUMNNAME_ReportPrefix, ReportPrefix);
}
@Override
public java.lang.String getReportPrefix()
{
return get_ValueAsString(COLUMNNAME_ReportPrefix);
}
/**
* StoreCreditCardData AD_Reference_ID=540197
* Reference name: StoreCreditCardData
*/
public static final int STORECREDITCARDDATA_AD_Reference_ID=540197;
/** Speichern = STORE */
public static final String STORECREDITCARDDATA_Speichern = "STORE";
/** Nicht Speichern = DONT */
public static final String STORECREDITCARDDATA_NichtSpeichern = "DONT";
/** letzte 4 Stellen = LAST4 */
public static final String STORECREDITCARDDATA_Letzte4Stellen = "LAST4";
@Override
public void setStoreCreditCardData (final java.lang.String StoreCreditCardData)
{
set_Value (COLUMNNAME_StoreCreditCardData, StoreCreditCardData);
}
@Override
public java.lang.String getStoreCreditCardData()
{
return get_ValueAsString(COLUMNNAME_StoreCreditCardData);
}
@Override
public void setSupervisor_ID (final int Supervisor_ID)
{
if (Supervisor_ID < 1)
set_Value (COLUMNNAME_Supervisor_ID, null);
else
set_Value (COLUMNNAME_Supervisor_ID, Supervisor_ID);
}
@Override
public int getSupervisor_ID()
{
return get_ValueAsInt(COLUMNNAME_Supervisor_ID);
}
@Override
public void setTimeZone (final @Nullable java.lang.String TimeZone)
{
set_Value (COLUMNNAME_TimeZone, TimeZone);
}
@Override
public java.lang.String getTimeZone() | {
return get_ValueAsString(COLUMNNAME_TimeZone);
}
@Override
public void setTransferBank_ID (final int TransferBank_ID)
{
if (TransferBank_ID < 1)
set_Value (COLUMNNAME_TransferBank_ID, null);
else
set_Value (COLUMNNAME_TransferBank_ID, TransferBank_ID);
}
@Override
public int getTransferBank_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferBank_ID);
}
@Override
public org.compiere.model.I_C_CashBook getTransferCashBook()
{
return get_ValueAsPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class);
}
@Override
public void setTransferCashBook(final org.compiere.model.I_C_CashBook TransferCashBook)
{
set_ValueFromPO(COLUMNNAME_TransferCashBook_ID, org.compiere.model.I_C_CashBook.class, TransferCashBook);
}
@Override
public void setTransferCashBook_ID (final int TransferCashBook_ID)
{
if (TransferCashBook_ID < 1)
set_Value (COLUMNNAME_TransferCashBook_ID, null);
else
set_Value (COLUMNNAME_TransferCashBook_ID, TransferCashBook_ID);
}
@Override
public int getTransferCashBook_ID()
{
return get_ValueAsInt(COLUMNNAME_TransferCashBook_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgInfo.java | 1 |
请完成以下Java代码 | public Optional<String> getCaption() {return getByPathAsString("caption");}
public Optional<MobileApplicationId> getApplicationId() {return getByPathAsString("applicationId").map(MobileApplicationId::ofNullableString);}
public Optional<String> getDeviceId() {return getByPathAsString("device", "deviceId");}
public Optional<String> getTabId() {return getByPathAsString("device", "tabId");}
public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");}
public Optional<String> getByPathAsString(final String... path)
{
return getByPath(path).map(Object::toString);
}
public Optional<Object> getByPath(final String... path)
{
Object currentValue = properties;
for (final String pathElement : path)
{
if (!(currentValue instanceof Map))
{
//throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties);
return Optional.empty();
}
//noinspection unchecked
final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null);
if (value == null)
{
return Optional.empty();
} | else
{
currentValue = value;
}
}
return Optional.of(currentValue);
}
private static Optional<Object> getByKey(final Map<String, Object> map, final String key)
{
return map.entrySet()
.stream()
.filter(e -> e.getKey().equalsIgnoreCase(key))
.map(Map.Entry::getValue)
.filter(Objects::nonNull)
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java | 1 |
请完成以下Java代码 | public int read(char[] cbuf, int off, int len) throws IOException {
int charactersRead = wrappedReader.read(cbuf, off, len);
if (charactersRead > 0) {
if (rewindable && pos + charactersRead > buffer.length) {
rewindable = false;
}
if (pos < buffer.length) {
int freeBufferSpace = buffer.length - pos;
int insertableCharacters = Math.min(charactersRead, freeBufferSpace);
System.arraycopy(cbuf, off, buffer, pos, insertableCharacters);
pos += insertableCharacters;
}
}
return charactersRead;
}
public int read() throws IOException {
int nextCharacter = wrappedReader.read();
if (nextCharacter != -1) {
if (pos < buffer.length) {
buffer[pos] = (char) nextCharacter;
pos++;
} else if (rewindable && pos >= buffer.length) {
rewindable = false;
}
}
return nextCharacter;
}
public void close() throws IOException {
wrappedReader.close();
}
public synchronized void mark(int readlimit) throws IOException {
wrappedReader.mark(readlimit);
}
public boolean markSupported() {
return wrappedReader.markSupported();
}
public synchronized void reset() throws IOException {
wrappedReader.reset();
}
public long skip(long n) throws IOException {
return wrappedReader.skip(n);
}
/** | * Rewinds the reader such that the initial characters are returned when invoking read().
*
* Throws an exception if more than the buffering limit has already been read.
* @throws IOException
*/
public void rewind() throws IOException {
if (!rewindable) {
throw LOG.unableToRewindReader();
}
wrappedReader.unread(buffer, 0, pos);
pos = 0;
}
public int getRewindBufferSize() {
return buffer.length;
}
/**
*
* @return the number of characters that can still be read and rewound.
*/
public int getCurrentRewindableCapacity() {
return buffer.length - pos;
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\util\RewindableReader.java | 1 |
请完成以下Java代码 | public final class JwtClaimValidator<T> implements OAuth2TokenValidator<Jwt> {
private final Log logger = LogFactory.getLog(getClass());
private final String claim;
private final Predicate<T> test;
private final OAuth2Error error;
/**
* Constructs a {@link JwtClaimValidator} using the provided parameters
* @param claim - is the name of the claim in {@link Jwt} to validate.
* @param test - is the predicate function for the claim to test against.
*/
public JwtClaimValidator(String claim, Predicate<T> test) {
Assert.notNull(claim, "claim can not be null");
Assert.notNull(test, "test can not be null");
this.claim = claim;
this.test = test; | this.error = new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, "The " + this.claim + " claim is not valid",
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
@Override
public OAuth2TokenValidatorResult validate(Jwt token) {
Assert.notNull(token, "token cannot be null");
T claimValue = token.getClaim(this.claim);
if (this.test.test(claimValue)) {
return OAuth2TokenValidatorResult.success();
}
this.logger.debug(this.error.getDescription());
return OAuth2TokenValidatorResult.failure(this.error);
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtClaimValidator.java | 1 |
请完成以下Java代码 | public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
@Override
public void setPackageNetTotal (final BigDecimal PackageNetTotal)
{
set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal);
}
@Override
public BigDecimal getPackageNetTotal()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPackageWeight (final @Nullable BigDecimal PackageWeight)
{
set_Value (COLUMNNAME_PackageWeight, PackageWeight);
}
@Override
public BigDecimal getPackageWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
throw new IllegalArgumentException ("ProductName is virtual column"); } | @Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductValue (final @Nullable java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
@Override
public java.lang.String getProductValue()
{
return get_ValueAsString(COLUMNNAME_ProductValue);
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU)
{
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShippingPackage.java | 1 |
请完成以下Java代码 | String getExpirationKey(long expires) {
return this.lookupExpirationKey.apply(expires);
}
String getSessionKey(String sessionId) {
return this.lookupSessionKey.apply(sessionId);
}
void cleanExpiredSessions() {
long now = System.currentTimeMillis();
long prevMin = roundDownMinute(now);
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up sessions expiring at " + new Date(prevMin));
}
String expirationKey = getExpirationKey(prevMin);
Set<Object> sessionsToExpire = this.redis.boundSetOps(expirationKey).members();
this.redis.delete(expirationKey);
for (Object session : sessionsToExpire) {
String sessionKey = getSessionKey((String) session);
touch(sessionKey);
}
}
/**
* By trying to access the session we only trigger a deletion if it the TTL is
* expired. This is done to handle
* https://github.com/spring-projects/spring-session/issues/93
* @param key the key
*/
private void touch(String key) {
this.redis.hasKey(key);
}
static long expiresInMillis(Session session) {
int maxInactiveInSeconds = (int) session.getMaxInactiveInterval().getSeconds();
long lastAccessedTimeInMillis = session.getLastAccessedTime().toEpochMilli(); | return lastAccessedTimeInMillis + TimeUnit.SECONDS.toMillis(maxInactiveInSeconds);
}
static long roundUpToNextMinute(long timeInMs) {
Calendar date = Calendar.getInstance();
date.setTimeInMillis(timeInMs);
date.add(Calendar.MINUTE, 1);
date.clear(Calendar.SECOND);
date.clear(Calendar.MILLISECOND);
return date.getTimeInMillis();
}
static long roundDownMinute(long timeInMs) {
Calendar date = Calendar.getInstance();
date.setTimeInMillis(timeInMs);
date.clear(Calendar.SECOND);
date.clear(Calendar.MILLISECOND);
return date.getTimeInMillis();
}
} | repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionExpirationPolicy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void handlePutProductsRequest(final PutProductsRequest request)
{
logger.debug("Importing: {}", request);
int countImported = 0;
int countError = 0;
for (final SyncProduct syncProduct : request.getProducts())
{
try
{
productsImportService.importProduct(syncProduct);
countImported++;
}
catch (final Exception e)
{
countError++;
logger.error("Failed importing {}. Skipped.", syncProduct, e);
}
}
logger.info("{} products imported, got {} errors", countImported, countError);
}
public void handlePutInfoMessageRequest(final PutInfoMessageRequest request)
{
logger.debug("Importing: {}", request);
try
{
settingsImportService.importSyncInfoMessage(request);
}
catch (final Exception e)
{
logger.error("Failed importing {}. Skipped.", request, e);
}
}
public void handlePutConfirmationToProcurementWebRequest(final PutConfirmationToProcurementWebRequest request)
{
logger.debug("Importing: {}", request);
for (final SyncConfirmation syncConfirmation : request.getSyncConfirmations())
{
try
{
confirmationsImportService.importConfirmation(syncConfirmation);
}
catch (final Exception e)
{
logger.error("Failed importing confirmation: {}", syncConfirmation, e);
}
}
}
public void handlePutRfQsRequest(@NonNull final PutRfQsRequest request)
{
logger.debug("Importing: {}", request);
if (request.isEmpty())
{
return;
}
for (final SyncRfQ syncRfq : request.getSyncRfqs())
{
try | {
rfqImportService.importRfQ(syncRfq);
}
catch (final Exception e)
{
logger.error("Failed importing RfQ: {}", syncRfq, e);
}
}
}
public void handlePutRfQCloseEventsRequest(final PutRfQCloseEventsRequest request)
{
logger.debug("Importing: {}", request);
if (request.isEmpty())
{
return;
}
for (final SyncRfQCloseEvent syncRfQCloseEvent : request.getSyncRfQCloseEvents())
{
try
{
rfqImportService.importRfQCloseEvent(syncRfQCloseEvent);
}
catch (final Exception e)
{
logger.error("Failed importing: {}", syncRfQCloseEvent, e);
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\ReceiverFromMetasfreshHandler.java | 2 |
请完成以下Java代码 | public void segment(String text, String normalized, List<String> output)
{
int[] obsArray = new int[text.length()];
for (int i = 0; i < obsArray.length; i++)
{
obsArray[i] = vocabulary.idOf(normalized.substring(i, i + 1));
}
int[] tagArray = new int[text.length()];
model.predict(obsArray, tagArray);
StringBuilder result = new StringBuilder();
result.append(text.charAt(0));
for (int i = 1; i < tagArray.length; i++)
{
if (tagArray[i] == tagSet.B || tagArray[i] == tagSet.S)
{
output.add(result.toString());
result.setLength(0);
}
result.append(text.charAt(i));
}
if (result.length() != 0)
{
output.add(result.toString());
}
}
@Override
protected List<String[]> convertToSequence(Sentence sentence)
{
List<String[]> charList = new LinkedList<String[]>();
for (Word w : sentence.toSimpleWordList())
{
String word = CharTable.convert(w.value);
if (word.length() == 1)
{
charList.add(new String[]{word, "S"});
}
else
{
charList.add(new String[]{word.substring(0, 1), "B"});
for (int i = 1; i < word.length() - 1; ++i)
{
charList.add(new String[]{word.substring(i, i + 1), "M"});
}
charList.add(new String[]{word.substring(word.length() - 1), "E"});
}
}
return charList;
}
@Override
protected TagSet getTagSet()
{
return tagSet; | }
/**
* 获取兼容旧的Segment接口
*
* @return
*/
public Segment toSegment()
{
return new Segment()
{
@Override
protected List<Term> segSentence(char[] sentence)
{
List<String> wordList = segment(new String(sentence));
List<Term> termList = new LinkedList<Term>();
for (String word : wordList)
{
termList.add(new Term(word, null));
}
return termList;
}
}.enableCustomDictionary(false);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMSegmenter.java | 1 |
请完成以下Java代码 | private void appendDetails(StringBuilder message, MutuallyExclusiveConfigurationPropertiesException cause,
List<Descriptor> descriptors) {
descriptors.sort(Comparator.comparing((descriptor) -> descriptor.propertyName));
message.append(String.format("The following configuration properties are mutually exclusive:%n%n"));
sortedStrings(cause.getMutuallyExclusiveNames())
.forEach((name) -> message.append(String.format("\t%s%n", name)));
message.append(String.format("%n"));
message.append(
String.format("However, more than one of those properties has been configured at the same time:%n%n"));
Set<String> configuredDescriptions = sortedStrings(descriptors,
(descriptor) -> String.format("\t%s%s%n", descriptor.propertyName,
(descriptor.origin != null) ? " (originating from '" + descriptor.origin + "')" : ""));
configuredDescriptions.forEach(message::append);
}
private Set<String> sortedStrings(Collection<String> input) {
return sortedStrings(input, Function.identity());
}
private <S> Set<String> sortedStrings(Collection<S> input, Function<S, String> converter) {
TreeSet<String> results = new TreeSet<>();
for (S item : input) {
results.add(converter.apply(item));
}
return results;
}
private static final class Descriptor {
private final String propertyName; | private final @Nullable Origin origin;
private Descriptor(String propertyName, @Nullable Origin origin) {
this.propertyName = propertyName;
this.origin = origin;
}
static Descriptor get(PropertySource<?> source, String propertyName) {
Origin origin = OriginLookup.getOrigin(source, propertyName);
return new Descriptor(propertyName, origin);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\MutuallyExclusiveConfigurationPropertiesFailureAnalyzer.java | 1 |
请完成以下Java代码 | public final class AllowDenyCollectionManager<T> {
private final Collection<T> allowList;
private final Collection<T> denyList;
private final Collection<Predicate<T>> predicates;
public AllowDenyCollectionManager(Collection<T> allowList, Collection<T> denyList) {
this.allowList = allowList;
this.denyList = denyList;
this.predicates = Collections.singletonList(getDefaultPredicate(allowList, denyList));
}
public AllowDenyCollectionManager(Collection<T> allowList, Collection<T> denyList, Collection<Predicate<T>> predicates) {
Assert.notNull(allowList, () -> "AllowList cannot be null");
Assert.notNull(denyList, () -> "DenyList cannot be null");
Assert.notNull(predicates, () -> "Predicates cannot be null");
this.allowList = allowList;
this.denyList = denyList;
this.predicates = predicates;
}
public Predicate<T> getDefaultPredicate(Collection<T> allowList, Collection<T> denyList) {
return objectToCheck -> !denyList.contains(objectToCheck)
&& (allowList.isEmpty() || allowList.contains(objectToCheck));
}
public boolean isAllowed(T objectToCheck) {
return this.predicates
.stream() | .allMatch(predicate -> predicate.test(objectToCheck));
}
public boolean areAllowed(T[] objects) {
return Arrays.stream(objects)
.allMatch(this::isAllowed);
}
public static <T> AllowDenyCollectionManager<T> createManagerFor(Collection<T> allowList, Collection<T> denyList) {
return new AllowDenyCollectionManager<>(allowList, denyList);
}
public static <T> AllowDenyCollectionManager<T> createManagerFor(Collection<T> allowList, Collection<T> denyList, Collection<Predicate<T>> predicates) {
return new AllowDenyCollectionManager<>(allowList, denyList, predicates);
}
public boolean hasNoRestrictions() {
return this.allowList.isEmpty()
&& this.denyList.isEmpty();
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\AllowDenyCollectionManager.java | 1 |
请完成以下Java代码 | public final String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public final List<Object> getSqlParams(final Properties ctx_NOTUSED)
{
return getSqlParams();
}
public final List<Object> getSqlParams()
{
buildSql();
return sqlParams;
} | private void buildSql()
{
if (sqlBuilt)
{
return;
}
final String sqlLikeValue = prefix.replace("%", "\\%") + "%";
sqlWhereClause = operand.getColumnName() + " LIKE ? ESCAPE '\\'";
sqlParams = Collections.singletonList(sqlLikeValue);
sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\StringStartsWithFilter.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName; | }
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return this.firstName + " " + this.lastName + ", " + this.age + " years old";
}
} | repos\tutorials-master\persistence-modules\spring-data-geode\src\main\java\com\baeldung\springdatageode\domain\Author.java | 1 |
请完成以下Java代码 | public void setPosted (boolean Posted)
{
set_Value (COLUMNNAME_Posted, Boolean.valueOf(Posted));
}
/** Get Verbucht.
@return Posting status
*/
@Override
public boolean isPosted ()
{
Object oo = get_Value(COLUMNNAME_Posted);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/**
* PriorityRule AD_Reference_ID=154
* Reference name: _PriorityRule
*/
public static final int PRIORITYRULE_AD_Reference_ID=154;
/** High = 3 */
public static final String PRIORITYRULE_High = "3";
/** Medium = 5 */
public static final String PRIORITYRULE_Medium = "5";
/** Low = 7 */
public static final String PRIORITYRULE_Low = "7";
/** Urgent = 1 */
public static final String PRIORITYRULE_Urgent = "1";
/** Minor = 9 */
public static final String PRIORITYRULE_Minor = "9";
/** Set Priorität.
@param PriorityRule
Priority of a document
*/
@Override
public void setPriorityRule (java.lang.String PriorityRule)
{
set_Value (COLUMNNAME_PriorityRule, PriorityRule);
}
/** Get Priorität.
@return Priority of a document
*/
@Override
public java.lang.String getPriorityRule ()
{
return (java.lang.String)get_Value(COLUMNNAME_PriorityRule);
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/ | @Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Summe Zeilen.
@param TotalLines
Total of all document lines
*/
@Override
public void setTotalLines (java.math.BigDecimal TotalLines)
{
set_Value (COLUMNNAME_TotalLines, TotalLines);
}
/** Get Summe Zeilen.
@return Total of all document lines
*/
@Override
public java.math.BigDecimal getTotalLines ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalLines);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Requisition.java | 1 |
请完成以下Java代码 | public String getCode ()
{
return (String)get_Value(COLUMNNAME_Code);
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity | */
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintFont.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void eraseCredentials() {
this.delegate.eraseCredentials();
}
@Override
public void setDetails(Object details) {
this.delegate.setDetails(details);
}
@Override
public Object getDetails() {
return this.delegate.getDetails();
}
@Override
public void setAuthenticated(boolean authenticated) {
this.delegate.setAuthenticated(authenticated);
}
@Override
public boolean isAuthenticated() {
return this.delegate.isAuthenticated();
}
@Override
public String getName() {
return this.delegate.getName();
}
@Override
public Collection<GrantedAuthority> getAuthorities() {
return this.delegate.getAuthorities();
}
@Override
public Map<String, Object> getTokenAttributes() {
return this.delegate.getTokenAttributes(); | }
/**
* Returns a JWT. It usually refers to a token string expressing with 'eyXXX.eyXXX.eyXXX' format.
*
* @return the token value as a String
*/
public String tokenValue() {
return delegate.getToken().getTokenValue();
}
/**
* Extract Subject from JWT. Here, Subject is the user ID in UUID format.
*
* @return the user ID as a UUID
*/
public UUID userId() {
return UUID.fromString(delegate.getName());
}
} | repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\config\AuthToken.java | 2 |
请完成以下Java代码 | public boolean isPurchaseQty ()
{
Object oo = get_Value(COLUMNNAME_IsPurchaseQty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set RfQ Quantity.
@param IsRfQQty
The quantity is used when generating RfQ Responses
*/
@Override
public void setIsRfQQty (boolean IsRfQQty)
{
set_Value (COLUMNNAME_IsRfQQty, Boolean.valueOf(IsRfQQty));
}
/** Get RfQ Quantity.
@return The quantity is used when generating RfQ Responses
*/
@Override
public boolean isRfQQty ()
{
Object oo = get_Value(COLUMNNAME_IsRfQQty);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Margin %.
@param Margin
Margin for a product as a percentage
*/
@Override
public void setMargin (java.math.BigDecimal Margin)
{
set_Value (COLUMNNAME_Margin, Margin);
}
/** Get Margin %.
@return Margin for a product as a percentage
*/
@Override
public java.math.BigDecimal getMargin ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Margin);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Offer Amount.
@param OfferAmt
Amount of the Offer
*/ | @Override
public void setOfferAmt (java.math.BigDecimal OfferAmt)
{
set_Value (COLUMNNAME_OfferAmt, OfferAmt);
}
/** Get Offer Amount.
@return Amount of the Offer
*/
@Override
public java.math.BigDecimal getOfferAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OfferAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Menge.
@param Qty
Quantity
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Quantity
*/
@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.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQLineQty.java | 1 |
请完成以下Java代码 | public AggregatedCostAmount retainOnlyAccountable(@NonNull final AcctSchema as)
{
final AcctSchemaCosting costing = as.getCosting();
final LinkedHashMap<CostElement, CostAmountDetailed> amountsPerElementNew = new LinkedHashMap<>();
amountsPerElement.forEach((costElement, costAmount) -> {
if (costElement.isAccountable(costing))
{
amountsPerElementNew.put(costElement, costAmount);
}
});
if (amountsPerElementNew.size() == amountsPerElement.size())
{
return this;
}
return new AggregatedCostAmount(costSegment, amountsPerElementNew);
} | public CostAmountDetailed getTotalAmountToPost(@NonNull final AcctSchema as)
{
return getTotalAmount(as.getCosting()).orElseGet(() -> CostAmountDetailed.zero(as.getCurrencyId()));
}
@VisibleForTesting
Optional<CostAmountDetailed> getTotalAmount(@NonNull final AcctSchemaCosting asCosting)
{
return getCostElements()
.stream()
.filter(costElement -> costElement.isAccountable(asCosting))
.map(this::getCostAmountForCostElement)
.reduce(CostAmountDetailed::add);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\AggregatedCostAmount.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserInfoController {
@Autowired
private RpUserInfoService rpUserInfoService;
/**
* 函数功能说明 : 查询用户信息
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/list", method ={RequestMethod.POST, RequestMethod.GET})
public String list(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/list";
}
/**
* 函数功能说明 :跳转添加
*
* @参数: @return
* @return String
* @throws
*/
@RequiresPermissions("user:userInfo:add")
@RequestMapping(value = "/addUI", method = RequestMethod.GET)
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代码 | private static Set<DayOfWeek> extractWeekDays(@NonNull final I_M_TourVersion tourVersion)
{
final Set<DayOfWeek> weekDays = new HashSet<>();
if (tourVersion.isOnSunday())
{
weekDays.add(DayOfWeek.SUNDAY);
}
if (tourVersion.isOnMonday())
{
weekDays.add(DayOfWeek.MONDAY);
}
if (tourVersion.isOnTuesday())
{
weekDays.add(DayOfWeek.TUESDAY);
}
if (tourVersion.isOnWednesday())
{
weekDays.add(DayOfWeek.WEDNESDAY);
}
if (tourVersion.isOnThursday()) | {
weekDays.add(DayOfWeek.THURSDAY);
}
if (tourVersion.isOnFriday())
{
weekDays.add(DayOfWeek.FRIDAY);
}
if (tourVersion.isOnSaturday())
{
weekDays.add(DayOfWeek.SATURDAY);
}
return weekDays;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\TourDAO.java | 1 |
请完成以下Java代码 | public List<String> getImageUrls() {
return imageUrls;
}
public void setImageUrls(List<String> imageUrls) {
this.imageUrls = imageUrls;
}
public List<String> getVideoUrls() {
return videoUrls;
}
public void setVideoUrls(List<String> videoUrls) {
this.videoUrls = videoUrls;
}
public Integer getStock() {
return stock;
} | public void setStock(Integer stock) {
this.stock = stock;
}
@Override
public String toString() {
return "ProductModel{" +
"name='" + name + '\'' +
", description='" + description + '\'' +
", status='" + status + '\'' +
", currency='" + currency + '\'' +
", price=" + price +
", imageUrls=" + imageUrls +
", videoUrls=" + videoUrls +
", stock=" + stock +
'}';
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphqlvsrest\model\ProductModel.java | 1 |
请完成以下Java代码 | public class ResponseEntity {
int status = 200;
String message = "ok";
Object data = new HashMap();
private ResponseEntity() {
}
public static ResponseEntity ok(Object data) {
ResponseEntity ResponseEntity = new ResponseEntity();
ResponseEntity.setData(data);
return ResponseEntity;
}
public static ResponseEntity error(InfoCode infoCode) {
ResponseEntity ResponseEntity = new ResponseEntity();
ResponseEntity.setStatus(infoCode.getStatus());
ResponseEntity.setMessage(infoCode.getMsg());
return ResponseEntity;
}
public static ResponseEntity ok() {
ResponseEntity ResponseEntity = new ResponseEntity();
return ResponseEntity;
}
public static ResponseEntity error(int code, String msg) {
ResponseEntity ResponseEntity = new ResponseEntity();
ResponseEntity.setStatus(code);
ResponseEntity.setMessage(msg);
return ResponseEntity;
}
public int getStatus() { | return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data == null ? new HashMap() : data;
}
public void setData(Object data) {
this.data = data;
}
} | repos\springBoot-master\abel-util\src\main\java\cn\abel\response\ResponseEntity.java | 1 |
请完成以下Java代码 | public void delete(@NonNull final RecordWarningQuery query)
{
toSqlQuery(query).create().delete();
}
private IQueryBuilder<I_AD_Record_Warning> toSqlQuery(@NonNull final RecordWarningQuery query)
{
final IQueryBuilder<I_AD_Record_Warning> queryBuilder = queryBL.createQueryBuilder(I_AD_Record_Warning.class);
if(query.getRootRecordRef() != null)
{
final TableRecordReference rootRecordRef = query.getRootRecordRef();
queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Root_AD_Table_ID, rootRecordRef.getAD_Table_ID())
.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Root_Record_ID, rootRecordRef.getRecord_ID());
}
if(query.getRecordRef() != null)
{
final TableRecordReference recordRef = query.getRecordRef();
queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID())
.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Record_ID, recordRef.getRecord_ID());
}
if (query.getBusinessRuleId() != null)
{ | queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_AD_BusinessRule_ID, query.getBusinessRuleId());
}
if(query.getSeverity() != null)
{
queryBuilder.addEqualsFilter(I_AD_Record_Warning.COLUMNNAME_Severity, query.getSeverity().getCode());
}
return queryBuilder;
}
public boolean hasErrors(@NonNull final TableRecordReference recordRef)
{
final RecordWarningQuery query = RecordWarningQuery.builder()
.recordRef(recordRef)
.severity(Severity.Error)
.build();
return toSqlQuery(query)
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\record\warning\RecordWarningRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorAnthologyViewRepository authorAnthologyViewRepository;
public BookstoreService(AuthorAnthologyViewRepository authorAnthologyViewRepository) {
this.authorAnthologyViewRepository = authorAnthologyViewRepository;
}
@Transactional
public void updateAuthorAgeViaView() {
AuthorAnthologyView author
= authorAnthologyViewRepository.findByName("Quartis Young");
author.setAge(author.getAge() + 1);
} | public void insertAuthorViaView() {
AuthorAnthologyView newAuthor = new AuthorAnthologyView();
newAuthor.setName("Toij Kalu");
newAuthor.setGenre("Anthology");
newAuthor.setAge(42);
authorAnthologyViewRepository.save(newAuthor);
}
@Transactional
public void deleteAuthorViaView() {
AuthorAnthologyView author
= authorAnthologyViewRepository.findByName("Mark Janel");
authorAnthologyViewRepository.delete(author);
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseViewUpdateInsertDelete\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public boolean applies(final IPricingContext pricingCtx, final IPricingResult result)
{
if (result.isCalculated())
{
log.debug("Not applying because already calculated");
return false;
}
if (pricingCtx.getProductId() == null)
{
log.debug("Not applying because there is no M_Product_ID specified in context");
return false;
}
if (pricingCtx.getPriceListId() == null)
{ | final String msg = "pricingCtx {} contains no priceList";
Loggables.addLog(msg, pricingCtx);
log.error(msg, pricingCtx);
Trace.printStack();
return false; // false;
}
if (pricingCtx.getPriceListId().isNone())
{
log.info("Not applying because PriceList is NoPriceList ({})", pricingCtx);
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\AbstractPriceListBasedRule.java | 1 |
请完成以下Java代码 | private boolean isAttrDocumentRelevant(final I_M_Attribute attribute)
{
final String docTableName = getSourceTableName();
if (I_C_InvoiceLine.Table_Name.equals(docTableName))
{
return attribute.isAttrDocumentRelevant();
}
else
{
return true;
}
}
public CountryAwareAttributeUpdater setSourceModel(final Object sourceModel)
{
this.sourceModel = sourceModel;
return this;
}
private Object getSourceModel()
{
Check.assumeNotNull(sourceModel, "sourceModel not null");
return sourceModel;
}
private String getSourceTableName()
{ | return InterfaceWrapperHelper.getModelTableName(getSourceModel());
}
public CountryAwareAttributeUpdater setCountryAwareFactory(final ICountryAwareFactory countryAwareFactory)
{
this.countryAwareFactory = countryAwareFactory;
return this;
}
private ICountryAwareFactory getCountryAwareFactory()
{
Check.assumeNotNull(countryAwareFactory, "countryAwareFactory not null");
return countryAwareFactory;
}
public final CountryAwareAttributeUpdater setCountryAwareAttributeService(final ICountryAwareAttributeService countryAwareAttributeService)
{
this.countryAwareAttributeService = countryAwareAttributeService;
return this;
}
private ICountryAwareAttributeService getCountryAwareAttributeService()
{
Check.assumeNotNull(countryAwareAttributeService, "countryAwareAttributeService not null");
return countryAwareAttributeService;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\CountryAwareAttributeUpdater.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return eventSubscriptionEntityManager;
}
public EventSubscriptionServiceConfiguration setEventSubscriptionEntityManager(EventSubscriptionEntityManager eventSubscriptionEntityManager) {
this.eventSubscriptionEntityManager = eventSubscriptionEntityManager;
return this;
}
@Override
public ObjectMapper getObjectMapper() {
return objectMapper;
}
@Override
public EventSubscriptionServiceConfiguration setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
return this;
} | public Duration getEventSubscriptionLockTime() {
return eventSubscriptionLockTime;
}
public EventSubscriptionServiceConfiguration setEventSubscriptionLockTime(Duration eventSubscriptionLockTime) {
this.eventSubscriptionLockTime = eventSubscriptionLockTime;
return this;
}
public String getLockOwner() {
return lockOwner;
}
public EventSubscriptionServiceConfiguration setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
return this;
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\EventSubscriptionServiceConfiguration.java | 2 |
请完成以下Java代码 | static SourceDocument toSourceDocumentOrNull(final Object obj)
{
if (obj == null)
{
return null;
}
if (obj instanceof SourceDocument)
{
return (SourceDocument)obj;
}
final PO po = getPO(obj);
return new POSourceDocument(po);
}
}
@AllArgsConstructor
private static final class POSourceDocument implements SourceDocument
{
@NonNull
private final PO po;
@Override
public boolean hasFieldValue(final String fieldName)
{
return po.get_ColumnIndex(fieldName) >= 0;
}
@Override
public Object getFieldValue(final String fieldName)
{
return po.get_Value(fieldName);
}
} | @AllArgsConstructor
private static final class GridTabSourceDocument implements SourceDocument
{
@NonNull
private final GridTab gridTab;
@Override
public boolean hasFieldValue(final String fieldName)
{
return gridTab.getField(fieldName) != null;
}
@Override
public Object getFieldValue(final String fieldName)
{
return gridTab.getValue(fieldName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\letters\model\MADBoilerPlate.java | 1 |
请完成以下Java代码 | private static Object extractValue(
@NonNull final SearchHit hit,
@NonNull final ESFieldName esFieldName,
@NonNull final FTSJoinColumn.ValueType valueType)
{
if (ESFieldName.ID.equals(esFieldName))
{
final String esDocumentId = hit.getId();
return convertValueToType(esDocumentId, valueType);
}
else
{
final Object value = hit.getSourceAsMap().get(esFieldName.getAsString());
return convertValueToType(value, valueType);
}
}
@Nullable
private static Object convertValueToType(@Nullable final Object valueObj, @NonNull final FTSJoinColumn.ValueType valueType)
{
if (valueObj == null)
{
return null;
}
if (valueType == FTSJoinColumn.ValueType.INTEGER)
{
return NumberUtils.asIntegerOrNull(valueObj);
} | else if (valueType == FTSJoinColumn.ValueType.STRING)
{
return valueObj.toString();
}
else
{
throw new AdempiereException("Cannot convert `" + valueObj + "` (" + valueObj.getClass() + ") to " + valueType);
}
}
private static String toJson(@NonNull final SearchHit hit)
{
return Strings.toString(hit, true, true);
}
public FTSConfig getConfigById(@NonNull final FTSConfigId ftsConfigId)
{
return ftsConfigService.getConfigById(ftsConfigId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\FTSSearchService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void importContracts(final BPartner bpartner, final List<SyncContract> syncContracts)
{
final Map<String, Contract> contracts = mapByUuid(contractsRepo.findByBpartnerAndDeletedFalse(bpartner));
final List<Entry<SyncContract, Contract>> contractsToImport = new ArrayList<>();
for (final SyncContract syncContract : syncContracts)
{
// If delete request, skip importing the contract.
// As a result, if there is a contract for this sync-contract, it will be deleted below.
if (syncContract.isDeleted())
{
continue;
}
final Contract contract = contracts.remove(syncContract.getUuid());
contractsToImport.add(Maps.immutableEntry(syncContract, contract));
}
//
// Delete contracts
for (final Contract contract : contracts.values())
{
try
{
contractsImportService.deleteContract(contract);
}
catch (final Exception ex)
{
logger.error("Failed deleting contract {}. Ignored.", contract, ex);
}
}
// | // Import contracts
for (final Entry<SyncContract, Contract> e : contractsToImport)
{
final SyncContract syncContract = e.getKey();
final Contract contract = e.getValue();
try
{
contractsImportService.importContract(bpartner, syncContract, contract);
}
catch (final Exception ex)
{
logger.error("Failed importing contract {} for {}. Skipped.", contract, bpartner, ex);
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\sync\SyncContractListImportService.java | 2 |
请完成以下Java代码 | public Builder withNewButton(final boolean withNewButton)
{
this.withNewButton = withNewButton;
return this;
}
public Builder withRefreshButton()
{
return withRefreshButton(true);
}
public Builder withRefreshButton(final boolean withRefreshButton)
{
this.withRefreshButton = withRefreshButton;
return this;
}
public Builder withResetButton(final boolean withResetButton)
{
this.withResetButton = withResetButton;
return this;
}
public Builder withCustomizeButton(final boolean withCustomizeButton)
{
this.withCustomizeButton = withCustomizeButton;
return this;
}
public Builder withHistoryButton(final boolean withHistoryButton)
{
this.withHistoryButton = withHistoryButton;
return this;
}
public Builder withZoomButton(final boolean withZoomButton)
{
this.withZoomButton = withZoomButton;
return this;
}
/**
* Advice builder to create the buttons with text on them.
*/
public Builder withText()
{ | return withText(true);
}
/**
* Advice builder to create the buttons without any text on them.
*
* NOTE: this is the default option anyway. You can call it just to explicitly state the obvious.
*/
public Builder withoutText()
{
return withText(false);
}
/**
* Advice builder to create the buttons with or without text on them.
*
* @param withText true if buttons shall have text on them
*/
public Builder withText(final boolean withText)
{
this.withText = withText;
return this;
}
public Builder withSmallButtons(final boolean withSmallButtons)
{
smallButtons = withSmallButtons;
return this;
}
}
} // ConfirmPanel | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\ConfirmPanel.java | 1 |
请完成以下Java代码 | public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
Assert.notNull(authenticationFailureHandler, "authenticationFailureHandler cannot be null");
this.authenticationFailureHandler = authenticationFailureHandler;
}
private void sendClientRegistrationResponse(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
OidcClientRegistration clientRegistration = ((OidcClientRegistrationAuthenticationToken) authentication)
.getClientRegistration();
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
if (HttpMethod.POST.name().equals(request.getMethod())) {
httpResponse.setStatusCode(HttpStatus.CREATED);
}
else {
httpResponse.setStatusCode(HttpStatus.OK);
}
this.clientRegistrationHttpMessageConverter.write(clientRegistration, null, httpResponse);
}
private void sendErrorResponse(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authenticationException) throws IOException { | OAuth2Error error = ((OAuth2AuthenticationException) authenticationException).getError();
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
if (OAuth2ErrorCodes.INVALID_TOKEN.equals(error.getErrorCode())) {
httpStatus = HttpStatus.UNAUTHORIZED;
}
else if (OAuth2ErrorCodes.INSUFFICIENT_SCOPE.equals(error.getErrorCode())) {
httpStatus = HttpStatus.FORBIDDEN;
}
else if (OAuth2ErrorCodes.INVALID_CLIENT.equals(error.getErrorCode())) {
httpStatus = HttpStatus.UNAUTHORIZED;
}
ServletServerHttpResponse httpResponse = new ServletServerHttpResponse(response);
httpResponse.setStatusCode(httpStatus);
this.errorHttpResponseConverter.write(error, null, httpResponse);
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\oidc\web\OidcClientRegistrationEndpointFilter.java | 1 |
请完成以下Java代码 | public ResponseEntity<PageResult<DictDto>> queryDict(DictQueryCriteria resources, Pageable pageable){
return new ResponseEntity<>(dictService.queryAll(resources,pageable),HttpStatus.OK);
}
@Log("新增字典")
@ApiOperation("新增字典")
@PostMapping
@PreAuthorize("@el.check('dict:add')")
public ResponseEntity<Object> createDict(@Validated @RequestBody Dict resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
dictService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改字典")
@ApiOperation("修改字典")
@PutMapping | @PreAuthorize("@el.check('dict:edit')")
public ResponseEntity<Object> updateDict(@Validated(Dict.Update.class) @RequestBody Dict resources){
dictService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除字典")
@ApiOperation("删除字典")
@DeleteMapping
@PreAuthorize("@el.check('dict:del')")
public ResponseEntity<Object> deleteDict(@RequestBody Set<Long> ids){
dictService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\DictController.java | 1 |
请完成以下Java代码 | public boolean equals(Address x, Address y) {
if (x == y) {
return true;
}
if (Objects.isNull(x) || Objects.isNull(y)) {
return false;
}
return x.equals(y);
}
@Override
public int hashCode(Address x) {
return x.hashCode();
}
@Override
public Address deepCopy(Address value) {
if (Objects.isNull(value)) {
return null;
}
Address newEmpAdd = new Address();
newEmpAdd.setAddressLine1(value.getAddressLine1());
newEmpAdd.setAddressLine2(value.getAddressLine2());
newEmpAdd.setCity(value.getCity());
newEmpAdd.setCountry(value.getCountry());
newEmpAdd.setZipCode(value.getZipCode());
return newEmpAdd;
} | @Override
public boolean isMutable() {
return true;
}
@Override
public Serializable disassemble(Address value) {
return (Serializable) deepCopy(value);
}
@Override
public Address assemble(Serializable cached, Object owner) {
return deepCopy((Address) cached);
}
@Override
public Address replace(Address detached, Address managed, Object owner) {
return detached;
}
@Override
public boolean isInstance(Object object) {
return CompositeUserType.super.isInstance(object);
}
@Override
public boolean isSameClass(Object object) {
return CompositeUserType.super.isSameClass(object);
}
} | repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\AddressType.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isInverse() {
return inverse;
}
public void setInverse(boolean inverse) {
this.inverse = inverse;
}
public List<String> getData() { | return data;
}
public void setData(List<String> data) {
this.data = data;
}
public YAxisLabel getAxisLabel() {
return axisLabel;
}
public void setAxisLabel(YAxisLabel axisLabel) {
this.axisLabel = axisLabel;
}
} | repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\YAxis.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AlarmsUnassignTaskProcessor extends HousekeeperTaskProcessor<AlarmsUnassignHousekeeperTask> {
private final TbAlarmService tbAlarmService;
private final AlarmService alarmService;
@Override
public void process(AlarmsUnassignHousekeeperTask task) throws Exception {
TenantId tenantId = task.getTenantId();
UserId userId = (UserId) task.getEntityId();
if (task.getAlarms() == null) {
AlarmId lastId = null;
long lastCreatedTime = 0;
while (true) {
List<TbPair<UUID, Long>> alarms = alarmService.findAlarmIdsByAssigneeId(tenantId, userId, lastCreatedTime, lastId, 64);
if (alarms.isEmpty()) {
break;
}
housekeeperClient.submitTask(new AlarmsUnassignHousekeeperTask(tenantId, userId, task.getUserTitle(), alarms.stream().map(TbPair::getFirst).toList()));
TbPair<UUID, Long> last = alarms.get(alarms.size() - 1); | lastId = new AlarmId(last.getFirst());
lastCreatedTime = last.getSecond();
log.debug("[{}][{}] Submitted task for unassigning {} alarms", tenantId, userId, alarms.size());
}
} else {
tbAlarmService.unassignDeletedUserAlarms(tenantId, userId, task.getUserTitle(), task.getAlarms(), task.getTs());
log.debug("[{}][{}] Unassigned {} alarms", tenantId, userId, task.getAlarms().size());
}
}
@Override
public HousekeeperTaskType getTaskType() {
return HousekeeperTaskType.UNASSIGN_ALARMS;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\housekeeper\processor\AlarmsUnassignTaskProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Duration step() {
return obtain(GangliaProperties::getStep, GangliaConfig.super::step);
}
@Override
public TimeUnit durationUnits() {
return obtain(GangliaProperties::getDurationUnits, GangliaConfig.super::durationUnits);
}
@Override
public GMetric.UDPAddressingMode addressingMode() {
return obtain(GangliaProperties::getAddressingMode, GangliaConfig.super::addressingMode);
}
@Override | public int ttl() {
return obtain(GangliaProperties::getTimeToLive, GangliaConfig.super::ttl);
}
@Override
public String host() {
return obtain(GangliaProperties::getHost, GangliaConfig.super::host);
}
@Override
public int port() {
return obtain(GangliaProperties::getPort, GangliaConfig.super::port);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\ganglia\GangliaPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public String getFeld() {
return feld;
}
/**
* Sets the value of the feld property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFeld(String value) {
this.feld = value;
}
/**
* Gets the value of the stackTrace property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getStackTrace() {
return stackTrace;
}
/**
* Sets the value of the stackTrace property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setStackTrace(String value) {
this.stackTrace = value;
} | /**
* Gets the value of the beschreibung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getBeschreibung() {
return beschreibung;
}
/**
* Sets the value of the beschreibung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setBeschreibung(String value) {
this.beschreibung = value;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Fehlerbehandlung.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.