instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Collection<Class<? extends SupplyRequiredDecreasedEvent>> getHandledEventType()
{
return ImmutableList.of(SupplyRequiredDecreasedEvent.class);
}
@Override
public void handleEvent(@NonNull final SupplyRequiredDecreasedEvent event)
{
final SupplyRequiredDescriptor descriptor = event.getSupplyRequiredDescriptor();
final MaterialPlanningContext context = helper.createContextOrNull(descriptor);
final MaterialDescriptor materialDescriptor = descriptor.getMaterialDescriptor();
Quantity remainingQtyToHandle = Quantitys.of(materialDescriptor.getQuantity(), ProductId.ofRepoId(materialDescriptor.getProductId()));
Loggables.withLogger(log, Level.DEBUG).addLog("Trying to decrease supply of {} by {}.", descriptor.getOrderId(), remainingQtyToHandle);
if (context != null)
{
for (final SupplyRequiredAdvisor advisor : supplyRequiredAdvisors)
{ | if (remainingQtyToHandle.signum() > 0)
{
remainingQtyToHandle = advisor.handleQuantityDecrease(event, remainingQtyToHandle);
}
}
}
if (remainingQtyToHandle.signum() > 0)
{
Loggables.withLogger(log, Level.WARN).addLog("Could not decrease the qty for event {}. Qty left: {}", event, remainingQtyToHandle);
SupplyRequiredDecreasedNotificationProducer.newInstance().sendNotification(context, descriptor, remainingQtyToHandle);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\event\SupplyRequiredDecreasedHandler.java | 1 |
请完成以下Java代码 | public AttributeId retrieveInAusLandAttributeId(final int adClientId, final int adOrgId)
{
final int inAusAttributeId = Services.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_InAusLandAttribute,
-1, // defaultValue
adClientId,
adOrgId);
return AttributeId.ofRepoIdOrNull(inAusAttributeId);
}
@Override
public AttributeListValue retrieveInAusLandAttributeValue(final Properties ctx, final String inAusLand)
{
final I_M_Attribute inAusLandAttribute = retrieveInAusLandAttribute(ctx);
if (inAusLandAttribute == null)
{
return null;
}
return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(inAusLandAttribute, inAusLand);
} | @Override
public I_M_Attribute retrieveInAusLandAttribute(final Properties ctx)
{
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx);
final AttributeId inAusLandAttributeId = retrieveInAusLandAttributeId(adClientId, adOrgId);
if (inAusLandAttributeId == null)
{
return null;
}
return Services.get(IAttributeDAO.class).getAttributeRecordById(inAusLandAttributeId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InAusLandAttributeDAO.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Notice.
@param Notice
Contains last write notice
*/
public void setNotice (String Notice)
{
set_Value (COLUMNNAME_Notice, Notice);
}
/** Get Notice.
@return Contains last write notice
*/
public String getNotice ()
{
return (String)get_Value(COLUMNNAME_Notice);
}
/** Set Priority.
@param Priority
Indicates if this request is of a high, medium or low priority.
*/
public void setPriority (int Priority)
{
set_Value (COLUMNNAME_Priority, Integer.valueOf(Priority));
}
/** Get Priority.
@return Indicates if this request is of a high, medium or low priority.
*/
public int getPriority ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Priority);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set Relative URL.
@param RelativeURL
Contains the relative URL for the container
*/
public void setRelativeURL (String RelativeURL)
{
set_Value (COLUMNNAME_RelativeURL, RelativeURL);
}
/** Get Relative URL.
@return Contains the relative URL for the container
*/
public String getRelativeURL ()
{
return (String)get_Value(COLUMNNAME_RelativeURL);
}
/** Set StructureXML.
@param StructureXML
Autogenerated Containerdefinition as XML Code
*/
public void setStructureXML (String StructureXML)
{
set_Value (COLUMNNAME_StructureXML, StructureXML);
}
/** Get StructureXML.
@return Autogenerated Containerdefinition as XML Code
*/
public String getStructureXML ()
{
return (String)get_Value(COLUMNNAME_StructureXML);
}
/** Set Title.
@param Title
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public R save(@Valid @RequestBody Region region) {
return R.status(regionService.save(region));
}
/**
* 修改 行政区划表
*/
@PostMapping("/update")
@ApiOperationSupport(order = 6)
@Operation(summary = "修改", description = "传入region")
public R update(@Valid @RequestBody Region region) {
return R.status(regionService.updateById(region));
}
/**
* 新增或修改 行政区划表
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 7)
@Operation(summary = "新增或修改", description = "传入region")
public R submit(@Valid @RequestBody Region region) {
return R.status(regionService.submit(region));
} | /**
* 删除 行政区划表
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 8)
@Operation(summary = "删除", description = "传入主键")
public R remove(@Parameter(description = "主键", required = true) @RequestParam String id) {
return R.status(regionService.removeRegion(id));
}
/**
* 行政区划下拉数据源
*/
@GetMapping("/select")
@ApiOperationSupport(order = 9)
@Operation(summary = "下拉数据源", description = "传入tenant")
public R<List<Region>> select(@RequestParam(required = false, defaultValue = "00") String code) {
List<Region> list = regionService.list(Wrappers.<Region>query().lambda().eq(Region::getParentCode, code));
return R.data(list);
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\RegionController.java | 2 |
请完成以下Java代码 | private void listTaskVariables(Task task) {
logger.info(">>> Task variables:");
taskRuntime
.variables(TaskPayloadBuilder.variables().withTaskId(task.getId()).build())
.forEach(variableInstance ->
logger.info("\t> " + variableInstance.getName() + " -> " + variableInstance.getValue())
);
}
private void listProcessVariables(ProcessInstance processInstance) {
logger.info(">>> Process variables:");
List<VariableInstance> variables = processRuntime.variables(
ProcessPayloadBuilder.variables().withProcessInstance(processInstance).build()
);
variables.forEach(variableInstance ->
logger.info("\t> " + variableInstance.getName() + " -> " + variableInstance.getValue())
);
}
private ProcessInstance startProcess() {
ProcessInstance processInstance = processRuntime.start(
ProcessPayloadBuilder.start()
.withProcessDefinitionKey("RankMovieId")
.withName("myProcess")
.withVariable("movieToRank", "Lord of the rings")
.build()
);
logger.info(">>> Created Process Instance: " + processInstance);
return processInstance;
}
private void listAvailableProcesses() {
Page<ProcessDefinition> processDefinitionPage = processRuntime.processDefinitions(Pageable.of(0, 10));
logger.info("> Available Process definitions: " + processDefinitionPage.getTotalItems());
for (ProcessDefinition pd : processDefinitionPage.getContent()) {
logger.info("\t > Process definition: " + pd);
}
} | @Bean("Movies.getMovieDesc")
public Connector getMovieDesc() {
return getConnector();
}
@Bean("MoviesWithUUIDs.getMovieDesc")
public Connector getMovieDescUUIDs() {
return getConnector();
}
private Connector getConnector() {
return integrationContext -> {
Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
logger.info(">>inbound: " + inBoundVariables);
integrationContext.addOutBoundVariable(
"movieDescription",
"The Lord of the Rings is an epic high fantasy novel written by English author and scholar J. R. R. Tolkien"
);
return integrationContext;
};
}
@Bean
public VariableEventListener<VariableCreatedEvent> variableCreatedEventListener() {
return variableCreatedEvent -> variableCreatedEvents.add(variableCreatedEvent);
}
@Bean
public ProcessRuntimeEventListener<ProcessCompletedEvent> processCompletedEventListener() {
return processCompletedEvent -> processCompletedEvents.add(processCompletedEvent);
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplication.java | 1 |
请完成以下Java代码 | public class RequestInfo {
private final String appId;
private final String url;
private final String queryString;
private final String body;
private final String encoding;
private final String method;
private final Map<String, String> cookies;
private final String contentType;
private final Map<String, List<String>> headers;
private final String protocol;
private final String remoteInfo;
@JsonCreator
public RequestInfo(@JsonProperty("appId") String appId,
@JsonProperty("url") String url,
@JsonProperty("queryString") String queryString,
@JsonProperty("body") String body,
@JsonProperty("encoding") String encoding,
@JsonProperty("method") String method,
@JsonProperty("cookies") Map<String, String> cookies,
@JsonProperty("contentType") String contentType,
@JsonProperty("headers") Map<String, List<String>> headers,
@JsonProperty("protocol") String protocol,
@JsonProperty("remoteInfo") String remoteInfo) {
this.appId = appId;
this.url = url;
this.queryString = queryString;
this.body = body;
this.encoding = encoding;
this.method = method;
this.cookies = cookies;
this.contentType = contentType;
this.headers = headers;
this.protocol = protocol;
this.remoteInfo = remoteInfo;
}
public String getAppId() {
return appId;
}
public String getUrl() {
return url;
}
public String getQueryString() { | return queryString;
}
public String getBody() {
return body;
}
public String getEncoding() {
return encoding;
}
public String getMethod() {
return method;
}
public Map<String, String> getCookies() {
return cookies;
}
public String getContentType() {
return contentType;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public String getProtocol() {
return protocol;
}
public String getRemoteInfo() {
return remoteInfo;
}
} | repos\spring-examples-java-17\spring-demo\src\main\java\itx\examples\springboot\demo\dto\RequestInfo.java | 1 |
请完成以下Java代码 | protected BigInteger coerceToBigInteger(Object value) {
if (value instanceof BigInteger) {
return (BigInteger)value;
}
else if (value instanceof BigDecimal) {
return ((BigDecimal)value).toBigInteger();
}
else if (value instanceof Number) {
return BigInteger.valueOf(((Number)value).longValue());
}
else {
throw LOG.unableToConvertValue(value, BigInteger.class);
}
}
@Override
protected Double coerceToDouble(Object value) {
if (value instanceof Double) {
return (Double)value;
}
else if (value instanceof Number) {
return ((Number) value).doubleValue();
}
else {
throw LOG.unableToConvertValue(value, Double.class);
}
}
@Override
protected Long coerceToLong(Object value) {
if (value instanceof Long) {
return (Long)value;
}
else if (value instanceof Number && isLong((Number) value)) {
return ((Number) value).longValue();
}
else {
throw LOG.unableToConvertValue(value, Long.class);
} | }
@Override
protected String coerceToString(Object value) {
if (value instanceof String) {
return (String)value;
}
else if (value instanceof Enum<?>) {
return ((Enum<?>)value).name();
}
else {
throw LOG.unableToConvertValue(value, String.class);
}
}
@Override
public <T> T convert(Object value, Class<T> type) throws ELException {
try {
return super.convert(value, type);
}
catch (ELException e) {
throw LOG.unableToConvertValue(value, type, e);
}
}
protected boolean isLong(Number value) {
double doubleValue = value.doubleValue();
return doubleValue == (long) doubleValue;
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\el\FeelTypeConverter.java | 1 |
请完成以下Java代码 | public AsyncExecutor getAsyncExecutor() {
return asyncExecutor;
}
public ProcessEngineConfiguration setAsyncExecutor(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
return this;
}
public int getLockTimeAsyncJobWaitTime() {
return lockTimeAsyncJobWaitTime;
}
public ProcessEngineConfiguration setLockTimeAsyncJobWaitTime(int lockTimeAsyncJobWaitTime) {
this.lockTimeAsyncJobWaitTime = lockTimeAsyncJobWaitTime;
return this;
}
public int getDefaultFailedJobWaitTime() {
return defaultFailedJobWaitTime;
}
public ProcessEngineConfiguration setDefaultFailedJobWaitTime(int defaultFailedJobWaitTime) {
this.defaultFailedJobWaitTime = defaultFailedJobWaitTime;
return this;
}
public int getAsyncFailedJobWaitTime() {
return asyncFailedJobWaitTime;
}
public ProcessEngineConfiguration setAsyncFailedJobWaitTime(int asyncFailedJobWaitTime) {
this.asyncFailedJobWaitTime = asyncFailedJobWaitTime; | return this;
}
public boolean isEnableProcessDefinitionInfoCache() {
return enableProcessDefinitionInfoCache;
}
public ProcessEngineConfiguration setEnableProcessDefinitionInfoCache(boolean enableProcessDefinitionInfoCache) {
this.enableProcessDefinitionInfoCache = enableProcessDefinitionInfoCache;
return this;
}
public ProcessEngineConfiguration setCopyVariablesToLocalForTasks(boolean copyVariablesToLocalForTasks) {
this.copyVariablesToLocalForTasks = copyVariablesToLocalForTasks;
return this;
}
public boolean isCopyVariablesToLocalForTasks() {
return copyVariablesToLocalForTasks;
}
public void setEngineAgendaFactory(ActivitiEngineAgendaFactory engineAgendaFactory) {
this.engineAgendaFactory = engineAgendaFactory;
}
public ActivitiEngineAgendaFactory getEngineAgendaFactory() {
return engineAgendaFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\ProcessEngineConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String[] selectImports(AnnotationMetadata importMetadata) {
if (!importMetadata.hasAnnotation(EnableReactiveMethodSecurity.class.getName())) {
return new String[0];
}
EnableReactiveMethodSecurity annotation = importMetadata.getAnnotations()
.get(EnableReactiveMethodSecurity.class)
.synthesize();
List<String> imports = new ArrayList<>(Arrays.asList(this.autoProxy.selectImports(importMetadata)));
if (annotation.useAuthorizationManager()) {
imports.add(ReactiveAuthorizationManagerMethodSecurityConfiguration.class.getName());
}
else {
imports.add(ReactiveMethodSecurityConfiguration.class.getName());
}
if (isDataPresent) {
imports.add(AuthorizationProxyDataConfiguration.class.getName());
}
if (isObservabilityPresent) {
imports.add(ReactiveMethodObservationConfiguration.class.getName());
} | imports.add(AuthorizationProxyConfiguration.class.getName());
return imports.toArray(new String[0]);
}
private static final class AutoProxyRegistrarSelector
extends AdviceModeImportSelector<EnableReactiveMethodSecurity> {
private static final String[] IMPORTS = new String[] { AutoProxyRegistrar.class.getName(),
MethodSecurityAdvisorRegistrar.class.getName() };
@Override
protected String[] selectImports(@NonNull AdviceMode adviceMode) {
if (adviceMode == AdviceMode.PROXY) {
return IMPORTS;
}
throw new IllegalStateException("AdviceMode " + adviceMode + " is not supported");
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\ReactiveMethodSecuritySelector.java | 2 |
请完成以下Spring Boot application配置 | server.port=9090
server.servlet.contextPath=/springbootapp
management.server.port=8081
management.server.address=127.0.0.1
#debug=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto = update
management.endpoints.jmx.domain=Spring Sample Application
spring.jmx.unique-names=true
management.endpoints.web.exposure.include=*
management.endpoint.shutdown.enabled=true
##jolokia.config.debug=true
##endpoints.jolokia.enabled=true
##endpoints.jolokia.path=jolokia
spring.jmx.enabled=true
## for pretty printing of jso | n when endpoints accessed over HTTP
http.mappers.jsonPrettyPrint=true
logging.level.org.springframework=INFO
#Servlet Configuration
servlet.name=dispatcherExample
servlet.mapping=/dispatcherExampleURL
contactInfoType=email | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-4\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public I_AD_User getFrom()
{
return from;
}
/**
* @return <code>null</code>
*/
@Override
public String getMessage()
{
return MESSAGE;
}
/**
* @return the title of the process
*/
@Override
public String getSubject()
{
return subject;
}
/** | * @return the title of the process
*/
@Override
public String getTitle()
{
return title;
}
@Override
public String getTo()
{
return to;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public int getSUMUP_LastSync_Error_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_LastSync_Error_ID);
}
/**
* SUMUP_LastSync_Status AD_Reference_ID=541901
* Reference name: SUMUP_LastSync_Status
*/
public static final int SUMUP_LASTSYNC_STATUS_AD_Reference_ID=541901;
/** OK = OK */
public static final String SUMUP_LASTSYNC_STATUS_OK = "OK";
/** Error = ERR */
public static final String SUMUP_LASTSYNC_STATUS_Error = "ERR";
@Override
public void setSUMUP_LastSync_Status (final @Nullable java.lang.String SUMUP_LastSync_Status)
{
set_Value (COLUMNNAME_SUMUP_LastSync_Status, SUMUP_LastSync_Status);
}
@Override
public java.lang.String getSUMUP_LastSync_Status()
{
return get_ValueAsString(COLUMNNAME_SUMUP_LastSync_Status);
}
@Override
public void setSUMUP_LastSync_Timestamp (final @Nullable java.sql.Timestamp SUMUP_LastSync_Timestamp)
{
set_Value (COLUMNNAME_SUMUP_LastSync_Timestamp, SUMUP_LastSync_Timestamp);
}
@Override
public java.sql.Timestamp getSUMUP_LastSync_Timestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_SUMUP_LastSync_Timestamp);
}
@Override
public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code() | {
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
@Override
public void setSUMUP_Transaction_ID (final int SUMUP_Transaction_ID)
{
if (SUMUP_Transaction_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Transaction_ID, SUMUP_Transaction_ID);
}
@Override
public int getSUMUP_Transaction_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Transaction_ID);
}
@Override
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Transaction.java | 2 |
请完成以下Java代码 | public static WebApplicationType deduce() {
for (Deducer deducer : SpringFactoriesLoader.forDefaultResourceLocation().load(Deducer.class)) {
WebApplicationType deduced = deducer.deduceWebApplicationType();
if (deduced != null) {
return deduced;
}
}
return isServletApplication() ? WebApplicationType.SERVLET : WebApplicationType.NONE;
}
private static boolean isServletApplication() {
for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) {
if (!ClassUtils.isPresent(servletIndicatorClass, null)) {
return false;
}
}
return true;
}
static class WebApplicationTypeRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) {
registerTypeIfPresent(servletIndicatorClass, classLoader, hints);
}
}
private void registerTypeIfPresent(String typeName, @Nullable ClassLoader classLoader, RuntimeHints hints) {
if (ClassUtils.isPresent(typeName, classLoader)) {
hints.reflection().registerType(TypeReference.of(typeName));
}
} | }
/**
* Strategy that may be implemented by a module that can deduce the
* {@link WebApplicationType}.
*
* @since 4.0.1
*/
@FunctionalInterface
public interface Deducer {
/**
* Deduce the web application type.
* @return the deduced web application type or {@code null}
*/
@Nullable WebApplicationType deduceWebApplicationType();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\WebApplicationType.java | 1 |
请完成以下Java代码 | public void setC_Cycle_ID (int C_Cycle_ID)
{
if (C_Cycle_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID));
}
/** Get Project Cycle.
@return Identifier for this Project Reporting Cycle
*/
public int getC_Cycle_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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_C_Cycle.java | 1 |
请完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
try {
String value = metadata.getAnnotations().get(ConditionalOnPropertyExists.class).getString("value");
String property = context.getEnvironment().getProperty(value);
if (!StringUtils.hasText(property)) {
return ConditionOutcome.noMatch(value + " property is not set or is empty.");
}
return ConditionOutcome.match(value + " property is not empty.");
}
catch (NoSuchElementException e) {
return ConditionOutcome.noMatch("Missing required property 'value' of @ConditionalOnPropertyExists");
}
}
} | @Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@Conditional(OnPropertyExistsCondition.class)
@interface ConditionalOnPropertyExists {
/**
* @return the property
*/
String value();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\TrustedProxies.java | 1 |
请完成以下Java代码 | public void setPriority (int Priority)
{
set_Value (COLUMNNAME_Priority, Integer.valueOf(Priority));
}
/** Get Priority.
@return Indicates if this request is of a high, medium or low priority.
*/
public int getPriority ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Priority);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Relative URL.
@param RelativeURL
Contains the relative URL for the container
*/
public void setRelativeURL (String RelativeURL)
{
set_Value (COLUMNNAME_RelativeURL, RelativeURL);
}
/** Get Relative URL.
@return Contains the relative URL for the container
*/
public String getRelativeURL ()
{ | return (String)get_Value(COLUMNNAME_RelativeURL);
}
/** Set StructureXML.
@param StructureXML
Autogenerated Containerdefinition as XML Code
*/
public void setStructureXML (String StructureXML)
{
set_Value (COLUMNNAME_StructureXML, StructureXML);
}
/** Get StructureXML.
@return Autogenerated Containerdefinition as XML Code
*/
public String getStructureXML ()
{
return (String)get_Value(COLUMNNAME_StructureXML);
}
/** Set Title.
@param Title
Name this entity is referred to as
*/
public void setTitle (String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
/** Get Title.
@return Name this entity is referred to as
*/
public String getTitle ()
{
return (String)get_Value(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_CStage.java | 1 |
请完成以下Java代码 | protected String getContentType(String file) {
if (file.endsWith(".js")) {
return MIME_TYPE_TEXT_JAVASCRIPT;
} else
if (file.endsWith(".html")) {
return MIME_TYPE_TEXT_HTML;
} else
if (file.endsWith(".css")) {
return MIME_TYPE_TEXT_CSS;
} else {
return MIME_TYPE_TEXT_PLAIN;
}
}
/**
* Returns an input stream for a given resource
*
* @param resourceName
* @return
*/
protected InputStream getPluginAssetAsStream(AppPlugin plugin, String fileName) {
String assetDirectory = plugin.getAssetDirectory();
if (assetDirectory == null) {
return null;
}
InputStream result = getWebResourceAsStream(assetDirectory, fileName); | if (result == null) {
result = getClasspathResourceAsStream(plugin, assetDirectory, fileName);
}
return result;
}
protected InputStream getWebResourceAsStream(String assetDirectory, String fileName) {
String resourceName = String.format("/%s/%s", assetDirectory, fileName);
return servletContext.getResourceAsStream(resourceName);
}
protected InputStream getClasspathResourceAsStream(AppPlugin plugin, String assetDirectory, String fileName) {
String resourceName = String.format("%s/%s", assetDirectory, fileName);
return plugin.getClass().getClassLoader().getResourceAsStream(resourceName);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\plugin\resource\AbstractAppPluginRootResource.java | 1 |
请完成以下Java代码 | public void createSummaryForOrderLine(@NonNull final I_C_OrderLine ol, @NonNull final I_C_Flatrate_Term flatrateTerm)
{
final OrderId orderId = OrderId.ofRepoId(ol.getC_Order_ID());
final I_C_Order order = orderBL.getById(orderId);
final CallOrderSummaryData callOrderSummaryData = CallOrderSummaryData.builder()
.orderId(orderId)
.orderLineId(OrderLineId.ofRepoId(ol.getC_OrderLine_ID()))
.productId(ProductId.ofRepoId(ol.getM_Product_ID()))
.uomId(UomId.ofRepoId(ol.getC_UOM_ID()))
.qtyEntered(ol.getQtyEntered())
.flatrateTermId(FlatrateTermId.ofRepoId(flatrateTerm.getC_Flatrate_Term_ID()))
.soTrx(SOTrx.ofBoolean(order.isSOTrx()))
.attributeSetInstanceId(AttributeSetInstanceId.ofRepoIdOrNull(ol.getM_AttributeSetInstance_ID()))
.build();
summaryRepo.create(callOrderSummaryData);
}
public void addQtyDelivered(@NonNull final CallOrderSummaryId callOrderSummaryId, @NonNull final Quantity deltaQtyDelivered)
{
final CallOrderSummary callOrderSummary = summaryRepo.getById(callOrderSummaryId);
final CallOrderSummaryData summaryData = callOrderSummary.getSummaryData();
final Quantity currentQtyDelivered = Quantitys.of(summaryData.getQtyDelivered(), summaryData.getUomId());
final Quantity sum = conversionBL.computeSum( | UOMConversionContext.of(callOrderSummary.getSummaryData().getProductId()),
ImmutableList.of(currentQtyDelivered, deltaQtyDelivered),
currentQtyDelivered.getUomId());
final BigDecimal newQtyDelivered = sum.toBigDecimal();
summaryRepo.update(callOrderSummary.withSummaryData(summaryData.withQtyDelivered(newQtyDelivered)));
}
public void addQtyInvoiced(@NonNull final CallOrderSummaryId callOrderSummaryId, @NonNull final Quantity deltaQtyInvoiced)
{
final CallOrderSummary callOrderSummary = summaryRepo.getById(callOrderSummaryId);
final CallOrderSummaryData summaryData = callOrderSummary.getSummaryData();
final Quantity currentQtyInvoiced = Quantitys.of(summaryData.getQtyInvoiced(), summaryData.getUomId());
final Quantity sum = conversionBL.computeSum(
UOMConversionContext.of(callOrderSummary.getSummaryData().getProductId()),
ImmutableList.of(currentQtyInvoiced, deltaQtyInvoiced),
currentQtyInvoiced.getUomId());
final BigDecimal newQtyInvoiced = sum.toBigDecimal();
summaryRepo.update(callOrderSummary.withSummaryData(summaryData.withQtyInvoiced(newQtyInvoiced)));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\summary\CallOrderSummaryService.java | 1 |
请完成以下Java代码 | public static class EventLogEntryRequestBuilder
{
public EventLogEntryRequestBuilder formattedMessage(
@NonNull final String message,
@Nullable final Object... params)
{
message(StringUtils.formatMessage(message, params));
return this;
}
}
}
/**
* Creates a builder to log a message to the current event processing log.
* <p>
* Note: as your current code was most probably invoked via {@link #invokeHandlerAndLog(InvokeHandlerAndLogRequest)},
* it might be more convenient to use {@link Loggables#get()}.
*
* @param handlerClass the class to be logged in the record.
*/
private EventLogEntryRequest.EventLogEntryRequestBuilder newLogEntry(@NonNull final Class<?> handlerClass)
{
return EventLogEntryRequest.builder()
.eventHandlerClass(handlerClass);
}
/**
* Creates a builder to log a an error to the current event processing log.
* <p>
* Note: as your current code was most probably invoked via {@link #invokeHandlerAndLog(InvokeHandlerAndLogRequest)},
* it might be more convenient just throw a runtime exception.
*
* @param handlerClass the class to be logged in the record.
*/
public EventLogEntryRequest.EventLogEntryRequestBuilder newErrorLogEntry(
@NonNull final Class<?> handlerClass,
@NonNull final Exception e)
{
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e);
return EventLogEntryRequest.builder()
.error(true)
.eventHandlerClass(handlerClass)
.message(e.getMessage())
.adIssueId(issueId);
}
@Value
@Builder
public static class InvokeHandlerAndLogRequest
{
@NonNull
Class<?> handlerClass;
@NonNull
Runnable invokaction;
@Default
boolean onlyIfNotAlreadyProcessed = true;
}
/**
* Invokes the given {@code request}'s runnable and sets up a threadlocal {@link ILoggable}. | */
public void invokeHandlerAndLog(@NonNull final InvokeHandlerAndLogRequest request)
{
if (request.isOnlyIfNotAlreadyProcessed()
&& wasEventProcessedByHandler(request.getHandlerClass()))
{
return;
}
try (final IAutoCloseable loggable = EventLogLoggable.createAndRegisterThreadLocal(request.getHandlerClass()))
{
request.getInvokaction().run();
newLogEntry(request.getHandlerClass())
.formattedMessage("this handler is done")
.processed(true)
.createAndStore();
}
catch (final RuntimeException e)
{
// e.printStackTrace();
newErrorLogEntry(
request.getHandlerClass(), e)
.createAndStore();
}
}
private boolean wasEventProcessedByHandler(@NonNull final Class<?> handlerClass)
{
final EventLogEntryCollector eventLogCollector = EventLogEntryCollector.getThreadLocal();
final Collection<String> processedByHandlerClassNames = eventLogCollector.getEvent()
.getProperty(PROPERTY_PROCESSED_BY_HANDLER_CLASS_NAMES);
return processedByHandlerClassNames != null
&& processedByHandlerClassNames.contains(handlerClass.getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogUserService.java | 1 |
请完成以下Java代码 | public boolean isInternal() {
return this.internal;
}
/**
* Return a camel cased representation of this instance.
* @return the property in camel case format
*/
public String toCamelCaseFormat() {
String[] tokens = this.property.split("[-.]");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < tokens.length; i++) {
String part = tokens[i];
if (i > 0) {
part = StringUtils.capitalize(part);
}
sb.append(part);
}
return sb.toString();
}
public String toStandardFormat() {
return this.property;
}
private static String validateFormat(String property) {
for (char c : property.toCharArray()) {
if (Character.isUpperCase(c)) {
throw new IllegalArgumentException("Invalid property '" + property + "', must not contain upper case");
}
if (!Character.isLetterOrDigit(c) && !SUPPORTED_CHARS.contains(c)) {
throw new IllegalArgumentException("Unsupported character '" + c + "' for '" + property + "'");
}
}
return property; | }
@Override
public int compareTo(VersionProperty o) {
return this.property.compareTo(o.property);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
VersionProperty that = (VersionProperty) o;
return this.internal == that.internal && this.property.equals(that.property);
}
@Override
public int hashCode() {
return Objects.hash(this.property, this.internal);
}
@Override
public String toString() {
return this.property;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionProperty.java | 1 |
请完成以下Java代码 | public class SendTaskXMLConverter extends BaseBpmnXMLConverter {
public Class<? extends BaseElement> getBpmnElementType() {
return SendTask.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TASK_SEND;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
SendTask sendTask = new SendTask();
BpmnXMLUtil.addXMLLocation(sendTask, xtr);
sendTask.setType(xtr.getAttributeValue(ACTIVITI_EXTENSIONS_NAMESPACE, ATTRIBUTE_TYPE));
if ("##WebService".equals(xtr.getAttributeValue(null, ATTRIBUTE_TASK_IMPLEMENTATION))) {
sendTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE);
sendTask.setOperationRef(
parseOperationRef(xtr.getAttributeValue(null, ATTRIBUTE_TASK_OPERATION_REF), model)
);
}
parseChildElements(getXMLElementName(), sendTask, model, xtr);
return sendTask;
}
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
SendTask sendTask = (SendTask) element;
if (StringUtils.isNotEmpty(sendTask.getType())) {
writeQualifiedAttribute(ATTRIBUTE_TYPE, sendTask.getType(), xtw);
}
}
@Override
protected boolean writeExtensionChildElements(
BaseElement element,
boolean didWriteExtensionStartElement,
XMLStreamWriter xtw
) throws Exception { | SendTask sendTask = (SendTask) element;
didWriteExtensionStartElement = FieldExtensionExport.writeFieldExtensions(
sendTask.getFieldExtensions(),
didWriteExtensionStartElement,
xtw
);
return didWriteExtensionStartElement;
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {}
protected String parseOperationRef(String operationRef, BpmnModel model) {
String result = null;
if (StringUtils.isNotEmpty(operationRef)) {
int indexOfP = operationRef.indexOf(':');
if (indexOfP != -1) {
String prefix = operationRef.substring(0, indexOfP);
String resolvedNamespace = model.getNamespace(prefix);
result = resolvedNamespace + ":" + operationRef.substring(indexOfP + 1);
} else {
result = model.getTargetNamespace() + ":" + operationRef;
}
}
return result;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\SendTaskXMLConverter.java | 1 |
请完成以下Java代码 | public void updateSuspensionState(JobSuspensionStateDto dto) {
dto.setJobId(jobId);
dto.updateSuspensionState(engine);
}
@Override
public void setJobPriority(PriorityDto dto) {
if (dto.getPriority() == null) {
throw new RestException(Status.BAD_REQUEST, "Priority for job '" + jobId + "' cannot be null.");
}
try {
ManagementService managementService = engine.getManagementService();
managementService.setJobPriority(jobId, dto.getPriority());
} catch (AuthorizationException e) {
throw e;
} catch (NotFoundException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); | }
}
public void deleteJob() {
try {
engine.getManagementService()
.deleteJob(jobId);
} catch (AuthorizationException e) {
throw e;
} catch (NullValueException e) {
throw new InvalidRequestException(Status.NOT_FOUND, e.getMessage());
} catch (ProcessEngineException e) {
throw new RestException(Status.INTERNAL_SERVER_ERROR, e.getMessage());
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\runtime\impl\JobResourceImpl.java | 1 |
请完成以下Java代码 | Integer get(String key)
{
return d.get(key);
}
public int get(char[]... keyArray)
{
Integer f = get(convert(keyArray));
if (f == null) return 0;
return f;
}
public int get(char... key)
{
Integer f = d.get(key);
if (f == null) return 0;
return f;
}
public double freq(String key)
{
Integer f = get(key);
if (f == null) f = 0;
return f / (double) total;
}
public double freq(char[]... keyArray)
{
return freq(convert(keyArray));
}
public double freq(char... keyArray)
{
Integer f = d.get(keyArray);
if (f == null) f = 0;
return f / (double) total;
}
public Set<String> samples()
{
return d.keySet();
}
void add(String key, int value)
{
Integer f = get(key);
if (f == null) f = 0;
f += value;
d.put(key, f);
total += value;
}
void add(int value, char... key)
{
Integer f = d.get(key);
if (f == null) f = 0;
f += value;
d.put(key, f);
total += value;
}
public void add(int value, char[]... keyArray) | {
add(convert(keyArray), value);
}
public void add(int value, Collection<char[]> keyArray)
{
add(convert(keyArray), value);
}
private String convert(Collection<char[]> keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.size() * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
static private String convert(char[]... keyArray)
{
StringBuilder sbKey = new StringBuilder(keyArray.length * 2);
for (char[] key : keyArray)
{
sbKey.append(key[0]);
sbKey.append(key[1]);
}
return sbKey.toString();
}
@Override
public void save(DataOutputStream out) throws Exception
{
out.writeInt(total);
Integer[] valueArray = d.getValueArray(new Integer[0]);
out.writeInt(valueArray.length);
for (Integer v : valueArray)
{
out.writeInt(v);
}
d.save(out);
}
@Override
public boolean load(ByteArray byteArray)
{
total = byteArray.nextInt();
int size = byteArray.nextInt();
Integer[] valueArray = new Integer[size];
for (int i = 0; i < valueArray.length; ++i)
{
valueArray[i] = byteArray.nextInt();
}
d.load(byteArray, valueArray);
return true;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\trigram\frequency\Probability.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class MessageMatcherFactoryBean implements FactoryBean<MessageMatcher<?>>, ApplicationContextAware {
private PathPatternMessageMatcher.Builder builder;
private final SimpMessageType method;
private final String path;
public MessageMatcherFactoryBean(String path) {
this(path, null);
}
public MessageMatcherFactoryBean(String path, SimpMessageType method) {
this.method = method;
this.path = path;
}
@Override | public MessageMatcher<?> getObject() throws Exception {
return this.builder.matcher(this.method, this.path);
}
@Override
public Class<?> getObjectType() {
return null;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.builder = context.getBean(PathPatternMessageMatcher.Builder.class);
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\MessageMatcherFactoryBean.java | 2 |
请完成以下Java代码 | public String toString()
{
return "QueryOrderBy[" + items + "]";
}
@Override
public String getSql()
{
if (sqlOrderByCompiled)
{
return sqlOrderBy;
}
if (items != null && !items.isEmpty())
{
final StringBuilder sqlBuf = new StringBuilder();
for (final QueryOrderByItem item : items)
{
appendSql(sqlBuf, item);
}
sqlOrderBy = sqlBuf.toString();
}
else
{
sqlOrderBy = null;
}
sqlOrderByCompiled = true;
return sqlOrderBy;
}
// NOTE: not static just because we want to build nice exceptions
private void appendSql(final StringBuilder sql, final QueryOrderByItem item)
{
if (sql.length() > 0)
{
sql.append(", ");
}
//
// ColumnName
sql.append(item.getColumnName());
//
// Direction ASC/DESC
final Direction direction = item.getDirection();
if (direction == Direction.Ascending)
{
sql.append(" ASC");
}
else if (direction == Direction.Descending)
{
sql.append(" DESC");
}
else
{
throw new IllegalStateException("Unknown direction '" + direction + "' for " + this);
}
//
// Nulls First/Last
final Nulls nulls = item.getNulls();
if (nulls == Nulls.First)
{
sql.append(" NULLS FIRST");
}
else if (nulls == Nulls.Last)
{
sql.append(" NULLS LAST");
}
else
{
throw new IllegalStateException("Unknown NULLS option '" + nulls + "' for " + this);
}
}
@Override | public Comparator<Object> getComparator()
{
if (comparator != null)
{
return comparator;
}
if (items != null && !items.isEmpty())
{
final ComparatorChain<Object> cmpChain = new ComparatorChain<>();
for (final QueryOrderByItem item : items)
{
@SuppressWarnings("rawtypes")
final ModelAccessor<Comparable> accessor = new ModelAccessor<>(item.getColumnName());
final boolean reverse = item.getDirection() == Direction.Descending;
final Comparator<Object> cmpDirection = new AccessorComparator<>(
ComparableComparatorNullsEqual.getInstance(),
accessor);
cmpChain.addComparator(cmpDirection, reverse);
final boolean nullsFirst = item.getNulls() == Nulls.First;
final Comparator<Object> cmpNulls = new AccessorComparator<>(
ComparableComparator.getInstance(nullsFirst),
accessor);
cmpChain.addComparator(cmpNulls);
}
comparator = cmpChain;
}
else
{
comparator = NullComparator.getInstance();
}
return comparator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryOrderBy.java | 1 |
请完成以下Java代码 | public void setM_PropertiesConfig_Line_ID (int M_PropertiesConfig_Line_ID)
{
if (M_PropertiesConfig_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_PropertiesConfig_Line_ID, Integer.valueOf(M_PropertiesConfig_Line_ID));
}
/** Get Properties Configuration Line.
@return Properties Configuration Line */
@Override
public int getM_PropertiesConfig_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig_Line.java | 1 |
请完成以下Java代码 | public int getAD_InfoWindow_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_InfoWindow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override | public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Sql FROM.
@param FromClause
SQL FROM clause
*/
@Override
public void setFromClause (java.lang.String FromClause)
{
set_Value (COLUMNNAME_FromClause, FromClause);
}
/** Get Sql FROM.
@return SQL FROM clause
*/
@Override
public java.lang.String getFromClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_FromClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoWindow_From.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class StoresController {
private static final List<Distance> DISTANCES = Arrays.asList(new Distance(0.5, MILES), new Distance(1, MILES),
new Distance(2, MILES));
private static final Distance DEFAULT_DISTANCE = new Distance(1, Metrics.MILES);
private static final Map<String, Point> KNOWN_LOCATIONS;
static {
KNOWN_LOCATIONS = Map.of("Pivotal SF", new Point(-122.4041764, 37.7819286), "Timesquare NY",
new Point(-73.995146, 40.740337));
}
private final StoreRepository repository;
private final RepositoryEntityLinks entityLinks;
/**
* Looks up the stores in the given distance around the given location.
*
* @param model the {@link Model} to populate.
* @param location the optional location, if none is given, no search results will be returned.
* @param distance the distance to use, if none is given the {@link #DEFAULT_DISTANCE} is used.
* @param pageable the pagination information
* @return
*/ | @GetMapping("/")
String index(Model model, @RequestParam Optional<Point> location, @RequestParam Optional<Distance> distance,
Pageable pageable) {
var point = location.orElse(KNOWN_LOCATIONS.get("Timesquare NY"));
var stores = repository.findByAddressLocationNear(point, distance.orElse(DEFAULT_DISTANCE), pageable);
model.addAttribute("stores", stores);
model.addAttribute("distances", DISTANCES);
model.addAttribute("selectedDistance", distance.orElse(DEFAULT_DISTANCE));
model.addAttribute("location", point);
model.addAttribute("locations", KNOWN_LOCATIONS);
model.addAttribute("api",
entityLinks.linkToSearchResource(Store.class, LinkRelation.of("by-location"), pageable).getHref());
return "index";
}
} | repos\spring-data-examples-main\rest\starbucks\src\main\java\example\springdata\rest\stores\web\StoresController.java | 2 |
请完成以下Java代码 | public UniqueKey<StoreRecord> getPrimaryKey() {
return Keys.STORE_PKEY;
}
@Override
public Store as(String alias) {
return new Store(DSL.name(alias), this);
}
@Override
public Store as(Name alias) {
return new Store(alias, this);
}
@Override
public Store as(Table<?> alias) {
return new Store(alias.getQualifiedName(), this);
}
/**
* Rename this table
*/
@Override
public Store rename(String name) {
return new Store(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Store rename(Name name) {
return new Store(name, null);
}
/**
* Rename this table
*/
@Override
public Store rename(Table<?> name) {
return new Store(name.getQualifiedName(), null);
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Condition condition) {
return new Store(getQualifiedName(), aliased() ? this : null, null, condition);
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Collection<? extends Condition> conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Condition... conditions) {
return where(DSL.and(conditions));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store where(Field<Boolean> condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(SQL condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override | @PlainSQL
public Store where(@Stringly.SQL String condition) {
return where(DSL.condition(condition));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, Object... binds) {
return where(DSL.condition(condition, binds));
}
/**
* Create an inline derived table from this table
*/
@Override
@PlainSQL
public Store where(@Stringly.SQL String condition, QueryPart... parts) {
return where(DSL.condition(condition, parts));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereExists(Select<?> select) {
return where(DSL.exists(select));
}
/**
* Create an inline derived table from this table
*/
@Override
public Store whereNotExists(Select<?> select) {
return where(DSL.notExists(select));
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\Store.java | 1 |
请完成以下Java代码 | public class JwtUtil {
public static String BEARER = TokenConstant.BEARER;
public static String CRYPTO = TokenConstant.CRYPTO;
public static Integer AUTH_LENGTH = 7;
/**
* jwt配置
*/
@Getter
private static JwtProperties jwtProperties;
public static void setJwtProperties(JwtProperties properties) {
if (JwtUtil.jwtProperties == null) {
JwtUtil.jwtProperties = properties;
}
}
/**
* 签名加密
*/
public static String getBase64Security() {
return Base64.getEncoder().encodeToString(getJwtProperties().getSignKey().getBytes(StandardCharsets.UTF_8));
}
/**
* 获取请求传递的token串
*
* @param auth token
* @return String
*/
public static String getToken(String auth) {
if (isBearer(auth) || isCrypto(auth)) {
return auth.substring(AUTH_LENGTH);
}
return null;
}
/**
* 判断token类型为bearer
*
* @param auth token
* @return String
*/
public static Boolean isBearer(String auth) {
if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
String headStr = auth.substring(0, 6).toLowerCase();
return headStr.compareTo(BEARER) == 0;
}
return false; | }
/**
* 判断token类型为crypto
*
* @param auth token
* @return String
*/
public static Boolean isCrypto(String auth) {
if ((auth != null) && (auth.length() > AUTH_LENGTH)) {
String headStr = auth.substring(0, 6).toLowerCase();
return headStr.compareTo(CRYPTO) == 0;
}
return false;
}
/**
* 解析jsonWebToken
*
* @param jsonWebToken token串
* @return Claims
*/
public static Claims parseJWT(String jsonWebToken) {
try {
return Jwts.parser()
.verifyWith(Keys.hmacShaKeyFor(Base64.getDecoder().decode(getBase64Security()))).build()
.parseSignedClaims(jsonWebToken)
.getPayload();
} catch (Exception ex) {
return null;
}
}
} | repos\SpringBlade-master\blade-gateway\src\main\java\org\springblade\gateway\utils\JwtUtil.java | 1 |
请完成以下Java代码 | <T> T stopExecutionUsingException(T object) {
if (object instanceof Number) {
throw new IllegalArgumentException("Parameter can not be number.");
}
T upperCase = (T) String.valueOf(object)
.toUpperCase(Locale.ENGLISH);
return upperCase;
}
int processLines(String[] lines) {
int statusCode = 0;
parser:
for (String line : lines) {
System.out.println("Processing line: " + line);
if (line.equals("stop")) {
System.out.println("Stopping parsing...");
statusCode = -1;
break parser; // Stop parsing and exit the loop
}
System.out.println("Line processed.");
}
return statusCode;
} | void download(String fileUrl, String destinationPath) throws MalformedURLException, URISyntaxException {
if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) {
return;
}
// execute downloading
URL url = new URI(fileUrl).toURL();
try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\stopexecution\StopExecutionFurtherCode.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static ImmutableList<JSONTriggerAction> getCurrentFrontendTriggerActionsOrEmpty()
{
final Execution execution = currentExecutionHolder.get();
return execution != null
? execution.getFrontendTriggerActions()
: ImmutableList.of();
}
public static final class ExecutionBuilder
{
private String name = "";
private int versionErrorRetryCount;
private boolean inTransaction = true;
private ExecutionBuilder()
{
}
public <T> T execute(final Callable<T> callable)
{
Callable<T> callableEffective = callable;
//
// First(important). Run in transaction
if (inTransaction)
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
final ITrxManager trxManager = Services.get(ITrxManager.class);
try
{
return trxManager.callInNewTrx(beforeCall);
}
catch (final Exception ex)
{
logger.info("Changes that will be discarded: {}", getCurrentDocumentChangesCollectorOrNull());
throw AdempiereException.wrapIfNeeded(ex);
}
};
}
//
// Retry on version error
if (versionErrorRetryCount > 0)
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
InvalidDocumentVersionException versionException = null;
for (int retry = 0; retry < versionErrorRetryCount; retry++)
{
try
{
return beforeCall.call();
}
catch (final InvalidDocumentVersionException ex)
{
versionException = ex;
logger.info("Version error on run {}/{}", retry + 1, versionErrorRetryCount, versionException);
}
}
Check.assumeNotNull(versionException, "VersionException must not be null");
throw versionException;
};
}
// | // Last, measure and log
{
final Callable<T> beforeCall = callableEffective;
callableEffective = () -> {
boolean error = true;
final Stopwatch stopwatch = Stopwatch.createStarted();
try
{
final T result = beforeCall.call();
error = false;
return result;
}
finally
{
if (!error)
{
logger.debug("Executed {} in {} ({})", name, stopwatch, callable);
}
else
{
logger.warn("Failed executing {} (took {}) ({})", name, stopwatch, callable);
}
}
};
}
//
// Run the effective callable in a new execution
try (final Execution ignored = startExecution())
{
return callableEffective.call();
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex);
}
}
public ExecutionBuilder name(final String name)
{
this.name = name;
return this;
}
public ExecutionBuilder retryOnVersionError(final int retryCount)
{
Preconditions.checkArgument(retryCount > 0);
versionErrorRetryCount = retryCount;
return this;
}
public ExecutionBuilder outOfTransaction()
{
inTransaction = false;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\Execution.java | 2 |
请完成以下Java代码 | public int hashCode() {
return this.delegate.hashCode();
}
@Override
public void print(boolean b) throws IOException {
trackContentLength(b);
this.delegate.print(b);
}
@Override
public void print(char c) throws IOException {
trackContentLength(c);
this.delegate.print(c);
}
@Override
public void print(double d) throws IOException {
trackContentLength(d);
this.delegate.print(d);
}
@Override
public void print(float f) throws IOException {
trackContentLength(f);
this.delegate.print(f);
}
@Override
public void print(int i) throws IOException {
trackContentLength(i);
this.delegate.print(i);
}
@Override
public void print(long l) throws IOException {
trackContentLength(l);
this.delegate.print(l);
}
@Override
public void print(String s) throws IOException {
trackContentLength(s);
this.delegate.print(s);
}
@Override
public void println() throws IOException {
trackContentLengthLn();
this.delegate.println();
}
@Override
public void println(boolean b) throws IOException {
trackContentLength(b);
trackContentLengthLn();
this.delegate.println(b);
}
@Override
public void println(char c) throws IOException {
trackContentLength(c);
trackContentLengthLn();
this.delegate.println(c);
}
@Override
public void println(double d) throws IOException {
trackContentLength(d); | trackContentLengthLn();
this.delegate.println(d);
}
@Override
public void println(float f) throws IOException {
trackContentLength(f);
trackContentLengthLn();
this.delegate.println(f);
}
@Override
public void println(int i) throws IOException {
trackContentLength(i);
trackContentLengthLn();
this.delegate.println(i);
}
@Override
public void println(long l) throws IOException {
trackContentLength(l);
trackContentLengthLn();
this.delegate.println(l);
}
@Override
public void println(String s) throws IOException {
trackContentLength(s);
trackContentLengthLn();
this.delegate.println(s);
}
@Override
public void write(byte[] b) throws IOException {
trackContentLength(b);
this.delegate.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
checkContentLength(len);
this.delegate.write(b, off, len);
}
@Override
public String toString() {
return getClass().getName() + "[delegate=" + this.delegate.toString() + "]";
}
@Override
public boolean isReady() {
return this.delegate.isReady();
}
@Override
public void setWriteListener(WriteListener writeListener) {
this.delegate.setWriteListener(writeListener);
}
}
} | repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\OnCommittedResponseWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<InputStreamResource> imt2txt(@RequestParam("file") MultipartFile file){
try {
String originalFilename = file.getOriginalFilename();
HttpHeaders headers = new HttpHeaders();
// 支持jpg、png
if(originalFilename.toLowerCase().endsWith("jpg")||originalFilename.toLowerCase().endsWith("png")){
File outFile = img2TxtService.save(file.getBytes(), originalFilename);
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", outFile.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(outFile.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new FileInputStream(outFile)));
}else{
File error = new File(img2TxtService.getErrorPath());
headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); | headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", error.getName()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity
.ok()
.headers(headers)
.contentLength(error.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(new FileInputStream(error)));
}
} catch (IOException e) {
logger.error(e);
return new ResponseEntity("暂不支持的文件格式",HttpStatus.BAD_REQUEST);
}
// return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
} | repos\spring-boot-quick-master\quick-img2txt\src\main\java\com\quick\controller\Img2TxtController.java | 2 |
请完成以下Java代码 | public int getTrayNumber()
{
return trayNumber;
}
public void setTrayNumber(int trayNumber)
{
this.trayNumber = trayNumber;
}
public int getCalX()
{
return calX;
}
public void setCalX(int calX)
{
this.calX = calX;
}
public int getCalY()
{
return calY;
}
public void setCalY(int calY)
{
this.calY = calY;
}
public String getPrintService()
{
return printService;
}
/**
* @param printService the printService to set
*/
public void setPrintService(String printService)
{
this.printService = printService;
}
public String getTray()
{
return tray;
}
/**
* @param tray the tray to set
*/
public void setTray(String tray)
{
this.tray = tray;
}
public int getPageFrom()
{
return pageFrom;
}
/**
* @param pageFrom the pageFrom to set
*/
public void setPageFrom(int pageFrom)
{
this.pageFrom = pageFrom;
}
public int getPageTo()
{
return pageTo;
}
/**
* @param pageTo the pageTo to set
*/
public void setPageTo(int pageTo)
{
this.pageTo = pageTo;
} | @Override
public String toString()
{
return "PrintPackageInfo [printService=" + printService + ", tray=" + tray + ", pageFrom=" + pageFrom + ", pageTo=" + pageTo + ", calX=" + calX + ", calY=" + calY + "]";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + calX;
result = prime * result + calY;
result = prime * result + pageFrom;
result = prime * result + pageTo;
result = prime * result + ((printService == null) ? 0 : printService.hashCode());
result = prime * result + ((tray == null) ? 0 : tray.hashCode());
result = prime * result + trayNumber;
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PrintPackageInfo other = (PrintPackageInfo)obj;
if (calX != other.calX)
return false;
if (calY != other.calY)
return false;
if (pageFrom != other.pageFrom)
return false;
if (pageTo != other.pageTo)
return false;
if (printService == null)
{
if (other.printService != null)
return false;
}
else if (!printService.equals(other.printService))
return false;
if (tray == null)
{
if (other.tray != null)
return false;
}
else if (!tray.equals(other.tray))
return false;
if (trayNumber != other.trayNumber)
return false;
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\PrintPackageInfo.java | 1 |
请完成以下Java代码 | private static final class MenuResultItemSource implements org.compiere.swing.autocomplete.ResultItemSource
{
public static MenuResultItemSource forRootNode(final MTreeNode root)
{
final Enumeration<?> nodesEnum = root.preorderEnumeration();
final List<MenuResultItem> items = new ArrayList<>();
while (nodesEnum.hasMoreElements())
{
final MTreeNode node = (MTreeNode)nodesEnum.nextElement();
if (node == root)
{
continue;
}
if (node.isSummary())
{
continue;
}
final MenuResultItem item = new MenuResultItem(node);
items.add(item);
}
return new MenuResultItemSource(items);
}
private final ImmutableList<MenuResultItem> items;
private MenuResultItemSource(final List<MenuResultItem> items)
{
super();
this.items = ImmutableList.copyOf(items);
}
@Override
public List<MenuResultItem> query(final String searchText, final int limit)
{
return items;
}
}
/**
* {@link MenuResultItem} renderer.
*/
private static final class ResultItemRenderer implements ListCellRenderer<ResultItem>
{
private final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(final JList<? extends ResultItem> list, final ResultItem value, final int index, final boolean isSelected, final boolean cellHasFocus) | {
final String valueAsText;
final Icon icon;
boolean enabled = true;
if (value == null)
{
// shall not happen
valueAsText = "";
icon = null;
}
else if (value == MORE_Marker)
{
valueAsText = "...";
icon = null;
enabled = false;
}
else if (value instanceof MenuResultItem)
{
final MenuResultItem menuItem = (MenuResultItem)value;
valueAsText = menuItem.getText();
icon = menuItem.getIcon();
}
else
{
valueAsText = value.toString();
icon = null;
}
defaultRenderer.getListCellRendererComponent(list, valueAsText, index, isSelected, cellHasFocus);
defaultRenderer.setIcon(icon);
defaultRenderer.setEnabled(enabled);
return defaultRenderer;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\TreeSearchAutoCompleter.java | 1 |
请完成以下Java代码 | protected void executeParse(BpmnParse bpmnParse, SequenceFlow sequenceFlow) {
ScopeImpl scope = bpmnParse.getCurrentScope();
ActivityImpl sourceActivity = scope.findActivity(sequenceFlow.getSourceRef());
ActivityImpl destinationActivity = scope.findActivity(sequenceFlow.getTargetRef());
Expression skipExpression;
if (StringUtils.isNotEmpty(sequenceFlow.getSkipExpression())) {
ExpressionManager expressionManager = bpmnParse.getExpressionManager();
skipExpression = expressionManager.createExpression(sequenceFlow.getSkipExpression());
} else {
skipExpression = null;
}
TransitionImpl transition = sourceActivity.createOutgoingTransition(sequenceFlow.getId(), skipExpression);
bpmnParse.getSequenceFlows().put(sequenceFlow.getId(), transition); | transition.setProperty("name", sequenceFlow.getName());
transition.setProperty("documentation", sequenceFlow.getDocumentation());
transition.setDestination(destinationActivity);
if (StringUtils.isNotEmpty(sequenceFlow.getConditionExpression())) {
Condition expressionCondition = new UelExpressionCondition(sequenceFlow.getConditionExpression());
transition.setProperty(PROPERTYNAME_CONDITION_TEXT, sequenceFlow.getConditionExpression());
transition.setProperty(PROPERTYNAME_CONDITION, expressionCondition);
}
createExecutionListenersOnTransition(bpmnParse, sequenceFlow.getExecutionListeners(), transition);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SequenceFlowParseHandler.java | 1 |
请完成以下Java代码 | public LookupValue lookupProduct(@Nullable final ProductId productId)
{
if (productId == null)
{
return null;
}
return productLookup.findById(productId.getRepoId());
}
public LookupValue lookupPriceType(@NonNull final PriceSpecificationType priceType)
{
return priceTypeLookup.findById(priceType.getCode());
}
public LookupValue lookupPricingSystem(@Nullable final PricingSystemId pricingSystemId)
{
if (pricingSystemId == null)
{
return null;
}
return pricingSystemLookup.findById(pricingSystemId.getRepoId());
}
public LookupValue lookupPaymentTerm(@Nullable final PaymentTermId paymentTermId)
{
if (paymentTermId == null)
{
return null;
}
return paymentTermLookup.findById(paymentTermId.getRepoId());
}
public LookupValue lookupCurrency(@Nullable final CurrencyId currencyId)
{
if (currencyId == null)
{
return null;
}
return currencyIdLookup.findById(currencyId.getRepoId());
}
public LookupValuesPage getFieldTypeahead(@NonNull final String fieldName, final String query)
{
return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), query);
}
public LookupValuesList getFieldDropdown(@NonNull final String fieldName)
{
return getLookupDataSource(fieldName).findEntities(Evaluatees.empty(), 20).getValues();
}
private LookupDataSource getLookupDataSource(@NonNull final String fieldName)
{
if (PricingConditionsRow.FIELDNAME_PaymentTerm.equals(fieldName))
{
return paymentTermLookup;
}
else if (PricingConditionsRow.FIELDNAME_BasePriceType.equals(fieldName))
{
return priceTypeLookup;
}
else if (PricingConditionsRow.FIELDNAME_BasePricingSystem.equals(fieldName))
{ | return pricingSystemLookup;
}
else if (PricingConditionsRow.FIELDNAME_C_Currency_ID.equals(fieldName))
{
return currencyIdLookup;
}
else
{
throw new AdempiereException("Field " + fieldName + " does not exist or it's not a lookup field");
}
}
public String getTemporaryPriceConditionsColor()
{
return temporaryPriceConditionsColorCache.getOrLoad(0, this::retrieveTemporaryPriceConditionsColor);
}
private String retrieveTemporaryPriceConditionsColor()
{
final ColorId temporaryPriceConditionsColorId = Services.get(IOrderLinePricingConditions.class).getTemporaryPriceConditionsColorId();
return toHexString(Services.get(IColorRepository.class).getColorById(temporaryPriceConditionsColorId));
}
private static String toHexString(@Nullable final MFColor color)
{
if (color == null)
{
return null;
}
final Color awtColor = color.toFlatColor().getFlatColor();
return ColorValue.toHexString(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsRowLookups.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class TransactionTemplateConfiguration {
@Bean
@ConditionalOnMissingBean(TransactionOperations.class)
TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
return new TransactionTemplate(transactionManager);
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(TransactionManager.class)
@ConditionalOnMissingBean(AbstractTransactionManagementConfiguration.class)
static class EnableTransactionManagementConfiguration {
@Configuration(proxyBeanMethods = false)
@EnableTransactionManagement(proxyTargetClass = false)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", havingValue = false)
static class JdkDynamicAutoProxyConfiguration {
} | @Configuration(proxyBeanMethods = false)
@EnableTransactionManagement(proxyTargetClass = true)
@ConditionalOnBooleanProperty(name = "spring.aop.proxy-target-class", matchIfMissing = true)
static class CglibAutoProxyConfiguration {
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(AbstractTransactionAspect.class)
static class AspectJTransactionManagementConfiguration {
@Bean
static LazyInitializationExcludeFilter eagerTransactionAspect() {
return LazyInitializationExcludeFilter.forBeanTypes(AbstractTransactionAspect.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-transaction\src\main\java\org\springframework\boot\transaction\autoconfigure\TransactionAutoConfiguration.java | 2 |
请完成以下Java代码 | public static final KeyNamePair of(
@Nullable final int key,
@Nullable final String name)
{
return of(key, name, null/* description */);
}
public static final KeyNamePair of(
@Nullable final RepoIdAware key,
@Nullable final String name,
@Nullable final String description)
{
final int keyInt = key != null ? key.getRepoId() : EMPTY.getKey();
return of(keyInt, name, description);
}
@JsonCreator
public static final KeyNamePair of(
@JsonProperty("k") final int key,
@JsonProperty("n") final String name,
@JsonProperty("description") final String description)
{
if (key == EMPTY.getKey() && Objects.equals(name, EMPTY.getName()))
{
return EMPTY;
}
return new KeyNamePair(key, name, description);
}
public static final KeyNamePair of(final int key)
{
if (key < 0)
{
return EMPTY;
}
return new KeyNamePair(key, "<" + key + ">", null/* help */);
}
private static final long serialVersionUID = 6347385376010388473L;
public static final KeyNamePair EMPTY = new KeyNamePair(-1, "", null/* description */);
/**
* @deprecated please use the static creator methods instead.
*/
@Deprecated
public KeyNamePair(final int key, final String name)
{
super(name, null/* description */);
this.m_key = key;
}
/**
* Constructor KeyValue Pair -
*
* @param key Key (-1 is considered as null)
* @param name string representation
* @deprecated please use the static creator methods instead.
*/
@Deprecated
public KeyNamePair(final int key, @Nullable final String name, @Nullable final String description)
{
super(name, description); | this.m_key = key;
}
/** The Key */
private final int m_key;
/**
* Get Key
*
* @return key
*/
@JsonProperty("k")
public int getKey()
{
return m_key;
} // getKey
/**
* Get ID (key as String)
*
* @return String value of key or null if -1
*/
@Override
@JsonIgnore
public String getID()
{
if (m_key == -1)
return null;
return String.valueOf(m_key);
} // getID
/**
* Equals
*
* @param obj object
* @return true if equal
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof KeyNamePair)
{
KeyNamePair pp = (KeyNamePair)obj;
if (pp.getKey() == m_key
&& pp.getName() != null
&& pp.getName().equals(getName()))
return true;
return false;
}
return false;
} // equals
@Override
public int hashCode()
{
return Objects.hash(m_key);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\KeyNamePair.java | 1 |
请完成以下Java代码 | public ImmutableRowsIndex<T> removingIf(@NonNull final Predicate<T> predicate)
{
final int sizeBeforeRemove = rowIds.size();
final ArrayList<T> rowsAfterRemove = new ArrayList<>(sizeBeforeRemove);
for (final DocumentId rowId : this.rowIds)
{
final T row = rowsById.get(rowId);
final boolean remove = predicate.test(row);
if (!remove)
{
rowsAfterRemove.add(row);
}
}
if (rowsAfterRemove.size() == sizeBeforeRemove)
{
return this; // nothing was deleted
}
return new ImmutableRowsIndex<>(this.initialRowIds, rowsAfterRemove);
}
public <ID extends RepoIdAware> ImmutableSet<ID> getRecordIdsToRefresh(
@NonNull final DocumentIdsSelection rowIds,
@NonNull final Function<DocumentId, ID> idMapper)
{
if (rowIds.isEmpty())
{
return ImmutableSet.of();
}
else if (rowIds.isAll())
{
return Stream.concat(this.rowIds.stream(), this.initialRowIds.stream())
.map(idMapper)
.collect(ImmutableSet.toImmutableSet());
}
else
{ | return rowIds.stream()
.filter(this::isRelevantForRefreshing)
.map(idMapper)
.collect(ImmutableSet.toImmutableSet());
}
}
public Stream<T> stream() {return rowsById.values().stream();}
public Stream<T> stream(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate);}
public long count(final Predicate<T> predicate) {return rowsById.values().stream().filter(predicate).count();}
public boolean anyMatch(final Predicate<T> predicate) {return rowsById.values().stream().anyMatch(predicate);}
public List<T> list() {return rowIds.stream().map(rowsById::get).collect(ImmutableList.toImmutableList());}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\template\ImmutableRowsIndex.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CrossVersionServiceRegistry
{
private final ImmutableMap<String, CrossVersionRequestConverter> xsdName2Requestconverter;
private final ImmutableMap<XmlVersion, CrossVersionRequestConverter> simpleVersionName2RequestConverter;
private final ImmutableMap<String, CrossVersionResponseConverter> xsdName2ResponseConverter;
private final ImmutableMap<XmlVersion, CrossVersionResponseConverter> simpleVersionName2ResponseConverter;
public CrossVersionServiceRegistry(
@NonNull final Optional<List<CrossVersionRequestConverter>> crossVersionRequestConverters,
@NonNull final Optional<List<CrossVersionResponseConverter>> crossVersionResponseConverters
)
{
final List<CrossVersionRequestConverter> //
requestConverterList = crossVersionRequestConverters.orElse(ImmutableList.of());
this.xsdName2Requestconverter = Maps.uniqueIndex(requestConverterList, CrossVersionRequestConverter::getXsdName);
this.simpleVersionName2RequestConverter = Maps.uniqueIndex(requestConverterList, CrossVersionRequestConverter::getVersion);
final List<CrossVersionResponseConverter> //
responseConverterList = crossVersionResponseConverters.orElse(ImmutableList.of());
this.xsdName2ResponseConverter = Maps.uniqueIndex(responseConverterList, CrossVersionResponseConverter::getXsdName);
this.simpleVersionName2ResponseConverter = Maps.uniqueIndex(responseConverterList, CrossVersionResponseConverter::getVersion);
} | public CrossVersionRequestConverter getRequestConverterForXsdName(@NonNull final String xsdName)
{
return xsdName2Requestconverter.get(xsdName);
}
public CrossVersionRequestConverter getRequestConverterForSimpleVersionName(@NonNull final XmlVersion version)
{
return simpleVersionName2RequestConverter.get(version);
}
public CrossVersionResponseConverter getResponseConverterForXsdName(@NonNull final String xsdName)
{
return xsdName2ResponseConverter.get(xsdName);
}
public CrossVersionResponseConverter getResponseConverterForSimpleVersionName(@NonNull final XmlVersion version)
{
return simpleVersionName2ResponseConverter.get(version);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\CrossVersionServiceRegistry.java | 2 |
请完成以下Java代码 | public byte[] getP() {
return p;
}
/**
* Sets the value of the p property.
*
* @param value
* allowed object is
* byte[]
*/
public void setP(byte[] value) {
this.p = value;
}
/**
* Gets the value of the q property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getQ() {
return q;
}
/**
* Sets the value of the q property.
*
* @param value
* allowed object is
* byte[]
*/
public void setQ(byte[] value) {
this.q = value;
}
/**
* Gets the value of the g property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getG() {
return g;
}
/**
* Sets the value of the g property.
*
* @param value
* allowed object is
* byte[]
*/
public void setG(byte[] value) {
this.g = value;
}
/**
* Gets the value of the y property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getY() {
return y;
}
/**
* Sets the value of the y property.
*
* @param value
* allowed object is
* byte[]
*/
public void setY(byte[] value) {
this.y = value;
} | /**
* Gets the value of the j property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getJ() {
return j;
}
/**
* Sets the value of the j property.
*
* @param value
* allowed object is
* byte[]
*/
public void setJ(byte[] value) {
this.j = value;
}
/**
* Gets the value of the seed property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getSeed() {
return seed;
}
/**
* Sets the value of the seed property.
*
* @param value
* allowed object is
* byte[]
*/
public void setSeed(byte[] value) {
this.seed = value;
}
/**
* Gets the value of the pgenCounter property.
*
* @return
* possible object is
* byte[]
*/
public byte[] getPgenCounter() {
return pgenCounter;
}
/**
* Sets the value of the pgenCounter property.
*
* @param value
* allowed object is
* byte[]
*/
public void setPgenCounter(byte[] value) {
this.pgenCounter = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\DSAKeyValueType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
airagMcpService.removeById(id);
return Result.OK("删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@Operation(summary = "MCP-通过id查询")
@GetMapping(value = "/queryById")
public Result<AiragMcp> queryById(@RequestParam(name = "id", required = true) String id) {
AiragMcp airagMcp = airagMcpService.getById(id);
if (airagMcp == null) {
return Result.error("未找到对应数据");
}
return Result.OK(airagMcp);
}
/**
* 导出excel
*
* @param request
* @param airagMcp
*/
// @RequiresPermissions("llm:airag_mcp:exportXls")
@RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, AiragMcp airagMcp) {
return super.exportXls(request, airagMcp, AiragMcp.class, "MCP");
} | /**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
// @RequiresPermissions("llm:airag_mcp:importExcel")
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, AiragMcp.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-module\jeecg-boot-module-airag\src\main\java\org\jeecg\modules\airag\llm\controller\AiragMcpController.java | 2 |
请完成以下Java代码 | public void setUIStyle (final @Nullable java.lang.String UIStyle)
{
set_Value (COLUMNNAME_UIStyle, UIStyle);
}
@Override
public java.lang.String getUIStyle()
{
return get_ValueAsString(COLUMNNAME_UIStyle);
}
/**
* ViewEditMode AD_Reference_ID=541263
* Reference name: ViewEditMode
*/
public static final int VIEWEDITMODE_AD_Reference_ID=541263;
/** Never = N */
public static final String VIEWEDITMODE_Never = "N";
/** OnDemand = D */
public static final String VIEWEDITMODE_OnDemand = "D";
/** Always = Y */
public static final String VIEWEDITMODE_Always = "Y";
@Override
public void setViewEditMode (final @Nullable java.lang.String ViewEditMode)
{
set_Value (COLUMNNAME_ViewEditMode, ViewEditMode);
}
@Override
public java.lang.String getViewEditMode()
{
return get_ValueAsString(COLUMNNAME_ViewEditMode);
}
/** | * WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** ExtraLarge = XL */
public static final String WIDGETSIZE_ExtraLarge = "XL";
/** XXL = XXL */
public static final String WIDGETSIZE_XXL = "XXL";
@Override
public void setWidgetSize (final @Nullable java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
@Override
public java.lang.String getWidgetSize()
{
return get_ValueAsString(COLUMNNAME_WidgetSize);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Element.java | 1 |
请完成以下Java代码 | public void setContextAttributesMapper(
Function<OAuth2AuthorizeRequest, Map<String, Object>> contextAttributesMapper) {
Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null");
this.contextAttributesMapper = contextAttributesMapper;
}
/**
* Sets the {@link OAuth2AuthorizationSuccessHandler} that handles successful
* authorizations.
*
* <p>
* The default saves {@link OAuth2AuthorizedClient}s in the
* {@link OAuth2AuthorizedClientService}.
* @param authorizationSuccessHandler the {@link OAuth2AuthorizationSuccessHandler}
* that handles successful authorizations
* @since 5.3
*/
public void setAuthorizationSuccessHandler(OAuth2AuthorizationSuccessHandler authorizationSuccessHandler) {
Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null");
this.authorizationSuccessHandler = authorizationSuccessHandler;
}
/**
* Sets the {@link OAuth2AuthorizationFailureHandler} that handles authorization
* failures.
*
* <p>
* A {@link RemoveAuthorizedClientOAuth2AuthorizationFailureHandler} is used by
* default.
* @param authorizationFailureHandler the {@link OAuth2AuthorizationFailureHandler}
* that handles authorization failures
* @since 5.3
* @see RemoveAuthorizedClientOAuth2AuthorizationFailureHandler
*/
public void setAuthorizationFailureHandler(OAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
}
/**
* The default implementation of the {@link #setContextAttributesMapper(Function) | * contextAttributesMapper}.
*/
public static class DefaultContextAttributesMapper
implements Function<OAuth2AuthorizeRequest, Map<String, Object>> {
@Override
public Map<String, Object> apply(OAuth2AuthorizeRequest authorizeRequest) {
Map<String, Object> contextAttributes = Collections.emptyMap();
String scope = authorizeRequest.getAttribute(OAuth2ParameterNames.SCOPE);
if (StringUtils.hasText(scope)) {
contextAttributes = new HashMap<>();
contextAttributes.put(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME,
StringUtils.delimitedListToStringArray(scope, " "));
}
return contextAttributes;
}
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\AuthorizedClientServiceOAuth2AuthorizedClientManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public TestQueueConsumer consumer() {
log.info("init jmsQueueListener Consumer");
return new TestQueueConsumer();
}
@Bean
public Runnable dynamicConfiguration4Simpe() throws Exception {
log.info("init jmsSimpeQueueListeners");
String[] concurrencys = simpeQueuesConcurrency.split(",");
ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext;
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory();
for (int i = 1; i <= 5; i++) {
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultJmsListenerContainerFactory.class);
/**
* 设置属性
*/
beanDefinitionBuilder.addPropertyValue("connectionFactory", applicationContext.getBean("activeMQConnectionFactory")); | beanDefinitionBuilder.addPropertyValue("concurrency", concurrencys[i-1]);
beanDefinitionBuilder.addPropertyValue("recoveryInterval", 1000L);
beanDefinitionBuilder.addPropertyValue("sessionAcknowledgeMode", 2);
/**
* 注册到spring容器中
*/
beanFactory.registerBeanDefinition("jmsSimpeQueueListener" + i, beanDefinitionBuilder.getBeanDefinition());
}
return null;
}
} | repos\spring-boot-quick-master\quick-activemq2\src\main\java\com\active2\config\AcitveMQConfig.java | 2 |
请完成以下Java代码 | public VariableInstanceQuery variableValueEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) {
wrappedVariableInstanceQuery.variableValueNotEquals(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLike(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLike(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) {
wrappedVariableInstanceQuery.variableValueLikeIgnoreCase(variableName, variableValue);
return this;
}
@Override
public VariableInstanceQuery orderByVariableName() {
wrappedVariableInstanceQuery.orderByVariableName();
return this;
}
@Override
public VariableInstanceQuery asc() {
wrappedVariableInstanceQuery.asc();
return this;
}
@Override
public VariableInstanceQuery desc() {
wrappedVariableInstanceQuery.desc(); | return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property) {
wrappedVariableInstanceQuery.orderBy(property);
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return wrappedVariableInstanceQuery.count();
}
@Override
public VariableInstance singleResult() {
return wrappedVariableInstanceQuery.singleResult();
}
@Override
public List<VariableInstance> list() {
return wrappedVariableInstanceQuery.list();
}
@Override
public List<VariableInstance> listPage(int firstResult, int maxResults) {
return wrappedVariableInstanceQuery.listPage(firstResult, maxResults);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java | 1 |
请完成以下Java代码 | protected @NonNull String toJson(@NonNull Region region) {
return this.regionValuesToJsonConverter.convert(region);
}
/**
* Converts the array of {@link Byte#TYPE bytes} containing multiple {@link String JSON} objects
* into an array of {@link PdxInstance PdxInstances}.
*
* @param json array of {@link Byte#TYPE bytes} containing the {@link String JSON} to convert to PDX.
* @return an array of {@link PdxInstance PdxInstances} for each {@link String JSON} object.
* @see org.apache.geode.pdx.PdxInstance
* @see #getJsonToPdxArrayConverter()
*/
protected @NonNull PdxInstance[] toPdx(@NonNull byte[] json) {
return isNotEmpty(json)
? getJsonToPdxArrayConverter().convert(json)
: EMPTY_PDX_INSTANCE_ARRAY;
}
/**
* Converts all {@link Region#values() values} in the targeted {@link Region} into {@literal JSON}. | *
* The converter is capable of handling both {@link Object Objects} and PDX.
*
* @see org.springframework.geode.data.json.converter.AbstractObjectArrayToJsonConverter
*/
static class RegionValuesToJsonConverter extends AbstractObjectArrayToJsonConverter {
@NonNull <K, V> String convert(@NonNull Region<K, V> region) {
Assert.notNull(region, "Region must not be null");
return super.convert(CollectionUtils.nullSafeCollection(CacheUtils.collectValues(region)));
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\JsonCacheDataImporterExporter.java | 1 |
请完成以下Java代码 | protected AbstractDataAssociation createDataInputAssociation(DataAssociation dataAssociationElement) {
if (dataAssociationElement.getAssignments().isEmpty()) {
return new MessageImplicitDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
} else {
SimpleDataInputAssociation dataAssociation = new SimpleDataInputAssociation(dataAssociationElement.getSourceRef(), dataAssociationElement.getTargetRef());
ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager();
for (org.flowable.bpmn.model.Assignment assignmentElement : dataAssociationElement.getAssignments()) {
if (StringUtils.isNotEmpty(assignmentElement.getFrom()) && StringUtils.isNotEmpty(assignmentElement.getTo())) {
Expression from = expressionManager.createExpression(assignmentElement.getFrom());
Expression to = expressionManager.createExpression(assignmentElement.getTo());
Assignment assignment = new Assignment(from, to);
dataAssociation.addAssignment(assignment);
}
} | return dataAssociation;
}
}
protected AbstractDataAssociation createDataOutputAssociation(DataAssociation dataAssociationElement) {
if (StringUtils.isNotEmpty(dataAssociationElement.getSourceRef())) {
return new MessageImplicitDataOutputAssociation(dataAssociationElement.getTargetRef(), dataAssociationElement.getSourceRef());
} else {
ExpressionManager expressionManager = CommandContextUtil.getProcessEngineConfiguration().getExpressionManager();
Expression transformation = expressionManager.createExpression(dataAssociationElement.getTransformation());
AbstractDataAssociation dataOutputAssociation = new TransformationDataOutputAssociation(null, dataAssociationElement.getTargetRef(), transformation);
return dataOutputAssociation;
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\WebServiceActivityBehavior.java | 1 |
请完成以下Java代码 | public Builder append(final StringBuilder constant)
{
if (constant == null || constant.length() <= 0)
{
return this;
}
append(constant.toString());
return this;
}
public Builder append(final Builder otherBuilder)
{
for (final IStringExpression expr : otherBuilder.expressions)
{
append(expr);
}
if (otherBuilder._lastConstantBuffer != null && otherBuilder._lastConstantBuffer.length() > 0)
{
appendToLastConstantBuffer(otherBuilder._lastConstantBuffer.toString());
}
return this;
}
public Builder append(final CtxName name)
{
append(new SingleParameterStringExpression(name.toStringWithMarkers(), name));
return this;
}
/** | * Wraps the entire content of this builder using given wrapper.
* After this method invocation the builder will contain only the wrapped expression.
*/
public Builder wrap(final IStringExpressionWrapper wrapper)
{
Check.assumeNotNull(wrapper, "Parameter wrapper is not null");
final IStringExpression expression = build();
final IStringExpression expressionWrapped = wrapper.wrap(expression);
expressions.clear();
append(expressionWrapped);
return this;
}
/**
* If the {@link Condition} is <code>true</code> then it wraps the entire content of this builder using given wrapper.
* After this method invocation the builder will contain only the wrapped expression.
*/
public Builder wrapIfTrue(final boolean condition, final IStringExpressionWrapper wrapper)
{
if (!condition)
{
return this;
}
return wrap(wrapper);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\CompositeStringExpression.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Net Days.
@param NetDays
Net Days in which payment is due
*/
public void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{ | set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FurtherIdentificationType {
@XmlValue
protected String value;
@XmlAttribute(name = "IdentificationType", namespace = "http://erpel.at/schemas/1p0/documents/extensions/edifact", required = true)
protected String identificationType;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Used to identify the type of further information. Currently, the following identification types are used:
* ZZZ ... mutually defined ID by both parties
* IssuedBySupplier ... ID given by supplier
* IssuedByCustomer ... ID given by customer
* FiscalNumber ... fiscal number of party
*
*
* @return
* possible object is | * {@link String }
*
*/
public String getIdentificationType() {
return identificationType;
}
/**
* Sets the value of the identificationType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIdentificationType(String value) {
this.identificationType = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\FurtherIdentificationType.java | 2 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_TaxGroup[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Tax Group.
@param C_TaxGroup_ID Tax Group */
public void setC_TaxGroup_ID (int C_TaxGroup_ID)
{
if (C_TaxGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_TaxGroup_ID, Integer.valueOf(C_TaxGroup_ID));
}
/** Get Tax Group.
@return Tax Group */
public int getC_TaxGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
} | /** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxGroup.java | 1 |
请完成以下Java代码 | private LookupValuesList getAllCountriesById()
{
final Object cacheKey = "ALL";
return allCountriesCache.getOrLoad(cacheKey, this::retriveAllCountriesById);
}
private LookupValuesList retriveAllCountriesById()
{
return Services.get(ICountryDAO.class)
.getCountries(Env.getCtx())
.stream()
.map(this::createLookupValue)
.collect(LookupValuesList.collect());
}
private IntegerLookupValue createLookupValue(final I_C_Country countryRecord)
{ | final int countryId = countryRecord.getC_Country_ID();
final IModelTranslationMap modelTranslationMap = InterfaceWrapperHelper.getModelTranslationMap(countryRecord);
final ITranslatableString countryName = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Name, countryRecord.getName());
final ITranslatableString countryDescription = modelTranslationMap.getColumnTrl(I_C_Country.COLUMNNAME_Description, countryRecord.getName());
return IntegerLookupValue.of(countryId, countryName, countryDescription);
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressCountryLookupDescriptor.java | 1 |
请完成以下Java代码 | public Builder attributeValue(
@NonNull final I_M_Attribute attribute,
@Nullable final Object attributeValue,
@Nullable final AttributeValueId attributeValueId)
{
final AttributeId attributeId = AttributeId.ofRepoId(attribute.getM_Attribute_ID());
attributesById.put(attributeId, attribute);
final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue());
attributesByCode.put(attributeCode, attribute);
if (attributeValue == null)
{
valuesByAttributeCode.remove(attributeCode);
}
else
{
valuesByAttributeCode.put(attributeCode, attributeValue);
}
if (attributeValueId == null)
{
valueIdsByAttributeCode.remove(attributeCode); | }
else
{
valueIdsByAttributeCode.put(attributeCode, attributeValueId);
}
return this;
}
public Builder createCopy()
{
return new Builder(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\ImmutableAttributeSet.java | 1 |
请完成以下Java代码 | public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
throw new UnsupportedOperationException();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final KeyNamePair huPiItemProductKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_M_HU_PI_Item_Product_ID);
if (huPiItemProductKNP == null)
{
return -1;
}
final int piItemProductId = huPiItemProductKNP.getKey();
if (piItemProductId <= 0)
{
return -1;
}
return piItemProductId;
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal qty = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_QtyPacks);
return qty;
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
infoWindow.setValueByColumnName(IHUPackingAware.COLUMNNAME_QtyPacks, rowIndexModel, qtyPacks);
}
@Override
public int getC_UOM_ID()
{
return Services.get(IProductBL.class).getStockUOMId(getM_Product_ID()).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
throw new UnsupportedOperationException();
}
@Override
public void setC_BPartner_ID(final int partnerId)
{ | throw new UnsupportedOperationException();
}
@Override
public int getC_BPartner_ID()
{
final KeyNamePair bpartnerKNP = infoWindow.getValue(rowIndexModel, IHUPackingAware.COLUMNNAME_C_BPartner_ID);
return bpartnerKNP != null ? bpartnerKNP.getKey() : -1;
}
@Override
public boolean isInDispute()
{
// there is no InDispute flag to be considered
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareInfoWindowAdapter.java | 1 |
请完成以下Java代码 | public final class ALoginRes_es extends ListResourceBundle
{
/** Translation Content */
static final Object[][] contents = new String[][]
{
{ "Connection", "Conexi\u00f3n" },
{ "Defaults", "Predeterminados" },
{ "Login", "Autenticaci\u00f3n ADempiere" },
{ "File", "Archivo" },
{ "Exit", "Salir" },
{ "Help", "Ayuda" },
{ "About", "Acerca de" },
{ "Host", "&Servidor" },
{ "Database", "Base de datos" },
{ "User", "&Usuario" },
{ "EnterUser", "Introduzca Usuario Aplicaci\u00f3n" },
{ "Password", "&Contrase\u00f1a" },
{ "EnterPassword", "Introduzca Contrase\u00f1a Aplicaci\u00f3n" },
{ "Language", "&Idioma" },
{ "SelectLanguage", "Seleccione su idioma" },
{ "Role", "Perfil" },
{ "Client", "Entidad" },
{ "Organization", "Organizaci\u00f3n" },
{ "Date", "Fecha" },
{ "Warehouse", "Almac\u00e9n" },
{ "Printer", "Impresora" },
{ "Connected", "Conectado" },
{ "NotConnected", "No Conectado" },
{ "DatabaseNotFound", "Base de datos no encontrada" },
{ "UserPwdError", "Usuario-Contrase\u00f1a no coinciden" },
{ "RoleNotFound", "Perfil no encontrado/incompleto" }, | { "Authorized", "Autorizado" },
{ "Ok", "Aceptar" },
{ "Cancel", "Cancelar" },
{ "VersionConflict", "Conflicto de versi\u00f3n:" },
{ "VersionInfo", "Servidor <> Cliente" },
{ "PleaseUpgrade", "Favor descargar una nueva versi\u00f3n desde el servidor" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes_es | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_es.java | 1 |
请完成以下Java代码 | public Customer findById(Long id) {
return em.find(Customer.class, id);
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findAll()
*/
@Override
public List<Customer> findAll() {
return em.createQuery("select c from Customer c", Customer.class).getResultList();
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findAll(int, int)
*/
@Override
public List<Customer> findAll(int page, int pageSize) {
var query = em.createQuery("select c from Customer c", Customer.class);
query.setFirstResult(page * pageSize);
query.setMaxResults(pageSize);
return query.getResultList();
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#save(example.springdata.jpa.showcase.core.Customer)
*/
@Override
@Transactional
public Customer save(Customer customer) {
// Is new?
if (customer.getId() == null) {
em.persist(customer);
return customer;
} else {
return em.merge(customer); | }
}
/*
* (non-Javadoc)
* @see example.springdata.jpa.showcase.before.CustomerService#findByLastname(java.lang.String, int, int)
*/
@Override
public List<Customer> findByLastname(String lastname, int page, int pageSize) {
var query = em.createQuery("select c from Customer c where c.lastname = ?1", Customer.class);
query.setParameter(1, lastname);
query.setFirstResult(page * pageSize);
query.setMaxResults(pageSize);
return query.getResultList();
}
} | repos\spring-data-examples-main\jpa\showcase\src\main\java\example\springdata\jpa\showcase\before\CustomerServiceImpl.java | 1 |
请完成以下Java代码 | public List<Class<? extends Entity>> getDeletionOrder() {
return deletionOrder;
}
public void setDeletionOrder(List<Class<? extends Entity>> deletionOrder) {
this.deletionOrder = deletionOrder;
}
public Collection<Class<? extends Entity>> getImmutableEntities() {
return immutableEntities;
}
public void setImmutableEntities(Collection<Class<? extends Entity>> immutableEntities) {
this.immutableEntities = immutableEntities;
}
public void addLogicalEntityClassMapping(String logicalName, Class<?> entityClass) {
logicalNameToClassMapping.put(logicalName, entityClass); | }
public Map<String, Class<?>> getLogicalNameToClassMapping() {
return logicalNameToClassMapping;
}
public void setLogicalNameToClassMapping(Map<String, Class<?>> logicalNameToClassMapping) {
this.logicalNameToClassMapping = logicalNameToClassMapping;
}
public boolean isUsePrefixId() {
return usePrefixId;
}
public void setUsePrefixId(boolean usePrefixId) {
this.usePrefixId = usePrefixId;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\db\DbSqlSessionFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FileService {
private final Path rootLocation;
public FileService(AppProperties appProperties) {
this.rootLocation = Path.of(appProperties.getFileStorage().getUploadFolder());
}
public String store(ReceivedFile.FileGroup fileGroup, @NotNull MultipartFile file) {
try {
String fileIdentifier = getCleanedFileName(file.getOriginalFilename());
Path targetPath = getStoredFilePath(fileGroup, fileIdentifier);
file.transferTo(targetPath);
return fileIdentifier;
} catch (IOException e) {
throw new StorageException("Failed to store file " + file, e);
}
}
public Resource loadAsResource(ReceivedFile.FileGroup fileGroup, String fileIdentifier) {
try {
Path targetPath = getStoredFilePath(fileGroup, fileIdentifier);
Resource resource = new UrlResource(targetPath.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new IOException("Could not read file: " + targetPath);
}
} catch (IOException e) {
throw new RetrievalException("Could not read file: " + fileIdentifier + " , group " + fileGroup, e);
}
} | private String getCleanedFileName(String originalName) throws IOException {
if (originalName == null || originalName.isEmpty()) {
throw new IOException("Failed to store empty file " + originalName);
}
if (originalName.contains("..")) {
// This is a security check
throw new IOException("Cannot store file with relative path outside current directory " + originalName);
}
return UUID.randomUUID().toString();
}
private String getSubFolder(ReceivedFile.FileGroup fileGroup) throws IOException {
if (fileGroup == ReceivedFile.FileGroup.NOTE_ATTACHMENT) {
return fileGroup.path;
}
throw new IOException("File group subfolder " + fileGroup + " is not implemented");
}
private Path getStoredFilePath(ReceivedFile.FileGroup fileGroup, String fileIdentifier) throws IOException {
return rootLocation.resolve(getSubFolder(fileGroup)).resolve(fileIdentifier);
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\modules\file\FileService.java | 2 |
请完成以下Java代码 | public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setIsSimulation (final boolean IsSimulation)
{
set_Value (COLUMNNAME_IsSimulation, IsSimulation);
}
@Override
public boolean isSimulation()
{
return get_ValueAsBoolean(COLUMNNAME_IsSimulation);
}
@Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public void setLevelHierarchy (final int LevelHierarchy)
{
set_ValueNoCheck (COLUMNNAME_LevelHierarchy, LevelHierarchy);
}
@Override
public int getLevelHierarchy()
{
return get_ValueAsInt(COLUMNNAME_LevelHierarchy);
}
@Override
public void setPointsSum_Forecasted (final BigDecimal PointsSum_Forecasted)
{
set_Value (COLUMNNAME_PointsSum_Forecasted, PointsSum_Forecasted);
}
@Override
public BigDecimal getPointsSum_Forecasted()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Forecasted);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setPointsSum_Invoiceable (final BigDecimal PointsSum_Invoiceable)
{
set_ValueNoCheck (COLUMNNAME_PointsSum_Invoiceable, PointsSum_Invoiceable);
}
@Override
public BigDecimal getPointsSum_Invoiceable()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiceable);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_Invoiced (final BigDecimal PointsSum_Invoiced)
{
set_Value (COLUMNNAME_PointsSum_Invoiced, PointsSum_Invoiced);
}
@Override
public BigDecimal getPointsSum_Invoiced()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Invoiced);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_Settled (final BigDecimal PointsSum_Settled)
{
set_Value (COLUMNNAME_PointsSum_Settled, PointsSum_Settled);
}
@Override
public BigDecimal getPointsSum_Settled()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_Settled);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPointsSum_ToSettle (final BigDecimal PointsSum_ToSettle)
{
set_Value (COLUMNNAME_PointsSum_ToSettle, PointsSum_ToSettle);
}
@Override
public BigDecimal getPointsSum_ToSettle()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsSum_ToSettle);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Share.java | 1 |
请完成以下Java代码 | public List<String[]> parseFixedWidthFile(String relativePath) {
try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) {
FixedWidthFields fieldLengths = new FixedWidthFields(8, 30, 10);
FixedWidthParserSettings settings = new FixedWidthParserSettings(fieldLengths);
FixedWidthParser parser = new FixedWidthParser(settings);
List<String[]> parsedRows = parser.parseAll(inputReader);
return parsedRows;
} catch (IOException e) {
logger.error("IOException opening file: " + relativePath + " " + e.getMessage());
return new ArrayList<String[]>();
}
}
public List<Product> parseCsvFileIntoBeans(String relativePath) {
try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) {
BeanListProcessor<Product> rowProcessor = new BeanListProcessor<Product>(Product.class);
CsvParserSettings settings = new CsvParserSettings();
settings.setHeaderExtractionEnabled(true);
settings.setProcessor(rowProcessor);
CsvParser parser = new CsvParser(settings);
parser.parse(inputReader);
return rowProcessor.getBeans(); | } catch (IOException e) {
logger.error("IOException opening file: " + relativePath + " " + e.getMessage());
return new ArrayList<Product>();
}
}
public List<String[]> parseCsvFileInBatches(String relativePath) {
try (Reader inputReader = new InputStreamReader(new FileInputStream(new File(relativePath)), "UTF-8")) {
CsvParserSettings settings = new CsvParserSettings();
settings.setProcessor(new BatchedColumnProcessor(5) {
@Override
public void batchProcessed(int rowsInThisBatch) {
}
});
CsvParser parser = new CsvParser(settings);
List<String[]> parsedRows = parser.parseAll(inputReader);
return parsedRows;
} catch (IOException e) {
logger.error("IOException opening file: " + relativePath + " " + e.getMessage());
return new ArrayList<String[]>();
}
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\univocity\ParsingService.java | 1 |
请完成以下Java代码 | public void setCamundaDecisionVersion(String camundaDecisionVersion) {
camundaDecisionVersionAttribute.setValue(this, camundaDecisionVersion);
}
public String getCamundaDecisionTenantId() {
return camundaDecisionTenantIdAttribute.getValue(this);
}
public void setCamundaDecisionTenantId(String camundaDecisionTenantId) {
camundaDecisionTenantIdAttribute.setValue(this, camundaDecisionTenantId);
}
@Override
public String getCamundaMapDecisionResult() {
return camundaMapDecisionResultAttribute.getValue(this);
}
@Override
public void setCamundaMapDecisionResult(String camundaMapDecisionResult) {
camundaMapDecisionResultAttribute.setValue(this, camundaMapDecisionResult);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTask.class, CMMN_ELEMENT_DECISION_TASK)
.namespaceUri(CMMN11_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTask>() {
public DecisionTask newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTaskImpl(instanceContext);
}
});
decisionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_DECISION_REF)
.build(); | /** Camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaDecisionTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_DECISION_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
camundaMapDecisionResultAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_MAP_DECISION_RESULT)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
decisionRefExpressionChild = sequenceBuilder.element(DecisionRefExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionTaskImpl.java | 1 |
请完成以下Java代码 | public POSCashJournal changeJournalById(@NonNull final POSCashJournalId cashJournalId, @NonNull final Consumer<POSCashJournal> updater)
{
final I_C_POS_Journal record = retrieveRecordById(cashJournalId);
final List<I_C_POS_JournalLine> lineRecords = retrieveLineRecordsByJournalId(cashJournalId);
final POSCashJournal journal = fromRecord(record, lineRecords);
updater.accept(journal);
updateRecord(record, journal);
InterfaceWrapperHelper.save(record);
final ImmutableList<POSCashJournalLine> lines = journal.getLines();
for (int i = 0; i < lines.size(); i++)
{
final POSCashJournalLine line = lines.get(i);
I_C_POS_JournalLine lineRecord = i < lineRecords.size() ? lineRecords.get(i) : null;
if (lineRecord == null)
{ | lineRecord = InterfaceWrapperHelper.newInstance(I_C_POS_JournalLine.class);
lineRecord.setC_POS_Journal_ID(record.getC_POS_Journal_ID());
}
lineRecord.setAD_Org_ID(record.getAD_Org_ID());
updateRecord(lineRecord, line);
InterfaceWrapperHelper.save(lineRecord);
}
for (int i = lines.size(); i < lineRecords.size(); i++)
{
InterfaceWrapperHelper.delete(lineRecords.get(i));
}
return journal;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSCashJournalRepository.java | 1 |
请完成以下Java代码 | public ImmutableSet<ResourceTypeId> getResourceTypeIds()
{
final ImmutableSet.Builder<ResourceTypeId> result = ImmutableSet.builder();
for (final ManufacturingJobFacets.FacetId facetId : set)
{
if (ManufacturingJobFacetGroup.RESOURCE_TYPE.equals(facetId.getGroup()))
{
result.add(facetId.getResourceTypeIdNotNull());
}
}
return result.build();
}
}
@Value(staticConstructor = "of")
public static class Facet
{
@NonNull FacetId facetId;
@NonNull ITranslatableString caption;
public WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder newWorkflowLaunchersFacetGroupBuilder()
{
return facetId.getGroup().newWorkflowLaunchersFacetGroupBuilder();
}
public WorkflowLaunchersFacet toWorkflowLaunchersFacet(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
final WorkflowLaunchersFacetId facetId = this.facetId.toWorkflowLaunchersFacetId();
return WorkflowLaunchersFacet.builder()
.facetId(facetId)
.caption(caption)
.isActive(activeFacetIds != null && activeFacetIds.contains(facetId))
.build();
}
}
@EqualsAndHashCode
@ToString
public static class FacetsCollection implements Iterable<Facet>
{
private static final FacetsCollection EMPTY = new FacetsCollection(ImmutableSet.of());
private final ImmutableSet<Facet> set;
private FacetsCollection(@NonNull final ImmutableSet<Facet> set) | {
this.set = set;
}
public static FacetsCollection ofCollection(final Collection<Facet> collection)
{
return !collection.isEmpty() ? new FacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY;
}
@Override
@NonNull
public Iterator<Facet> iterator() {return set.iterator();}
public boolean isEmpty() {return set.isEmpty();}
public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
if (isEmpty())
{
return WorkflowLaunchersFacetGroupList.EMPTY;
}
final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>();
for (final ManufacturingJobFacets.Facet manufacturingFacet : set)
{
final WorkflowLaunchersFacet facet = manufacturingFacet.toWorkflowLaunchersFacet(activeFacetIds);
groupBuilders.computeIfAbsent(facet.getGroupId(), k -> manufacturingFacet.newWorkflowLaunchersFacetGroupBuilder())
.facet(facet);
}
final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values()
.stream()
.map(WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder::build)
.collect(ImmutableList.toImmutableList());
return WorkflowLaunchersFacetGroupList.ofList(groups);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobFacets.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getReportType() {
return reportType;
}
public void setReportType(Integer reportType) {
this.reportType = reportType;
}
public String getReportMemberName() {
return reportMemberName;
}
public void setReportMemberName(String reportMemberName) {
this.reportMemberName = reportMemberName;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public String getReportObject() {
return reportObject;
}
public void setReportObject(String reportObject) {
this.reportObject = reportObject;
}
public Integer getReportStatus() {
return reportStatus;
}
public void setReportStatus(Integer reportStatus) {
this.reportStatus = reportStatus;
}
public Integer getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(Integer handleStatus) { | this.handleStatus = handleStatus;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", reportType=").append(reportType);
sb.append(", reportMemberName=").append(reportMemberName);
sb.append(", createTime=").append(createTime);
sb.append(", reportObject=").append(reportObject);
sb.append(", reportStatus=").append(reportStatus);
sb.append(", handleStatus=").append(handleStatus);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsMemberReport.java | 1 |
请完成以下Java代码 | public BootstrapConfig remove(String endpoint) {
writeLock.lock();
try {
return super.remove(endpoint);
} finally {
writeLock.unlock();
}
}
public void addToStore(String endpoint, BootstrapConfig config) throws InvalidConfigurationException {
configChecker.verify(config);
// Check PSK identity uniqueness for bootstrap server:
PskByServer pskToAdd = getBootstrapPskIdentity(config);
if (pskToAdd != null) {
BootstrapConfig existingConfig = bootstrapByPskId.get(pskToAdd);
if (existingConfig != null) { | // check if this config will be replace by the new one.
BootstrapConfig previousConfig = bootstrapByEndpoint.get(endpoint);
if (previousConfig != existingConfig) {
throw new InvalidConfigurationException(
"Psk identity [%s] already used for this bootstrap server [%s]", pskToAdd.identity,
pskToAdd.serverUrl);
}
}
}
bootstrapByEndpoint.put(endpoint, config);
if (pskToAdd != null) {
bootstrapByPskId.put(pskToAdd, config);
}
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\bootstrap\store\LwM2MInMemoryBootstrapConfigStore.java | 1 |
请完成以下Java代码 | public TaskService getTaskService() {
return taskService;
}
@Override
public HistoryService getHistoryService() {
return historicDataService;
}
@Override
public RuntimeService getRuntimeService() {
return runtimeService;
}
@Override
public RepositoryService getRepositoryService() {
return repositoryService;
}
@Override
public FormService getFormService() {
return formService;
} | @Override
public DynamicBpmnService getDynamicBpmnService() {
return dynamicBpmnService;
}
@Override
public ProcessMigrationService getProcessMigrationService() {
return processInstanceMigrationService;
}
@Override
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessEngineImpl.java | 1 |
请完成以下Java代码 | public java.lang.String getUserElementString6()
{
return get_ValueAsString(COLUMNNAME_UserElementString6);
}
@Override
public void setUserElementString7 (final @Nullable java.lang.String UserElementString7)
{
set_Value (COLUMNNAME_UserElementString7, UserElementString7);
}
@Override
public java.lang.String getUserElementString7()
{
return get_ValueAsString(COLUMNNAME_UserElementString7);
}
@Override
public void setVesselName (final @Nullable java.lang.String VesselName)
{
throw new IllegalArgumentException ("VesselName is virtual column"); }
@Override
public java.lang.String getVesselName()
{
return get_ValueAsString(COLUMNNAME_VesselName);
}
@Override
public void setExternalHeaderId (final @Nullable String ExternalHeaderId)
{
set_Value (COLUMNNAME_ExternalHeaderId, ExternalHeaderId);
}
@Override | public String getExternalHeaderId()
{
return get_ValueAsString(COLUMNNAME_ExternalHeaderId);
}
@Override
public void setExternalLineId (final @Nullable String ExternalLineId)
{
set_Value (COLUMNNAME_ExternalLineId, ExternalLineId);
}
@Override
public String getExternalLineId()
{
return get_ValueAsString(COLUMNNAME_ExternalLineId);
}
@Override
public void setExternalSystem_ID (final int ExternalSystem_ID)
{
if (ExternalSystem_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID);
}
@Override
public int getExternalSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule.java | 1 |
请完成以下Java代码 | public abstract class SpinValueSerializer extends AbstractSerializableValueSerializer<SpinValue> {
protected DataFormat<?> dataFormat;
protected String name;
public SpinValueSerializer(SerializableValueType type, DataFormat<?> dataFormat, String name) {
super(type, dataFormat.getName());
this.dataFormat = dataFormat;
this.name = name;
}
public String getName() {
return name;
}
protected void writeToValueFields(SpinValue value, ValueFields valueFields, byte[] serializedValue) {
valueFields.setByteArrayValue(serializedValue);
}
protected void updateTypedValue(SpinValue value, String serializedStringValue) {
SpinValueImpl spinValue = (SpinValueImpl) value;
spinValue.setValueSerialized(serializedStringValue);
spinValue.setSerializationDataFormat(serializationDataFormat);
}
protected boolean canSerializeValue(Object value) {
if (value instanceof Spin<?>) {
Spin<?> wrapper = (Spin<?>) value;
return wrapper.getDataFormatName().equals(serializationDataFormat);
}
return false;
}
protected byte[] serializeToByteArray(Object deserializedObject) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStreamWriter outWriter = new OutputStreamWriter(out, Context.getProcessEngineConfiguration().getDefaultCharset());
BufferedWriter bufferedWriter = new BufferedWriter(outWriter);
try { | Spin<?> wrapper = (Spin<?>) deserializedObject;
wrapper.writeToWriter(bufferedWriter);
return out.toByteArray();
}
finally {
IoUtil.closeSilently(out);
IoUtil.closeSilently(outWriter);
IoUtil.closeSilently(bufferedWriter);
}
}
protected Object deserializeFromByteArray(byte[] object, ValueFields valueFields) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(object);
InputStreamReader inReader = new InputStreamReader(bais, Context.getProcessEngineConfiguration().getDefaultCharset());
BufferedReader bufferedReader = new BufferedReader(inReader);
try {
Object wrapper = dataFormat.getReader().readInput(bufferedReader);
return dataFormat.createWrapperInstance(wrapper);
}
finally{
IoUtil.closeSilently(bais);
IoUtil.closeSilently(inReader);
IoUtil.closeSilently(bufferedReader);
}
}
protected boolean isSerializationTextBased() {
return true;
}
} | repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\impl\SpinValueSerializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class CourseService {
@Autowired
private CourseDao courseDao;
@Transactional
public void createCourseDeclarativeWithRuntimeException(Course course) {
courseDao.create(course);
throw new DataIntegrityViolationException("Throwing exception for demoing Rollback!!!");
}
@Transactional(rollbackFor = { SQLException.class })
public void createCourseDeclarativeWithCheckedException(Course course) throws SQLException {
courseDao.create(course);
throw new SQLException("Throwing exception for demoing Rollback!!!");
} | public void createCourseDefaultRatingProgramatic(Course course) {
try {
courseDao.create(course);
throw new DataIntegrityViolationException("Throwing exception for demoing Rollback!!!");
} catch (Exception e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
@Transactional(noRollbackFor = { SQLException.class })
public void createCourseDeclarativeWithNoRollBack(Course course) throws SQLException {
courseDao.create(course);
throw new SQLException("Throwing exception for demoing Rollback!!!");
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\spring\transaction\CourseService.java | 2 |
请完成以下Java代码 | public final class HttpsRedirectWebFilter implements WebFilter {
private PortMapper portMapper = new PortMapperImpl();
private ServerWebExchangeMatcher requiresHttpsRedirectMatcher = ServerWebExchangeMatchers.anyExchange();
private final ServerRedirectStrategy redirectStrategy = new DefaultServerRedirectStrategy();
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return Mono.just(exchange)
.filter(this::isInsecure)
.flatMap(this.requiresHttpsRedirectMatcher::matches)
.filter((matchResult) -> matchResult.isMatch())
.switchIfEmpty(chain.filter(exchange).then(Mono.empty()))
.map((matchResult) -> createRedirectUri(exchange))
.flatMap((uri) -> this.redirectStrategy.sendRedirect(exchange, uri));
}
/**
* Use this {@link PortMapper} for mapping custom ports
* @param portMapper the {@link PortMapper} to use
*/
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
/**
* Use this {@link ServerWebExchangeMatcher} to narrow which requests are redirected | * to HTTPS.
*
* The filter already first checks for HTTPS in the uri scheme, so it is not necessary
* to include that check in this matcher.
* @param requiresHttpsRedirectMatcher the {@link ServerWebExchangeMatcher} to use
*/
public void setRequiresHttpsRedirectMatcher(ServerWebExchangeMatcher requiresHttpsRedirectMatcher) {
Assert.notNull(requiresHttpsRedirectMatcher, "requiresHttpsRedirectMatcher cannot be null");
this.requiresHttpsRedirectMatcher = requiresHttpsRedirectMatcher;
}
private boolean isInsecure(ServerWebExchange exchange) {
return !"https".equals(exchange.getRequest().getURI().getScheme());
}
private URI createRedirectUri(ServerWebExchange exchange) {
int port = exchange.getRequest().getURI().getPort();
UriComponentsBuilder builder = UriComponentsBuilder.fromUri(exchange.getRequest().getURI());
if (port > 0) {
Integer httpsPort = this.portMapper.lookupHttpsPort(port);
Assert.state(httpsPort != null, () -> "HTTP Port '" + port + "' does not have a corresponding HTTPS Port");
builder.port(httpsPort);
}
return builder.scheme("https").build().toUri();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\transport\HttpsRedirectWebFilter.java | 1 |
请完成以下Java代码 | public class X_MobileUI_HUManager_Attribute extends org.compiere.model.PO implements I_MobileUI_HUManager_Attribute, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1824647476L;
/** Standard Constructor */
public X_MobileUI_HUManager_Attribute (final Properties ctx, final int MobileUI_HUManager_Attribute_ID, @Nullable final String trxName)
{
super (ctx, MobileUI_HUManager_Attribute_ID, trxName);
}
/** Load Constructor */
public X_MobileUI_HUManager_Attribute (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setM_Attribute_ID (final int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_Value (COLUMNNAME_M_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_Attribute_ID, M_Attribute_ID);
}
@Override
public int getM_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Attribute_ID);
}
@Override
public void setMobileUI_HUManager_Attribute_ID (final int MobileUI_HUManager_Attribute_ID)
{
if (MobileUI_HUManager_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MobileUI_HUManager_Attribute_ID, MobileUI_HUManager_Attribute_ID); | }
@Override
public int getMobileUI_HUManager_Attribute_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_Attribute_ID);
}
@Override
public org.compiere.model.I_MobileUI_HUManager getMobileUI_HUManager()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class);
}
@Override
public void setMobileUI_HUManager(final org.compiere.model.I_MobileUI_HUManager MobileUI_HUManager)
{
set_ValueFromPO(COLUMNNAME_MobileUI_HUManager_ID, org.compiere.model.I_MobileUI_HUManager.class, MobileUI_HUManager);
}
@Override
public void setMobileUI_HUManager_ID (final int MobileUI_HUManager_ID)
{
if (MobileUI_HUManager_ID < 1)
set_Value (COLUMNNAME_MobileUI_HUManager_ID, null);
else
set_Value (COLUMNNAME_MobileUI_HUManager_ID, MobileUI_HUManager_ID);
}
@Override
public int getMobileUI_HUManager_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_HUManager_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_HUManager_Attribute.java | 1 |
请完成以下Java代码 | void setPubrelMessage(MqttMessage pubrelMessage) {
pubrelRetransmissionHandler.setOriginalMessage(pubrelMessage);
}
void startPubrelRetransmissionTimer(EventLoop eventLoop, Consumer<Object> sendPacket) {
pubrelRetransmissionHandler.setHandler((fixedHeader, originalMessage) ->
sendPacket.accept(new MqttMessage(fixedHeader, originalMessage.variableHeader())));
pubrelRetransmissionHandler.start(eventLoop);
}
void onPubcompReceived() {
pubrelRetransmissionHandler.stop();
}
void onChannelClosed() {
publishRetransmissionHandler.stop();
pubrelRetransmissionHandler.stop();
if (payload != null) {
payload.release();
}
}
static Builder builder() {
return new Builder();
}
static class Builder {
private int messageId;
private Promise<Void> future;
private ByteBuf payload;
private MqttPublishMessage message;
private MqttQoS qos;
private String ownerId;
private MqttClientConfig.RetransmissionConfig retransmissionConfig;
private PendingOperation pendingOperation;
Builder messageId(int messageId) {
this.messageId = messageId;
return this;
}
Builder future(Promise<Void> future) {
this.future = future;
return this;
}
Builder payload(ByteBuf payload) {
this.payload = payload;
return this;
}
Builder message(MqttPublishMessage message) {
this.message = message;
return this; | }
Builder qos(MqttQoS qos) {
this.qos = qos;
return this;
}
Builder ownerId(String ownerId) {
this.ownerId = ownerId;
return this;
}
Builder retransmissionConfig(MqttClientConfig.RetransmissionConfig retransmissionConfig) {
this.retransmissionConfig = retransmissionConfig;
return this;
}
Builder pendingOperation(PendingOperation pendingOperation) {
this.pendingOperation = pendingOperation;
return this;
}
MqttPendingPublish build() {
return new MqttPendingPublish(messageId, future, payload, message, qos, ownerId, retransmissionConfig, pendingOperation);
}
}
} | repos\thingsboard-master\netty-mqtt\src\main\java\org\thingsboard\mqtt\MqttPendingPublish.java | 1 |
请完成以下Java代码 | public int getM_HU_PackagingCode_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PackagingCode_ID);
}
@Override
public void setM_HU_PackagingCode_Text (final @Nullable java.lang.String M_HU_PackagingCode_Text)
{
throw new IllegalArgumentException ("M_HU_PackagingCode_Text is virtual column"); }
@Override
public java.lang.String getM_HU_PackagingCode_Text()
{
return get_ValueAsString(COLUMNNAME_M_HU_PackagingCode_Text);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
throw new IllegalArgumentException ("M_InOut_ID is virtual column"); } | @Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java | 1 |
请完成以下Java代码 | private final JXPanel createComponent(final JComponent editor, final JComponent prev, final JComponent next)
{
if (editor == null)
{
return null;
}
final JXPanel container = new JXPanel();
//
// Force 0 padding, wrap after 3rd component, force fill space with component and 5lp gap between components
final LayoutManager layout = new MigLayout("insets 0, wrap 3", "[fill]5px");
container.setLayout(layout);
container.add(editor);
container.add(prev);
container.add(next);
container.setAlignmentX(Component.LEFT_ALIGNMENT);
return container;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
final Object field;
if (returnValueTo)
{
field = index == 0 ? editor2 : null;
}
else
{
field = index == 0 ? editor : null;
}
if (field == null)
{
return null;
}
if (field instanceof CEditor)
{
final CEditor editor = (CEditor)field;
return editor.getValue();
}
else
{
throw new AdempiereException("Component type not supported - " + field);
}
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
final I_AD_InfoColumn infoColumn = getAD_InfoColumn();
if (infoColumn.isTree())
{
return null;
}
final Object value = getParameterValue(0, false);
//
// Set Context Value
{
final String column = infoColumn.getName();
final IInfoSimple parent = getParent();
if (value == null)
{
final int displayType = infoColumn.getAD_Reference_ID();
if (DisplayType.Date == displayType) | {
parent.setCtxAttribute(column, de.metas.common.util.time.SystemTime.asDayTimestamp());
}
else if (DisplayType.Time == displayType)
{
parent.setCtxAttribute(column, de.metas.common.util.time.SystemTime.asTimestamp());
}
else if (DisplayType.DateTime == displayType)
{
parent.setCtxAttribute(column, SystemTime.asDate());
}
}
else
{
parent.setCtxAttribute(column, value);
}
}
//
// create the actual where clause
// task: 08329: as of now, the date is a real column of the underlying view/table
{
final StringBuilder where = new StringBuilder();
where.append(infoColumn.getSelectClause());
where.append("=?");
params.add(value);
return new String[] { where.toString() };
}
}
@Override
public String getText()
{
if (editor == null)
{
return null;
}
final Object value = editor.getValue();
if (value == null)
{
return null;
}
return value.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaDateModifier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Long getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(Long minEvictableIdleTimeMillis) {
this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
public String getValidationQuery() {
return validationQuery;
}
public void setValidationQuery(String validationQuery) {
this.validationQuery = validationQuery;
}
public Boolean getTestWhileIdle() {
return testWhileIdle;
}
public void setTestWhileIdle(Boolean testWhileIdle) {
this.testWhileIdle = testWhileIdle;
}
public Boolean getTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(Boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
public Boolean getTestOnReturn() {
return testOnReturn;
}
public void setTestOnReturn(Boolean testOnReturn) {
this.testOnReturn = testOnReturn;
}
public Boolean getPoolPreparedStatements() {
return poolPreparedStatements; | }
public void setPoolPreparedStatements(Boolean poolPreparedStatements) {
this.poolPreparedStatements = poolPreparedStatements;
}
public Integer getMaxPoolPreparedStatementPerConnectionSize() {
return maxPoolPreparedStatementPerConnectionSize;
}
public void setMaxPoolPreparedStatementPerConnectionSize(Integer maxPoolPreparedStatementPerConnectionSize) {
this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
}
public String getFilters() {
return filters;
}
public void setFilters(String filters) {
this.filters = filters;
}
} | repos\spring-boot-quick-master\quick-multi-data\src\main\java\com\quick\mulit\config\DruidConfigPrimaryProperties.java | 2 |
请完成以下Java代码 | public void updateLUTUConfigurationFromDocumentLine(
@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration,
@NonNull final I_PP_Order ppOrder)
{
lutuConfiguration.setC_BPartner_ID(ppOrder.getC_BPartner_ID());
final int ppOrderReceiptLocatorId = ppOrder.getM_Locator_ID();
lutuConfiguration.setM_Locator_ID(ppOrderReceiptLocatorId);
lutuConfiguration.setHUStatus(X_M_HU.HUSTATUS_Active);
}
@Override
public void setCurrentLUTUConfiguration(final I_PP_Order documentLine, final I_M_HU_LUTU_Configuration lutuConfiguration)
{ | documentLine.setM_HU_LUTU_Configuration(lutuConfiguration);
}
@Override
public I_M_HU_LUTU_Configuration getCurrentLUTUConfigurationOrNull(final I_PP_Order documentLine)
{
final I_M_HU_LUTU_Configuration lutuConfiguration = documentLine.getM_HU_LUTU_Configuration();
if (lutuConfiguration == null || lutuConfiguration.getM_HU_LUTU_Configuration_ID() <= 0)
{
return null;
}
return lutuConfiguration;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderDocumentLUTUConfigurationHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public APIProcessCandidateStarterGroupConverter apiProcessCandidateStarterGroupConverter() {
return new APIProcessCandidateStarterGroupConverter();
}
@Bean
@ConditionalOnMissingBean(name = "registerProcessCandidateStarterUserRemovedListenerDelegate")
public InitializingBean registerProcessCandidateStarterUserRemovedListenerDelegate(
RuntimeService runtimeService,
@Autowired(required = false) List<
ProcessRuntimeEventListener<ProcessCandidateStarterUserRemovedEvent>
> listeners,
ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter
) {
return () ->
runtimeService.addEventListener(
new ProcessCandidateStarterUserRemovedListenerDelegate(
getInitializedListeners(listeners),
processCandidateStarterUserRemovedEventConverter
),
ActivitiEventType.ENTITY_DELETED
);
}
@Bean
@ConditionalOnMissingBean
public ToAPIProcessCandidateStarterUserRemovedEventConverter processCandidateStarterUserRemovedEventConverter(
APIProcessCandidateStarterUserConverter processCandidateStarterUserConverter
) {
return new ToAPIProcessCandidateStarterUserRemovedEventConverter(processCandidateStarterUserConverter);
}
@Bean
@ConditionalOnMissingBean(name = "registerProcessCandidateStarterGroupRemovedListenerDelegate")
public InitializingBean registerProcessCandidateStarterGroupRemovedListenerDelegate( | RuntimeService runtimeService,
@Autowired(required = false) List<
ProcessRuntimeEventListener<ProcessCandidateStarterGroupRemovedEvent>
> listeners,
ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter
) {
return () ->
runtimeService.addEventListener(
new ProcessCandidateStarterGroupRemovedListenerDelegate(
getInitializedListeners(listeners),
processCandidateStarterGroupRemovedEventConverter
),
ActivitiEventType.ENTITY_DELETED
);
}
@Bean
@ConditionalOnMissingBean
public ToAPIProcessCandidateStarterGroupRemovedEventConverter processCandidateStarterGroupRemovedEventConverter(
APIProcessCandidateStarterGroupConverter processCandidateStarterGroupConverter
) {
return new ToAPIProcessCandidateStarterGroupRemovedEventConverter(processCandidateStarterGroupConverter);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\conf\ProcessRuntimeAutoConfiguration.java | 2 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer ("X_A_Depreciation[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Depreciation Type.
@param A_Depreciation_ID Depreciation Type */
public void setA_Depreciation_ID (int A_Depreciation_ID)
{
if (A_Depreciation_ID < 1)
set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_A_Depreciation_ID, Integer.valueOf(A_Depreciation_ID));
}
/** Get Depreciation Type.
@return Depreciation Type */
public int getA_Depreciation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Depreciation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set DepreciationType.
@param DepreciationType DepreciationType */
public void setDepreciationType (String DepreciationType)
{
set_Value (COLUMNNAME_DepreciationType, DepreciationType);
}
/** Get DepreciationType.
@return DepreciationType */
public String getDepreciationType ()
{
return (String)get_Value(COLUMNNAME_DepreciationType);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set 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);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Text.
@param Text Text */
public void setText (String Text)
{
set_Value (COLUMNNAME_Text, Text);
}
/** Get Text.
@return Text */
public String getText ()
{
return (String)get_Value(COLUMNNAME_Text);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java | 1 |
请完成以下Java代码 | public String getCallbackId() {
return callbackId;
}
public void setCallbackId(String callbackId) {
this.callbackId = callbackId;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType(String callbackType) {
this.callbackType = callbackType;
}
public String getReferenceId() {
return referenceId;
}
public void setReferenceId(String referenceId) {
this.referenceId = referenceId;
}
public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
} | public String getOwnerId() {
return ownerId;
}
public void setOwnerId(String ownerId) {
this.ownerId = ownerId;
}
public String getAssigneeId() {
return assigneeId;
}
public void setAssigneeId(String assigneeId) {
this.assigneeId = assigneeId;
}
public String getInitiatorVariableName() {
return initiatorVariableName;
}
public void setInitiatorVariableName(String initiatorVariableName) {
this.initiatorVariableName = initiatorVariableName;
}
public String getOverrideDefinitionTenantId() {
return overrideDefinitionTenantId;
}
public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) {
this.overrideDefinitionTenantId = overrideDefinitionTenantId;
}
public String getPredefinedProcessInstanceId() {
return predefinedProcessInstanceId;
}
public void setPredefinedProcessInstanceId(String predefinedProcessInstanceId) {
this.predefinedProcessInstanceId = predefinedProcessInstanceId;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\interceptor\StartProcessInstanceBeforeContext.java | 1 |
请完成以下Java代码 | private final IActivityAware getDocLineActivityAwareOrNull(final I_Fact_Acct_ActivityChangeRequest request)
{
final Class<?> lineClass = getDocLineClass(request.getAD_Table_ID());
if (lineClass == null)
{
addLog("Skip {0} because it's not supported", request);
return null;
}
final int lineId = request.getLine_ID();
if (lineId <= 0)
{
addLog("Skip {0} because it does not have the Line_ID set", request);
return null;
}
final Object line = InterfaceWrapperHelper.create(getCtx(), lineId, lineClass, ITrx.TRXNAME_ThreadInherited);
final IActivityAware activityAware = InterfaceWrapperHelper.asColumnReferenceAwareOrNull(line, IActivityAware.class);
if (activityAware == null) | {
// no activity on line level
addLog("Skip {0} because it does not provide an activity", line);
return null;
}
return activityAware;
}
@VisibleForTesting
static interface IActivityAware
{
String COLUMNNAME_C_Activity_ID = "C_Activity_ID";
int getC_Activity_ID();
void setC_Activity_ID(final int activityId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\Fact_Acct_ActivityChangeRequest_Process.java | 1 |
请完成以下Java代码 | public void setTypeMRP (java.lang.String TypeMRP)
{
set_Value (COLUMNNAME_TypeMRP, TypeMRP);
}
/** Get TypeMRP.
@return TypeMRP */
@Override
public java.lang.String getTypeMRP ()
{
return (java.lang.String)get_Value(COLUMNNAME_TypeMRP);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version | Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java | 1 |
请完成以下Java代码 | static class NextMatchAction extends TextAction {
/**
*
*/
private static final long serialVersionUID = 2987063701364646859L;
JTextComponent textComponent;
AutoCompleteDocument document;
final AbstractAutoCompleteAdaptor adaptor;
final List<String> items;
int currentIndex = 0;
public NextMatchAction(JTextComponent textComponent, AutoCompleteDocument document, final AbstractAutoCompleteAdaptor adaptor) {
super("NextMatchAction");
this.textComponent = textComponent;
this.document = document;
this.adaptor = adaptor;
items = new ArrayList<String>(adaptor.getItemCount());
for (int i = 0; i < adaptor.getItemCount(); i++) {
Object o = adaptor.getItem(i);
items.add((o!=null)?(String) adaptor.getItem(i):"");
}
Collections.sort(items);
}
private String getNextMatch(String start) {
for (int i = currentIndex; i < items.size(); i++) {
if(items.get(i).toLowerCase().startsWith(start.toLowerCase())) {
currentIndex = i+1;
return items.get(i);
}
}
currentIndex=0;
return start;
}
/**
* Shows the next match.
*
* @param e the action event
*/
public void actionPerformed(ActionEvent e) {
JTextComponent target = getTextComponent(e);
if ((target != null) && (e != null)) {
if ((! target.isEditable()) || (! target.isEnabled())) {
UIManager.getLookAndFeel().provideErrorFeedback(target);
return;
} | String content = target.getText();
if (content != null && target.getSelectionStart()>0) {
content = content.substring(0,target.getSelectionStart());
}
if (content != null) {
target.setText(getNextMatch(content));
adaptor.markText(content.length());
}
}
}
}
/**
* A TextAction that provides an error feedback for the text component that invoked
* the action. The error feedback is most likely a "beep".
*/
static Object errorFeedbackAction = new TextAction("provide-error-feedback") {
/**
*
*/
private static final long serialVersionUID = 6251452041316544686L;
public void actionPerformed(ActionEvent e) {
UIManager.getLookAndFeel().provideErrorFeedback(getTextComponent(e));
}
};
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\ADempiereAutoCompleteDecorator.java | 1 |
请完成以下Java代码 | public void start() {
this.subscription = this.eventStore.findAll().concatWith(this.eventStore).subscribe(this::updateSnapshot);
}
public void stop() {
if (this.subscription != null) {
this.subscription.dispose();
this.subscription = null;
}
}
protected Mono<Instance> rehydrateSnapshot(InstanceId id) {
return super.find(id).map((instance) -> this.snapshots.compute(id, (key, snapshot) -> {
// check if the loaded version hasn't been already outdated by a snapshot
if (snapshot == null || instance.getVersion() >= snapshot.getVersion()) {
return instance;
}
else {
return snapshot;
}
}));
} | protected void updateSnapshot(InstanceEvent event) {
try {
this.snapshots.compute(event.getInstance(), (key, old) -> {
Instance instance = (old != null) ? old : Instance.create(key);
if (event.getVersion() > instance.getVersion()) {
return instance.apply(event);
}
return instance;
});
}
catch (Exception ex) {
log.warn("Error while updating the snapshot with event {}", event, ex);
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\domain\entities\SnapshottingInstanceRepository.java | 1 |
请完成以下Java代码 | public class ViewChangesCollectorAutoCloseable implements IAutoCloseable
{
@NonNull private final ThreadLocal<ViewChangesCollector> threadLocal;
@NonNull @Getter private final ViewChangesCollector collector;
private final boolean isNewCollector;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final boolean isContextViewIdChanged;
private final ViewId previousContextViewId;
ViewChangesCollectorAutoCloseable(
@NonNull final ThreadLocal<ViewChangesCollector> threadLocal,
@Nullable final ViewId contextViewId)
{
this.threadLocal = threadLocal;
final ViewChangesCollector currentCollector = threadLocal.get();
if (currentCollector == null)
{
this.collector = new ViewChangesCollector(false);
this.isNewCollector = true;
threadLocal.set(this.collector);
}
else
{
this.collector = currentCollector;
this.isNewCollector = false;
}
if (contextViewId != null)
{
this.isContextViewIdChanged = true;
this.previousContextViewId = this.collector.getContextViewId();
this.collector.setContextViewId(contextViewId);
}
else
{
this.isContextViewIdChanged = false;
this.previousContextViewId = null;
}
} | @Override
public void close()
{
if (closed.getAndSet(true))
{
return;
}
if (isNewCollector)
{
collector.close();
threadLocal.remove();
}
else
{
collector.flush();
if (isContextViewIdChanged)
{
collector.setContextViewId(previousContextViewId);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollectorAutoCloseable.java | 1 |
请完成以下Java代码 | public int getParameter_ToAsInt()
{
return getParameter_ToAsInt(0);
}
public int getParameter_ToAsInt(final int defaultValueWhenNull)
{
return toInt(m_Parameter_To, defaultValueWhenNull);
}
private static int toInt(@Nullable final Object value, final int defaultValueWhenNull)
{
if (value == null)
{
return defaultValueWhenNull;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else if (value instanceof RepoIdAware)
{
return ((RepoIdAware)value).getRepoId();
}
else
{
final BigDecimal bd = new BigDecimal(value.toString());
return bd.intValue();
}
}
public boolean getParameterAsBoolean()
{
return StringUtils.toBoolean(m_Parameter);
}
@Nullable
public Boolean getParameterAsBooleanOrNull()
{
return StringUtils.toBoolean(m_Parameter, null);
}
@Nullable
public Boolean getParameterAsBoolean(@Nullable Boolean defaultValue)
{
return StringUtils.toBoolean(m_Parameter, defaultValue);
}
public boolean getParameter_ToAsBoolean()
{
return StringUtils.toBoolean(m_Parameter_To);
}
@Nullable
public Timestamp getParameterAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter);
}
@Nullable
public Timestamp getParameter_ToAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter_To);
}
@Nullable
public LocalDate getParameterAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter);
}
@Nullable
public LocalDate getParameter_ToAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter_To);
}
@Nullable | public ZonedDateTime getParameterAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter);
}
@Nullable
public Instant getParameterAsInstant()
{
return TimeUtil.asInstant(m_Parameter);
}
@Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter_To);
}
@Nullable
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java | 1 |
请完成以下Java代码 | public static List<String> lines(MultipartFile file) {
try {
Path tmp = Files.write(File.createTempFile("mongo-upload", null)
.toPath(), file.getBytes());
return Files.readAllLines(tmp);
} catch (IOException e) {
log.error("reading lines from " + file, e);
return null;
}
}
public static List<String> lines(File file) {
try {
return Files.readAllLines(file.toPath());
} catch (IOException e) {
log.error("reading lines from " + file, e);
return null; | }
}
public static List<String> linesFromResource(String resource) {
Resource input = new ClassPathResource(resource);
try {
Path path = input.getFile()
.toPath();
return Files.readAllLines(path);
} catch (IOException e) {
log.error("reading lines from classpath resource: " + resource, e);
return null;
}
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\json\convertfile\ImportUtils.java | 1 |
请完成以下Java代码 | public class JeecgEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* ID
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "ID")
private java.lang.String id;
/**
* 创建人
*/
@Schema(description = "创建人")
@Excel(name = "创建人", width = 15)
private java.lang.String createBy;
/**
* 创建时间
*/
@Schema(description = "创建时间") | @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date createTime;
/**
* 更新人
*/
@Schema(description = "更新人")
@Excel(name = "更新人", width = 15)
private java.lang.String updateBy;
/**
* 更新时间
*/
@Schema(description = "更新时间")
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private java.util.Date updateTime;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\base\entity\JeecgEntity.java | 1 |
请完成以下Spring Boot application配置 | #---
#camelCasing
#customProperties.name="Baeldung"
#PascalCasing
#CustomProperties.name="Baeldung"
#SnakingCasing
#custom_properties.name="Baeldung"
#KebabCasing
custom-properties.name="Bael | dung"
application.name=Baeldung
article.name=Properties in BeanFactoryPostProcessor | repos\tutorials-master\spring-boot-modules\spring-boot-properties-4\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public static void concatByStringJoinerBy10000(Blackhole blackhole) {
concatByStringJoiner(ITERATION_10000, blackhole);
}
public static void concatByStringJoiner(int iterations, Blackhole blackhole) {
StringJoiner concatBuf = new StringJoiner("");
for (int n=0; n<iterations; n++) concatBuf.add(TOKEN);
blackhole.consume(concatBuf);
}
@Benchmark
public static void concatByStringBufferBy100(Blackhole blackhole) {
concatByStringBuffer(ITERATION_100, blackhole);
}
@Benchmark
public static void concatByStringBufferBy1000(Blackhole blackhole) {
concatByStringBuffer(ITERATION_1000, blackhole);
}
@Benchmark
public static void concatByStringBufferBy10000(Blackhole blackhole) {
concatByStringBuffer(ITERATION_10000, blackhole);
}
public static void concatByStringBuffer(int iterations, Blackhole blackhole) {
StringBuffer concatBuf = new StringBuffer();
for (int n=0; n<iterations; n++) concatBuf.append(TOKEN);
blackhole.consume(concatBuf);
}
@Benchmark
public static void concatByStringBuilderBy100(Blackhole blackhole) {
concatByStringBuilder(ITERATION_100, blackhole);
}
@Benchmark
public static void concatByStringBuilderBy1000(Blackhole blackhole) {
concatByStringBuilder(ITERATION_1000, blackhole);
}
@Benchmark
public static void concatByStringBuilderBy10000(Blackhole blackhole) {
concatByStringBuilder(ITERATION_10000, blackhole); | }
public static void concatByStringBuilder(int iterations, Blackhole blackhole) {
StringBuilder concatBuf = new StringBuilder();
for (int n=0; n<iterations; n++) concatBuf.append(TOKEN);
blackhole.consume(concatBuf);
}
@Benchmark
public static void concatByStreamBy100(Blackhole blackhole) {
concatByStream(ITERATION_100, blackhole);
}
@Benchmark
public static void concatByStreamBy1000(Blackhole blackhole) {
concatByStream(ITERATION_1000, blackhole);
}
@Benchmark
public static void concatByStreamBy10000(Blackhole blackhole) {
concatByStream(ITERATION_10000, blackhole);
}
public static void concatByStream(int iterations, Blackhole blackhole) {
String concatString = "";
List<String> strList = new ArrayList<>();
strList.add(concatString);
strList.add(TOKEN);
for (int n=0; n<iterations; n++) {
concatString = strList.stream().collect(Collectors.joining(""));
strList.set(0, concatString);
}
blackhole.consume(concatString);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(LoopConcatBenchmark.class.getSimpleName()).threads(1)
.shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-6\src\main\java\com\baeldung\performance\LoopConcatBenchmark.java | 1 |
请完成以下Java代码 | public boolean isAvailable()
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
if (gridField == null)
{
return false;
}
final int displayType = gridField.getDisplayType();
if (displayType == DisplayType.String || displayType == DisplayType.Text || displayType == DisplayType.TextLong)
{
return true;
}
return false;
}
@Override
public boolean isRunnable()
{
return true;
}
@Override
public void run()
{
throw new UnsupportedOperationException();
} | @Override
public boolean createUI(java.awt.Container parent)
{
final VEditor editor = getEditor();
final GridField gridField = editor.getField();
final Container textComponent = (Container)editor;
final List<JMenuItem> items = BoilerPlateMenu.createMenuElements(textComponent, gridField);
if (items == null || items.isEmpty())
{
return false;
}
for (JMenuItem item : items)
{
parent.add(item);
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\BoilerPlateMenuAction.java | 1 |
请完成以下Java代码 | public class PayloadSizeFilter extends OncePerRequestFilter {
private final Map<String, Long> limits = new LinkedHashMap<>();
private final AntPathMatcher pathMatcher = new AntPathMatcher();
public PayloadSizeFilter(String limitsConfiguration) {
for (String limit : limitsConfiguration.split(";")) {
try {
String urlPathPattern = limit.split("=")[0];
long maxPayloadSize = Long.parseLong(limit.split("=")[1]);
limits.put(urlPathPattern, maxPayloadSize);
} catch (Exception e) {
throw new IllegalArgumentException("Failed to parse size limits configuration: " + limitsConfiguration);
}
}
log.info("Initialized payload size filter with configuration: {}" , limitsConfiguration);
}
@Override
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
for (String url : limits.keySet()) {
if (pathMatcher.match(url, request.getRequestURI())) {
if (checkMaxPayloadSizeExceeded(request, response, limits.get(url))) {
return;
}
break;
}
}
chain.doFilter(request, response); | }
private boolean checkMaxPayloadSizeExceeded(HttpServletRequest request, HttpServletResponse response, long maxPayloadSize) throws IOException {
if (request.getContentLength() > maxPayloadSize) {
log.info("[{}] [{}] Payload size {} exceeds the limit of {} bytes", request.getRemoteAddr(), request.getRequestURL(), request.getContentLength(), maxPayloadSize);
handleMaxPayloadSizeExceededException(response, new MaxPayloadSizeExceededException(maxPayloadSize));
return true;
}
return false;
}
@Override
protected boolean shouldNotFilterAsyncDispatch() {
return false;
}
@Override
protected boolean shouldNotFilterErrorDispatch() {
return false;
}
private void handleMaxPayloadSizeExceededException(HttpServletResponse response, MaxPayloadSizeExceededException exception) throws IOException {
response.setStatus(HttpStatus.PAYLOAD_TOO_LARGE.value());
JacksonUtil.writeValue(response.getWriter(), exception.getMessage());
}
} | repos\thingsboard-master\common\transport\http\src\main\java\org\thingsboard\server\transport\http\config\PayloadSizeFilter.java | 1 |
请完成以下Java代码 | public boolean isValueDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsValueDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/
@Override
public void setOrderByClause (java.lang.String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
@Override
public java.lang.String getOrderByClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Inaktive Werte anzeigen.
@param ShowInactiveValues Inaktive Werte anzeigen */
@Override
public void setShowInactiveValues (boolean ShowInactiveValues)
{
set_Value (COLUMNNAME_ShowInactiveValues, Boolean.valueOf(ShowInactiveValues));
}
/** Get Inaktive Werte anzeigen.
@return Inaktive Werte anzeigen */
@Override
public boolean isShowInactiveValues ()
{
Object oo = get_Value(COLUMNNAME_ShowInactiveValues);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); | return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java | 1 |
请完成以下Java代码 | public MethodInfo getMethodInfo() {
return this.methodInfo;
}
/**
* Obtain the annotations on the method to which the associated expression resolves.
*
* @return The annotations on the method to which the associated expression resolves. If the are no annotations,
* then an empty array is returned.
*/
public Annotation[] getAnnotations() {
return annotations;
}
/**
* Obtain the evaluated parameter values that will be passed to the method to which the associated expression
* resolves.
*
* @return The evaluated parameters.
*/
public Object[] getEvaluatedParameters() {
return evaluatedParameters;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(annotations);
result = prime * result + ((base == null) ? 0 : base.hashCode());
result = prime * result + Arrays.deepHashCode(evaluatedParameters);
result = prime * result + ((methodInfo == null) ? 0 : methodInfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
} | if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MethodReference other = (MethodReference) obj;
if (!Arrays.equals(annotations, other.annotations)) {
return false;
}
if (base == null) {
if (other.base != null) {
return false;
}
} else if (!base.equals(other.base)) {
return false;
}
if (!Arrays.deepEquals(evaluatedParameters, other.evaluatedParameters)) {
return false;
}
if (methodInfo == null) {
return other.methodInfo == null;
} else {
return methodInfo.equals(other.methodInfo);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\MethodReference.java | 1 |
请完成以下Java代码 | public List<User> getUserList() {
// 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
List<User> r = new ArrayList<User>(users.values());
return r;
}
/**
* 处理"/users/"的POST请求,用来创建User
*
* @param user
* @return
*/
@PostMapping("/")
public String postUser(@RequestBody User user) {
// @RequestBody注解用来绑定通过http请求中application/json类型上传的数据
users.put(user.getId(), user);
return "success";
}
/**
* 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
*
* @param id
* @return
*/
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// url中的id可通过@PathVariable绑定到函数的参数中
return users.get(id);
}
/**
* 处理"/users/{id}"的PUT请求,用来更新User信息
*
* @param id
* @param user
* @return
*/
@PutMapping("/{id}")
public String putUser(@PathVariable Long id, @RequestBody User user) {
User u = users.get(id); | u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
/**
* 处理"/users/{id}"的DELETE请求,用来删除User
*
* @param id
* @return
*/
@DeleteMapping("/{id}")
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
} | repos\SpringBoot-Learning-master\2.x\chapter2-1\src\main\java\com\didispace\chapter21\UserController.java | 1 |
请完成以下Java代码 | public class JsonTypeConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonType.class);
private ObjectMapper objectMapper;
private String javaClassFieldForJackson;
public JsonTypeConverter(ObjectMapper objectMapper, String javaClassFieldForJackson) {
this.objectMapper = objectMapper;
this.javaClassFieldForJackson = javaClassFieldForJackson;
}
public Object convertToValue(JsonNode jsonValue, ValueFields valueFields) {
Object convertedValue = jsonValue;
if (jsonValue != null && StringUtils.isNotBlank(javaClassFieldForJackson)) {
//can find type so long as JsonTypeInfo annotation on the class - see https://stackoverflow.com/a/28384407/9705485
JsonNode classNode = jsonValue.get(javaClassFieldForJackson);
try {
if (classNode != null) {
final String type = classNode.asText();
convertedValue = convertToType(jsonValue, type); | } else if (
valueFields.getTextValue2() != null &&
!jsonValue.getClass().getName().equals(valueFields.getTextValue2())
) {
convertedValue = convertToType(jsonValue, valueFields.getTextValue2());
}
} catch (ClassNotFoundException e) {
LOGGER.warn("Unable to obtain type for json variable object " + valueFields.getName(), e);
}
}
return convertedValue;
}
private Object convertToType(JsonNode jsonValue, String type) throws ClassNotFoundException {
return objectMapper.convertValue(jsonValue, loadClass(type));
}
private Class<?> loadClass(String type) throws ClassNotFoundException {
return Class.forName(type, false, this.getClass().getClassLoader());
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JsonTypeConverter.java | 1 |
请完成以下Java代码 | public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Item item = (Item) o;
if (code != null ? !code.equals(item.code) : item.code != null)
return false;
if (price != null ? !price.equals(item.price) : item.price != null)
return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null; | }
@Override
public int hashCode() {
int result = code != null ? code.hashCode() : 0;
result = 31 * result + (price != null ? price.hashCode() : 0);
result = 31 * result + (quantity != null ? quantity.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
}
} | repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\libraries\smooks\model\Item.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Page<QuoteDTO> findAll(Pageable pageable) {
log.debug("Request to get all Quotes");
return quoteRepository.findAll(pageable)
.map(quoteMapper::toDto);
}
/**
* Get one quote by id.
*
* @param id the id of the entity
* @return the entity
*/
@Override
@Transactional(readOnly = true)
public Optional<QuoteDTO> findOne(Long id) { | log.debug("Request to get Quote : {}", id);
return quoteRepository.findById(id)
.map(quoteMapper::toDto);
}
/**
* Delete the quote by id.
*
* @param id the id of the entity
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Quote : {}", id);
quoteRepository.deleteById(id);
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\impl\QuoteServiceImpl.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.